/* ============================================================
   UPGRADE PICKER — vul de upgrade-slots van een schip met echte
   kaarten uit de catalogus (gefilterd op slot + factie + uniek).
   Klik een kaart → detail (feiten + opzoek-link + eigen notitie)
   → bevestigen om toe te voegen.
   ============================================================ */
const { useState: useStateUP } = React;

// directe link naar de kaartpagina op de Armada-wiki (reproduceert zelf geen tekst)
function cardWikiUrl(title) {
  return "https://starwars-armada.fandom.com/wiki/" + encodeURIComponent((title || "").replace(/ /g, "_"));
}

function UpgradePicker({ ship, fleetShips = [], onSet, onClose }) {
  const [openSlot, setOpenSlot] = useStateUP(null);
  const [q, setQ] = useStateUP("");
  const [detail, setDetail] = useStateUP(null);   // { slot, card, existing } — kaart in detailweergave
  const [note, setNote] = useStateUP("");
  const fc = FACTIONS[ship.faction] ? FACTIONS[ship.faction].color : "var(--accent)";
  const chosen = (slot) => (ship.upgrades || []).find((u) => u.slot === slot) || null;
  const upPts = (ship.upgrades || []).reduce((n, u) => n + (u.points || 0), 0);

  const openDetail = (slot, card, existing) => { setDetail({ slot, card }); setNote((existing && existing.note) || ""); };
  const confirmAdd = () => {
    const { slot, card } = detail;
    const rest = (ship.upgrades || []).filter((u) => u.slot !== slot);
    onSet([...rest, { slot, id: card.id, name: card.title, points: card.points, unique: !!card.unique, note: note.trim() || undefined }]);
    setDetail(null); setOpenSlot(null); setQ(""); setNote("");
  };
  const clear = (slot) => onSet((ship.upgrades || []).filter((u) => u.slot !== slot));

  // ---- detailweergave van één kaart ----
  if (detail) {
    const c = detail.card;
    const el = upgradeEligible(c, ship, fleetShips);
    return (
      <Dialog title={c.title} onClose={onClose}
        foot={<><button className="btn btn-ghost" onClick={() => setDetail(null)}>← Terug</button>
               <button className="btn btn-accent" disabled={!el.ok} title={el.ok ? undefined : el.reason} onClick={confirmAdd}>Voeg toe ({c.points} pts)</button></>}>
        <div className="up-detail">
          <div className="up-detail-facts">
            <span className="up-tag" style={{ "--fc": fc }}>{SLOT_LABEL[c.slot] || c.slot}</span>
            <span className="up-tag">{Array.isArray(c.faction) ? c.faction.map((f) => FACTIONS[f]?.name || f).join("/") : (FACTIONS[c.faction] ? FACTIONS[c.faction].name : "Neutraal")}</span>
            <span className="up-tag">{c.points} pts</span>
            {c.unique ? <span className="up-tag">◆ Uniek</span> : null}
            {c.ship ? <span className="up-tag">alleen: {c.ship}</span> : null}
          </div>
          {!el.ok ? <div className="import-error" style={{ marginTop: 10 }}>{el.reason}</div> : null}
          <div className="field" style={{ marginTop: 12 }}>
            <span className="lbl">Effect</span>
            {(() => {
              const eff = (typeof upgradeEffect === "function") ? upgradeEffect(c.title, c.slot) : null;
              if (eff) return <div className="up-effect-text">{eff}</div>;
              return (
                <>
                  <div className="mono up-note-info">
                    De kaarttekst is nog niet geladen. Laad je eigen effect-bestand via “Kaarteffecten” in het menu, open de kaart op de Armada-wiki, of vul hieronder je eigen korte omschrijving in.
                  </div>
                  <a className="btn btn-ghost" href={cardWikiUrl(c.title)} target="_blank" rel="noopener noreferrer" style={{ marginTop: 8, display: "inline-flex" }}>
                    📖 Open “{c.title}” op de Armada-wiki
                  </a>
                </>
              );
            })()}
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <span className="lbl">Jouw notitie</span>
            <textarea className="textarea" style={{ minHeight: 90 }} value={note} spellCheck={false}
                      placeholder="bv. kort wat de kaart doet…" onChange={(e) => setNote(e.target.value)} />
          </div>
        </div>
      </Dialog>
    );
  }

  return (
    <Dialog title={`Upgrades — ${ship.name}`} onClose={onClose}
      foot={<><span className="mono" style={{ flex: 1, color: "var(--text-dim)", fontSize: 12 }}>Schip {ship.points} + upgrades {upPts} = <b style={{ color: "var(--text)" }}>{ship.points + upPts}</b> pts</span>
             <button className="btn btn-accent" onClick={onClose}>Klaar</button></>}>
      {ship.slots && ship.slots.length ? ship.slots.map((slot) => {
        const cur = chosen(slot);
        const open = openSlot === slot;
        const cards = upgradesForSlot(slot, ship.faction).filter((c) => (c.title || "").toLowerCase().includes(q.toLowerCase()));
        return (
          <div className="up-slot" key={slot}>
            <div className="up-slot-head">
              <span className="lbl" style={{ color: fc }}>{SLOT_LABEL[slot] || slot}</span>
              {cur ? (
                <>
                  <span className="up-cur">{cur.name}{cur.unique ? " ◆" : ""}{cur.note ? " · 📝" : ""}</span>
                  <span className="mono up-cur-pts">{cur.points}</span>
                  <button className="btn btn-sq" title="Info / notitie" style={{ width: "auto", height: 26, padding: "0 8px", fontSize: 11 }}
                          onClick={() => openDetail(slot, (upgradesForSlot(slot, ship.faction).find((x) => x.id === cur.id) || { id: cur.id, title: cur.name, points: cur.points, slot, faction: ship.faction, unique: cur.unique }), cur)}>ℹ</button>
                  <button className="btn btn-sq" style={{ width: "auto", height: 26, padding: "0 8px", fontSize: 10.5 }} onClick={() => clear(slot)}>✕</button>
                </>
              ) : <span className="up-empty mono">leeg</span>}
              <button className="btn btn-sq" style={{ width: "auto", height: 26, padding: "0 10px", fontSize: 10.5 }} onClick={() => { setOpenSlot(open ? null : slot); setQ(""); }}>
                {open ? "Sluit" : cur ? "Wijzig" : "Kies"}
              </button>
            </div>
            {cur && cur.note ? <div className="up-note-shown">{cur.note}</div> : null}
            {open ? (
              <div className="up-list">
                <input className="input" placeholder={`Zoek ${SLOT_LABEL[slot] || slot}…`} value={q} autoFocus onChange={(e) => setQ(e.target.value)} style={{ marginBottom: 6 }} />
                <div className="cat-list">
                  {cards.map((c) => {
                    const el = upgradeEligible(c, ship, fleetShips);
                    return (
                      <button key={c.id} className="cat-row" title={el.ok ? "Klik voor info" : el.reason}
                              style={{ "--fc": fc, opacity: el.ok ? 1 : 0.5 }} onClick={() => openDetail(slot, c, cur && cur.id === c.id ? cur : null)}>
                        <span className="cat-name">{c.title}{c.unique ? " ◆" : ""}</span>
                        {!el.ok ? <span className="cat-slots mono" style={{ color: "var(--bad)" }}>{el.reason}</span> : null}
                        <span className="cat-pts mono">{c.points}</span>
                        <span className="cat-add">{cur && cur.id === c.id ? "✓" : "ℹ"}</span>
                      </button>
                    );
                  })}
                  {cards.length === 0 ? <div className="mono" style={{ color: "var(--text-faint)", fontSize: 12, padding: "6px 2px" }}>Geen kaarten voor dit slot.</div> : null}
                </div>
              </div>
            ) : null}
          </div>
        );
      }) : <div className="mono" style={{ color: "var(--text-faint)", fontSize: 12 }}>Dit schip heeft geen upgrade-slots (handmatig toegevoegd schip). Voeg het via “Catalogus” toe voor echte slots.</div>}
    </Dialog>
  );
}

Object.assign(window, { UpgradePicker });
