// pages-shared.jsx — Nav, Footer, Modal, ScrollProgress, PageApp
// Requires: app/i18n.js (LOCALES, t), app/primitives.jsx (LangContext, useLang, etc.)
const { useState: useSP, useEffect: useEF, useRef: useRF } = React;

/* ── Inline locale data for sub-page nav (5 links) ────────────────────── */
const SUBNAV = {
  en: [["Product","how-it-works.html"],["Leakage","what-we-catch.html"],["Security","security.html"],["About","about.html"],["Contact","contact.html"]],
  fi: [["Tuote","how-it-works.html"],["Vuodot","what-we-catch.html"],["Tietoturva","security.html"],["Tietoja","about.html"],["Yhteystiedot","contact.html"]],
  sv: [["Produkt","how-it-works.html"],["L\xe4ckage","what-we-catch.html"],["S\xe4kerhet","security.html"],["Om oss","about.html"],["Kontakt","contact.html"]],
};

/* ── PageApp — LangContext provider for sub-pages ──────────────────────── */
function PageApp({ children }) {
  const [lang, setLangRaw] = useSP(() => localStorage.getItem("lang") || "en");
  const setLang = l => { setLangRaw(l); localStorage.setItem("lang", l); document.documentElement.lang = l; };
  useEF(() => { document.documentElement.lang = lang; }, [lang]);
  const langCtx = { lang, setLang, t: key => window.t(lang, key) };
  return React.createElement(LangContext.Provider, { value: langCtx }, children);
}

/* ── SiteLangSwitch ────────────────────────────────────────────────────── */
function SiteLangSwitch({ dark = false }) {
  const { lang, setLang } = useLang();
  const activeCol   = dark ? "var(--on-dark)"       : "var(--ink)";
  const activeBg    = dark ? "rgba(255,255,255,.12)" : "var(--paper-2)";
  const activeBdr   = dark ? "rgba(255,255,255,.25)" : "var(--line)";
  const inactiveCol = dark ? "rgba(255,255,255,.45)" : "var(--muted)";
  return (
    <div className="lang-switch" style={{ display:"flex", gap:4, alignItems:"center" }}>
      {LOCALES.map(({ code, flag, label }) => {
        const active = lang === code;
        return (
          <button key={code} onClick={() => setLang(code)}
            aria-label={`Switch to ${label}`} aria-pressed={active}
            style={{
              display:"flex", alignItems:"center", gap:5,
              padding:"5px 9px", borderRadius:8, cursor:"pointer",
              fontSize:12.5, fontFamily:"var(--mono)", fontWeight:600,
              border: active ? `1px solid ${activeBdr}` : "1px solid transparent",
              background: active ? activeBg : "transparent",
              color: active ? activeCol : inactiveCol,
              transition:"all .2s ease"
            }}
            onMouseEnter={e => { if (!active) e.currentTarget.style.color = activeCol; }}
            onMouseLeave={e => { if (!active) e.currentTarget.style.color = inactiveCol; }}
          >
            <span aria-hidden="true">{flag}</span>{label}
          </button>
        );
      })}
    </div>
  );
}

