/* Tarot Battle UI Kit — progression screens: starter draft + unlock reward */

function StarterSelect({ onDone }) {
  const P = window.TBProfile;
  const pool = P.STARTER_POOL.map((id) => window.TB_UNITS.find((u) => u.id === id)).filter(Boolean);
  const PICK = P.STARTER_PICK;
  const [chosen, setChosen] = React.useState([]);
  function toggle(id) {
    setChosen((c) => c.includes(id) ? c.filter((x) => x !== id) : (c.length >= PICK ? (tbToast(`Choose ${PICK}.`, { kind: "danger" }), c) : [...c, id]));
  }
  function confirm() { P.start(chosen); tbToast("Your journey begins. Win battles to unlock the rest of the arcana.", { title: "Deck forged", duration: 4000 }); onDone(); }

  return (
    <div className="screen">
      <div className="screen-head"><div className="eyebrow">Forge your beginning</div><h1>Choose your starter deck</h1>
        <p>Every reader begins with a hand of fate. Pick <b>{PICK}</b> of these {pool.length} arcana to form your starting collection — the remaining {window.TB_UNITS.length - PICK} cards are unlocked one at a time by winning battles.</p></div>
      <div className="starter-bar">
        <div className="starter-count"><span className={chosen.length === PICK ? "done" : ""}>{chosen.length}</span> / {PICK} chosen</div>
        <Btn kind="primary" icon="Check" onClick={confirm} disabled={chosen.length !== PICK}>Begin with these {PICK}</Btn>
      </div>
      <div className="starter-grid">
        {pool.map((u) => (
          <div key={u.id} className={"starter-card" + (chosen.includes(u.id) ? " on" : "")} onClick={() => toggle(u.id)}>
            <TarotCard unit={u} flippable={false} flipped={false} />
            <div className="pick-badge">{chosen.includes(u.id) ? <Icon name="Check" size={14} /> : <Icon name="Plus" size={14} />}</div>
            <div className="sc-cap"><span className="nm">{u.name}</span><span>{u.m}·{u.a}·{u.d}</span></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RewardModal({ card, wins, onClose }) {
  if (!card) return null;
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal reward" onClick={(e) => e.stopPropagation()}>
        <div className="reward-eyebrow">Victory · {wins} {wins === 1 ? "win" : "wins"}</div>
        <h3>A new arcanum joins you</h3>
        <div className="reward-card"><div style={{ width: 150, aspectRatio: "70/130" }}><TarotCard unit={card} flippable={false} flipped={false} /></div></div>
        <p style={{ textAlign: "center" }}><b>{card.name}</b> — {card.type} — is now in your collection. Add it to your deck in the Deck Builder.</p>
        <div className="actions" style={{ justifyContent: "center" }}>
          <Btn kind="primary" icon="Check" onClick={onClose}>Claim</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StarterSelect, RewardModal, AccountModal });

/* ---------- Cloud save / account ---------- */
function AccountModal({ open, onClose }) {
  const C = window.TBCloud;
  const [, bump] = React.useReducer((x) => x + 1, 0);
  const [url, setUrl] = React.useState(() => { try { return (C.creds() && C.creds().url) || localStorage.getItem("tb-server") || window.TBNet.defaultServerUrl(); } catch (e) { return ""; } });
  const [code, setCode] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [sync, setSync] = React.useState(C.lastSync());
  React.useEffect(() => {
    const onC = () => bump(); const onS = (e) => setSync(e.detail);
    window.addEventListener("tb-cloud", onC); window.addEventListener("tb-cloud-sync", onS);
    return () => { window.removeEventListener("tb-cloud", onC); window.removeEventListener("tb-cloud-sync", onS); };
  }, []);
  if (!open) return null;
  const creds = C.creds();

  async function doEnable() {
    if (!url.trim()) { tbToast("Enter your server URL first.", { kind: "danger" }); return; }
    try { localStorage.setItem("tb-server", url.trim()); } catch (e) {}
    setBusy(true);
    try { const c = await C.enable(url); tbToast("Cloud save on — keep your code safe!", { title: "Synced", icon: "Cloud" }); navigator.clipboard && navigator.clipboard.writeText(c); }
    catch (e) { tbToast(e.message || "Couldn't reach the server.", { kind: "danger" }); }
    setBusy(false); bump();
  }
  async function doLogin() {
    if (!url.trim() || !code.trim()) { tbToast("Enter the server URL and your save code.", { kind: "danger" }); return; }
    setBusy(true);
    try { await C.login(url, code); tbToast("Welcome back — progress restored.", { title: "Signed in", icon: "Cloud" }); }
    catch (e) { tbToast(e.message || "Login failed.", { kind: "danger" }); }
    setBusy(false); bump();
  }
  const saveCode = creds ? creds.id + "." + creds.token : "";

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 460 }}>
        <button className="x" onClick={onClose}><Icon name="X" size={20} /></button>
        <h3>Cloud Save</h3>
        {creds ? (
          <div>
            <p>Signed in. Your progress syncs to the cloud automatically and follows you to any device with your save code.</p>
            <div className="field" style={{ marginBottom: 14 }}>
              <label>Your save code — keep it private</label>
              <div className="code-row">
                <code className="save-code">{saveCode}</code>
                <Btn kind="ghost" icon="Copy" onClick={() => { navigator.clipboard && navigator.clipboard.writeText(saveCode); tbToast("Save code copied.", { title: "Copied" }); }}>Copy</Btn>
              </div>
            </div>
            <div className="sync-row">
              <span className={"sync-dot" + (sync ? (sync.ok ? " ok" : " bad") : "")} />
              <span>{sync ? (sync.ok ? "Last sync just now" : "Sync failed — will retry on next change") : "Synced"}</span>
            </div>
            <div className="actions">
              <Btn kind="ghost" icon="RefreshCw" onClick={() => C.push()}>Sync now</Btn>
              <Btn kind="ghost" icon="LogOut" onClick={() => { C.logout(); bump(); }}>Sign out (this device)</Btn>
            </div>
          </div>
        ) : (
          <div>
            <p>Turn on cloud save to back up your collection and play across devices. Uses your deployed Cloudflare Worker — no password, just a save code you keep.</p>
            <div className="field" style={{ marginBottom: 12 }}>
              <label>Server URL</label>
              <input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="tarot-battle.you.workers.dev" style={{ fontFamily: "var(--font-body)" }} />
            </div>
            <Btn kind="primary" icon="Cloud" onClick={doEnable} disabled={busy}>Enable Cloud Save</Btn>
            <div className="or-rule"><span>or log in on a new device</span></div>
            <div className="field" style={{ marginBottom: 12 }}>
              <label>Save code</label>
              <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="ABC123.xxxxxxxxxxxxxxxx" style={{ fontFamily: "var(--font-numeric)" }} />
            </div>
            <Btn kind="ghost" icon="LogIn" onClick={doLogin} disabled={busy}>Log in with code</Btn>
          </div>
        )}
      </div>
    </div>
  );
}
