// App.jsx — Ozimiz landing page
// Structure: TopNav → Hero (with product peek card) → Proof strip → Features
// → Dual-persona row → Locales/currencies → Pricing → FAQ → Final CTA → Footer

const APP_ORIGIN = "https://app.ozimiz.net";
const LANG_MAP = { ru: "ru", kk: "kk-Cyrl", en: "en" };
function appUrl(lang, path) {
  const l = LANG_MAP[lang] || "ru";
  return APP_ORIGIN + "/" + l + (path || "");
}
Object.assign(window, { appUrl });

function useI18n() {
  const [lang, setLang] = React.useState(() => {
    try { return localStorage.getItem("ozimiz.lang") || "ru"; } catch(_) { return "ru"; }
  });
  const [dark, setDark] = React.useState(() => {
    try { return localStorage.getItem("ozimiz.theme") === "dark"; } catch(_) { return false; }
  });
  React.useEffect(() => {
    try { localStorage.setItem("ozimiz.lang", lang); } catch(_) {}
    document.documentElement.setAttribute("lang", lang === "kk" ? "kk" : lang);
  }, [lang]);
  React.useEffect(() => {
    try { localStorage.setItem("ozimiz.theme", dark ? "dark" : "light"); } catch(_) {}
    document.documentElement.setAttribute("data-theme", dark ? "dark" : "light");
  }, [dark]);
  const t = window.I18N[lang] || window.I18N.ru;
  return { lang, setLang, dark, setDark, t };
}

// Cross-origin session probe: if the visitor is already signed in at
// app.ozimiz.net, swap the "sign in / start" CTAs for an "open app" link.
function useAppSession() {
  const [user, setUser] = React.useState(null);
  const [ready, setReady] = React.useState(false);
  React.useEffect(() => {
    let cancelled = false;
    fetch(APP_ORIGIN + "/api/auth/get-session", { credentials: "include" })
      .then(r => r.ok ? r.json() : null)
      .then(data => { if (!cancelled) setUser(data && data.user ? data.user : null); })
      .catch(() => undefined)
      .finally(() => { if (!cancelled) setReady(true); });
    return () => { cancelled = true; };
  }, []);
  return { user, ready };
}
Object.assign(window, { useAppSession });

