// Shared components: Nav, Footer, Currency, Cart, Logo

const { useState, useEffect, useRef, useMemo, useCallback } = React;

const D = window.FBO_DATA;

// ----- Logo -----
function Logo({ size = 22 }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "baseline", gap: 10, fontFamily: "var(--serif)", letterSpacing: "-0.02em", fontSize: size, lineHeight: 1 }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: size * 0.5, color: "var(--text)", letterSpacing: "0.14em", padding: "5px 8px 4px", border: "1px solid var(--text)", borderRadius: 2, fontWeight: 500, lineHeight: 1 }}>FBO</span>
      <span style={{ fontStyle: "italic" }}>For Best Offer</span>
    </div>
  );
}

// ----- Masthead (editorial strip above nav) -----
function Masthead({ ccy, setCode }) {
  const today = new Date().toLocaleDateString("en-GB", { weekday: "long", day: "2-digit", month: "long", year: "numeric" }).toUpperCase();
  return (
    <div style={{
      background: "var(--text)", color: "var(--bg)",
      borderBottom: "1px solid var(--text)",
      fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase",
    }}>
      <div className="container" style={{ height: 32, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
          <span><span className="live-dot" style={{ marginRight: 10, verticalAlign: 1 }} />LIVE BANK</span>
          <span style={{ opacity: 0.6 }}>VOL. IV · ISSUE 02</span>
        </div>
        <div style={{ opacity: 0.85 }} data-hide="tablet">{today}</div>
        {ccy && setCode && (
          <div style={{ display: "inline-flex", gap: 2, padding: 0 }}>
            {D.currencies.map((c, i) => (
              <button key={c.code}
                onClick={() => setCode(c.code)}
                style={{
                  fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.12em",
                  padding: "3px 9px",
                  borderLeft: i === 0 ? "none" : "1px solid color-mix(in oklab, var(--bg) 25%, transparent)",
                  color: c.code === ccy.code ? "var(--accent)" : "color-mix(in oklab, var(--bg) 65%, transparent)",
                  fontWeight: c.code === ccy.code ? 600 : 400,
                  transition: "color 0.15s",
                }}>
                {c.code}
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ----- Section opener (editorial divider) -----
function SectionOpener({ num, label, title, sub }) {
  return (
    <div style={{ marginBottom: 56 }}>
      <div className="section-label">
        <span className="num">{num}.</span>
        <span className="lbl">{label}</span>
        <span style={{ flex: 1, height: 1, background: "var(--border)" }} />
      </div>
      <h2 className="h-section" style={{ margin: 0, maxWidth: 980 }}>{title}</h2>
      {sub && <p style={{ marginTop: 28, fontSize: 17, color: "var(--text-2)", maxWidth: 600, lineHeight: 1.55 }}>{sub}</p>}
    </div>
  );
}

// ----- Currency context (just a ref-style helper) -----
function useCurrency() {
  const [code, setCode] = useState(() => localStorage.getItem("fbo-ccy") || "GBP");
  useEffect(() => { localStorage.setItem("fbo-ccy", code); }, [code]);
  const ccy = D.currencies.find(c => c.code === code) || D.currencies[0];
  const fmt = (gbp) => {
    const v = gbp * ccy.rate;
    const rounded = v >= 100 ? Math.round(v) : v.toFixed(v < 10 ? 2 : 0);
    return `${ccy.symbol}${rounded}`;
  };
  return { code, setCode, ccy, fmt };
}

// ----- Currency switcher -----
function CurrencySwitch({ ccy, setCode, compact }) {
  return (
    <div style={{ display: "inline-flex", border: "1px solid var(--border)", borderRadius: 999, padding: 3, gap: 0, background: "var(--bg)" }}>
      {D.currencies.map(c => (
        <button key={c.code}
          onClick={() => setCode(c.code)}
          style={{
            fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.06em",
            padding: compact ? "4px 8px" : "5px 11px",
            borderRadius: 999,
            color: c.code === ccy.code ? "var(--accent-fg)" : "var(--text-2)",
            background: c.code === ccy.code ? "var(--accent)" : "transparent",
            fontWeight: c.code === ccy.code ? 600 : 400,
            transition: "all 0.15s",
          }}>
          {c.code}
        </button>
      ))}
    </div>
  );
}

// ----- Cart hook -----
function useCart() {
  const [items, setItems] = useState(() => {
    try { return JSON.parse(localStorage.getItem("fbo-cart") || "[]"); } catch { return []; }
  });
  const [open, setOpen] = useState(false);
  useEffect(() => { localStorage.setItem("fbo-cart", JSON.stringify(items)); }, [items]);

  const add = (company, role, variant) => {
    const key = `${company.t}|${role}|${variant.id}`;
    setItems(prev => {
      const exists = prev.find(x => x.key === key);
      if (exists) return prev.map(x => x.key === key ? { ...x, qty: x.qty + 1 } : x);
      return [...prev, { kind: "bank", key, company: company.n, ticker: company.t, role, variant: variant.name, gbp: variant.gbp, qty: 1 }];
    });
    setOpen(true);
  };
  const addService = (svc) => {
    const key = `svc|${svc.id}`;
    setItems(prev => {
      const exists = prev.find(x => x.key === key);
      if (exists) return prev.map(x => x.key === key ? { ...x, qty: x.qty + 1 } : x);
      return [...prev, { kind: "service", key, company: svc.name, ticker: svc.ticker, role: svc.sub, variant: "1:1 session", gbp: svc.gbp, qty: 1 }];
    });
    setOpen(true);
  };
  const remove = (key) => setItems(items.filter(x => x.key !== key));
  const clear = () => setItems([]);
  const total = items.reduce((s, x) => s + x.gbp * x.qty, 0);
  const count = items.reduce((s, x) => s + x.qty, 0);

  return { items, open, setOpen, add, addService, remove, clear, total, count };
}

// ----- Cart drawer -----
function CartDrawer({ cart, fmt, ccy, setPage }) {
  return (
    <React.Fragment>
      <div onClick={() => cart.setOpen(false)}
        style={{
          position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)", backdropFilter: "blur(4px)",
          zIndex: 90, opacity: cart.open ? 1 : 0, pointerEvents: cart.open ? "auto" : "none",
          transition: "opacity 0.3s",
        }} />
      <aside style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: "min(440px, 100vw)",
        background: "var(--bg-soft)", borderLeft: "1px solid var(--border)", zIndex: 100,
        transform: cart.open ? "translateX(0)" : "translateX(100%)",
        transition: "transform 0.35s cubic-bezier(.22,1,.36,1)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ padding: "22px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div className="serif-italic" style={{ fontSize: 26 }}>Your cart</div>
          <button onClick={() => cart.setOpen(false)} style={{ color: "var(--text-2)", fontSize: 22, lineHeight: 1 }}>×</button>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "12px 24px" }}>
          {cart.items.length === 0 ? (
            <div style={{ textAlign: "center", padding: "60px 0", color: "var(--text-3)" }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>EMPTY</div>
              <div className="serif-italic" style={{ fontSize: 22, color: "var(--text-2)" }}>No modules yet</div>
              <div style={{ fontSize: 13, marginTop: 8 }}>Add a question bank to begin.</div>
            </div>
          ) : cart.items.map(item => (
            <div key={item.key} style={{ padding: "16px 0", borderBottom: "1px solid var(--border)", display: "flex", gap: 12 }}>
              <div className="placeholder-img" style={{ width: 56, height: 56, flexShrink: 0, background: item.kind === "service" ? "linear-gradient(135deg, rgba(212,160,74,0.18), transparent)" : undefined, borderColor: item.kind === "service" ? "var(--accent-dim)" : undefined }}>
                <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: item.kind === "service" ? "var(--accent)" : "var(--text-2)", letterSpacing: "0.06em" }}>{item.ticker}</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{item.company}</div>
                <div style={{ fontSize: 12, color: "var(--text-2)", marginTop: 2 }}>{item.role}</div>
                <div style={{ fontSize: 11, color: "var(--accent)", marginTop: 4, fontFamily: "var(--mono)", letterSpacing: "0.05em" }}>{item.variant}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="mono" style={{ fontSize: 14 }}>{fmt(item.gbp * item.qty)}</div>
                <button onClick={() => cart.remove(item.key)} style={{ fontSize: 11, color: "var(--text-3)", marginTop: 6 }}>Remove</button>
              </div>
            </div>
          ))}
        </div>
        {cart.items.length > 0 && (
          <div style={{ padding: 24, borderTop: "1px solid var(--border)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14 }}>
              <span className="eyebrow">SUBTOTAL · {ccy.code}</span>
              <span className="mono" style={{ fontSize: 18 }}>{fmt(cart.total)}</span>
            </div>
            <button className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }} onClick={() => { cart.setOpen(false); setPage && setPage("checkout"); }}>
              Checkout — instant delivery
            </button>
            <div style={{ fontSize: 11, color: "var(--text-3)", textAlign: "center", marginTop: 10, fontFamily: "var(--mono)", letterSpacing: "0.05em" }}>
              Auto-delivery via secure cloud link · 24/7
            </div>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
}

// ----- Nav -----
function Nav({ page, setPage, cart, fmt, ccy, setCode, account }) {
  const items = [
    { id: "home", label: "Home" },
    { id: "shop", label: "Question Banks" },
    { id: "coaching", label: "Coaching" },
    { id: "pricing", label: "Pricing" },
    { id: "blog", label: "Journal" },
    { id: "about", label: "About" },
  ];
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
    }}>
      <Masthead ccy={ccy} setCode={setCode} />
      <div style={{
        background: "color-mix(in oklab, var(--bg) 88%, transparent)",
        backdropFilter: "blur(16px)",
        borderBottom: "1px solid var(--border)",
      }}>
      <div className="container" style={{ height: 64, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24 }}>
        <button onClick={() => setPage("home")} style={{ display: "flex", alignItems: "center" }}>
          <Logo size={20} />
        </button>
        <nav style={{ display: "flex", gap: 4 }}>
          {items.map(it => (
            <button key={it.id} onClick={() => setPage(it.id)}
              style={{
                padding: "8px 14px",
                fontSize: 13.5,
                color: page === it.id ? "var(--text)" : "var(--text-2)",
                position: "relative",
              }}>
              {it.label}
              {page === it.id && <span style={{ position: "absolute", left: 14, right: 14, bottom: -2, height: 1, background: "var(--accent)" }} />}
            </button>
          ))}
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          {account && account.user ? (
            <button onClick={() => setPage("library")} style={{ padding: "8px 14px", border: "1px solid var(--border-strong)", borderRadius: 999, fontSize: 13, display: "inline-flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--accent)", color: "var(--accent-fg)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontSize: 10, fontWeight: 600 }}>{(account.user.name || account.user.email)[0].toUpperCase()}</span>
              <span data-hide="tablet">Library</span>
            </button>
          ) : (
            <button onClick={() => setPage("login")} style={{ padding: "8px 14px", fontSize: 13, color: "var(--text-2)", whiteSpace: "nowrap" }}>Sign in</button>
          )}
          <button onClick={() => cart.setOpen(true)}
            style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "8px 14px", border: "1px solid var(--border-strong)", borderRadius: 999,
              fontSize: 13,
            }}>
            <span>Cart</span>
            <span style={{
              background: cart.count > 0 ? "var(--accent)" : "var(--surface-2)",
              color: cart.count > 0 ? "var(--accent-fg)" : "var(--text-2)",
              fontFamily: "var(--mono)", fontSize: 11, fontWeight: 600,
              padding: "1px 7px", borderRadius: 999, minWidth: 18, textAlign: "center",
            }}>{cart.count}</span>
          </button>
        </div>
      </div>
      </div>
    </header>
  );
}

// ----- Footer -----
function Footer({ setPage }) {
  return (
    <footer style={{ borderTop: "1px solid var(--border)", marginTop: 80, background: "var(--bg-soft)", position: "relative", overflow: "hidden" }}>
      <div className="container" style={{ paddingTop: 80, paddingBottom: 24 }}>
        {/* Brand block */}
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) auto", gap: 60, alignItems: "end", marginBottom: 64, paddingBottom: 48, borderBottom: "1px solid var(--border)" }}>
          <div style={{ maxWidth: 460 }}>
            <Logo size={24} />
            <p style={{ marginTop: 22, color: "var(--text-2)", fontSize: 15, lineHeight: 1.55 }}>
              The question bank built by candidates who sat the interview last month — not by recruiters guessing what’s typical.
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
            <div className="eyebrow">EDITION INDEX</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--text-2)", letterSpacing: "0.1em" }}>VOL. IV · ISSUE 02</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--text-3)", letterSpacing: "0.08em" }}>83 FIRMS · 240+ ROLES · 720+ MODULES</div>
          </div>
        </div>

        {/* Link columns */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0, 1fr))", gap: 32, marginBottom: 80 }} data-mobile="split2">
          <FooterCol title="Catalogue" items={[
            ["Investment Banking", () => setPage("shop")],
            ["Consulting", () => setPage("shop")],
            ["Big Four", () => setPage("shop")],
            ["Quant & Trading", () => setPage("shop")],
            ["Asset Management", () => setPage("shop")],
          ]} />
          <FooterCol title="Service" items={[
            ["Question Banks", () => setPage("shop")],
            ["1:1 Coaching", () => setPage("coaching")],
            ["Mock Interviews", () => setPage("coaching")],
            ["Pricing", () => setPage("pricing")],
          ]} />
          <FooterCol title="Resources" items={[
            ["Journal", () => setPage("blog")],
            ["About FBO", () => setPage("about")],
            ["My Library", () => setPage("library")],
            ["Order History", () => setPage("orders")],
            ["Account Settings", () => setPage("settings")],
          ]} />
          <FooterCol title="Legal" items={[
            ["Terms of Service", () => setPage("terms")],
            ["Privacy Policy", () => setPage("privacy")],
            ["Refund Policy", () => setPage("refund")],
            ["Admin (internal)", () => setPage("admin")],
            ["Email templates", () => setPage("emails")],
          ]} />
        </div>
        <div className="serif-italic" style={{ fontSize: "clamp(80px, 14vw, 200px)", lineHeight: 0.9, color: "color-mix(in oklab, var(--text) 12%, transparent)", letterSpacing: "-0.04em", marginBottom: 40, userSelect: "none" }}>
          For Best Offer.
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", color: "var(--text-3)", fontSize: 12, fontFamily: "var(--mono)", letterSpacing: "0.05em" }}>
          <span>© 2026 FOR BEST OFFER LTD · LONDON · HONG KONG</span>
          <span>VERSION 4.2 · UPDATED MAY 2026</span>
        </div>
      </div>
    </footer>
  );
}
function FooterCol({ title, items }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 18 }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map(([label, fn], i) => (
          <li key={i}>
            <button onClick={fn} style={{ color: "var(--text-2)", fontSize: 13.5, textAlign: "left" }}
              onMouseOver={e => e.currentTarget.style.color = "var(--text)"}
              onMouseOut={e => e.currentTarget.style.color = "var(--text-2)"}>
              {label}
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ----- Price ticker (continuously scrolling editorial strip) -----
function PriceTicker() {
  const items = [
    { tag: "NEW",     t: "Lazard IBD SA",       p: 15, kind: "OT" },
    { tag: "↑",       t: "McKinsey BA case",    p: 30, kind: "FULL" },
    { tag: "REFRESHED", t: "Optiver Trader",    p: 18, kind: "VI" },
    { tag: "NEW",     t: "Citi Markets",        p: 30, kind: "FULL" },
    { tag: "↑",       t: "Goldman IBD",         p: 30, kind: "FULL" },
    { tag: "REFRESHED", t: "Bain AC",           p: 30, kind: "FULL" },
    { tag: "NEW",     t: "DBS Management Trainee", p: 18, kind: "VI" },
    { tag: "↑",       t: "Blackstone PE",       p: 30, kind: "FULL" },
    { tag: "REFRESHED", t: "Barclays Spring",   p: 15, kind: "OT" },
    { tag: "NEW",     t: "EY-Parthenon",        p: 30, kind: "FULL" },
    { tag: "↑",       t: "SIG Quant",           p: 18, kind: "VI" },
    { tag: "REFRESHED", t: "Standard Chartered IG", p: 30, kind: "FULL" },
  ];
  return (
    <div style={{ overflow: "hidden", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)", padding: "14px 0", background: "var(--bg-soft)", display: "flex" }}>
      <div style={{ padding: "0 24px", display: "flex", alignItems: "center", gap: 10, borderRight: "1px solid var(--border)", flexShrink: 0 }}>
        <span className="live-dot" /> <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em", color: "var(--text-2)" }}>BANK FEED</span>
      </div>
      <div style={{ flex: 1, overflow: "hidden", paddingLeft: 24 }}>
        <div className="ticker-track" style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--text-2)", letterSpacing: "0.04em" }}>
          {[...items, ...items].map((it, i) => (
            <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
              <span style={{ color: it.tag === "NEW" ? "var(--accent)" : "var(--text-3)", fontSize: 10, letterSpacing: "0.1em" }}>{it.tag}</span>
              <span style={{ color: "var(--text)" }}>{it.t}</span>
              <span style={{ color: "var(--text-3)" }}>{it.kind}</span>
              <span style={{ color: "var(--accent)" }}>£{it.p}</span>
              <span style={{ color: "var(--border-strong)", margin: "0 14px" }}>•</span>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

// ----- Marquee of company names -----
function CompanyMarquee() {
  const list = D.companies.filter(c => c.hot).concat(D.companies.slice(0, 30));
  const items = list.map(c => `${c.n} · ${c.t}`);
  return (
    <div style={{ overflow: "hidden", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)", padding: "22px 0", background: "var(--bg-soft)" }}>
      <div className="marquee-track" style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
        {[...items, ...items].map((s, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 56 }}>
            <span>{s}</span>
            <span style={{ color: "var(--accent)", fontSize: 10 }}>◆</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ----- Section header -----
function SectionHeader({ eyebrow, title, sub, align = "left" }) {
  return (
    <div style={{ marginBottom: 56, display: "flex", flexDirection: "column", alignItems: align === "center" ? "center" : "flex-start", textAlign: align }}>
      <div className="eyebrow" style={{ marginBottom: 18 }}>{eyebrow}</div>
      <h2 className="h-section" style={{ margin: 0, maxWidth: 900 }}>{title}</h2>
      {sub && <p style={{ marginTop: 28, fontSize: 17, color: "var(--text-2)", maxWidth: 560, lineHeight: 1.55 }}>{sub}</p>}
    </div>
  );
}

// expose globals
Object.assign(window, {
  D, useCurrency, useCart, CurrencySwitch, CartDrawer, Nav, Footer, Logo, CompanyMarquee, SectionHeader, SectionOpener, Masthead, PriceTicker,
});
