/* global React, Icon, Eyebrow, Serif, Rule, Reveal, AnalysisBody, CaptureText, Rise,
   useCapture, readStore, BridgeObject, FuturesFork, AssumptionsGrid,
   ReadinessLadders, LensSwitcher, CruxRanking, IdentityInstall, PitchBuilder, DATA */
/* =====================================================================
   Stop layout shell + Listening panel + session synthesis
   ===================================================================== */
const { useState: useSt, useEffect: useStE } = React;

/* ----------------------------------------------------- LISTENING (01) */
function ListeningPanel({ stop }) {
  const [flipped, setFlipped] = useSt(() => new Set());
  const flip = (i) => setFlipped((p) => { const n = new Set(p); n.has(i) ? n.delete(i) : n.add(i); return n; });
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(280px,1fr))",
        gap: "clamp(24px,4vw,52px)" }}>
        {/* five core ideas */}
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
            textTransform: "uppercase", color: "var(--fg2)", marginBottom: 16 }}>What we heard · five ideas</div>
          <div style={{ borderTop: "1px solid var(--ink)" }}>
            {stop.ideas.map((idea, i) => (
              <div key={i} style={{ padding: "16px 0", borderBottom: "1px solid var(--fog)" }}>
                <div style={{ display: "flex", gap: 14, alignItems: "baseline" }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--signal)",
                    flex: "0 0 auto" }}>{String(i + 1).padStart(2, "0")}</span>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 16.5, lineHeight: 1.3,
                      letterSpacing: "-0.01em", color: "var(--ink)" }}>{idea.h}</div>
                    <div style={{ fontSize: 14, color: "var(--ash)", lineHeight: 1.5, marginTop: 6 }}>{idea.p}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* verbatim quotes — flip to meaning */}
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
            textTransform: "uppercase", color: "var(--fg2)", marginBottom: 16 }}>Verbatim · tap to hear the shift</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {stop.quotes.map((q, i) => {
              const on = flipped.has(i);
              return (
                <button key={i} onClick={() => flip(i)} className="focus-ring" style={{
                  all: "unset", cursor: "pointer", border: "1px solid var(--ink)",
                  padding: "16px 18px", background: on ? "var(--bone)" : "transparent",
                  transition: "background var(--dur-fast) var(--ease)", display: "block" }}>
                  <div style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 19,
                    lineHeight: 1.3, color: "var(--ink)" }}>“{q.said}”</div>
                  <div style={{ display: "grid", gridTemplateRows: on ? "1fr" : "0fr",
                    transition: "grid-template-rows var(--dur) var(--ease)" }}>
                    <div style={{ overflow: "hidden", minHeight: 0 }}>
                      <div style={{ display: "flex", gap: 10, alignItems: "baseline", marginTop: 12,
                        paddingTop: 12, borderTop: "1px solid var(--fog)" }}>
                        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em",
                          textTransform: "uppercase", color: "var(--signal)", flex: "0 0 auto" }}>means</span>
                        <span style={{ fontSize: 14.5, color: "var(--ash)", lineHeight: 1.45 }}>{q.means}</span>
                      </div>
                    </div>
                  </div>
                  {!on && <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em",
                    textTransform: "uppercase", color: "var(--fg2)", marginTop: 12, display: "flex",
                    alignItems: "center", gap: 7, whiteSpace: "nowrap" }}><Icon name="plus" size={11} /> the shift</div>}
                </button>
              );
            })}
          </div>
        </div>
      </div>

      <div style={{ marginTop: 30 }}>
        <CaptureText id={stop.capture.id} prompt={stop.capture.prompt} placeholder={stop.capture.placeholder} />
      </div>
    </div>
  );
}

