/* Unified soft-delete trash bin used across the whole site.
   Items go to localStorage (kcc_trash_global) and are removable from D1.
   Restoration re-PUTs to the right collection and re-injects into the in-memory list. */

const KCC_TRASH_KEY = "kcc_trash_global";

// Map between "type" used in trash and the actual D1 col + window array name
const KCC_ENTITY = {
  suppliers: { col: "suppliers", arr: () => window.SUPPLIERS, label: "Fournisseur" },
  products:  { col: "products",  arr: () => window.PRODUCTS,  label: "Produit" },
  tasks:     { col: "tasks",     arr: () => window.TASKS,     label: "Tâche" },
  shipments: { col: "shipments", arr: () => window.SHIPMENTS, label: "Expédition" },
  alerts:    { col: "alerts",    arr: () => window.ALERTS,    label: "Alerte" },
  returns:   { col: "returns",   arr: () => window.RETURNS,   label: "Retour" },
  expenses:  { col: "expenses",  arr: () => window.EXPENSES,  label: "Dépense" },
  catalogs:  { col: "catalogs",  arr: () => window.CATALOGS,  label: "Catalogue" },
  asins:     { col: "asins",     arr: () => window.ASIN_LIBRARY, label: "ASIN" },
  accounts:  { col: "accounts",  arr: () => window.OPEN_ACCOUNTS, label: "Compte" },
  picks:     { col: "picks",     arr: () => window.DAILY_PICKS,   label: "Pick" },
};

const _readTrash = () => {
  try { return JSON.parse(localStorage.getItem(KCC_TRASH_KEY) || "[]"); }
  catch { return []; }
};
const _writeTrash = (list) => {
  try { localStorage.setItem(KCC_TRASH_KEY, JSON.stringify(list)); } catch {}
  // notify listeners (in-page only)
  try { window.dispatchEvent(new CustomEvent("kcc-trash-changed", { detail: { count: list.length } })); } catch {}
};

const KCCTrash = {
  list() { return _readTrash(); },
  count() { return _readTrash().length; },

  // Move an entity to the trash, remove it from its in-memory array, and delete it from D1.
  async send(type, item, { skipRemote = false } = {}) {
    if (!item || !item.id) return;
    const entity = KCC_ENTITY[type];
    const arr = entity?.arr?.();
    if (Array.isArray(arr)) {
      const idx = arr.findIndex(x => x.id === item.id);
      if (idx >= 0) arr.splice(idx, 1);
    }
    const trash = _readTrash();
    trash.push({ ...item, _kccType: type, _kccCol: entity?.col || type, _trashedAt: Date.now() });
    _writeTrash(trash);
    if (!skipRemote && entity?.col) {
      try {
        await fetch(`/api/sync?col=${encodeURIComponent(entity.col)}&id=${encodeURIComponent(item.id)}`, { method: "DELETE" });
      } catch (_) {}
    }
  },

  // Restore from trash: PUT it back to D1 and push to in-memory array.
  async restore(id) {
    const trash = _readTrash();
    const item = trash.find(t => t.id === id);
    if (!item) return null;
    const type = item._kccType;
    const col = item._kccCol || KCC_ENTITY[type]?.col || type;
    const { _kccType, _kccCol, _trashedAt, ...clean } = item;
    const arr = KCC_ENTITY[type]?.arr?.();
    if (Array.isArray(arr) && !arr.find(x => x.id === clean.id)) arr.push(clean);
    _writeTrash(trash.filter(t => t.id !== id));
    if (col) {
      try {
        await fetch("/api/sync", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ col, items: [clean] }),
        });
      } catch (_) {}
    }
    return clean;
  },

  // Permanently remove a single item from the trash.
  remove(id) {
    _writeTrash(_readTrash().filter(t => t.id !== id));
  },

  // Empty all
  empty() { _writeTrash([]); },

  // Convenience: subscribe to changes (returns unsubscribe)
  subscribe(handler) {
    const fn = (e) => handler(e.detail?.count ?? _readTrash().length);
    window.addEventListener("kcc-trash-changed", fn);
    return () => window.removeEventListener("kcc-trash-changed", fn);
  },

  entityLabel(type) { return KCC_ENTITY[type]?.label || type; },
};

window.KCCTrash = KCCTrash;
window.KCC_ENTITY = KCC_ENTITY;

// React hook for components that need to render trash count / list
const useKCCTrash = () => {
  const [items, setItems] = React.useState(() => KCCTrash.list());
  React.useEffect(() => {
    const unsub = KCCTrash.subscribe(() => setItems(KCCTrash.list()));
    return unsub;
  }, []);
  return {
    items,
    count: items.length,
    send: async (type, item) => { await KCCTrash.send(type, item); setItems(KCCTrash.list()); },
    restore: async (id) => { const r = await KCCTrash.restore(id); setItems(KCCTrash.list()); return r; },
    remove: (id) => { KCCTrash.remove(id); setItems(KCCTrash.list()); },
    empty: () => { KCCTrash.empty(); setItems([]); },
  };
};

window.useKCCTrash = useKCCTrash;