/* ================================================================ NAV */
function SiteNav({ onAudit, current = "", heroDark = false }) {
  const [scrolled, setScrolled] = useSP(false);
  const [menuOpen, setMenuOpen] = useSP(false);
  const { lang, t } = useLang();
  useEF(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);

  const links = SUBNAV[lang] || SUBNAV.en;
  const onDark   = heroDark && !scrolled;
  const col      = onDark ? "var(--on-dark)"        : "var(--ink)";
  const colMuted = onDark ? "rgba(242,239,231,.65)"  : "var(--ink-2)";

  return (<>
    <header style={{ position:"fixed", top:0, left:0, right:0, zIndex:30, transition:"all .4s ease" }}>
      <div style={{ margin: scrolled ? "10px auto" : "0 auto", maxWidth:"100%", transition:"all .45s cubic-bezier(.2,.8,.2,1)" }}>
        <div className="wrap" style={{
          display:"flex", alignItems:"center", justifyContent:"space-between", gap:24,
          maxWidth: scrolled ? "var(--maxw)" : "100%",
          height: scrolled ? 62 : 78,
          background: scrolled ? "rgba(247,245,239,.78)" : "transparent",
          backdropFilter: scrolled ? "blur(16px) saturate(1.3)" : "none",
          borderRadius: scrolled ? 100 : 0,
          border: scrolled ? "1px solid var(--line)" : "1px solid transparent",
          boxShadow: scrolled ? "0 10px 40px -24px rgba(20,20,22,.5)" : "none",
          transition:"all .45s cubic-bezier(.2,.8,.2,1)", marginInline:"auto"
        }}>
          <a href="index.html"><Logo on={onDark ? "dark" : "light"} size={scrolled ? 28 : 34} /></a>
          <nav style={{ display:"flex", gap:30, alignItems:"center" }} className="nav-links">
            {links.map(([label, href]) => {
              const active = current === href || current === label;
              return (
                <a key={href} href={href} style={{
                  fontSize:14.5, fontWeight:500,
                  color: active ? col : colMuted,
                  letterSpacing:"-.01em", transition:"color .2s",
                  borderBottom: active ? `1.5px solid ${col}` : "1.5px solid transparent",
                  paddingBottom: 3
                }}
                  onMouseEnter={e => e.currentTarget.style.color = col}
                  onMouseLeave={e => e.currentTarget.style.color = active ? col : colMuted}
                >{label}</a>
              );
            })}
          </nav>
          <div style={{ display:"flex", gap:12, alignItems:"center", flexShrink:0 }}>
            <SiteLangSwitch dark={onDark} />
            <a href="#" className="signin" style={{ fontSize:14.5, fontWeight:600, color:col, whiteSpace:"nowrap", transition:"color .45s" }}>{t("nav.signIn")}</a>
            <NavBurger open={false} onClick={() => setMenuOpen(true)} color={col}
              border={onDark ? "var(--line-dark)" : "var(--line)"} />
            <Btn variant="primary" arrow={false} onClick={onAudit}>{t("nav.cta")}</Btn>
          </div>
        </div>
      </div>
    </header>
    <MobileMenu open={menuOpen} onClose={() => setMenuOpen(false)} links={links}
      ctaLabel={t("nav.cta")} onAudit={onAudit} signinLabel={t("nav.signIn")} langSwitch={<SiteLangSwitch />} />
  </>);
}

