/* ============================================================
   COMMAND PLANNER — secret dial planning, hotseat pass-device
   Each faction plans privately, then hands the device over.
   ============================================================ */
const { useState: useStateCP } = React;

function CommandPlanner({ order, ships, round, onComplete, onCancel }) {
  const [idx, setIdx] = useStateCP(0);
  const [revealed, setRevealed] = useStateCP(false); // current faction's screen unlocked?
  const [queues, setQueues] = useStateCP({});         // shipId -> [dialId,...]

  const faction = order[idx];
  const fc = FACTIONS[faction].color;
  const myShips = ships.filter((s) => s.faction === faction && !s.destroyed);

  const planFor = (ship) => {
    const need = dialsToPlan(ship, round);
    const cur = queues[ship.id] || [];
    return { need, cur };
  };
  const setDial = (shipId, slot, dialId) => {
    setQueues((q) => {
      const cur = (q[shipId] || []).slice();
      cur[slot] = dialId;
      return { ...q, [shipId]: cur };
    });
  };

  const allPlanned = myShips.every((s) => {
    const { need, cur } = planFor(s);
    return cur.filter(Boolean).length >= need;
  });

  const next = () => {
    if (idx + 1 < order.length) { setIdx(idx + 1); setRevealed(false); }
    else { onComplete(queues); }
  };

  return (
    <div className="scrim">
      <div className="dialog cp-dialog" style={{ "--fc": fc }}>
        {!revealed ? (
          <div className="cp-handoff">
            <div className="cp-lock">
              <svg width="40" height="40" viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="9" rx="2" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M8 11 V8 a4 4 0 0 1 8 0 v3" fill="none" stroke="currentColor" strokeWidth="1.6"/></svg>
            </div>
            <div className="cp-handoff-step lbl">Command-fase · Ronde {round}</div>
            <h2>Geef het apparaat aan <span style={{ color: fc }}>{FACTIONS[faction].name}</span></h2>
            <p>Alleen deze speler plant nu — verborgen voor de tegenstander. Klaar? Onthul je planscherm.</p>
            <button className="btn btn-accent btn-lg" onClick={() => setRevealed(true)}>
              <FactionDot faction={faction} size={11} /> Ik ben {FACTIONS[faction].name} — onthul
            </button>
            {idx === 0 ? <button className="btn btn-ghost" onClick={onCancel} style={{ marginTop: 8 }}>Annuleer</button> : null}
          </div>
        ) : (
          <>
            <div className="dialog-head">
              <span className="sec-accent" style={{ background: fc }} />
              <span className="dh-title">Plan dials — {FACTIONS[faction].name}</span>
              <span style={{ flex: 1 }} />
              <span className="mono cp-count">{idx + 1}/{order.length}</span>
            </div>
            <div className="dialog-body">
              <p className="cp-hint">{round === 1 ? "Ronde 1: plan zoveel dials als de command-waarde van elk schip." : "Plan één nieuwe dial per schip (onderaan de wachtrij)."}</p>
              <div className="dial-legend">
                {DIAL_ORDER.map((d) => (
                  <div className="dial-legend-item" key={d}>
                    <span className="dial-legend-badge" style={{ "--fc": fc }}>{DIALS[d].short}</span>
                    <div className="dial-legend-txt">
                      <span className="dial-legend-name">{DIALS[d].name}</span>
                      <span className="dial-legend-desc">{DIALS[d].desc}</span>
                    </div>
                  </div>
                ))}
              </div>
              {myShips.map((s) => {
                const { need, cur } = planFor(s);
                return (
                  <div className="cp-ship" key={s.id}>
                    <div className="cp-ship-head">
                      <span style={{ color: fc, display: "grid", placeItems: "center" }}><ShipGlyph baseSize={s.baseSize} color={fc} size={16} /></span>
                      <span className="cp-ship-name">{s.name}</span>
                      <span className="mono cp-ship-cmd">command {s.command}</span>
                    </div>
                    {s.commandQueue.length ? (
                      <div className="cp-queue mono">in wachtrij: {s.commandQueue.map((d) => DIALS[d].short).join(" → ")}</div>
                    ) : null}
                    <div className="cp-slots">
                      {Array.from({ length: need }).map((_, slot) => (
                        <div className="cp-slot" key={slot}>
                          <span className="cp-slot-n mono">{slot + 1}</span>
                          <div className="cp-dialpick">
                            {DIAL_ORDER.map((d) => (
                              <button key={d} className="cp-dial" data-active={(cur[slot]) === d}
                                      title={DIALS[d].desc} onClick={() => setDial(s.id, slot, d)}>{DIALS[d].short}</button>
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="dialog-foot">
              <button className="btn btn-accent" disabled={!allPlanned} onClick={next}>
                {idx + 1 < order.length ? "Klaar — volgende speler →" : "Klaar — begin ship-fase →"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CommandPlanner });
