/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * The shared "store catalogue" — the products the **admin** has selected from the
 * global catalogue (each with a quantity). This curated list is what **store
 * users** see and pick from. It's the design-stage bridge between the admin
 * catalogue page (InventoryView) and the user catalogue page (StoreCatalogView).
 *
 * Persisted in localStorage so the flow is fully demonstrable on one device; it
 * syncs live across tabs/pages via a storage event. The backend equivalents
 * (once built) are:
 *   • admin curates → POST /products/createproductlocation  (productid, qty, …)
 *   • user reads    → GET  /products/getlocationproducts
 * Swap `read`/`write` for those calls when the API is ready; the hook API stays.
 */

import { useEffect, useState } from 'react';

export interface StoreCatalogueItem {
  productid: string;
  name: string;
  image: string;
  category: string;
  sku?: string;
  price: number;
  unit: string;
  /** Quantity the admin intends to stock for this product. */
  qty: number;
}

const KEY = 'nearledaily.storeCatalogue';
const EVENT = 'nearledaily:storeCatalogue';

function read(): StoreCatalogueItem[] {
  try {
    const raw = localStorage.getItem(KEY);
    return raw ? (JSON.parse(raw) as StoreCatalogueItem[]) : [];
  } catch {
    return [];
  }
}

function write(items: StoreCatalogueItem[]): void {
  try {
    localStorage.setItem(KEY, JSON.stringify(items));
  } catch {
    /* storage unavailable */
  }
  // Notify listeners in this tab (storage event only fires in OTHER tabs).
  window.dispatchEvent(new Event(EVENT));
}

/**
 * Live view of the store catalogue + curation helpers. Re-renders whenever the
 * catalogue changes (this tab or another).
 */
export function useStoreCatalogue() {
  const [items, setItems] = useState<StoreCatalogueItem[]>(read);

  useEffect(() => {
    const sync = () => setItems(read());
    window.addEventListener(EVENT, sync);
    window.addEventListener('storage', sync);
    return () => {
      window.removeEventListener(EVENT, sync);
      window.removeEventListener('storage', sync);
    };
  }, []);

  const has = (id: string) => items.some((i) => i.productid === id);
  const getQty = (id: string) => items.find((i) => i.productid === id)?.qty ?? 0;
  const add = (item: StoreCatalogueItem) => write([...read().filter((i) => i.productid !== item.productid), item]);
  const remove = (id: string) => write(read().filter((i) => i.productid !== id));
  const setQty = (id: string, qty: number) =>
    write(read().map((i) => (i.productid === id ? { ...i, qty: Math.max(1, Math.round(qty) || 1) } : i)));

  return { items, has, getQty, add, remove, setQty };
}
