/* global React, window, Contours, LocationHead, LayerTag, NextButton */
const { useState: useStateB } = React;

/* =========================================================
   ICEBERG ARCHIVE — Assumptions. Pull an idea below the
   waterline to surface what must be true.
   ========================================================= */
function Iceberg({ loc, data, carto, onNext }) {
  const [pulled, setPulled] = useStateB({});
  const pull = (id) => setPulled((p) => ({ ...p, [id]: !p[id] }));
  const pulledCount = Object.values(pulled).filter(Boolean).length;
  return (
    <section className="stage" data-screen-label="IV · The Iceberg Archive">
      <Contours density={carto} seed={43} />
      <div className="stage__inner">
        <LocationHead loc={loc} />
        <LayerTag n="01 · Observation">{data.intro}</LayerTag>

        <div className="berg-grid fade-rise-2">
          {data.items.map((it) => {
            const open = !!pulled[it.id];
            return (
              <div key={it.id} className={"berg" + (open ? " open" : "")}>
                <button className="berg__above" onClick={() => pull(it.id)}>
                  <span className="berg__weight">{it.weight}</span>
                  <span className="berg__idea serif">{it.idea}</span>
                  <span className="berg__pull">{open ? "▲ above water" : "▼ pull to reveal"}</span>
                </button>
                <span className="berg__waterline" />
                <div className="berg__below" aria-hidden={!open}>
                  <div className="berg__row">
                    <span className="berg__k">Must be true</span>
                    <p className="berg__v">{it.assumption}</p>
                  </div>
                  <div className="berg__row">
                    <span className="berg__k signal-word">If wrong</span>
                    <p className="berg__v">{it.counter}</p>
                  </div>
                  <div className="berg__row">
                    <span className="berg__k">Cheap test</span>
                    <p className="berg__v">{it.test}</p>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="layer-tag" style={{ marginTop: "var(--sp-8)" }}>
          <span className="n">02 · Reflection</span><span>Where the real risk sits</span>
        </div>
        <p className="pull serif" style={{ fontSize: 24, lineHeight: 1.3 }}>{data.framing}</p>

        <div className="row" style={{ marginTop: "var(--sp-6)", justifyContent: "space-between" }}>
          <span className="coord">{pulledCount} / {data.items.length} assumptions surfaced</span>
          <NextButton label="Walk down to the river" onClick={onNext} />
        </div>
      </div>
    </section>
  );
}

/* =========================================================
   RIVER CROSSING — Transformation. Two banks; what crosses,
   stays, disappears. (Placeholder content this session.)
   ========================================================= */
function River({ loc, data, carto, onNext }) {
  const [crossed, setCrossed] = useStateB({});
  const [q, setQ] = useStateB(0);
  const cross = (i) => setCrossed((c) => ({ ...c, [i]: !c[i] }));
  return (
    <section className="stage" data-screen-label="V · The River Crossing">
      <Contours density={carto} seed={57} />
      <div className="stage__inner">
        <LocationHead loc={loc} />

        <div className="river-note fade-rise">
          <span className="river-note__tag">STAGED · NOT YET ACTIVATED</span>
          <p className="body-s muted">{data.note}</p>
        </div>

        <LayerTag n="01 · Observation">{data.intro}</LayerTag>

        <div className="river fade-rise-2">
          <div className="bank">
            <span className="bank__lbl">{data.today.label}</span>
            {data.today.items.map((t, i) => (
              <button key={i} className={"bank__item" + (crossed[i] ? " crossed" : "")} onClick={() => cross(i)}>
                <span className="bank__num">{String(i + 1).padStart(2, "0")}</span>{t}
              </button>
            ))}
          </div>
          <div className="river__channel" aria-hidden="true">
            <span className="river__label">THE RIVER</span>
            <span className="river__bridge">{Object.keys(crossed).filter(k=>crossed[k]).length > 0 ? "BRIDGE FORMING" : "NO BRIDGE YET"}</span>
          </div>
          <div className="bank bank--far">
            <span className="bank__lbl signal-word">{data.tomorrow.label}</span>
            {data.tomorrow.items.map((t, i) => (
              <div key={i} className={"bank__item bank__item--far" + (crossed[i] ? " lit" : "")}>
                <span className="bank__num">{String(i + 1).padStart(2, "0")}</span>{t}
              </div>
            ))}
          </div>
        </div>

        <div className="layer-tag" style={{ marginTop: "var(--sp-8)" }}>
          <span className="n">02 · Reflection</span><span>The crossing, in three questions</span>
        </div>
        <div className="river-q fade-rise">
          <div className="river-q__tabs">
            {data.bridge.map((b, i) => (
              <button key={i} className={"river-q__tab" + (q === i ? " on" : "")} onClick={() => setQ(i)}>
                {b.q}
              </button>
            ))}
          </div>
          <p className="river-q__a serif">{data.bridge[q].a}</p>
        </div>

        <div className="row" style={{ marginTop: "var(--sp-7)", justifyContent: "space-between" }}>
          <span className="coord">Place items on the near bank to begin forming the bridge.</span>
          <NextButton label="Climb to the pass" onClick={onNext} />
        </div>
      </div>
    </section>
  );
}

/* =========================================================
   MOUNTAIN PASS — Crux. Compare candidates; the crux emerges.
   ========================================================= */
function MountainPass({ loc, data, carto, onNext }) {
  const [i, setI] = useStateB(0);
  const [seen, setSeen] = useStateB({ c1: true });
  const [decided, setDecided] = useStateB(false);
  const c = data.candidates[i];
  const go = (ni) => { setI(ni); setSeen((s) => ({ ...s, [data.candidates[ni].id]: true })); };
  return (
    <section className="stage" data-screen-label="VI · The Mountain Pass">
      <Contours density={carto} seed={67} />
      <div className="stage__inner">
        <LocationHead loc={loc} />
        <LayerTag n="01 · Observation">{data.intro}</LayerTag>

        {!decided ? (
          <div className="pass fade-rise-2">
            <div className="pass__rail">
              {data.candidates.map((cand, idx) => (
                <button key={cand.id}
                  className={"pass__rung" + (idx === i ? " on" : "") + (seen[cand.id] ? " seen" : "")}
                  onClick={() => go(idx)}>
                  <span className="pass__rank">{cand.rank}</span>
                  <span className="pass__rrailto">{cand.to}</span>
                </button>
              ))}
            </div>
            <div className="pass__card">
              <div className="pass__rankbig">CANDIDATE 0{c.rank}</div>
              <div className="pass__reframe">
                <span className="pass__from">{c.from}</span>
                <span className="pass__arrow">→</span>
                <span className="pass__to serif">{c.to}</span>
              </div>
              <div className="pass__rows">
                <div><span className="pass__k">Why it works</span><p>{c.why}</p></div>
                <div><span className="pass__k signal-word">The critique</span><p>{c.crit}</p></div>
              </div>
              {c.recommended && <div className="pass__rec">▲ Ranked #1 — the recommended crux</div>}
              <div className="row" style={{ marginTop: "var(--sp-5)", justifyContent: "space-between" }}>
                <span className="coord">{Object.keys(seen).length} / {data.candidates.length} candidates compared</span>
                <div className="row">
                  {i < data.candidates.length - 1 && <button className="btn" onClick={() => go(i + 1)}>Next candidate →</button>}
                  <button className="btn btn--signal" disabled={Object.keys(seen).length < 3} onClick={() => setDecided(true)}>
                    Name the crux
                  </button>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="crux-final fade-rise">
            <div className="layer-tag"><span className="n">02 · Synthesis</span><span>The recommended crux statement</span></div>
            <p className="crux-statement serif">{data.statement}</p>
            <div className="layer-tag" style={{ marginTop: "var(--sp-7)" }}>
              <span className="n">03 · Coherent action</span><span>Three non-theatrical proofs</span>
            </div>
            <div className="grid grid-3">
              {data.moves.map((m) => (
                <div key={m.n} className="move">
                  <span className="move__n">{m.n}</span>
                  <h3 className="move__t">{m.t}</h3>
                  <p className="body-s muted">{m.d}</p>
                </div>
              ))}
            </div>
            <div className="row" style={{ marginTop: "var(--sp-7)", justifyContent: "flex-end" }}>
              <NextButton label="Enter the constellation" onClick={onNext} variant="primary" />
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

/* =========================================================
   CONSTELLATION CHAMBER — Integration. Dark. Stars connect.
   ========================================================= */
function Constellation({ loc, data, onFinish, onRestart }) {
  const [active, setActive] = useStateB(null);
  const [lit, setLit] = useStateB({});
  const touch = (id) => { setActive(id); setLit((l) => ({ ...l, [id]: true })); };
  const litCount = Object.keys(lit).length;
  const pos = (id) => data.stars.find((s) => s.id === id);
  return (
    <section className="stage" data-screen-label="VII · The Constellation Chamber">
      <div className="stage__inner">
        <LocationHead loc={loc} />
        <LayerTag n="01 · Observation">{data.intro}</LayerTag>

        <div className="sky fade-rise-2">
          <svg className="sky__lines" viewBox="0 0 100 80" preserveAspectRatio="none" aria-hidden="true">
            {data.links.map(([a, b], i) => {
              const pa = pos(a), pb = pos(b);
              const on = lit[a] && lit[b];
              return <line key={i} x1={pa.x} y1={pa.y * 0.8} x2={pb.x} y2={pb.y * 0.8}
                stroke="var(--signal)" strokeWidth="0.25" vectorEffect="non-scaling-stroke"
                opacity={on ? 0.85 : 0.08} style={{ transition: "opacity 600ms" }} />;
            })}
          </svg>
          {data.stars.map((s) => (
            <button key={s.id}
              className={"star" + (active === s.id ? " active" : "") + (lit[s.id] ? " lit" : "")}
              style={{ left: s.x + "%", top: (s.y * 0.8) + "%" }}
              onMouseEnter={() => touch(s.id)} onClick={() => touch(s.id)}>
              <span className={"star__dot mag" + s.mag} />
              <span className="star__label">{s.label}</span>
            </button>
          ))}
        </div>

        <div className="constel-read">
          {active ? (
            <div className="constel-note fade-rise">
              <span className="coord signal-word">{pos(active).label}</span>
              <p className="serif" style={{ fontSize: 24, lineHeight: 1.3, marginTop: "var(--sp-3)" }}>{pos(active).note}</p>
            </div>
          ) : (
            <p className="muted coord">Touch a star to recall the insight. Connections illuminate as you go.</p>
          )}
        </div>

        <div className="layer-tag" style={{ marginTop: "var(--sp-8)" }}>
          <span className="n">02 · Reflection</span><span>The single truth</span>
        </div>
        <p className="pull serif" style={{ fontSize: 30, lineHeight: 1.22, borderColor: "var(--signal)" }}>{data.truth}</p>

        <div className="layer-tag" style={{ marginTop: "var(--sp-8)" }}>
          <span className="n">03 · Synthesis</span><span>What we carry out</span>
        </div>
        <p className="identity serif">{data.identity}</p>
        <p className="measure muted" style={{ marginTop: "var(--sp-4)" }}>{data.closing}</p>

        <div className="constel-foot">
          <span className="coord">{litCount} / {data.stars.length} insights recalled · the expedition is complete</span>
          <div className="row">
            <button className="btn" onClick={onRestart}>Return to the atlas</button>
            <button className="btn btn--signal btn--lg" onClick={onFinish}>Close the field notebook ✓</button>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Iceberg, River, MountainPass, Constellation });
