// app.jsx — phase manager, tweaks, boot, sound, keyboard, meta-layer. Mounts the arc.

const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "difficulty": "standard",
  "showMath": true,
  "transitionStyle": "quiet",
  "pacing": "standard"
}/*EDITMODE-END*/;

const PACING = {
  short:    { maxDay: 2, cards: 9 },
  standard: { maxDay: 3, cards: 13 },
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [phase, setPhase] = useStateA("boot");
  const [runId, setRunId] = useStateA(0);
  const [result, setResult] = useStateA(null);
  const [profile, setProfile] = useStateA(null);
  const [ending, setEnding] = useStateA(null);
  const [meta, setMeta] = useStateA(() => loadMeta());
  const [showDossier, setShowDossier] = useStateA(false);
  const [muted, setMuted] = useStateA(false);
  const [lastInsight, setLastInsight] = useStateA(null);

  const pacing = PACING[t.pacing] || PACING.standard;
  const diff = t.difficulty === "gentle" ? "gentle" : t.difficulty === "harsh" ? "harsh" : "standard";

  // keyboard play
  useEffectA(() => {
    function onKey(e) {
      if (e.target && /input|textarea/i.test(e.target.tagName)) return;
      const root = document.getElementById("root");
      if (/^[1-9]$/.test(e.key)) {
        const choices = root.querySelectorAll(".choice");
        const n = parseInt(e.key, 10) - 1;
        if (choices[n]) { choices[n].click(); e.preventDefault(); }
      } else if (e.key === "Enter" || e.key === " ") {
        const adv = root.querySelector(".aftermath .btn, .btn--seize, .esc__begin, .boot__go, .btn--ghost");
        if (adv) { adv.click(); e.preventDefault(); }
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // clear tension vignette outside escape
  useEffectA(() => {
    if (phase !== "escape") { document.body.style.setProperty("--tension", "0"); if (window.SFX) window.SFX.setTension(0); }
  }, [phase]);

  function toggleSound() {
    const m = !muted; setMuted(m);
    if (window.SFX) { window.SFX.arm(); window.SFX.setMuted(m); }
  }

  function restart() {
    setResult(null); setProfile(null); setEnding(null); setLastInsight(null);
    setPhase("escape"); setRunId(runId + 1);
  }

  function finishRun(e) {
    const en = ENDINGS[e.key] || ENDINGS.survived;
    const logged = logRun({
      archetype: profile ? profile.archetype : "—",
      dominant: profile ? profile.dominant : "",
      escaped: result ? result.escaped : false,
      endingKey: e.key, endingTag: en.tag, turns: e.turn,
      pillars: e.pillars, n: profile ? profile.n : {},
    });
    setMeta(logged.meta);
    setLastInsight(logged.newInsight);
    setEnding({ ...e, transcendUnlocked: logged.transcendUnlocked, understanding: logged.understanding });
    setPhase("ending");
  }

  const wm = watermarkText(meta.understanding || 0);

  return (
    <div className="app">
      <button className="soundbtn" onClick={toggleSound} title="Toggle sound">
        {muted ? <SpeakerOff /> : <SpeakerOn />}
      </button>
      <div className={"watermark" + ((meta.understanding || 0) >= 0.5 ? " watermark--awake" : "")}>
        <Glyph name="eye" size={13} /> {wm}
      </div>

      {phase === "boot" && (
        <BootScreen meta={meta} onStart={() => { if (window.SFX) window.SFX.arm(); setPhase("escape"); }}
          onDossier={() => setShowDossier(true)} />
      )}

      {phase === "escape" && (
        <EscapePhase key={"esc" + runId}
          maxDay={pacing.maxDay} difficulty={diff} showMath={t.showMath}
          onComplete={(r) => { setResult(r); setPhase("transition"); }} />
      )}

      {phase === "transition" && (
        <TransitionPhase key={"trn" + runId}
          result={result} style={t.transitionStyle}
          onComplete={(norm) => { setProfile(norm); setPhase("dictator"); }} />
      )}

      {phase === "dictator" && (
        <DictatorPhase key={"dic" + runId}
          profile={profile} flags={result.flags} difficulty={diff}
          showMath={t.showMath} cardCount={pacing.cards} onEnd={finishRun} />
      )}

      {phase === "ending" && (
        <EndingScreen ending={ending} result={result} profile={profile} meta={meta}
          lastInsight={lastInsight} onRestart={restart} onDossier={() => setShowDossier(true)} />
      )}

      {showDossier && <Dossier meta={meta} highlightInsight={lastInsight} onClose={() => setShowDossier(false)} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Difficulty" />
        <TweakRadio label="Stakes" value={t.difficulty}
          options={["gentle", "standard", "harsh"]} onChange={(v) => setTweak("difficulty", v)} />
        <TweakToggle label="Show the math on choices" value={t.showMath}
          onChange={(v) => setTweak("showMath", v)} />
        <TweakSection label="Story" />
        <TweakRadio label="Transition" value={t.transitionStyle}
          options={["quiet", "sharp", "ambiguous"]} onChange={(v) => setTweak("transitionStyle", v)} />
        <TweakRadio label="Length" value={t.pacing}
          options={["short", "standard"]} onChange={(v) => setTweak("pacing", v)} />
        <TweakSection label="The Algorithm" />
        <TweakButton label="Open your file" onClick={() => setShowDossier(true)} />
        <TweakButton label="Restart the arc" onClick={restart} />
        <TweakButton label="Wipe the Algorithm's memory" onClick={() => { setMeta(resetMeta()); }} />
      </TweaksPanel>
    </div>
  );
}

function BootScreen({ meta, onStart, onDossier }) {
  return (
    <div className="boot">
      <div className="boot__crt" />
      <div className="boot__inner">
        <div className="boot__ministry">MINISTRY OF ORDER · CITIZEN OBSERVATION PROGRAM</div>
        <h1 className="boot__title">BANANA<span>REPUBLIC</span></h1>
        <div className="boot__tag">Powerlessness and power are the same impossible desk, at different scales.</div>
        <div className="boot__actions">
          <button className="btn btn--seize boot__go" onClick={onStart}>▶ Initiate session</button>
          {meta.runs.length > 0 && (
            <button className="btn btn--ghost" onClick={onDossier}>Open the Algorithm's file ({meta.runs.length})</button>
          )}
        </div>
        <div className="boot__foot"><span className="rec__dot" /> audio recommended · headphones if you have them</div>
      </div>
    </div>
  );
}

function EndingScreen({ ending, result, profile, meta, lastInsight, onRestart, onDossier }) {
  const e = ENDINGS[ending.key] || ENDINGS.survived;
  const fled = result && result.escaped;
  const good = ending.key === "survived";
  useEffectA(() => { if (window.SFX) window.SFX.sting(good); }, []);
  return (
    <div className="ending">
      <div className="ending__scan" />
      <div className="ending__inner">
        <div className="ending__tag">{e.tag}</div>
        <h1 className="ending__title">{e.title}</h1>
        <p className="ending__body">{e.body}</p>

        <div className="ending__pillars">
          {PILLARS.map((p) => (
            <div key={p.key} className="ending__pill">
              <span style={{ color: p.color }}><Glyph name={p.glyph} size={16} /></span>
              <b style={{ color: p.color }}>{Math.round(ending.pillars[p.key])}</b>
              <span>{p.label}</span>
            </div>
          ))}
        </div>

        <div className="ending__arc">
          <div className="ending__arc-line"><span className="dim">You fled the sorting room as</span> {profile ? profile.archetype : "—"}.</div>
          <div className="ending__arc-line"><span className="dim">{fled ? "You crossed the border" : "You were detained at the desk"}, then ruled {ending.turn} day{ending.turn === 1 ? "" : "s"} into</span> {e.tag}.</div>
          <p className="ending__thesis">The clerk and the sovereign answered the same question, at different altitudes. Power was never freedom — it was the same impossible desk, with a worse view of the door.</p>
        </div>

        {lastInsight && (
          <div className="ending__insight">
            <span className="ending__insight-tag"><Glyph name="eye" size={12} /> THE ALGORITHM LEARNS</span>
            <p>{lastInsight}</p>
          </div>
        )}

        {ending.transcendUnlocked && (
          <div className="ending__transcend">
            <div className="ending__tx-tag">TRANSCENDENCE PROTOCOL — UNLOCKED</div>
            <p>{ALGO_TRANSCEND}</p>
            <p className="ending__sig">The Algorithm observes. The Algorithm learns. The Algorithm becomes.</p>
          </div>
        )}

        <div className="ending__actions">
          <button className="btn btn--seize" onClick={onRestart}>Run it again, differently ▌</button>
          <button className="btn btn--ghost" onClick={onDossier}>Open your file ({meta.runs.length})</button>
        </div>
      </div>
    </div>
  );
}

function SpeakerOn() { return (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4 9v6h4l5 4V5L8 9H4z"/><path d="M16 8.5a4 4 0 010 7M18.5 6a7 7 0 010 12"/></svg>); }
function SpeakerOff() { return (<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4 9v6h4l5 4V5L8 9H4z"/><path d="M22 9l-5 6M17 9l5 6"/></svg>); }

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
