/* site-shared.jsx - shared chrome + atoms for detail / manager / list pages.
   Loaded as Babel script BEFORE each page app. Exports to window. */
const { useState, useEffect, useRef, useCallback } = React;

/* ---- config (keep in sync with stahnout-report.html) ---- */
window.FKI_CONFIG = window.FKI_CONFIG || {
  LEAD_ENDPOINT: "/api/leads",
  TRACK_ENDPOINT: "/api/track",
  PRIVACY_URL: "privacy.html",
};
function fkiTrack(event, props) {
  try {
    // Consent gate: analytics beacons fire only after the visitor opts in (see consent.js).
    // First-party lead submissions (ActionGate) are separate and gated by the GDPR checkbox, not this.
    if (!window.clienteloConsent || window.clienteloConsent.analytics !== true) return;
    var C = window.FKI_CONFIG; if (!C.TRACK_ENDPOINT) return;
    var body = JSON.stringify(Object.assign({ event: event, ts: new Date().toISOString() }, props || {}));
    if (navigator.sendBeacon) navigator.sendBeacon(C.TRACK_ENDPOINT, new Blob([body], { type: "application/json" }));
    else fetch(C.TRACK_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: body, keepalive: true }).catch(function(){});
  } catch (e) {}
}
window.fkiTrack = fkiTrack;

/* ---- formatting ---- */
function fmtAum(milCZK) {
  if (milCZK == null) return "-";
  if (milCZK >= 1000) { const mld = milCZK / 1000; return (mld >= 10 ? mld.toFixed(1) : mld.toFixed(2)).replace(".", ",") + " mld Kč"; }
  return Math.round(milCZK) + " mil Kč";
}
window.fmtAum = fmtAum;

/* ---- nav + footer ---- */
function SiteNav({ active }) {
  const [open, setOpen] = useState(false);
  const [wl, setWl] = useState(0);
  useEffect(() => {
    const upd = () => setWl(window.FKIWatch ? window.FKIWatch.count() : 0);
    upd();
    const off = window.FKIWatch ? window.FKIWatch.onChange(upd) : null;
    return () => { if (off) off(); };
  }, []);
  const L = (href, label, key) => (
    <a className={"nav-link" + (active === key ? " is-active" : "")} href={href}>{label}</a>
  );
  return (
    <header className="nav">
      <div className="nav-inner">
        <a className="brand" href="domu.html">
          <span className="brand-mark" aria-hidden="true">◆</span>
          <span className="brand-name">Fkička</span>
        </a>
        <nav className={"nav-links" + (open ? " is-open" : "")}>
          {L("domu.html", "Domů", "home")}
          {L("seznam-fondu.html", "Seznam fondů", "funds")}
          {L("spravci.html", "Správci", "managers")}
          {L("srovnavac.html", "Srovnávač", "compare")}
          {L("co-je-noveho.html", "Co je nového", "changelog")}
          <a className={"nav-link" + (active === "saved" ? " is-active" : "")} href="ulozene.html">
            Uložené{wl > 0 ? <span className="wl-pill">{wl}</span> : null}
          </a>
        </nav>
        <button className="hamburger" aria-label="Menu" onClick={() => setOpen((o) => !o)}>
          <span></span><span></span><span></span>
        </button>
      </div>
    </header>
  );
}
function SiteFooter() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="brand"><span className="brand-mark" aria-hidden="true">◆</span><span className="brand-name">Fkička</span></div>
        <nav className="footer-links">
          <a href="domu.html">Domů</a><a href="seznam-fondu.html">Seznam fondů</a>
          <a href="spravci.html">Správci</a><a href="srovnavac.html">Srovnávač</a>
          <a href="co-je-noveho.html">Co je nového</a><a href="stahnout-report.html">Report 2026</a>
        <a href="privacy.html">Zásady ochrany osobních údajů</a><a href="cookies.html">Zásady používání cookies</a></nav>
        <span className="footer-fine">© Fkička 2026 · Informace nejsou investičním doporučením.</span><span className="footer-op">Provozovatel: Clientelo Czech s.r.o., IČO 221 93 456, se sídlem Platnéřská 90/13, 110 00 Praha 1, zapsaná v OR u MS v Praze, sp. zn. C 412348.</span>
      </div>
    </footer>
  );
}

/* ---- watchlist save button ---- */
function WatchButton({ id, label, mini }) {
  const [on, setOn] = useState(false);
  useEffect(() => {
    const upd = () => setOn(window.FKIWatch ? window.FKIWatch.has(id) : false);
    upd();
    const off = window.FKIWatch ? window.FKIWatch.onChange(upd) : null;
    return () => { if (off) off(); };
  }, [id]);
  const click = (e) => {
    e.stopPropagation(); e.preventDefault();
    const nowOn = window.FKIWatch.toggle(id);
    setOn(nowOn);
    fkiTrack(nowOn ? "watch_add" : "watch_remove", { id: id });
  };
  return (
    <button className={"wl-btn" + (mini ? " wl-mini" : "") + (on ? " is-on" : "")} onClick={click}
      aria-pressed={on} title={on ? "Uloženo" : "Uložit"} aria-label={on ? "Odebrat z uložených" : "Uložit"}>
      <svg className="wl-off-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21l-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
      <svg className="wl-on-ico" viewBox="0 0 24 24" fill="currentColor"><path d="M19 21l-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
      {!mini ? <span>{on ? (label ? label + " - uloženo" : "Uloženo") : (label || "Uložit")}</span> : null}
    </button>
  );
}

