/* global React */
const { useState, useEffect, useRef } = React;

// ============================================================
// Hero background — video on desktop, static photo on mobile
// (mobile crop of 16:9 video showed mostly empty pavement; photo + tighter
//  object-position keeps the bus fleet visible and looks intentional)
// ============================================================
function HeroVideoBg({ translate, reduceMotion }) {
  const videoRef = useRef(null);
  const [isMobile, setIsMobile] = useState(
    typeof window !== 'undefined' ? window.matchMedia('(max-width: 767px)').matches : false
  );

  useEffect(() => {
    const mq = window.matchMedia('(max-width: 767px)');
    const onChange = (e) => setIsMobile(e.matches);
    setIsMobile(mq.matches);
    mq.addEventListener ? mq.addEventListener('change', onChange) : mq.addListener(onChange);
    return () => {
      mq.removeEventListener ? mq.removeEventListener('change', onChange) : mq.removeListener(onChange);
    };
  }, []);

  useEffect(() => {
    if (isMobile) return; // no video on mobile
    const v = videoRef.current;
    if (!v) return;
    v.muted = true;
    v.defaultMuted = true;
    if (reduceMotion) {
      try { v.pause(); v.currentTime = 0; } catch (e) {}
      return;
    }
    const tryPlay = () => v.play().catch(() => {});
    tryPlay();
    if (v.readyState < 2) v.addEventListener('canplay', tryPlay, { once: true });
  }, [reduceMotion, isMobile]);

  const style = { transform: `translate3d(0, ${translate}px, 0)` };

  if (isMobile) {
    return (
      <img
        className="hero-bg hero-photo-mobile"
        src="assets/hero-poster.jpg"
        alt=""
        aria-hidden="true"
        style={style}
      />
    );
  }

  return (
    <video
      ref={videoRef}
      className="hero-bg hero-video"
      src="assets/hero-video.mp4"
      poster="assets/hero-poster.jpg"
      autoPlay={!reduceMotion}
      muted
      defaultMuted
      loop
      playsInline
      preload="auto"
      aria-hidden="true"
      style={style}
    />
  );
}

// ============================================================
// Hero – Default (Subtle)
// ============================================================
function HeroDefault({ tweaks }) {
  const [scrollY, setScrollY] = useState(0);
  const [reduceMotion, setReduceMotion] = useState(false);

  useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    setReduceMotion(mq.matches);
    const onScroll = () => setScrollY(window.scrollY);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const parallaxFactor = (tweaks.parallaxStrength ?? 40) / 100;
  const translate = reduceMotion ? 0 : scrollY * parallaxFactor;
  const gradAlpha = (tweaks.gradientIntensity ?? 70) / 100;

  return (
    <section className="hero" id="hero">
      <HeroVideoBg translate={translate} reduceMotion={reduceMotion} />
      <div
        className="hero-overlay"
        style={{
          background: `linear-gradient(180deg,
            hsl(220 22% 7% / ${0.5 * gradAlpha}) 0%,
            hsl(220 22% 7% / ${0.7 * gradAlpha}) 50%,
            hsl(220 22% 7% / ${Math.min(0.95 * gradAlpha + 0.1, 1)}) 100%)`,
        }}
      />
      {tweaks.showBgRailDots && <div className="hero-rail-dots" aria-hidden="true" />}

      <div className="container hero-content hero-content-left">
        <div className="t-eyebrow hero-eyebrow" style={{ animationDelay: '100ms' }}>
          <span className="dot"></span>Komerční areál Příbram – Březové Hory
        </div>

        <h1 className="t-display t-h1 hero-h1" style={{ animationDelay: '250ms' }}>
          Vyjely odsud miliony cest. <span className="hero-accent">Vaše</span> může být další.
        </h1>

        <p className="t-body-l hero-sub" style={{ animationDelay: '450ms', maxWidth: 640 }}>
          Komerční areál BUS real v Příbrami. Sklady, dílny a kanceláře k pronájmu od 15 m².
          Místo s autobusovou tradicí od roku 1958 a otevřeným prostorem pro nové firmy.
        </p>

        <div className="hero-cta" style={{ animationDelay: '650ms' }}>
          <a href="#prostory" className="btn btn-primary">
            Prohlédnout prostory
            <svg className="arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
          </a>
          <a href="#pribeh" className="btn btn-outline">Příběh areálu</a>
        </div>
      </div>

      <a href="#o-arealu" className="hero-scroll-hint" aria-label="Posunout dolů na další sekci">
        <svg className="hero-scroll-chev chev-1" viewBox="0 0 24 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="3 3 12 11 21 3"/></svg>
        <svg className="hero-scroll-chev chev-2" viewBox="0 0 24 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="3 3 12 11 21 3"/></svg>
      </a>
    </section>
  );
}