/* ================================================================ FOOTER */
function SiteFooter() {
  const { t } = useLang();
  const cols = [
    [t("footer.col1"), [
      [t("footer.l.howItWorks"),   "how-it-works.html"],
      [t("footer.l.leakage"),      "what-we-catch.html"],
      [t("footer.l.integrations"), "integrations.html"],
      [t("footer.l.pricing"),      "index.html#pricing"],
      [t("footer.l.security"),     "security.html"],
    ]],
    [t("footer.col2"), [
      [t("footer.l.about"),        "about.html"],
      [t("footer.l.careers"),      "careers.html"],
      [t("footer.l.contact"),      "contact.html"],
      [t("footer.l.finlandFirst"), "finland-first.html"],
    ]],
    [t("footer.col3"), [
      [t("footer.l.auditOverview"),"audit-overview.html"],
      [t("footer.l.faq"),          "index.html#faq"],
      [t("footer.l.casePackets"),  "case-packets.html"],
      [t("footer.l.privacy"),      "privacy.html"],
      [t("footer.l.terms"),        "terms.html"],
    ]],
  ];

  return (
    <footer style={{ background:"var(--dark)", color:"var(--on-dark)", borderTop:"1px solid var(--line-dark)" }}>
      <div className="wrap" style={{ paddingTop:56, paddingBottom:40 }}>
        <div className="foot-grid" style={{ display:"grid", gridTemplateColumns:"1.4fr repeat(3,1fr)", gap:"clamp(24px,4vw,56px)" }}>
          <div>
            <Logo on="dark" size={30} />
            <p style={{ marginTop:18, color:"var(--on-dark-muted)", fontSize:14.5, maxWidth:"30ch", lineHeight:1.55 }}>
              {t("footer.tagline")}
            </p>
          </div>
          {cols.map(([heading, items]) => (
            <div key={heading}>
              <Mono style={{ fontSize:11, color:"var(--on-dark-muted)", letterSpacing:".12em" }}>{heading.toUpperCase()}</Mono>
              <ul style={{ listStyle:"none", margin:"16px 0 0", padding:0, display:"grid", gap:11 }}>
                {items.map(([label, href]) => (
                  <li key={label}>
                    <a href={href} style={{ fontSize:14.5, color:"var(--on-dark)", opacity:.82, transition:"opacity .2s" }}
                      onMouseEnter={e => e.currentTarget.style.opacity = 1}
                      onMouseLeave={e => e.currentTarget.style.opacity = .82}
                    >{label}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <hr style={{ height:1, background:"var(--line-dark)", border:0, margin:"40px 0 22px" }} />
        <div style={{ display:"flex", justifyContent:"space-between", gap:16, flexWrap:"wrap" }}>
          <Mono style={{ fontSize:12, color:"var(--on-dark-muted)" }}>{t("footer.copyright")}</Mono>
          <Mono style={{ fontSize:12, color:"var(--on-dark-muted)" }}>{t("footer.motto")}</Mono>
        </div>
      </div>
    </footer>
  );
}

/* ================================================================ AUDIT MODAL */
function AuditModal({ open, onClose }) {
  const [sent, setSent] = useSP(false);
  const { lang, t } = useLang();
  useEF(() => {
    if (open) { setSent(false); document.body.style.overflow = "hidden"; }
    else document.body.style.overflow = "";
  }, [open]);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position:"fixed", inset:0, zIndex:60, display:"grid", placeItems:"center",
      padding:20, background:"rgba(14,15,18,.55)", backdropFilter:"blur(6px)", animation:"fade .3s ease"
    }}>
      <div onClick={e => e.stopPropagation()} className="card" style={{
        maxWidth:520, width:"100%", padding:"clamp(26px,4vw,40px)",
        boxShadow:"0 60px 120px -50px rgba(0,0,0,.6)"
      }}>
        {!sent ? <>
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start" }}>
            <div>
              <Mono style={{ fontSize:11, color:"var(--drift)", letterSpacing:".1em" }}>{t("modal.kicker")}</Mono>
              <h3 style={{ fontSize:28, marginTop:10, letterSpacing:"-.02em" }}>{t("modal.title")}</h3>
            </div>
            <button onClick={onClose} aria-label="Close" style={{
              background:"none", border:"1px solid var(--line)", borderRadius:8,
              width:34, height:34, cursor:"pointer", fontSize:18, color:"var(--ink-2)"
            }}>×</button>
          </div>
          <p style={{ marginTop:14, color:"var(--ink-2)", fontSize:15.5, lineHeight:1.55 }}>{t("modal.intro")}</p>
          <form onSubmit={e => { e.preventDefault(); setSent(true); }} style={{ marginTop:22, display:"grid", gap:13 }}>
            <MField label={t("modal.email")} type="email" placeholder="cfo@company.fi" required />
            <MField label={t("modal.company")} placeholder="Company Oy" required />
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:13 }}>
              <MField label={t("modal.role")} placeholder="CFO / Controller" />
              <MField label={t("modal.suppliers")} placeholder="~120" />
            </div>
            <button type="submit" className="btn btn-primary" style={{ marginTop:8, justifyContent:"center", width:"100%" }}>
              {t("modal.submit")}<Arrow />
            </button>
            <Mono style={{ fontSize:11, color:"var(--muted)", textAlign:"center" }}>{t("modal.disclaimer")}</Mono>
          </form>
        </> : (
          <div style={{ textAlign:"center", padding:"14px 0" }}>
            <div style={{ width:64, height:64, borderRadius:64, margin:"0 auto", display:"grid", placeItems:"center", background:"var(--agreed-soft)" }}>
              <svg width="30" height="30" viewBox="0 0 16 16">
                <path d="M3 8.5L6.2 11.5L13 4.5" stroke="var(--agreed)" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <h3 style={{ fontSize:26, marginTop:20, letterSpacing:"-.02em" }}>{t("modal.doneHeading")}</h3>
            <p style={{ marginTop:12, color:"var(--ink-2)", fontSize:15.5, maxWidth:"36ch", margin:"12px auto 0" }}>{t("modal.doneBody")}</p>
            <button onClick={onClose} className="btn btn-ghost" style={{ marginTop:24 }}>{t("modal.close")}</button>
          </div>
        )}
      </div>
    </div>
  );
}
function MField({ label, ...rest }) {
  return (
    <label style={{ display:"grid", gap:6 }}>
      <Mono style={{ fontSize:11, color:"var(--muted)", letterSpacing:".06em" }}>{label.toUpperCase()}</Mono>
      <input {...rest} style={{
        font:"inherit", fontSize:15, padding:"12px 14px", borderRadius:10,
        border:"1px solid var(--line)", background:"var(--paper)", color:"var(--ink)", width:"100%"
      }} />
    </label>
  );
}

/* ================================================================ SCROLL PROGRESS */
function ScrollProgress() {
  const ref = useRF(null);
  useEF(() => {
    const on = () => {
      const h = document.documentElement;
      const p = h.scrollTop / (h.scrollHeight - h.clientHeight || 1);
      if (ref.current) ref.current.style.transform = `scaleX(${p})`;
    };
    on(); window.addEventListener("scroll", on, { passive:true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  return (
    <div style={{ position:"fixed", top:0, left:0, right:0, height:2, zIndex:40, pointerEvents:"none" }}>
      <div ref={ref} style={{ height:"100%", background:"var(--drift)", transformOrigin:"0 50%", transform:"scaleX(0)" }} />
    </div>
  );
}

/* ================================================================ SHARED CTA */
function PageCTA({ onAudit, lines = ["Are you still","being billed what","you agreed?"], sub }) {
  const { t } = useLang();
  const subText = sub || t("cta.sub");
  return (
    <section className="dark on-dark" style={{
      background:"var(--dark)", color:"var(--on-dark)",
      position:"relative", overflow:"hidden",
      paddingTop:"clamp(90px,12vw,150px)", paddingBottom:"clamp(70px,9vw,120px)"
    }}>
      <div aria-hidden="true" style={{ position:"absolute", inset:0,
        background:"radial-gradient(70% 70% at 50% 120%, rgba(242,239,231,.08), transparent 60%)" }} />
      <div className="wrap" style={{ position:"relative", textAlign:"center" }}>
        <Reveal style={{ display:"flex", justifyContent:"center" }}>
          <img src="assets/sopisafe-mark.svg" alt="" style={{ filter:"invert(1)", opacity:.9, width:52, height:80 }} />
        </Reveal>
        <h2 className="d-xl" style={{ marginTop:28, color:"var(--on-dark)" }}>
          <ClipLines lines={lines} step={95} />
        </h2>
        <Reveal delay={360} style={{ marginTop:26, color:"var(--on-dark-muted)", fontSize:"clamp(17px,1.4vw,20px)", maxWidth:"48ch", margin:"26px auto 0" }}>
          {subText}
        </Reveal>
        <Reveal delay={480} style={{ marginTop:36, display:"flex", gap:14, justifyContent:"center", flexWrap:"wrap" }}>
          <Btn variant="primary" onClick={onAudit}>{t("cta.ctaPrimary")}</Btn>
          <Btn variant="ghost" href="how-it-works.html">{t("cta.ctaSecondary")}</Btn>
        </Reveal>
      </div>
    </section>
  );
}

/* ================================================================ MOBILE CSS
   (nav breakpoints + keyframes live in sopisafe.css) */

/* Export all */
window.PageApp        = PageApp;
window.SiteNav        = SiteNav;
window.SiteFooter     = SiteFooter;
window.SiteLangSwitch = SiteLangSwitch;
window.AuditModal     = AuditModal;
window.ScrollProgress = ScrollProgress;
window.PageCTA        = PageCTA;
