// ============================================================================
// vk-app.jsx — shell: boot, header, fullscreen menu (lang + theme), router.
// ============================================================================
const { VK: KS, t: TS, Wordmark: WM, Angular: AS, LANGS: LANGS_, RTL_LANGS: RTL_, applyTheme: AT } = window;
const { uS: s, uE: e } = window;

function Header({ lang, nav, openMenu, menuOpen }) {
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 60, height: 64, display: "flex", alignItems: "center",
      justifyContent: "space-between", padding: "0 clamp(16px,4vw,40px)", background: KS.glass,
      backdropFilter: "blur(14px)", borderBottom: `1px solid ${KS.line}` }}>
      <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
        <button onClick={openMenu} aria-label="menu" style={{ width: 40, height: 40, display: "flex", flexDirection: "column",
          justifyContent: "center", gap: 5, background: "none", border: "none", cursor: "pointer", padding: 0 }}>
          {menuOpen
            ? <span style={{ position: "relative", width: 22, height: 16, alignSelf: "center" }}>
                <span style={{ position: "absolute", top: 7, left: 0, width: 22, height: 2, background: KS.ink, transform: "rotate(45deg)" }} />
                <span style={{ position: "absolute", top: 7, left: 0, width: 22, height: 2, background: KS.ink, transform: "rotate(-45deg)" }} />
              </span>
            : <>
                <span style={{ width: 22, height: 2, background: KS.ink, alignSelf: "center" }} />
                <span style={{ width: 22, height: 2, background: KS.coral, alignSelf: "center" }} />
                <span style={{ width: 22, height: 2, background: KS.ink, alignSelf: "center" }} />
              </>}
        </button>
        <WM size={24} onClick={() => nav("home")} />
      </div>

    </header>
  );
}

function ThemeToggle({ theme, setTheme }) {
  const dark = theme === "dark";
  return (
    <button onClick={() => setTheme(dark ? "light" : "dark")} style={{ display: "inline-flex", alignItems: "center", gap: 9,
      cursor: "pointer", background: "transparent", border: `1px solid ${KS.line}`, padding: "8px 13px",
      fontFamily: KS.MONO, fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: KS.sub }}>
      {dark
        ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 12.8A8 8 0 1 1 11.2 3a6.5 6.5 0 0 0 9.8 9.8z" stroke={KS.coral} strokeWidth="1.7" strokeLinejoin="round" /></svg>
        : <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4.2" stroke={KS.coral} strokeWidth="1.7" /><path d="M12 2v2.5M12 19.5V22M2 12h2.5M19.5 12H22M4.6 4.6l1.8 1.8M17.6 17.6l1.8 1.8M19.4 4.6l-1.8 1.8M6.4 17.6l-1.8 1.8" stroke={KS.coral} strokeWidth="1.7" strokeLinecap="round" /></svg>}
      {dark ? "Dark" : "Light"}
    </button>
  );
}

function Menu({ open, onClose, nav, page, lang, setLang, theme, setTheme, rtl }) {
  const items = [
    { k: "home", code: "00", l: TS(lang, "nav_home") },
    { k: "exc", code: "01", l: TS(lang, "nav_exc") },
    { k: "finder", code: "02", l: TS(lang, "nav_finder") },
    { k: "rental", code: "03", l: TS(lang, "nav_rental") },
    { k: "contacts", code: "04", l: TS(lang, "nav_contact") },
  ];
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 55, pointerEvents: open ? "auto" : "none" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: KS.scrim, opacity: open ? 1 : 0, transition: "opacity .3s" }} />
      <nav style={{ position: "absolute", top: 0, bottom: 0, insetInlineStart: 0, width: "min(460px, 92vw)", background: KS.void,
        borderInlineEnd: `1px solid ${KS.line}`, transform: open ? "translateX(0)" : `translateX(${rtl ? "100%" : "-100%"})`,
        transition: "transform .42s cubic-bezier(.4,0,.1,1)", display: "flex", flexDirection: "column",
        padding: "84px clamp(28px,5vw,52px) 32px", overflowY: "auto" }}>
        <div style={{ position: "absolute", top: 24, insetInlineStart: "clamp(28px,5vw,52px)" }}>
          <span style={{ fontFamily: KS.MONO, fontSize: 11, letterSpacing: "0.2em", color: KS.faint, textTransform: "uppercase" }}>{TS(lang, "menu")} · DREAM TEAM</span>
        </div>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", gap: 4 }}>
          {items.map((it) => {
            const on = page === it.k;
            return (
              <button key={it.k} onClick={() => { nav(it.k); onClose(); }} style={{ display: "flex", alignItems: "baseline", gap: 16,
                background: "none", border: "none", cursor: "pointer", padding: "12px 0", textAlign: "start" }}>
                <span style={{ fontFamily: KS.MONO, fontSize: 12, color: on ? KS.coral : KS.faint, letterSpacing: "0.1em" }}>{it.code}</span>
                <span style={{ fontFamily: KS.HEAD, fontWeight: 800, fontSize: "clamp(30px,5vw,44px)", letterSpacing: "-0.02em",
                  color: on ? KS.coral : KS.ink, transition: "color .2s" }}
                  onMouseEnter={(ev) => { if (!on) ev.currentTarget.style.color = KS.coral; }}
                  onMouseLeave={(ev) => { if (!on) ev.currentTarget.style.color = KS.ink; }}>{it.l}</span>
                {on && <span style={{ width: 8, height: 8, background: KS.coral, alignSelf: "center" }} />}
              </button>
            );
          })}
        </div>
        <div style={{ borderTop: `1px solid ${KS.line}`, paddingTop: 22, display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4, alignItems: "center" }}>
            {LANGS_.map(([lg, label], i) => (
              <button key={lg} onClick={() => setLang(lg)} style={{ background: "none", border: "none", cursor: "pointer", padding: "3px 7px",
                fontFamily: KS.MONO, fontSize: 13, color: lang === lg ? KS.coral : KS.faint,
                borderBottom: lang === lg ? `2px solid ${KS.coral}` : "2px solid transparent" }}>{label}</button>
            ))}
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <ThemeToggle theme={theme} setTheme={setTheme} />
            <span style={{ fontFamily: KS.MONO, fontSize: 10.5, color: KS.faint, letterSpacing: "0.1em" }}>BLACK SEA · BG</span>
          </div>
        </div>
      </nav>
    </div>
  );
}

