
const { useState, useEffect, useRef } = React;

// ── Language / Theme selector controls ───────────────────────────────────────
const LangDropdown = ({ lang, setLang }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);
  const langs = Object.values(window.LANGS || {});
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'flex', alignItems: 'center', gap: 5,
        background: T.surfaceRaised, border: `1px solid ${T.border}`,
        borderRadius: 5, padding: '5px 10px', cursor: 'pointer',
        fontFamily: T.mono, fontSize: 11.5, fontWeight: 600, color: T.text,
        letterSpacing: '0.04em', transition: 'border-color 0.14s',
      }}>
        {lang}
        <span style={{ color: T.muted, fontSize: 9 }}>▾</span>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: '100%', right: 0, marginTop: 6,
          background: T.surface, border: `1px solid ${T.border}`,
          borderRadius: 8, overflow: 'hidden', minWidth: 140, zIndex: 200,
          boxShadow: `0 8px 24px oklch(0% 0 0 / 0.3)`,
        }}>
          {langs.map(l => (
            <button key={l.label} onClick={() => { setLang(l.label); setOpen(false); }} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 14px', background: lang === l.label ? T.accentSubtle : 'transparent',
              border: 'none', cursor: 'pointer', textAlign: 'left',
              transition: 'background 0.1s',
            }}
              onMouseEnter={e => { if (lang !== l.label) e.currentTarget.style.background = T.surfaceRaised; }}
              onMouseLeave={e => { if (lang !== l.label) e.currentTarget.style.background = 'transparent'; }}
            >
              <span style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 700, color: lang === l.label ? T.accent : T.muted, minWidth: 22 }}>
                {l.label}
              </span>
              <span style={{ fontFamily: T.sans, fontSize: 13, color: T.text }}>{l.name}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const ThemeToggle = ({ isDark, toggle }) => {
  const [hov, setHov] = useState(false);
  return (
    <button
      onClick={toggle}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      title={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        width: 32, height: 32, borderRadius: 6,
        background: hov ? T.surfaceRaised : 'transparent',
        border: `1px solid ${hov ? T.border : 'transparent'}`,
        cursor: 'pointer', fontSize: 15, transition: 'all 0.14s',
        color: T.muted,
      }}
    >
      {isDark ? '☀' : '☾'}
    </button>
  );
};

// ── Nav ────────────────────────────────────────────────────────────────────────
const Nav = ({ page, navigate, lang, setLang, isDark, toggleTheme }) => {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const h = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', h);
    return () => window.removeEventListener('scroll', h);
  }, []);
  const links = [
    { label: S.nav_product,  page: 'home' },
    { label: S.nav_pricing,  page: 'pricing' },
    { label: S.nav_docs,     page: 'faq' },
  ];
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      background: scrolled ? `${T.bg}f0` : T.bg,
      backdropFilter: scrolled ? 'blur(14px)' : 'none',
      borderBottom: `1px solid ${T.border}`,
      transition: 'all 0.2s ease',
    }}>
      <div className="ark-nav-inner" style={{ maxWidth: 1100, margin: '0 auto', padding: '0 40px', display: 'flex', alignItems: 'center', height: 60, gap: 4 }}>
        <button onClick={() => navigate('home')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '0 12px 0 0', marginRight: 4 }}>
          <span style={{ fontFamily: T.sans, fontSize: 15, fontWeight: 700, color: T.text, letterSpacing: '-0.02em' }}>
            DeveloperArk
          </span>
        </button>
        <div className="ark-nav-links" style={{ display: 'flex', gap: 0, flex: 1 }}>
          {links.map(link => (
            <button key={link.label} onClick={() => navigate(link.page)} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              fontFamily: T.sans, fontSize: 13.5, fontWeight: 400,
              color: page === link.page ? T.text : T.muted,
              padding: '6px 12px', borderRadius: 5, transition: 'color 0.14s',
              borderBottom: page === link.page ? `2px solid ${T.accent}` : '2px solid transparent',
            }}
              onMouseEnter={e => e.currentTarget.style.color = T.text}
              onMouseLeave={e => e.currentTarget.style.color = page === link.page ? T.text : T.muted}
            >
              {link.label}
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <ThemeToggle isDark={isDark} toggle={toggleTheme} />
          <LangDropdown lang={lang} setLang={setLang} />
          <Btn size="sm" onClick={() => navigate('order')} style={{ background: T.text, color: T.bg, borderRadius: 6 }}>
            {S.nav_get_started}
          </Btn>
        </div>
      </div>
    </nav>
  );
};

