/* Tarot Battle UI Kit — Deck Builder */
const DECK_MAX = 15;
const DECK_FILTERS = [
  { id: "all", label: "All" }, { id: "major", label: "Major" },
  { id: "cups", label: "Cups" }, { id: "swords", label: "Swords" },
  { id: "wands", label: "Wands" }, { id: "pentacles", label: "Pentacles" }
];

function DeckLocked() {
  return (
    <div className="deck-screen deck-locked">
      <EmptyState icon="Lock" title="Deck-building unlocks as you grow">
        You start with exactly the cards you chose, so there's no deck to build yet.
        Win battles to unlock new arcana — once your collection grows past your
        starting fifteen, this is where you'll tune your deck.
      </EmptyState>
    </div>
  );
}

// Deck-building is deferred for brand-new players: until you've won at least one
// new card (owned > starting 15), the pick already IS your collection. The gate
// lives in this thin wrapper so the editor's hooks stay unconditional.
function DeckBuilder() {
  const P = window.TBProfile;
  const unlocked = P.owned().length > P.STARTER_PICK;
  React.useEffect(() => {
    if (unlocked && !P.deckNudged()) {
      P.markDeckNudged();
      tbToast("Your collection has grown — tune your deck here.", { title: "Deck Builder unlocked", icon: "Layers", duration: 4200 });
    }
  }, [unlocked]);
  return unlocked ? <DeckBuilderInner /> : <DeckLocked />;
}