// ============================================================
// Hero – Departures Board (Experimental)
// ============================================================
const DEPARTURE_PHRASES = [
  'Vyjely odsud miliony cest.',
  'Tisíce odjezdů. Jeden areál.',
];

function DeparturesBoard() {
  const [phraseIdx, setPhraseIdx] = useState(0);
  const [stage, setStage] = useState('in');

  useEffect(() => {
    const t1 = setTimeout(() => setStage('hold'), 800);
    const t2 = setTimeout(() => setStage('out'), 4000);
    const t3 = setTimeout(() => {
      setPhraseIdx((i) => (i + 1) % DEPARTURE_PHRASES.length);
      setStage('in');
    }, 4600);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, [phraseIdx]);

  const words = DEPARTURE_PHRASES[phraseIdx].split(' ');
  return (
    <span className="dep-line" aria-live="polite">
      {words.map((w, i) => (
        <span
          key={`${phraseIdx}-${i}`}
          className={`dep-word dep-${stage}`}
          style={{ transitionDelay: `${i * 60}ms`, animationDelay: `${i * 60}ms` }}
        >
          {w}
        </span>
      ))}
    </span>
  );
}

function HeroDepartures({ tweaks }) {
  const [scrollY, setScrollY] = useState(0);
  const [reduceMotion, setReduceMotion] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    setReduceMotion(mq.matches);
    const onScroll = () => setScrollY(window.scrollY);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const parallaxFactor = (tweaks.parallaxStrength ?? 40) / 100;
  const translate = reduceMotion ? 0 : scrollY * parallaxFactor;
  const gradAlpha = (tweaks.gradientIntensity ?? 70) / 100;

  return (
    <section className="hero" id="hero">
      <HeroVideoBg translate={translate} reduceMotion={reduceMotion} />
      <div className="hero-overlay" style={{
        background: `linear-gradient(180deg,
          hsl(220 22% 7% / ${0.5 * gradAlpha}) 0%,
          hsl(220 22% 7% / ${0.7 * gradAlpha}) 50%,
          hsl(220 22% 7% / ${Math.min(0.95 * gradAlpha + 0.1, 1)}) 100%)`,
      }} />
      {tweaks.showBgRailDots && <div className="hero-rail-dots" aria-hidden="true" />}

      <div className="container hero-content hero-content-left">
        <div className="t-eyebrow hero-eyebrow">
          <span className="dot"></span>Komerční areál Příbram – Březové Hory
        </div>

        <h1 className="t-display t-h1 hero-h1 hero-h1-dep">
          <DeparturesBoard />
          <br />
          <span className="hero-accent">Vaše</span> může být další.
        </h1>

        <p className="t-body-l hero-sub" style={{ maxWidth: 640 }}>
          Komerční areál BUS real v Příbrami. Sklady, dílny a kanceláře k pronájmu od 15 m².
          Místo s autobusovou tradicí od roku 1958 a otevřeným prostorem pro nové firmy.
        </p>

        <div className="hero-cta">
          <a href="#prostory" className="btn btn-primary">
            Prohlédnout prostory
            <svg className="arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
          </a>
          <a href="#pribeh" className="btn btn-outline">Příběh areálu</a>
        </div>
      </div>

      <a href="#o-arealu" className="hero-scroll-hint" aria-label="Posunout dolů na další sekci">
        <svg className="hero-scroll-chev chev-1" viewBox="0 0 24 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="3 3 12 11 21 3"/></svg>
        <svg className="hero-scroll-chev chev-2" viewBox="0 0 24 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="3 3 12 11 21 3"/></svg>
      </a>
    </section>
  );
}

// ============================================================
// Navigation
// ============================================================
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [activeId, setActiveId] = useState(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
  }, [open]);

  const items = [
    { href: '#o-arealu', label: 'Areál' },
    { href: '#prostory', label: 'Prostory' },
    { href: '#pribeh', label: 'Příběh' },
    { href: '#sedlcany', label: 'Sedlčany' },
    { href: '#kontakt', label: 'Kontakt' },
  ];

  // Track which section is currently in the viewport (~upper third) for active nav highlight
  useEffect(() => {
    const ids = items.map((it) => it.href.slice(1));
    const els = ids.map((id) => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActiveId(e.target.id);
        });
      },
      { rootMargin: '-30% 0px -60% 0px', threshold: 0 }
    );
    els.forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  return (
    <>
      <nav className={`nav ${scrolled ? 'is-scrolled' : ''}`} aria-label="Hlavní navigace">
        <div className="container nav-inner">
          <a href="#hero" className="nav-logo" aria-label="BUS real – domů">
            <img src="assets/logo-bile.png" alt="BUS real" />
          </a>
          <div className="nav-right">
            <ul className="nav-list">
              {items.map((it) => {
                const id = it.href.slice(1);
                const active = activeId === id;
                return (
                  <li key={it.href}>
                    <a href={it.href} className={active ? 'is-active' : ''} aria-current={active ? 'page' : undefined}>
                      {it.label}
                    </a>
                  </li>
                );
              })}
            </ul>
            <a href="#kontakt" className="btn btn-primary nav-cta">Mám zájem o pronájem</a>
          </div>
          <button
            className="nav-burger"
            aria-label="Otevřít menu"
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              {open ? (
                <>
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </>
              ) : (
                <>
                  <line x1="3" y1="6" x2="21" y2="6"></line>
                  <line x1="3" y1="12" x2="21" y2="12"></line>
                  <line x1="3" y1="18" x2="21" y2="18"></line>
                </>
              )}
            </svg>
          </button>
        </div>
      </nav>

      <div className={`nav-overlay ${open ? 'is-open' : ''}`} aria-hidden={!open}>
        <ul>
          {items.map((it) => (
            <li key={it.href}>
              <a href={it.href} onClick={() => setOpen(false)}>{it.label}</a>
            </li>
          ))}
        </ul>
        <a href="#kontakt" className="btn btn-primary" onClick={() => setOpen(false)} style={{ alignSelf: 'flex-start' }}>
          Mám zájem o pronájem
        </a>
      </div>
    </>
  );
}

