/* ============================================================
   Fynch AI — app.jsx  (deck shell + mount)  — loaded LAST
   ============================================================ */
(function () {
  const SLIDES = (window.FYNCH_SLIDES || []).slice().sort((a, b) => a.no - b.no);
  const N = SLIDES.length;

  const PHASES = [
    { name: "Opening", start: 1, end: 4, min: 16 },
    { name: "Product", start: 5, end: 6, min: 8 },
    { name: "Workshops 1–3", start: 7, end: 19, min: 47 },
    { name: "Walkthrough", start: 20, end: 28, min: 22 },
    { name: "Strategy", start: 29, end: 34, min: 19 },
    { name: "Close", start: 35, end: 36, min: 8 },
  ];
  function SectionNav({ idx, go }) {
    const cur = idx + 1;
    const pi = PHASES.findIndex((p) => cur >= p.start && cur <= p.end);
    return (
      <div className="section-nav">
        {PHASES.map((p, i) => {
          const active = i === pi;
          const within = active ? ((cur - p.start + 1) / (p.end - p.start + 1)) * 100 : 0;
          return (
            <button key={p.name} className={"sn-tab" + (active ? " active" : "") + (i < pi ? " done" : "")} onClick={() => go(p.start - 1)}>
              <span className="sn-i">{i + 1}</span><span className="sn-name">{p.name}</span>
              {active && <span className="sn-min">~{p.min}m</span>}
              {active && <span className="sn-prog"><span style={{ width: within + "%" }}></span></span>}
            </button>
          );
        })}
      </div>
    );
  }
  function PresTimer() {
    const [t, setT] = useState(0);
    const start = useRef(Date.now());
    useEffect(() => { const id = setInterval(() => setT(Math.floor((Date.now() - start.current) / 1000)), 1000); return () => clearInterval(id); }, []);
    const mm = String(Math.floor(t / 60)).padStart(2, "0"), ss = String(t % 60).padStart(2, "0");
    const over = t > 120 * 60;
    return <button className="pres-timer" onClick={() => { start.current = Date.now(); setT(0); }} title="Elapsed — click to reset"><Icon d="M12 8v4l3 2M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z" size={14} /><span style={over ? { color: "#fca5a5" } : null}>{mm}:{ss}</span><span className="tt">/ 120m</span></button>;
  }

  function useScale() {
    useEffect(() => {
      const canvas = document.getElementById("canvas");
      function fit() {
        const s = Math.min(window.innerWidth / 1920, window.innerHeight / 1080);
        canvas.style.transform = "translate(-50%,-50%) scale(" + s + ")";
      }
      fit();
      window.addEventListener("resize", fit);
      return () => window.removeEventListener("resize", fit);
    }, []);
  }

  function clampIndex(i) { return Math.max(0, Math.min(N - 1, i)); }

  function Deck() {
    const store = useStore();
    const [idx, setIdx] = useState(() => {
      const h = parseInt((location.hash || "").replace("#", ""), 10);
      return clampIndex(isNaN(h) ? 0 : h - 1);
    });
    const [agendaOpen, setAgendaOpen] = useState(false);
    useScale();

    const go = useCallback((next) => {
      setIdx((cur) => {
        const v = clampIndex(typeof next === "function" ? next(cur) : next);
        location.hash = String(v + 1);
        return v;
      });
    }, []);

    // sync host's active workshop to the slide being shown
    useEffect(() => {
      const slide = SLIDES[idx];
      FynchStore.setActiveWorkshop(slide && slide.ws ? slide.ws : null);
    }, [idx]);

    useEffect(() => {
      function onHash() {
        const h = parseInt((location.hash || "").replace("#", ""), 10);
        if (!isNaN(h)) setIdx(clampIndex(h - 1));
      }
      window.addEventListener("hashchange", onHash);
      return () => window.removeEventListener("hashchange", onHash);
    }, []);

    useEffect(() => {
      function onKey(e) {
        if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
        if (e.target && e.target.isContentEditable) return;
        if (e.key === "ArrowRight" || e.key === "PageDown" || e.key === " ") { e.preventDefault(); go((i) => i + 1); }
        else if (e.key === "ArrowLeft" || e.key === "PageUp") { e.preventDefault(); go((i) => i - 1); }
        else if (e.key === "Home") go(0);
        else if (e.key === "End") go(N - 1);
        else if (e.key.toLowerCase() === "a") setAgendaOpen((o) => !o);
        else if (e.key.toLowerCase() === "h") document.body.classList.toggle("hc");
        else if (e.key.toLowerCase() === "w") document.body.classList.toggle("hide-client");
        else if (e.key === "Escape") setAgendaOpen(false);
        else if (/^[0-9]$/.test(e.key)) { /* buffered jump handled below */ window.__jb = (window.__jb || "") + e.key; clearTimeout(window.__jt); window.__jt = setTimeout(() => { const n = parseInt(window.__jb, 10); if (!isNaN(n)) go(n - 1); window.__jb = ""; }, 450); }
      }
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [go]);

    const cur = SLIDES[idx];
    const pcount = store ? FynchStore.participantCount() : 0;

    return (
      <React.Fragment>
        <div className="progressbar" style={{ width: ((idx + 1) / N) * 100 + "%" }}></div>

        <SectionNav idx={idx} go={go} />
        <PresTimer />

        <div className="host-badge" title="Live session — share the code on the participant link">
          <span className="live"></span>
          <img src="assets/fynch-mark.png" alt="" />
          <span>Session <b className="mono">{FynchStore.code()}</b></span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: "#93c5fd" }}>
            <Icon name="people" size={14} />{pcount}
          </span>
          {cur && cur.ws && (
            <span style={{ color: FynchStore.isLocked(cur.ws) ? "#fbbf24" : "#34d399" }} className="mono">
              {FynchStore.isLocked(cur.ws) ? "LOCKED" : "OPEN"}
            </span>
          )}
        </div>

        {SLIDES.map((s, i) => (
          <section key={s.no} className={"slide" + (s.dark ? " dark" : "")} {...(i === idx ? { "data-active": "" } : {})} data-screen-label={"Slide " + String(s.no).padStart(2, "0")}>
            {Math.abs(i - idx) <= 1 ? <SlideActiveCtx.Provider value={i === idx}><s.Comp active={i === idx} /></SlideActiveCtx.Provider> : null}
          </section>
        ))}

        <div className="deck-controls">
          <button onClick={() => setAgendaOpen(true)} title="Agenda (A)"><Icon name="grid" size={16} /></button>
          <span className="seg"></span>
          <button onClick={() => go((i) => i - 1)} title="Previous (←)"><Icon d="M15 18l-6-6 6-6" /></button>
          <span className="count">{String(idx + 1).padStart(2, "0")} / {N}</span>
          <button onClick={() => go((i) => i + 1)} title="Next (→)"><Icon d="M9 6l6 6-6 6" /></button>
        </div>

        <AgendaOverlay open={agendaOpen} onClose={() => setAgendaOpen(false)} onJump={(no) => { go(no - 1); setAgendaOpen(false); }} cur={idx + 1} />
      </React.Fragment>
    );
  }

  function AgendaOverlay({ open, onClose, onJump, cur }) {
    return (
      <div className={"agenda-overlay" + (open ? " open" : "")} onClick={onClose}>
        <div className="agenda-panel" onClick={(e) => e.stopPropagation()}>
          <h2>Session agenda</h2>
          <p className="sub">120-minute working session · click any block to jump · press A to toggle</p>
          <div className="agenda-list">
            {window.FYNCH_AGENDA.map((a, i) => {
              const first = parseInt(a.slides.split("–")[0], 10);
              const within = (() => { const parts = a.slides.split("–").map((x) => parseInt(x, 10)); return cur >= parts[0] && cur <= (parts[1] || parts[0]); })();
              return (
                <div key={i} className="agenda-item" onClick={() => onJump(first)} style={within ? { background: "var(--brand-50)", borderColor: "var(--brand-200)" } : null}>
                  <span className="time">{a.time}m</span>
                  <span><span className="nm">{a.section}</span><span className="ph" style={{ marginLeft: 12 }}>{a.purpose}</span></span>
                  <span className="sl">slides {a.slides}</span>
                </div>
              );
            })}
          </div>
          <div style={{ display: "flex", gap: 10, marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--line-200)", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <span className="label-meta">Shortcuts</span>
              <span className="mono" style={{ fontSize: 13, color: "var(--ink-500)", marginLeft: 10 }}>← → navigate · A agenda · H high-contrast · type a number to jump</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: "var(--ink-600)" }}>
              <Icon name="people" size={15} />Participants join at <b className="mono" style={{ color: "var(--brand-600)" }}>participant.html</b> · code <b className="mono" style={{ color: "var(--brand-600)" }}>{FynchStore.code()}</b>
            </div>
          </div>
        </div>
      </div>
    );
  }

  FynchStore.init("WLGTN");
  ReactDOM.createRoot(document.getElementById("canvas")).render(<Deck />);
})();
