// Spellstash: the shared deck VERSION picker (docs/deck-versions/SPEC-VERSION-PICKERS.md).
// Every tool that takes "one of my decks" can also take a version of it.
// A version is a LIST (oracle_id + qty). It has no printing, finish,
// condition, location or sideboard, so tools read it like a pasted list.
//
// No build step: loaded as its own Babel script AFTER spellstash-auth.jsx and
// BEFORE the page script. Exposes window.ssDeckVersions:
//   list(containerId)   -> Promise<[{ id, name, card_count, position }]>  (never rejects; [] on any failure)
//   listResult(cid)     -> Promise<{ ok, rows }>  (ok:false = the call failed, rows:[])
//   load(versionId)     -> Promise<{ version, container, cards, lines }>  (rejects with a human Error)
//   asInstances(cards)  -> container-instance-shaped rows for Deck Tech style readers
//   linesOf(cards)      -> "QTY Name" text
//   heading(deck, ver)  -> "<Deck> · <Version>" (just the deck name when ver is empty)
//   readUrlVersion()    -> ?version=<vid> as a Number, or null
//   writeUrlVersion(v)  -> sets / clears ?version= with history.replaceState
//   Picker({ containerId, value, onChange, onTrack, tool, style, labelStyle, label, id, disabled })
//   clearCache()
//
// Analytics: the Picker fires VersionToolPick { tool } once per user pick of
// a version (not for "In the box", not for a deep-link preselect), through
// onTrack(name, props) when given, else window.plausible. Pages should NOT
// also fire it themselves.
(() => {
  const { useState, useEffect, useRef } = React;

  const listCache = new Map(); // containerId -> Promise<array>
  const loadCache = new Map(); // versionId -> Promise<payload>

  function authed(url) {
    if (window.ssAuth && typeof window.ssAuth.authedFetch === "function") return window.ssAuth.authedFetch(url);
    return fetch(url, { credentials: "same-origin" });
  }

  function validId(v) {
    const n = Number(v);
    return Number.isInteger(n) && n > 0 ? n : null;
  }

  // Versions of a deck, in position order. Any failure (signed out, 400 for a
  // non-deck, 404, 503 versions_not_ready, network) resolves to [] so a tool
  // never blocks on this call. Failures are not cached; successes are, per
  // page load (clearCache() resets).
  // listResult(containerId) -> Promise<{ ok, rows }>. ok:false means the call
  // failed (so "this version is not in the deck" cannot be concluded);
  // ok:true with rows:[] means the deck really has no versions.
  function listResult(containerId) {
    const cid = validId(containerId);
    if (!cid) return Promise.resolve({ ok: false, rows: [] });
    if (listCache.has(cid)) return listCache.get(cid);
    const p = (async () => {
      try {
        const r = await authed(`/api/containers/${cid}/versions`);
        if (!r.ok) throw new Error("versions " + r.status);
        const data = await r.json();
        const rows = Array.isArray(data && data.versions) ? data.versions : [];
        return {
          ok: true,
          rows: rows
            .filter((v) => v && validId(v.id) && v.name)
            .map((v) => ({ id: Number(v.id), name: String(v.name), card_count: Number(v.card_count) || 0, position: Number(v.position) || 0 }))
            .sort((a, b) => a.position - b.position || a.id - b.id),
        };
      } catch (e) {
        listCache.delete(cid);
        return { ok: false, rows: [] };
      }
    })();
    listCache.set(cid, p);
    return p;
  }

  function list(containerId) {
    return listResult(containerId).then((res) => res.rows);
  }

  function linesOf(cards) {
    return (cards || [])
      .filter((c) => c && c.name && Number(c.qty) > 0)
      .map((c) => `${Number(c.qty)} ${c.name}`)
      .join("\n");
  }

  // One version's list. Rejects with an Error whose message can be shown.
  function load(versionId) {
    const vid = validId(versionId);
    if (!vid) return Promise.reject(new Error("That version link is not valid."));
    if (loadCache.has(vid)) return loadCache.get(vid);
    const p = (async () => {
      let r;
      try { r = await authed(`/api/versions/${vid}`); } catch (e) { throw new Error("Could not load that version. Check your connection."); }
      if (r.status === 404) throw new Error("That version is gone. It may have been deleted.");
      if (r.status === 401) throw new Error("Sign in to open your deck versions.");
      if (!r.ok) throw new Error("Could not load that version right now.");
      const data = await r.json().catch(() => null);
      if (!data || !data.version || !Array.isArray(data.cards)) throw new Error("Could not read that version.");
      return { version: data.version, container: data.container || null, cards: data.cards, totals: data.totals || null, lines: linesOf(data.cards) };
    })();
    loadCache.set(vid, p);
    p.catch(() => loadCache.delete(vid));
    return p;
  }

  // Rows shaped like GET /api/containers/:id instances[] (containers.js puts
  // the card fields FLAT on the row) plus a nested `card` object, so readers
  // of either shape work. deck-tech-engine.js flattenDeck reads `inst.card ||
  // inst`, so the nested object carries every field the engine reads.
  // Physical fields are null: a list line has no printing, finish, condition,
  // sleeve, location or move history. `id` is a string ("ver-<oracle_id>")
  // so React keys stay unique; never send it to an /api/instances route.
  function asInstances(cards) {
    return (cards || [])
      .filter((c) => c && c.oracle_id && Number(c.qty) > 0)
      .map((c) => {
        const card = {
          oracle_id: c.oracle_id,
          name: c.name || null,
          type_line: c.type_line || null,
          mana_cost: c.mana_cost || null,
          cmc: typeof c.cmc === "number" ? c.cmc : null,
          color_identity: Array.isArray(c.color_identity) ? c.color_identity : null,
          keywords: Array.isArray(c.keywords) ? c.keywords : null,
          oracle_text: c.oracle_text || null,
          edhrec_rank: typeof c.edhrec_rank === "number" ? c.edhrec_rank : null,
          image_small: c.image_small || null,
          image_normal: c.image_normal || null,
        };
        return {
          id: "ver-" + c.oracle_id,
          oracle_id: c.oracle_id,
          quantity: Number(c.qty),
          ...card,
          card_name: card.name,
          card,
          finish: null, condition: null, set_code: null, collector_number: null,
          sleeved: false, is_sideboard: false, variant: null, notes: null,
          added_at: null, last_moved_at: null, home_container_id: null,
          from_version: true,
        };
      });
  }

  function heading(deckName, versionName) {
    const d = String(deckName || "").trim() || "My deck";
    const v = String(versionName || "").trim();
    return v ? `${d} · ${v}` : d;
  }

  function readUrlVersion() {
    try { return validId(new URLSearchParams(location.search).get("version")); } catch (e) { return null; }
  }

  function writeUrlVersion(versionId) {
    try {
      const u = new URL(location.href);
      const vid = validId(versionId);
      if (vid) u.searchParams.set("version", String(vid));
      else u.searchParams.delete("version");
      history.replaceState(history.state, "", u.pathname + u.search + u.hash);
    } catch (e) { /* URL sync is a convenience */ }
  }

  function clearCache() { listCache.clear(); loadCache.clear(); }

  const SELECT = {
    width: "100%", maxWidth: 500, minHeight: 44, boxSizing: "border-box",
    padding: "0 0.8rem", background: "var(--bg-2)", color: "var(--ink)",
    border: "1px solid var(--line)", borderRadius: 6,
    fontFamily: "var(--cm-sans)", fontSize: "0.95rem",
  };
  const LABEL = {
    display: "block", margin: "0.7rem 0 0.3rem", fontFamily: "var(--cm-sans)",
    fontSize: "0.85rem", fontWeight: 700, color: "var(--ink-2)",
  };

  let seq = 0;

  // The dropdown. Renders nothing until the deck is known to have at least
  // one version. value: version id (Number) or null for "In the box".
  // onChange(versionId|null, meta|null) where meta = { id, name, card_count }.
  // If `value` names a version this deck does not have (stale deep link),
  // the Picker calls onChange(null, null, { stale: true }) once the list
  // arrives. A FAILED list call never clears `value`: the page keeps the
  // version it already loaded, and the dropdown stays hidden.
  function Picker({ containerId, value, onChange, onTrack, tool, style, labelStyle, label, id, disabled }) {
    const [versions, setVersions] = useState([]);
    const idRef = useRef(id || ("ss-version-pick-" + (++seq)));
    const reqRef = useRef(0);
    const cid = validId(containerId);

    useEffect(() => {
      const req = ++reqRef.current;
      setVersions([]);
      if (!cid) return;
      listResult(cid).then((res) => {
        if (req !== reqRef.current) return;
        setVersions(res.rows);
        if (!res.ok) return;
        const want = validId(value);
        if (want && !res.rows.some((v) => v.id === want) && onChange) onChange(null, null, { stale: true });
      });
    }, [cid]); // eslint-disable-line react-hooks/exhaustive-deps

    if (!cid || versions.length === 0) return null;

    const current = validId(value);
    function pick(raw) {
      const vid = validId(raw);
      const meta = vid ? versions.find((v) => v.id === vid) || null : null;
      if (onChange) onChange(meta ? vid : null, meta);
      if (meta) {
        const props = { tool: tool || "" };
        if (typeof onTrack === "function") onTrack("VersionToolPick", props);
        else if (typeof window.plausible === "function") window.plausible("VersionToolPick", { props });
      }
    }

    return (
      <div className="ss-version-pick">
        <label htmlFor={idRef.current} style={{ ...LABEL, ...(labelStyle || {}) }}>{label || "Version"}</label>
        <select
          id={idRef.current}
          value={current && versions.some((v) => v.id === current) ? String(current) : ""}
          onChange={(e) => pick(e.target.value)}
          disabled={!!disabled}
          style={{ ...SELECT, ...(style || {}) }}
        >
          <option value="">In the box</option>
          {versions.map((v) => (
            <option key={v.id} value={String(v.id)}>
              {v.name} · {v.card_count} {v.card_count === 1 ? "card" : "cards"}
            </option>
          ))}
        </select>
      </div>
    );
  }

  window.ssDeckVersions = { list, listResult, load, asInstances, linesOf, heading, readUrlVersion, writeUrlVersion, clearCache, Picker };
})();