function DeckBuilderInner() {
  const P = window.TBProfile;
  const owned = P.owned();
  const ownedSet = new Set(owned);
  const [deck, setDeck] = React.useState(() => {
    const d = P.deck();
    return (d && d.length) ? d : owned.slice(0, 6);
  });
  React.useEffect(() => { P.setDeck(deck); }, [deck]);
  const [filter, setFilter] = React.useState("all");
  const byId = (id) => window.TB_UNITS.find((u) => u.id === id);

  // owned cards first, then locked (shown dimmed as goals)
  const base = filter === "all" ? window.TB_UNITS : window.TB_UNITS.filter((u) => u.arcana === filter);
  const pool = base.slice().sort((a, b) => (ownedSet.has(b.id) ? 1 : 0) - (ownedSet.has(a.id) ? 1 : 0));
  const deckUnits = deck.map(byId);

  function toggle(id) {
    if (!ownedSet.has(id)) { tbToast("Locked — win battles to unlock this card.", { kind: "danger", title: "Locked" }); return; }
    setDeck((d) => {
      if (d.includes(id)) return d.filter((x) => x !== id);
      if (d.length >= DECK_MAX) { tbToast("Deck is full at " + DECK_MAX + " cards.", { kind: "danger", title: "Full" }); return d; }
      return [...d, id];
    });
  }

  // suit balance + averages
  const counts = { major: 0, cups: 0, swords: 0, wands: 0, pentacles: 0 };
  deckUnits.forEach((u) => counts[u.arcana]++);
  const avg = (key) => deckUnits.length ? (deckUnits.reduce((s, u) => s + u[key], 0) / deckUnits.length).toFixed(1) : "0.0";

  // synergy hints
  const hints = [];
  const dom = Object.entries(counts).sort((a, b) => b[1] - a[1])[0];
  if (dom && dom[1] >= 4) hints.push(<span key="d"><b>{window.TB_SUITS[dom[0]].label}-heavy.</b> Lean into a {window.TB_SUITS[dom[0]].element} core.</span>);
  if (deck.includes("king-of-swords") && counts.swords >= 3) hints.push(<span key="k"><b>King of Swords</b> grants your {counts.swords} Swords +1 Attack.</span>);
  if (deck.includes("the-emperor")) hints.push(<span key="e"><b>The Emperor</b> buffs adjacent Defense — pair with frontline units.</span>);
  if (avg("m") < 2.5 && deckUnits.length >= 5) hints.push(<span key="m">Low average Movement — you may struggle to reach objectives.</span>);
  if (!hints.length) hints.push(<span key="x">Add cards to surface synergy hints.</span>);

  return (
    <div className="deck-screen">
      <div>
        <div className="screen-head"><div className="eyebrow">Forge your fifteen</div><h1>Deck Builder</h1>
          <p>Tap any <b>owned</b> unit to add it to your deck. Locked cards are dimmed — win battles to unlock them. Balance your suits, watch the M·A·D averages, and read the synergy hints.</p></div>
        <div className="filters" style={{ marginTop: 18 }}>
          {DECK_FILTERS.map((f) => (
            <button key={f.id} className={"filter" + (filter === f.id ? " active" : "")} onClick={() => setFilter(f.id)}>
              {f.id !== "all" && <span style={{ color: filter === f.id ? "inherit" : window.TB_SUITS[f.id].color }}>{window.TB_SUITS[f.id].glyph}</span>}
              {f.label}
            </button>
          ))}
          <span style={{ marginLeft: "auto", alignSelf: "center", fontSize: 12, color: "var(--fg-3)" }}>Collection {owned.length}/{P.total()}</span>
        </div>
        <div className="pool-grid">
          {pool.map((u) => {
            const locked = !ownedSet.has(u.id);
            return (
              <div key={u.id} className={"pool-card" + (deck.includes(u.id) ? " in-deck" : "") + (locked ? " locked" : "")} onClick={() => toggle(u.id)}>
                <TarotCard unit={u} flippable={false} flipped={false} />
                {locked && <div className="lock-badge"><Icon name="Lock" size={16} /></div>}
                <div className="pc-cap"><span className="nm">{u.name}</span><span>{u.m}·{u.a}·{u.d}</span></div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="deck-panel">
        <h3>Your Deck <span className="ct">{deck.length}/{DECK_MAX}</span></h3>
        <div className="balance">
          {["major", "cups", "swords", "wands", "pentacles"].map((s) => (
            <div className="bal-row" key={s}>
              <span className="bl">{window.TB_SUITS[s].label}</span>
              <span className="bal-track"><span className="bal-fill" style={{ width: (deck.length ? counts[s] / deck.length * 100 : 0) + "%", background: window.TB_SUITS[s].color }} /></span>
              <span className="bv">{counts[s]}</span>
            </div>
          ))}
        </div>
        <div className="avg-row">
          <div className="avg m"><div className="v">{avg("m")}</div><div className="k">Avg Move</div></div>
          <div className="avg a"><div className="v">{avg("a")}</div><div className="k">Avg Atk</div></div>
          <div className="avg d"><div className="v">{avg("d")}</div><div className="k">Avg Def</div></div>
        </div>
        <div className="synergy"><Icon name="Sparkles" size={13} style={{ color: "var(--volt-green)", marginRight: 6 }} />{hints[0]}{hints[1] && <div style={{ marginTop: 6 }}>{hints[1]}</div>}</div>
        <div className="deck-list">
          {deckUnits.length === 0 && <div style={{ color: "var(--fg-3)", fontSize: 13, padding: "8px 2px" }}>No cards yet — tap units to add.</div>}
          {deckUnits.map((u) => (
            <div className="deck-item" key={u.id}>
              <span className="thumb" style={{ backgroundImage: `url('${u.img}')` }} />
              <span className="di-nm">{u.name}</span>
              <span className="di-mad">{u.m}·{u.a}·{u.d}</span>
              <span className="rm" onClick={() => toggle(u.id)}><Icon name="X" size={15} /></span>
            </div>
          ))}
        </div>
        <Btn kind="primary" icon="Check" onClick={() => { P.setDeck(deck); tbToast(deck.length + "-card deck saved — used in Battle.", { title: "Saved" }); }} disabled={!deck.length}>Save Deck</Btn>
      </div>
    </div>
  );
}
Object.assign(window, { DeckBuilder });