function Footer({ lang, nav }) {
  return (
    <footer style={{ borderTop: `1px solid ${KS.line}`, padding: "44px clamp(22px,5vw,60px) 36px", background: KS.void }}>
      <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 28, marginBottom: 32 }}>
        <div style={{ maxWidth: 320 }}>
          <WM size={26} onClick={() => nav("home")} />
          <p style={{ fontFamily: KS.BODY, fontSize: 13.5, lineHeight: 1.6, color: KS.sub, margin: "16px 0 0" }}>{TS(lang, "foot_about")}</p>
        </div>
        <div style={{ display: "flex", gap: 48, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontFamily: KS.MONO, fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: KS.faint, marginBottom: 14 }}>{TS(lang, "sec_sections")}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {[["exc", TS(lang, "nav_exc")], ["finder", TS(lang, "nav_finder")], ["rental", TS(lang, "nav_rental")], ["contacts", TS(lang, "nav_contact")]].map(([k, l]) => (
                <button key={k} onClick={() => nav(k)} style={{ background: "none", border: "none", cursor: "pointer", textAlign: "start",
                  fontFamily: KS.BODY, fontSize: 14, color: KS.sub, padding: 0 }} onMouseEnter={(e2) => e2.currentTarget.style.color = KS.ink} onMouseLeave={(e2) => e2.currentTarget.style.color = KS.sub}>{l}</button>
              ))}
            </div>
          </div>
          <div>
            <div style={{ fontFamily: KS.MONO, fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: KS.faint, marginBottom: 14 }}>{TS(lang, "sec_contact")}</div>
            <div style={{ fontFamily: KS.MONO, fontSize: 13, color: KS.ink, lineHeight: 1.9 }}>+359 88 100 0001<br />Sunny Beach, BG</div>
          </div>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 10, borderTop: `1px solid ${KS.line}`, paddingTop: 20,
        fontFamily: KS.MONO, fontSize: 10.5, letterSpacing: "0.1em", color: KS.faint }}>
        <span>DREAM TEAM © 2026 · BLACK SEA EXCURSIONS</span>
        <span style={{ display: "inline-flex", gap: 16, flexWrap: "wrap" }}>
          <a href="privacy.html" style={{ color: KS.sub, textDecoration: "none" }}>Privacy</a>
          <a href="privacy.html#terms" style={{ color: KS.sub, textDecoration: "none" }}>Terms</a>
        </span>
      </div>
    </footer>
  );
}

