/* ============================================================
   DICE PANEL — range gating, per-colour pool, roll, reroll, tally
   ============================================================ */
const { useState: useStateDP, useMemo: useMemoDP, useRef: useRefDP } = React;

function DicePanel() {
  const [range, setRange] = useStateDP("close");
  const [counts, setCounts] = useStateDP({ red: 0, blue: 0, black: 0 });
  const [rolled, setRolled] = useStateDP([]);
  const countsRef = useRefDP(counts);
  countsRef.current = counts;

  const changeRange = (r) => {
    setRange(r);
    // pool filtered to allowed colours (§8: rolled outcome stays)
    setCounts((c) => {
      const next = { ...c };
      DICE_ORDER.forEach((col) => { if (!dieAllowed(col, r)) next[col] = 0; });
      return next;
    });
  };

  const setCount = (col, v) => setCounts((c) => ({ ...c, [col]: Math.max(0, Math.min(8, v)) }));
  const bump = (col, d) => setCounts((c) => ({ ...c, [col]: Math.max(0, Math.min(8, c[col] + d)) }));
  const poolTotal = DICE_ORDER.reduce((n, c) => n + counts[c], 0);

  const roll = () => {
    const cur = countsRef.current;
    const dice = [];
    DICE_ORDER.forEach((col) => {
      for (let i = 0; i < cur[col]; i++) dice.push({ id: uid("d"), color: col, face: rollFace(col), rerolled: false });
    });
    setRolled(dice);
  };
  const reroll = (id) => setRolled((ds) => ds.map((d) => d.id === id ? { ...d, face: rollFace(d.color), rerolled: true } : d));
  const clear = () => { setCounts({ red: 0, blue: 0, black: 0 }); setRolled([]); };

  const tally = useMemoDP(() => tallyDice(rolled), [rolled]);

  return (
    <div>
      <div className="sec-body" style={{ paddingBottom: 12 }}>
        <div className="range-seg">
          {RANGES.map((r) => (
            <button key={r} data-active={range === r} onClick={() => changeRange(r)}>{RANGE_LABEL[r]}</button>
          ))}
        </div>

        <div className="dice-adders">
          {DICE_ORDER.map((col) => {
            const allowed = dieAllowed(col, range);
            return (
              <div className="die-adder" key={col} data-disabled={!allowed}>
                <DieChip color={col} />
                <div className="die-count-row">
                  <button onClick={() => bump(col, -1)} disabled={!allowed || counts[col] <= 0}>{"−"}</button>
                  <span className="die-count">{counts[col]}</span>
                  <button onClick={() => bump(col, +1)} disabled={!allowed || counts[col] >= 8}>+</button>
                </div>
                <span className="die-name">{DICE[col].label}</span>
              </div>
            );
          })}
        </div>

        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-accent btn-lg" style={{ flex: 1 }} onClick={roll} disabled={poolTotal === 0}>
            <svg width="16" height="16" viewBox="0 0 16 16"><rect x="2.5" y="2.5" width="11" height="11" rx="2.5" fill="none" stroke="currentColor" strokeWidth="1.4"/><circle cx="5.5" cy="5.5" r="1.2" fill="currentColor"/><circle cx="10.5" cy="10.5" r="1.2" fill="currentColor"/><circle cx="8" cy="8" r="1.2" fill="currentColor"/></svg>
            Roll {poolTotal ? `· ${poolTotal}` : ""}
          </button>
          <button className="btn btn-lg" onClick={clear} disabled={poolTotal === 0 && rolled.length === 0}>Clear</button>
        </div>
      </div>

      <div className="panel-sec" style={{ borderTop: "1px solid var(--line)" }}>
        <div className="sec-body" style={{ paddingTop: 12 }}>
          <div className={"dice-tray" + (rolled.length ? "" : " empty")}>
            {rolled.length
              ? rolled.map((d) => <Die key={d.id} d={d} onReroll={reroll} />)
              : <span className="tray-empty">Stel een pool samen en rol · tik een die om te herrollen</span>}
          </div>

          <div className="dice-result">
            <div className="res-card dmg"><div className="res-num">{tally.dmg}</div><div className="res-lbl">Schade</div></div>
            <div className="res-card crit"><div className="res-num">{tally.crit}</div><div className="res-lbl">Crits</div></div>
            <div className="res-card acc"><div className="res-num">{tally.acc}</div><div className="res-lbl">Accuracy</div></div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DicePanel });
