/* Mini-bible — premise / characters / threat / locations / world / motifs / forbidden,
   each with an AI builder showing how the agent assists the user. */

// PRD §12.4 top-level horror mini-bible fields.
const PremiseBuilder = ({ bible, projectId, isLive }) => {
  const fields = [
    ["fear_engine", "Fear engine", "What the audience is supposed to feel — the engine of dread."],
    ["horror_rule", "Horror rule", "The single rule that, if broken, escalates the threat."],
    ["safe_place_that_becomes_unsafe", "Safe place that becomes unsafe", "The location whose meaning inverts during the story."],
    ["final_image_strategy", "Final image strategy", "What the closing shot must do."],
  ];
  const gf = (bible && bible.genre_fields) || {};

  const save = (key) => (v) => {
    if (isLive && projectId && window.CinematonAPI) {
      const merged = { ...gf, [key]: v };
      window.CinematonAPI.patchBible(projectId, { genre_fields: merged })
        .catch((err) => console.error('bible patch failed', err));
    }
  };

  return (
    <div>
      <BuilderBar
        agent="Mini-bible agent"
        grounded="brief · threat · canon"
        status={{ label: "premise locked", tone: "ok" }}
        placeholder="e.g. 'Sharpen the fear engine'"
      />
      <div style={{ padding: 24 }}>
        <SectionHead eyebrow="Premise" title="Top-level mini-bible">
        </SectionHead>
        <div className="col gap-md">
          {fields.map(([key, label, hint]) => (
            <div key={key} className="card">
              <div className="card-title" style={{ marginBottom: 4 }}>{label}</div>
              <div className="dim" style={{ fontSize: 11, marginBottom: 8 }}>{hint}</div>
              <EditableField
                value={gf[key] || ""} serif multiline autosize
                placeholder={`Set ${label.toLowerCase()}...`}
                onSave={save(key)}
              />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const ScreenBible = ({ data }) => {
  const { brief, characters, threat, location, project } = data;
  const bible      = data._bible;
  const locations  = data._locations || (location ? [location] : []);
  const isLive     = Boolean(data._live);
  const [tab, setTab] = React.useState("premise");
  const [selectedChar, setSelectedChar] = React.useState(null);

  // Drill into a character
  if (selectedChar) {
    return (
      <div className="page" style={{ display: "grid", gridTemplateRows: "auto 1fr", height: "100%" }}>
        <PageHeader title="Mini-Bible / Character" sub={`Stage 02 / 09 · canon v${project.canon_version} · horror.v1`}>
          <span className="tag"><Icon name="lock" size={11}/> Canon locked</span>
        </PageHeader>
        <CharacterDetail
          char={selectedChar}
          refAsset={(data._refs && data._refs.character) ? data._refs.character[selectedChar.id] : null}
          clonedVoiceId={(data._character_voice || {})[selectedChar.id]}
          onBack={() => setSelectedChar(null)}
          onClose={() => setSelectedChar(null)}
        />
      </div>
    );
  }

  return (
    <div className="page" style={{ display: "grid", gridTemplateRows: "auto 1fr", height: "100%" }}>
      <PageHeader title="Mini-Bible" sub={`Stage 02 / 09 · canon v${project.canon_version} · horror.v1`}>
        <span className="tag"><Icon name="lock" size={11}/> Canon locked</span>
        <button className="btn ghost"><Icon name="regen"/> Repropose all</button>
        <button className="btn">Edit canon</button>
      </PageHeader>

      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr 360px", height: "100%", overflow: "hidden" }}>
        {/* LEFT RAIL */}
        <div className="panel">
          <div className="panel-header"><div className="htitle">Sections</div></div>
          <nav className="col" style={{ padding: 8 }}>
            {[
              ["premise",    "Premise",            4, "ok"],
              ["characters", "Characters",         characters.length, "ok"],
              ["threat",     "Threat profile",     1, "ok"],
              ["location",   "Locations",          locations.length, "ok"],
              ["world",      "World rules",        ((bible && bible.genre_fields && bible.genre_fields.world_rules) || []).length, "ok"],
              ["motifs",     "Visual & sound motifs", (((bible && bible.genre_fields && bible.genre_fields.visual_motifs) || []).length + ((bible && bible.genre_fields && bible.genre_fields.sound_motifs) || []).length), "ok"],
              ["forbid",     "Forbidden changes",  ((bible && bible.genre_fields && bible.genre_fields.forbidden_changes) || []).length, "ok"],
            ].map(([k, label, n, state]) => (
              <button key={k} onClick={() => setTab(k)}
                className="row"
                style={{
                  justifyContent: "space-between",
                  padding: "10px 12px", borderRadius: 4,
                  background: tab === k ? "var(--bg-2)" : "transparent",
                  color: tab === k ? "var(--fg)" : "var(--fg-muted)",
                  fontSize: 13, marginBottom: 2,
                  borderLeft: tab === k ? "2px solid var(--accent)" : "2px solid transparent",
                }}>
                <span>{label}</span>
                <span className="row gap-sm">
                  {state === "draft" && <span className="bib-state-dot draft" title="has open AI proposal"/>}
                  <span className="mono dim" style={{ fontSize: 10 }}>{n}</span>
                </span>
              </button>
            ))}
          </nav>

          <hr className="hr"/>

          <div style={{ padding: 12 }}>
            <div className="card-title" style={{ marginBottom: 6 }}>Agents</div>
            <div className="col gap-sm" style={{ fontSize: 11.5 }}>
              {[
                ["Mini-bible", "ok"],
                ["Character", "ok"],
                ["Threat", "ok"],
                ["Location", "ok"],
                ["Continuity", "warn"],
              ].map(([k, s]) => (
                <div key={k} className="row" style={{ justifyContent: "space-between" }}>
                  <span className="muted">{k}</span>
                  <span className={`agent-pill ${s}`}>
                    <span className="dot"/>
                    {s === "ok" ? "idle" : "1 issue"}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* CENTER */}
        <div className="scroll" style={{ padding: 0 }}>
          {tab === "premise"    && <PremiseBuilder bible={bible} projectId={project.id} isLive={isLive}/>}
          {tab === "characters" && <CharactersBuilder characters={characters} onOpen={setSelectedChar} projectId={project.id} isLive={isLive}/>}
          {tab === "threat"     && <ThreatBuilder threat={threat} brief={brief} isLive={isLive}/>}
          {tab === "location"   && <LocationBuilder location={location} locations={locations} projectId={project.id} isLive={isLive} refs={(data._refs && data._refs.location) || {}}/>}
          {tab === "world"      && <WorldRulesBuilderLive bible={bible} projectId={project.id} isLive={isLive}/>}
          {tab === "motifs"     && <MotifsBuilderLive bible={bible} projectId={project.id} isLive={isLive}/>}
          {tab === "forbid"     && <ForbiddenBuilderLive bible={bible} brief={brief} projectId={project.id} isLive={isLive}/>}
        </div>

        {/* RIGHT RAIL — canon meta */}
        <div className="panel right">
          <div className="panel-header"><div className="htitle">Canon</div></div>
          <div style={{ padding: 16 }} className="col gap-md">
            <div>
              <div className="card-title">Version</div>
              <div className="mono" style={{ fontSize: 16 }}>v{project.canon_version}</div>
              <div className="dim mono" style={{ fontSize: 11, marginTop: 4 }}>locked · 2026-04-26 14:02</div>
            </div>
            <hr className="hr"/>
            <div>
              <div className="card-title">Linked artifacts</div>
              <div className="col gap-sm" style={{ fontSize: 12 }}>
                {[["Outline", "5 scenes"], ["Screenplay", "12 pages"], ["Shots", "20 of 20"], ["Prompt packets", "20"]].map(([k, v]) => (
                  <div key={k} className="row" style={{ justifyContent: "space-between" }}>
                    <span className="muted">{k}</span><span className="mono">{v}</span>
                  </div>
                ))}
              </div>
            </div>
            <hr className="hr"/>
            <div>
              <div className="card-title">Recent changes</div>
              <div className="col gap-sm" style={{ fontSize: 11.5 }}>
                <div className="muted">v1.3.0 · added "shadow under door" motif</div>
                <div className="muted">v1.2.1 · tightened threat rule</div>
                <div className="muted">v1.2.0 · added Hess (supporting)</div>
                <div className="muted">v1.1.0 · world rule: floor must be empty</div>
              </div>
            </div>
            <hr className="hr"/>
            <div>
              <div className="card-title">Open proposals</div>
              <div className="col gap-sm" style={{ fontSize: 11.5 }}>
                <div className="row" style={{ justifyContent: "space-between" }}>
                  <span className="muted">World rules</span>
                  <span className="tag accent" style={{ fontSize: 10 }}>1 draft</span>
                </div>
                <div className="row" style={{ justifyContent: "space-between" }}>
                  <span className="muted">Characters</span>
                  <span className="tag" style={{ fontSize: 10 }}>2 open</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ScreenBible = ScreenBible;