function TopNav({ lang, setLang, dark, setDark, t }) {
  const { user, ready } = useAppSession();
  const [langOpen, setLangOpen] = React.useState(false);
  const langCodes = ["ru", "kk", "en"];
  const linkStyle = {
    font: "500 14px Manrope, sans-serif", color: "var(--fg-muted)",
    padding: "8px 12px", borderRadius: 8, textDecoration: "none",
    transition: "color var(--dur-base) var(--ease-standard), background var(--dur-base) var(--ease-standard)",
  };
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 40,
      background: "color-mix(in srgb, var(--bg) 88%, transparent)",
      backdropFilter: "saturate(1.1) blur(8px)",
      borderBottom: "1px solid var(--border)",
    }}>
      <div style={{
        maxWidth: 1240, margin: "0 auto",
        display: "flex", alignItems: "center", gap: 16,
        padding: "14px 32px",
      }}>
        <a href="#top" style={{ display: "inline-flex", alignItems: "center", gap: 8, textDecoration: "none" }}>
          <img src={dark ? "logo-ozimiz-dark.svg" : "logo-ozimiz.svg"} width="120" height="32" alt="Ozimiz"/>
        </a>
        <nav style={{ display: "flex", alignItems: "center", gap: 2, marginLeft: 20 }}>
          <a href="#features" style={linkStyle} className="oz-navlink">{t.nav.product}</a>
          <a href="#duo" style={linkStyle} className="oz-navlink">{t.nav.forCreators}</a>
          <a href="#pricing" style={linkStyle} className="oz-navlink">{t.nav.pricing}</a>
          <a href="#proof" style={linkStyle} className="oz-navlink">{t.nav.stories}</a>
        </nav>
        <div style={{ flex: 1 }}/>
        <div style={{ position: "relative" }}>
          <button onClick={() => setLangOpen(v => !v)} style={ghostBtn} aria-label="Language">
            <span style={{ fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", fontSize: 12 }}>
              {lang}
            </span>
            <Icon name="chevron" size={14} style={{ transform: "rotate(90deg)" }}/>
          </button>
          {langOpen && (
            <div onMouseLeave={() => setLangOpen(false)} style={{
              position: "absolute", top: "calc(100% + 6px)", right: 0,
              background: "var(--surface-raised)", border: "1px solid var(--border)",
              borderRadius: 10, boxShadow: "var(--shadow-md)",
              padding: 4, minWidth: 160, zIndex: 50,
            }}>
              {langCodes.map(code => (
                <button key={code} onClick={() => { setLang(code); setLangOpen(false); }} style={{
                  display: "flex", width: "100%", alignItems: "center", gap: 10,
                  padding: "10px 12px", border: 0, background: lang === code ? "var(--surface-sunken)" : "transparent",
                  borderRadius: 6, cursor: "pointer", textAlign: "left",
                  font: "500 14px Manrope, sans-serif", color: "var(--fg)",
                }}>
                  <span style={{ fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", fontSize: 11, color: "var(--fg-muted)", width: 22 }}>{code}</span>
                  {window.I18N[code].langLabel}
                  {lang === code && <span style={{ marginLeft: "auto" }}><Icon name="check" size={14} color="var(--brand-primary)"/></span>}
                </button>
              ))}
            </div>
          )}
        </div>
        <button onClick={() => setDark(v => !v)} style={ghostBtn} aria-label="Theme">
          <Icon name={dark ? "sun" : "moon"} size={16}/>
        </button>
        {ready && user ? (
          <a href={appUrl(lang, "/communities")} style={primaryBtn}>{t.nav.openApp}</a>
        ) : (
          <>
            <a href={appUrl(lang, "/signin")} style={{ ...linkStyle, color: "var(--fg)" }}>{t.nav.signIn}</a>
            <a href={appUrl(lang, "/signup")} style={primaryBtn}>{t.nav.start}</a>
          </>
        )}
      </div>
    </header>
  );
}

function Hero({ t, lang }) {
  return (
    <section id="top" style={{
      position: "relative",
      padding: "88px 32px 64px",
      borderBottom: "1px solid var(--divider)",
    }}>
      <div style={{ maxWidth: 1240, margin: "0 auto", display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 56, alignItems: "center" }}>
        <div>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "6px 12px", borderRadius: 999,
            background: "var(--info-bg)", color: "var(--brand-primary-hover)",
            font: "600 12px Manrope, sans-serif", letterSpacing: ".02em",
            marginBottom: 20,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--brand-primary)" }}/>
            {t.hero.eyebrow}
          </div>
          <h1 style={{
            font: "800 clamp(40px, 5vw, 64px)/1.06 Manrope, sans-serif",
            letterSpacing: "-0.025em", color: "var(--fg)",
            margin: "0 0 20px", textWrap: "balance",
          }}>{t.hero.title}</h1>
          <p style={{
            font: "400 19px/1.55 Manrope, sans-serif", color: "var(--fg-muted)",
            margin: "0 0 28px", maxWidth: 560, textWrap: "pretty",
          }}>{t.hero.sub}</p>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 16 }}>
            <a href={appUrl(lang, "/signup")} style={{ ...primaryBtn, padding: "14px 22px", fontSize: 15 }}>{t.hero.primaryCta}</a>
            <a href="#features" style={{ ...secondaryBtn, padding: "14px 22px", fontSize: 15 }}>
              <Icon name="play" size={12} color="var(--fg)"/> {t.hero.secondaryCta}
            </a>
          </div>
          <div style={{
            font: "500 13px Manrope, sans-serif", color: "var(--fg-subtle)",
          }}>{t.hero.foot}</div>
        </div>
        <HeroPeek t={t}/>
      </div>
    </section>
  );
}