/* ---- lead-capture modal (gated actions: kontakt, alert) ---- */
function ActionGate({ action, fund, onClose }) {
  // action: { kind:'contact'|'alert', title, sub, cta }
  const [form, setForm] = useState({ name: "", email: "", phone: "", gdpr: false });
  const [err, setErr] = useState({});
  const [state, setState] = useState("form"); // form | loading | done | error
  const firstRef = useRef(null);
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    if (firstRef.current) firstRef.current.focus();
    fkiTrack("action_gate_open", { kind: action.kind, fund: fund ? fund.slug : null });
    // prefill from prior lead
    try { const L = JSON.parse(localStorage.getItem("fki_lead") || "null"); if (L) setForm((f) => ({ ...f, name: L.name || "", email: L.email || "", phone: L.phone || "" })); } catch (e) {}
    return () => document.removeEventListener("keydown", onKey);
  }, []);
  function submit(e) {
    e.preventDefault();
    const ne = {};
    if (form.name.trim().length < 2) ne.name = true;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email.trim())) ne.email = true;
    if (form.phone.replace(/[^\d]/g, "").length < 9) ne.phone = true;
    if (!form.gdpr) ne.gdpr = true;
    setErr(ne);
    if (Object.keys(ne).length) return;
    const lead = { name: form.name.trim(), email: form.email.trim().toLowerCase(), phone: form.phone.trim(),
      source: action.kind === "alert" ? "fund_alert" : "fund_contact",
      fund: fund ? fund.slug : null, fundName: fund ? fund.name : null, ts: new Date().toISOString() };
    setState("loading");
    fkiTrack("action_submit_attempt", { kind: action.kind, fund: fund ? fund.slug : null });
    const finish = () => { try { localStorage.setItem("fki_lead", JSON.stringify(lead)); } catch (e) {} fkiTrack("lead_captured", { kind: action.kind, fund: fund ? fund.slug : null }); setState("done"); };
    const fail = () => { setState("error"); fkiTrack("action_submit_error", { kind: action.kind }); };
    const C = window.FKI_CONFIG;
    if (C.LEAD_ENDPOINT) {
      fetch(C.LEAD_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(lead) })
        .then((r) => (r && r.ok ? finish() : fail())).catch(fail);
    } else finish();
  }
  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-label={action.title}>
        <button className="modal-close" onClick={onClose} aria-label="Zavřít">✕</button>
        {state !== "done" ? (
          <React.Fragment>
            <p className="modal-eyebrow">{action.kind === "alert" ? "Hlídací pes" : "Kontakt"}</p>
            <h3 className="modal-title">{action.title}</h3>
            <p className="modal-sub">{action.sub}</p>
            <form onSubmit={submit} noValidate>
              <label className="field"><span>Jméno a příjmení</span>
                <input ref={firstRef} className={err.name ? "is-err" : ""} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Jan Novák" /></label>
              <label className="field"><span>E‑mail</span>
                <input className={err.email ? "is-err" : ""} value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="jan.novak@email.cz" inputMode="email" /></label>
              <label className="field"><span>Telefon</span>
                <input className={err.phone ? "is-err" : ""} value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+420 777 123 456" inputMode="tel" /></label>
              {fund ? <label className="field field--ro"><span>Fond</span><input value={fund.name} readOnly /></label> : null}
              <label className={"check" + (err.gdpr ? " is-err" : "")}>
                <input type="checkbox" checked={form.gdpr} onChange={(e) => setForm({ ...form, gdpr: e.target.checked })} />
                <span>Souhlasím se zpracováním osobních údajů dle <a href={window.FKI_CONFIG.PRIVACY_URL} target="_blank" rel="noopener">zásad ochrany údajů</a>. Povinné.</span>
              </label>
              {state === "error" ? <p className="modal-fine" style={{ color: "var(--warn-fg)" }}>Odeslání se nezdařilo. Zkuste to prosím znovu.</p> : null}
              <button type="submit" className="btn btn--primary btn--full" disabled={state === "loading"}>
                {state === "loading" ? "Odesílám…" : action.cta}</button>
              <p className="modal-fine">Bez spamu. Odhlásit se lze kdykoli.</p>
            </form>
          </React.Fragment>
        ) : (
          <div className="modal-done">
            <div className="check-circle" aria-hidden="true">✓</div>
            <h3 className="modal-title">Děkujeme, {form.name.split(" ")[0]}.</h3>
            <p className="modal-sub">{action.kind === "alert"
              ? <span>Budeme hlídat změny u fondu {fund ? <strong>{fund.name}</strong> : "tohoto fondu"} a dáme vám vědět na {form.email}.</span>
              : <span>Ozveme se na {form.email} do dvou pracovních dnů{fund ? <span> s podklady k fondu <strong>{fund.name}</strong></span> : null}.</span>}</p>
            <button className="btn btn--primary btn--full" onClick={onClose}>Zavřít</button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---- shared small atoms ---- */
function Badge({ kind }) {
  const map = { "Aktivní": "badge badge--active", "Warm": "badge badge--warm", "Cold": "badge badge--cold" };
  return <span className={map[kind] || "badge"}><span className="badge-dot">•</span>{kind}</span>;
}
function Stars({ n }) {
  return (
    <span className="stars" aria-label={n + " z 5"}>
      {[1, 2, 3, 4, 5].map((i) => (
        <svg key={i} viewBox="0 0 24 24" className={"star " + (i <= n ? "on" : "off")} width="14" height="14" aria-hidden="true">
          <path d="M12 2.5l2.9 6.06 6.6.86-4.85 4.6 1.2 6.58L12 17.9l-5.85 3.16 1.2-6.58L2.5 9.42l6.6-.86z" /></svg>
      ))}
    </span>
  );
}
function stratClass(s) { return "strat strat--" + String(s).replace(/[^a-zA-Z]/g, ""); }

Object.assign(window, { SiteNav, SiteFooter, WatchButton, ActionGate, Badge, Stars, stratClass });