/* --------------------------------------------- SESSION SYNTHESIS (09) */
const LABELS = {
  "text:heard": "What we're hearing",
  "text:future": "Future chosen",
  "text:worry": "Assumption that worries us most",
  "text:ladders": "Where we stand on the ladders",
  "text:conversion": "Biggest conversion failure",
  "text:commitments": "Behaviors committed to",
};
const FUTURE_NAME = { showcase: "The Showcase Accelerator", school: "The Founder School", platform: "The Adoption Platform" };
function fmtVal(key, v) {
  if (v == null || v === "" || (Array.isArray(v) && !v.length)) return null;
  if (key === "text:future") return FUTURE_NAME[v] || v;
  if (key === "text:ladders") {
    const parts = [];
    if (v.startup) parts.push("Startup · L" + v.startup);
    if (v.corporate) parts.push("Corporation · L" + v.corporate);
    return parts.length ? parts.join("   ·   ") : null;
  }
  if (Array.isArray(v)) return v.length + " committed";
  return String(v);
}
function SessionSynthesis() {
  const [store, setStore] = useSt(readStore());
  useStE(() => {
    const sync = () => setStore(readStore());
    window.addEventListener("capture-change", sync);
    return () => window.removeEventListener("capture-change", sync);
  }, []);
  const rows = Object.keys(LABELS).map((k) => ({ k, label: LABELS[k], val: fmtVal(k, store[k]) }))
    .filter((r) => r.val);
  if (!rows.length) return null;
  return (
    <div style={{ marginTop: 44, borderTop: "3px solid var(--ink)", paddingTop: 24 }}>
      <Eyebrow style={{ color: "var(--signal)", marginBottom: 18 }}>From this session · what this team decided</Eyebrow>
      <div style={{ borderTop: "1px solid var(--fog)" }}>
        {rows.map((r) => (
          <div key={r.k} style={{ display: "grid", gridTemplateColumns: "minmax(180px,260px) 1fr",
            gap: 20, padding: "13px 0", borderBottom: "1px solid var(--fog)", alignItems: "baseline" }}
            className="synth-row">
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.1em",
              textTransform: "uppercase", color: "var(--fg2)" }}>{r.label}</div>
            <div style={{ fontSize: 16, color: "var(--ink)", fontWeight: 500, lineHeight: 1.4 }}>{r.val}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ------------------------------------------------------ INTERACTION MAP */
function StopInteraction({ stop }) {
  switch (stop.id) {
    case "listening": return <ListeningPanel stop={stop} />;
    case "framing": return <BridgeObject data={DATA.bridge} />;
    case "envisioning": return <FuturesFork data={DATA.futures} />;
    case "assumptions": return <AssumptionsGrid data={DATA.assumptions} worryOptions={DATA.worryOptions} />;
    case "systems": return <ReadinessLadders data={DATA.ladders} others={DATA.otherTransforms} />;
    case "frames": return <LensSwitcher data={DATA.lenses} />;
    case "crux": return <CruxRanking cruxes={DATA.cruxes} pathway={DATA.pathway} conversionOptions={DATA.conversionOptions} />;
    case "integration": return <IdentityInstall identity={DATA.identity} behaviors={DATA.behaviors} />;
    case "narrative": return <><PitchBuilder pitches={DATA.pitches} pixar={DATA.pixar} /><SessionSynthesis /></>;
    default: return null;
  }
}

/* ------------------------------------------------------------ STOP VIEW */
function StopView({ stop, inverse, serifQ }) {
  const fg1 = inverse ? "var(--paper)" : "var(--ink)";
  const fg2 = inverse ? "rgba(242,240,235,0.62)" : "var(--ash)";
  const meta = inverse ? "rgba(242,240,235,0.5)" : "var(--fg2)";
  return (
    <article data-screen-label={"Stop " + stop.coord + " · " + stop.name}
      style={{ maxWidth: 1080, margin: "0 auto", padding: "clamp(40px,7vh,88px) clamp(24px,5vw,72px) 120px" }}>
      <Rise k={stop.id}>
        {/* header */}
        <header style={{ marginBottom: "clamp(32px,5vh,56px)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.14em",
              color: "var(--signal)" }}>STOP {stop.coord}</span>
            <span style={{ width: 6, height: 6, background: meta }} />
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.14em",
              textTransform: "uppercase", color: meta }}>{stop.band}</span>
            <span style={{ width: 6, height: 6, background: meta }} />
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.14em",
              textTransform: "uppercase", color: meta }}>{stop.name}</span>
          </div>
          <h1 style={{
            fontFamily: serifQ ? "var(--font-serif)" : "var(--font-sans)",
            fontStyle: serifQ ? "italic" : "normal",
            fontWeight: serifQ ? 400 : 900,
            fontSize: serifQ ? "clamp(40px,6.5vw,86px)" : "clamp(34px,5.4vw,72px)",
            letterSpacing: serifQ ? 0 : "-0.035em", lineHeight: serifQ ? 1.02 : 0.98,
            color: fg1, margin: "22px 0 0", maxWidth: "17ch",
          }}>{stop.question}</h1>
          <p style={{ color: fg2, fontSize: "clamp(17px,1.6vw,20px)", lineHeight: 1.55,
            margin: "26px 0 0", maxWidth: "60ch" }}>{stop.framing}</p>
          {stop.kicker && (
            <div style={{ borderLeft: "3px solid var(--signal)", padding: "2px 0 2px 20px",
              marginTop: 28, maxWidth: "56ch" }}>
              <div style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: "clamp(20px,2.4vw,28px)",
                lineHeight: 1.25, color: fg1 }}>{stop.kicker}</div>
            </div>
          )}
        </header>

        {/* interaction */}
        <section style={{ marginBottom: "clamp(28px,4vh,44px)" }}>
          <StopInteraction stop={stop} />
        </section>

        {/* reveal deeper analysis */}
        <Reveal inverse={inverse}><AnalysisBody analysis={stop.analysis} inverse={inverse} /></Reveal>

        {/* footer meta */}
        <footer style={{ marginTop: 40, display: "flex", justifyContent: "space-between",
          alignItems: "center", flexWrap: "wrap", gap: 12 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
            textTransform: "uppercase", color: meta }}>Dark Horse Works · prepared for Alisa Ellis</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
            color: meta }}>{stop.coord} / 09</span>
        </footer>
      </Rise>
    </article>
  );
}

Object.assign(window, { StopView, ListeningPanel, SessionSynthesis });