// A miniature of the actual product — pulled from the member kit's vocabulary.
function HeroPeek({ t }) {
  return (
    <div style={{ position: "relative", minHeight: 520 }}>
      {/* Backplate */}
      <div style={{
        position: "absolute", inset: "-8px -16px -8px -16px",
        background: "var(--surface)",
        borderRadius: 28,
        boxShadow: "var(--shadow-lg)",
        border: "1px solid var(--border)",
      }}/>
      <div style={{ position: "relative", padding: 18, display: "grid", gap: 12 }}>
        {/* Feed post */}
        <div style={peekCard}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <Avatar name="Айдана Жұмабекова" size={34} tint="#F4D6A8"/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ font: "600 13px Manrope, sans-serif", color: "var(--fg)" }}>Айдана Жұмабекова</div>
              <div style={{ font: "500 11px Manrope, sans-serif", color: "var(--fg-subtle)" }}>Модератор · 2ч</div>
            </div>
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 4,
              padding: "3px 8px", borderRadius: 999,
              background: "var(--info-bg)", color: "var(--brand-primary-hover)",
              font: "600 11px Manrope, sans-serif",
            }}>
              <Icon name="pin" size={10}/> Закреп
            </span>
          </div>
          <div style={{ font: "400 14px/1.55 Manrope, sans-serif", color: "var(--fg)", marginBottom: 10 }}>
            Добавила модуль «Портфель для новичка». Вопросы — в комментариях, отвечу до вечера.
          </div>
          <div style={{ display: "flex", gap: 14, paddingTop: 8, borderTop: "1px solid var(--divider)", color: "var(--fg-muted)", font: "600 12px Manrope, sans-serif" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="heart" size={13}/> 34</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="comment" size={13}/> 12</span>
          </div>
        </div>

        {/* Classroom module */}
        <div style={{ ...peekCard, padding: 0, overflow: "hidden" }}>
          <div style={{
            padding: "14px 16px 10px", display: "flex", alignItems: "center", gap: 10,
            borderBottom: "1px solid var(--divider)",
          }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--info-bg)", display: "grid", placeItems: "center", color: "var(--brand-primary)" }}>
              <Icon name="classroom" size={16}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ font: "600 13px Manrope, sans-serif", color: "var(--fg)" }}>Модуль 2 · Портфель для новичка</div>
              <div style={{ font: "500 11px Manrope, sans-serif", color: "var(--fg-subtle)" }}>4 урока · 38 мин</div>
            </div>
            <span className="oz-num" style={{ font: "700 12px Manrope, sans-serif", color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>2 / 4</span>
          </div>
          {[
            { t: "Во что инвестировать первые ₸100 000", m: "7 мин", done: true },
            { t: "ETF на KASE: полный разбор", m: "12 мин", done: true, current: false },
            { t: "Ребалансировка раз в квартал", m: "9 мин", done: false, current: true },
            { t: "Как не сливать на панике", m: "10 мин", done: false, locked: true },
          ].map((row, i) => (
            <div key={i} style={{
              display: "flex", alignItems: "center", gap: 10,
              padding: "10px 16px",
              borderTop: i ? "1px solid var(--divider)" : 0,
              background: row.current ? "color-mix(in srgb, var(--info-bg) 50%, transparent)" : "transparent",
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: 999,
                border: row.done ? 0 : "1.5px solid var(--border-strong)",
                background: row.done ? "var(--success)" : "transparent",
                display: "grid", placeItems: "center",
                color: "var(--success-fg)",
                flexShrink: 0,
              }}>
                {row.done && <Icon name="check" size={11}/>}
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ font: `${row.current ? 600 : 500} 13px Manrope, sans-serif`, color: row.locked ? "var(--fg-subtle)" : "var(--fg)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                  {row.t}
                </div>
              </div>
              <span style={{ font: "500 11px Manrope, sans-serif", color: "var(--fg-subtle)", fontVariantNumeric: "tabular-nums" }}>{row.m}</span>
              {row.locked && <Icon name="lock" size={13} color="var(--fg-subtle)"/>}
            </div>
          ))}
        </div>

        {/* Payment row */}
        <div style={{
          ...peekCard,
          display: "flex", alignItems: "center", gap: 12,
          padding: "14px 16px",
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 8,
            background: "var(--success-bg)", color: "var(--success)",
            display: "grid", placeItems: "center",
          }}>
            <Icon name="check" size={16}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ font: "600 13px Manrope, sans-serif", color: "var(--fg)" }}>Оплата прошла · ioka.kz</div>
            <div style={{ font: "500 11px Manrope, sans-serif", color: "var(--fg-subtle)" }}>Kaspi Gold · ··7821</div>
          </div>
          <div className="oz-num" style={{ font: "700 15px Manrope, sans-serif", color: "var(--fg)", fontVariantNumeric: "tabular-nums" }}>
            24{"\u202F"}900{"\u00A0"}₸
          </div>
        </div>
      </div>
    </div>
  );
}

const peekCard = {
  background: "var(--surface-raised)",
  border: "1px solid var(--border)",
  borderRadius: 14,
  padding: "14px 16px",
  boxShadow: "var(--shadow-sm)",
};

// --- Button tokens --- //
const primaryBtn = {
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
  padding: "10px 16px",
  background: "var(--brand-primary)", color: "var(--brand-primary-fg)",
  border: 0, borderRadius: 10,
  font: "600 14px Manrope, sans-serif",
  textDecoration: "none", cursor: "pointer",
  transition: "background var(--dur-base) var(--ease-standard)",
};
const secondaryBtn = {
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
  padding: "10px 16px",
  background: "var(--surface-raised)", color: "var(--fg)",
  border: "1px solid var(--border)", borderRadius: 10,
  font: "600 14px Manrope, sans-serif",
  textDecoration: "none", cursor: "pointer",
  transition: "background var(--dur-base) var(--ease-standard)",
};
const ghostBtn = {
  display: "inline-flex", alignItems: "center", gap: 6,
  padding: "8px 10px",
  background: "transparent", color: "var(--fg-muted)",
  border: "1px solid var(--border)", borderRadius: 8,
  font: "500 13px Manrope, sans-serif", cursor: "pointer",
  transition: "background var(--dur-base) var(--ease-standard), color var(--dur-base) var(--ease-standard)",
};

Object.assign(window, { useI18n, TopNav, Hero, primaryBtn, secondaryBtn, ghostBtn, peekCard });
