// ── Symframe Pin Store ──────────────────────────────────────────────────────
// Stage C of the Dynamic Glass Panel arc — see ~/Documents/dynamic-glass-panel.md §9.3.
//
// Per-browser pin persistence via localStorage. Pinned cards survive
// page reload, /new, and gateway reconnect — they are user-curated
// state, not agent-pushed state.
//
// Storage shape:
//   localStorage["symi:symframe:pins"] = JSON.stringify({
//     version: 1,
//     pins: [
//       { id, card: {...}, pinnedAt: <ms> },
//       ...
//     ]
//   })
//
// `card` is a snapshot of the card at pin time — frozen content. A
// dynamic card whose content changes after pinning will keep the
// pinned-time snapshot in the registry on next reload (intentional;
// the user pinned what they saw).
//
// Public API (window.symframePinStore):
//   list()       — snapshot of all pinned card records
//   pin(card)    — write a card to localStorage (idempotent on id)
//   unpin(id)    — remove a card from localStorage by id
//   isPinned(id) — boolean check
// ─────────────────────────────────────────────────────────────────────────────

"use strict";

(function () {
  const KEY = "symi:symframe:pins";
  const VERSION = 1;

  function readStore() {
    try {
      const raw = localStorage.getItem(KEY);
      if (!raw) {
        return { version: VERSION, pins: [] };
      }
      const parsed = JSON.parse(raw);
      if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.pins)) {
        return { version: VERSION, pins: [] };
      }
      return parsed;
    } catch (err) {
      console.warn("[symframe-pin-store] read failed; resetting:", err);
      return { version: VERSION, pins: [] };
    }
  }

  function writeStore(store) {
    try {
      localStorage.setItem(KEY, JSON.stringify(store));
    } catch (err) {
      console.warn("[symframe-pin-store] write failed:", err);
    }
  }

  function list() {
    return readStore().pins;
  }

  function pin(card) {
    if (!card || typeof card !== "object" || !card.id) {
      console.warn("[symframe-pin-store] pin: card missing id");
      return false;
    }
    const store = readStore();
    const existing = store.pins.findIndex((p) => p.id === card.id);
    const record = {
      id: card.id,
      card: { ...card, pinned: true },
      pinnedAt: Date.now(),
    };
    if (existing >= 0) {
      store.pins[existing] = record;
    } else {
      store.pins.push(record);
    }
    writeStore(store);
    return true;
  }

  function unpin(id) {
    if (!id) {
      return false;
    }
    const store = readStore();
    const before = store.pins.length;
    store.pins = store.pins.filter((p) => p.id !== id);
    if (store.pins.length === before) {
      return false;
    }
    writeStore(store);
    return true;
  }

  function isPinned(id) {
    return readStore().pins.some((p) => p.id === id);
  }

  window.symframePinStore = { list, pin, unpin, isPinned };
})();
