/* ===========================================================
   Reiktable — dice engine + Dice view
   Exposes (window): rollLog, DiceView, charTotal, skillTotal
   =========================================================== */
(function () {
  const { useState } = React;

  // total of a characteristic
  window.charTotal = (cmap, k) => {
    const c = cmap[k]; if (!c) return 0; return (c.base || 0) + (c.adv || 0);
  };
  // skill display target: explicit pct override OR char total + advances
  window.skillTotal = (charsMap, sk) => {
    if (sk.pct != null) return sk.pct;
    return window.charTotal(charsMap, sk.char) + (sk.adv || 0);
  };

  // perform a WFRP test, log it
  window.rollLog = function (entry) {
    const r = window.WFRP.rollTest(entry.target);
    const rec = {
      id: window.WFRP.ID(), t: Date.now(),
      who: entry.who || "—", label: entry.label || "Test",
      ...r,
    };
    window.Store.update(s => {
      s.rolls = [rec, ...(s.rolls || [])].slice(0, 60);
    });
    const txt = r.crit ? "Critical!" : r.fumble ? "Fumble!" : r.success ? "Success" : "Failure";
    window.toast(`${entry.who ? entry.who + " · " : ""}${entry.label}: ${r.roll} → ${txt} (${r.sl >= 0 ? "+" : ""}${r.sl} SL)`,
      r.success ? "grn" : "red");
    return rec;
  };

  function SLBadge({ r }) {
    if (r.crit) return <span className="tag grn">CRIT · +{r.sl} SL</span>;
    if (r.fumble) return <span className="tag red">FUMBLE · {r.sl} SL</span>;
    if (r.success) return <span className="tag grn">SUCCESS · +{r.sl} SL</span>;
    return <span className="tag red">FAIL · {r.sl} SL</span>;
  }
  window.SLBadge = SLBadge;

  // ---------------- Dice View ----------------
  window.DiceView = function () {
    const [s] = window.useStore();
    const pcs = s.characters;
    const [who, setWho] = useState(pcs[0] ? pcs[0].id : "");
    const [mode, setMode] = useState("char"); // char | skill
    const [pick, setPick] = useState("WS");
    const [mod, setMod] = useState(0);
    const [last, setLast] = useState(null);
    const [rolling, setRolling] = useState(false);

    const pc = pcs.find(c => c.id === who) || pcs[0];
    const base = mode === "char"
      ? window.charTotal(pc.chars, pick)
      : (() => { const sk = pc.skills.find(x => x.name === pick); return sk ? window.skillTotal(pc.chars, sk) : 0; })();
    const target = Math.max(1, base + mod);
    const label = mode === "char"
      ? (window.WFRP.CHARS.find(c => c.k === pick)?.name || pick)
      : pick;

    function doRoll() {
      setRolling(true);
      setTimeout(() => {
        const rec = window.rollLog({ who: pc.name, label: `${label} (${target})`, target });
        setLast(rec); setRolling(false);
      }, 280);
    }

    // generic dice
    const [gen, setGen] = useState(null);
    function genRoll(sides, count) {
      const rolls = Array.from({ length: count }, () => Math.floor(Math.random() * sides) + 1);
      const sum = rolls.reduce((a, b) => a + b, 0);
      setGen({ sides, count, rolls, sum });
      window.toast(`${count}d${sides}: [${rolls.join(", ")}] = ${sum}`);
    }

    return (
      <div className="content fade-in">
        <div className="page-h"><div><h1>Dice & Tests</h1><p>WFRP d100 tests with automatic Success Levels, criticals and fumbles.</p></div></div>
        <div className="cols s">
          <div className="card">
            <div className="card-h"><Icon name="dice" /><h3>Characteristic / Skill Test</h3></div>
            <div className="card-b">
              <div className="grid g3" style={{ marginBottom: 14 }}>
                <Field label="Character">
                  <select className="input" value={who} onChange={e => { setWho(e.target.value); }}>
                    {pcs.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </Field>
                <Field label="Test">
                  <select className="input" value={mode} onChange={e => { setMode(e.target.value); setPick(e.target.value === "char" ? "WS" : (pc.skills[0]?.name || "")); }}>
                    <option value="char">Characteristic</option>
                    <option value="skill">Skill</option>
                  </select>
                </Field>
                <Field label="Modifier">
                  <select className="input mono" value={mod} onChange={e => setMod(parseInt(e.target.value))}>
                    {[-30,-20,-10,0,10,20,30,40].map(m => <option key={m} value={m}>{m >= 0 ? "+" + m : m} {m === 0 ? "" : m > 0 ? "(easy)" : "(hard)"}</option>)}
                  </select>
                </Field>
              </div>
              <Field label={mode === "char" ? "Characteristic" : "Skill"}>
                {mode === "char" ? (
                  <div className="chars" style={{ gridTemplateColumns: "repeat(5,1fr)" }}>
                    {window.WFRP.CHARS.map(c => (
                      <div key={c.k} className={cls("ch click", pick === c.k && "on")} onClick={() => setPick(c.k)}
                        style={pick === c.k ? { borderColor: "var(--acc)", background: "var(--acc-soft)" } : {}}>
                        <div className="nm">{c.k}</div>
                        <div className="v">{window.charTotal(pc.chars, c.k)}</div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <select className="input" value={pick} onChange={e => setPick(e.target.value)}>
                    {pc.skills.length === 0 && <option>No skills on this sheet</option>}
                    {pc.skills.map(sk => <option key={sk.name} value={sk.name}>{sk.name} — {window.skillTotal(pc.chars, sk)}%</option>)}
                  </select>
                )}
              </Field>

              <div className="between" style={{ marginTop: 18, padding: "14px 16px", background: "var(--bg-2)", borderRadius: 10, border: "1px solid var(--line)" }}>
                <div>
                  <div className="eyebrow">Target Number</div>
                  <div className="mono" style={{ fontSize: 30, color: "var(--cyan)", lineHeight: 1 }}>{target}<span style={{ fontSize: 14, color: "var(--tx-3)" }}>%</span></div>
                  <div className="tx3" style={{ fontSize: 12 }}>{base} base {mod !== 0 ? `· ${mod > 0 ? "+" : ""}${mod} mod` : ""}</div>
                </div>
                {last && !rolling && (
                  <div className="center g12">
                    <div className={cls("die lg", last.crit && "crit", !last.crit && last.success && "hit", !last.success && "miss")}>{last.roll === 100 ? "00" : String(last.roll).padStart(2, "0")}</div>
                    <SLBadge r={last} />
                  </div>
                )}
                {rolling && <div className="die lg roll">··</div>}
                <Btn className="pri" icon="dice" onClick={doRoll}>Roll d100</Btn>
              </div>
            </div>
          </div>

          <div className="col g16">
            <div className="card">
              <div className="card-h"><Icon name="swords" /><h3>Quick Dice</h3></div>
              <div className="card-b">
                <div className="grid g4" style={{ gap: 8 }}>
                  {[["d100",100,1],["d20",20,1],["d10",10,1],["d6",6,1],["2d6",6,2],["3d6",6,3],["d10×2",10,2],["d4",4,1]].map(([lbl, sides, count]) => (
                    <Btn key={lbl} className="sm" onClick={() => genRoll(sides, count)}>{lbl}</Btn>
                  ))}
                </div>
                {gen && (
                  <div className="between" style={{ marginTop: 12, padding: "10px 14px", background: "var(--bg-2)", borderRadius: 9 }}>
                    <span className="mono tx2" style={{ fontSize: 13 }}>{gen.count}d{gen.sides}: [{gen.rolls.join(", ")}]</span>
                    <span className="mono" style={{ fontSize: 22, color: "var(--amb)" }}>{gen.sum}</span>
                  </div>
                )}
              </div>
            </div>
            <div className="card">
              <div className="card-h"><Icon name="clock" /><h3>Roll Log</h3><span className="x">{(s.rolls || []).length}</span></div>
              <div className="card-b tight scroll-y" style={{ maxHeight: 340 }}>
                {(s.rolls || []).length === 0 && <div className="empty" style={{ padding: 30 }}><div className="tx3">No rolls yet.</div></div>}
                {(s.rolls || []).map(r => (
                  <div key={r.id} className="log-row">
                    <span className={cls("dot")} style={{ background: r.success ? "var(--grn)" : "var(--red)" }}></span>
                    <span className="who">{r.who}</span>
                    <span className="tx3" style={{ fontSize: 12 }}>{r.label}</span>
                    <span className="res" style={{ color: r.success ? "var(--grn)" : "var(--red)" }}>{r.roll === 100 ? "00" : String(r.roll).padStart(2, "0")} · {r.sl >= 0 ? "+" : ""}{r.sl}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };
})();