function App() {
  const [page, setPage] = s(() => (location.hash.replace("#", "") || "home"));
  const [lang, setLangRaw] = s(() => localStorage.getItem("dt_lang") || "en");
  const [theme, setThemeRaw] = s(() => localStorage.getItem("dt_theme") || "light");
  const [menuOpen, setMenuOpen] = s(false);
  const [booking, setBooking] = s(null);
  e(() => { window.dtOpenBooking = (p) => setBooking(p); return () => { window.dtOpenBooking = null; }; }, []);
  const [booted, setBooted] = s(false);
  const [count, setCount] = s(0);

  // apply theme synchronously before first paint
  if (window.__dtTheme !== theme) { AT(theme); window.__dtTheme = theme; }
  const setTheme = (m) => { AT(m); window.__dtTheme = m; localStorage.setItem("dt_theme", m); setThemeRaw(m); };
  const setLang = (l) => { localStorage.setItem("dt_lang", l); setLangRaw(l); };

  const rtl = RTL_.includes(lang);
  e(() => { document.documentElement.dir = rtl ? "rtl" : "ltr"; document.documentElement.lang = lang; }, [rtl, lang]);
  e(() => { document.body.style.background = KS.void; document.documentElement.style.colorScheme = theme; }, [theme]);

  e(() => {
    let n = 0;
    const iv = setInterval(() => { n += Math.floor(8 + Math.random() * 16); if (n >= 100) { n = 100; clearInterval(iv); setTimeout(() => setBooted(true), 240); } setCount(n); }, 90);
    return () => clearInterval(iv);
  }, []);

  const nav = (p) => { setPage(p); location.hash = p; window.scrollTo({ top: 0, behavior: "auto" }); };
  e(() => {
    const onHash = () => setPage(location.hash.replace("#", "") || "home");
    window.addEventListener("hashchange", onHash); return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const Pages = {
    home: window.PageHome, exc: window.PageExcursions, finder: window.PageFinder,
    rental: window.PageRental, contacts: window.PageContacts,
  };
  const Cur = Pages[page] || window.PageHome;

  return (
    <div dir={rtl ? "rtl" : "ltr"} style={{ background: KS.void, minHeight: "100vh", color: KS.ink }}>
      {!booted && (
      <div style={{ position: "fixed", inset: 0, zIndex: 200, background: KS.void, display: "flex", flexDirection: "column",
        alignItems: "center", justifyContent: "center", gap: 24 }}>
        <WM size={40} />
        <div style={{ width: "min(280px, 70vw)", height: 2, background: KS.line, position: "relative" }}>
          <div style={{ position: "absolute", insetInlineStart: 0, top: 0, bottom: 0, width: `${count}%`, background: KS.coral, transition: "width .1s" }} />
        </div>
        <div style={{ fontFamily: KS.MONO, fontSize: 12, letterSpacing: "0.2em", color: KS.sub }}>{String(count).padStart(3, "0")} / 100</div>
      </div>
      )}

      <Header lang={lang} nav={nav} openMenu={() => setMenuOpen((o) => !o)} menuOpen={menuOpen} />
      <Menu open={menuOpen} onClose={() => setMenuOpen(false)} nav={nav} page={page} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} rtl={rtl} />
      {booking && window.BookingModal && <window.BookingModal key={booking.type + "-" + booking.id + "-" + theme} booking={booking} lang={lang} onClose={() => setBooking(null)} />}
      <main key={page + lang + theme} className="vk-page">
        <Cur lang={lang} nav={nav} />
      </main>
      <Footer lang={lang} nav={nav} />
    </div>
  );
}

Object.assign(window, { VKApp: App });