// ============================================================
// Sticky mobile phone CTA
// ============================================================
function StickyPhone() {
  return (
    <a className="sticky-mobile-cta" href="tel:+420720620718" aria-label="Zavolat: +420 720 620 718">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
      </svg>
    </a>
  );
}

// ============================================================
// Collapsible Tweaks subsection
// ============================================================
function ExperimentalSection({ children }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        className="twk-sect twk-experimental-toggle"
        onClick={() => setOpen(v => !v)}
        style={{
          appearance: 'none', background: 'transparent', border: 0,
          textAlign: 'left', padding: '10px 0 0', cursor: 'default',
          display: 'flex', alignItems: 'center', gap: 6,
          fontSize: 10, fontWeight: 600, letterSpacing: '0.06em',
          textTransform: 'uppercase', color: 'rgba(41,38,27,.45)',
        }}
      >
        <span>Experimental</span>
        <span style={{ fontSize: 9, opacity: 0.6 }}>{open ? '▾' : '▸'}</span>
      </button>
      {open && <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{children}</div>}
    </>
  );
}

// ============================================================
// Tweaks panel
// ============================================================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "subtle",
  "gradientIntensity": 70,
  "parallaxStrength": 40,
  "showBgRailDots": true
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const SectionOArealu = window.SectionOArealu;
  const SectionProstory = window.SectionProstory;
  const SectionVyhody = window.SectionVyhody;
  const SectionPribeh = window.SectionPribeh;
  const SectionSedlcany = window.SectionSedlcany;
  const SectionKontakt = window.SectionKontakt;
  const SiteFooter = window.SiteFooter;

  return (
    <>
      <Nav />
      {t.heroVariant === 'departures'
        ? <HeroDepartures tweaks={t} />
        : <HeroDefault tweaks={t} />}

      <SectionOArealu />
      <SectionProstory />
      <SectionVyhody />
      <SectionPribeh />
      <SectionSedlcany />
      <SectionKontakt />
      <SiteFooter />

      <StickyPhone />

      <TweaksPanel>
        <TweakSection label="Hero" />
        <TweakSlider
          label="Gradient intenzita"
          value={t.gradientIntensity}
          min={0} max={100} unit="%"
          onChange={(v) => setTweak('gradientIntensity', v)}
        />
        <TweakSlider
          label="Parallax síla"
          value={t.parallaxStrength}
          min={0} max={60} unit=""
          onChange={(v) => setTweak('parallaxStrength', v)}
        />
        <TweakToggle
          label="BG rail dots"
          value={t.showBgRailDots}
          onChange={(v) => setTweak('showBgRailDots', v)}
        />

        <ExperimentalSection>
          <TweakRadio
            label="Hero typografie"
            value={t.heroVariant}
            options={['subtle', 'departures']}
            onChange={(v) => setTweak('heroVariant', v)}
          />
        </ExperimentalSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