// ── Footer ─────────────────────────────────────────────────────────────────────
const Footer = ({ navigate }) => (
  <footer style={{ background: T.bg, borderTop: `1px solid ${T.border}` }}>
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: '48px 40px 32px' }}>
      <div className="ark-footer-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 40, marginBottom: 40 }}>
        <div>
          <div style={{ fontFamily: T.sans, fontSize: 15, fontWeight: 700, color: T.text, marginBottom: 8 }}>DeveloperArk</div>
          <p style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, lineHeight: 1.65, margin: 0 }}>
            {S.footer_tagline}
          </p>
        </div>
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.dim, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 14 }}>{S.footer_resources}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[[S.footer_link_doc,'faq'],[S.footer_link_pricing,'pricing'],[S.footer_link_api,'faq'],[S.footer_link_blog,'home']].map(([l, p]) => (
              <button key={l} onClick={() => navigate(p)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: T.sans, fontSize: 13, color: T.muted, padding: 0, textAlign: 'left' }}>{l}</button>
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.dim, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 14 }}>{S.footer_legal}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[[S.footer_link_privacy,'privacy'],[S.footer_link_terms,'terms'],[S.footer_link_security,'faq'],[S.footer_link_status,'home']].map(([l, p]) => (
              <button key={l} onClick={() => navigate(p)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: T.sans, fontSize: 13, color: T.muted, padding: 0, textAlign: 'left' }}>{l}</button>
            ))}
          </div>
        </div>
      </div>
      <div style={{ borderTop: `1px solid ${T.border}`, paddingTop: 16, marginBottom: 12 }}>
        <p style={{ fontFamily: T.sans, fontSize: 11.5, color: T.dim, lineHeight: 1.65, margin: 0, maxWidth: 800 }}>
          Launch Ark is a bounded continuity documentation package. It is not legal advice, compliance certification, security certification, DevOps implementation, uptime guarantee, payment approval, or delivery authorization. No secrets required. Unknowns stay visible.
        </p>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontFamily: T.sans, fontSize: 12, color: T.dim }}>{S.footer_copy}</span>
        <span style={{ fontFamily: T.mono, fontSize: 11, color: T.dim, letterSpacing: '0.04em' }}>Concierge pilot · {S.footer_contact}</span>
      </div>
    </div>
  </footer>
);

// ── App ────────────────────────────────────────────────────────────────────────
const App = () => {
  const getSaved = (key, def) => { try { return localStorage.getItem(key) || def; } catch { return def; } };
  const LANG_CODE_MAP = { en: 'EN', de: 'DE', fr: 'FR', it: 'IT', es: 'ES', pt: 'PT', ua: 'UA', uk: 'UA' };
  const toSupportedLang = (value) => {
    if (!value) return null;
    const normalized = String(value).trim().toLowerCase();
    return LANG_CODE_MAP[normalized] || null;
  };
  const getUrlLang = () => {
    try {
      const params = new URLSearchParams(window.location.search);
      return toSupportedLang(params.get('lang'));
    } catch {
      return null;
    }
  };
  const getBrowserLang = () => {
    try {
      const browserValue = navigator.language || navigator.userLanguage || '';
      return toSupportedLang(browserValue.split('-')[0]);
    } catch {
      return null;
    }
  };
  const getInitialLang = () => getUrlLang() || toSupportedLang(getSaved('ark_lang', 'EN')) || getBrowserLang() || 'EN';

  const [page, setPage]       = useState(getSaved('ark_page', 'home'));
  const [lang, setLangState]  = useState(getInitialLang);
  const [isDark, setIsDark]   = useState(getSaved('ark_theme', 'light') === 'dark');
  const [ver, setVer]         = useState(0); // triggers re-render on theme/lang change

  const navigate = (p) => {
    setPage(p);
    try { localStorage.setItem('ark_page', p); } catch {}
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const applyTheme = (dark) => {
    Object.assign(window.T, dark ? window.DARK_T : window.LIGHT_T);
    window.applyThemeCSSVars();
    try { localStorage.setItem('ark_theme', dark ? 'dark' : 'light'); } catch {}
  };

  const applyLang = (code) => {
    const safeCode = (window.LANGS && window.LANGS[code]) ? code : 'EN';
    if (window.LANGS && window.LANGS[safeCode]) Object.assign(window.S, window.LANGS[safeCode].s);
    if (window.NEW_S && window.NEW_S[safeCode]) Object.assign(window.S, window.NEW_S[safeCode]);
    window.CURRENT_LANG = safeCode;
    if (window.applyLangSEO) window.applyLangSEO(safeCode);
    try { localStorage.setItem('ark_lang', safeCode); } catch {}
    try {
      const url = new URL(window.location.href);
      url.searchParams.set('lang', safeCode.toLowerCase() === 'ua' ? 'ua' : safeCode.toLowerCase());
      window.history.replaceState({}, '', url.toString());
    } catch {}
    return safeCode;
  };

  // Apply saved preferences on mount
  useEffect(() => {
    applyTheme(isDark);
    applyLang(lang);
  }, []);

  useEffect(() => {
    const syncLangFromUrl = () => {
      const nextLang = getUrlLang();
      if (!nextLang || nextLang === window.CURRENT_LANG) return;
      applyLang(nextLang);
      setLangState(nextLang);
      setVer(v => v + 1);
    };
    window.addEventListener('popstate', syncLangFromUrl);
    return () => window.removeEventListener('popstate', syncLangFromUrl);
  }, []);

  const toggleTheme = () => {
    const next = !isDark;
    applyTheme(next);
    setIsDark(next);
    setVer(v => v + 1);
  };

  const setLang = (code) => {
    const safeCode = applyLang(code);
    setLangState(safeCode);
    setVer(v => v + 1);
  };

  const pages = { home: LandingPage, pricing: PricingPage, order: OrderFormPage, faq: FAQTrustPage, privacy: PrivacyPage, terms: TermsPage };
  const Page = pages[page] || LandingPage;

  return (
    <div key={ver} style={{ background: T.bg, minHeight: '100vh', color: T.text, transition: 'background 0.2s, color 0.2s' }}>
      <Nav page={page} navigate={navigate} lang={lang} setLang={setLang} isDark={isDark} toggleTheme={toggleTheme} />
      <div style={{ paddingTop: 60 }}>
        <Page navigate={navigate} lang={lang} />
      </div>
      <Footer navigate={navigate} />
    </div>
  );
};

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