/* global React */
const { useState: useState_s, useEffect: useEffect_s, useSyncExternalStore } = React;

/* =================================================
   Tiny global store for cart, user, saved.
   Persists to localStorage. Subscribers re-render via a custom event.
================================================= */

const STORAGE_KEY = "halden-store-v1";

function readStorage() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch (e) { return null; }
}

const initial = readStorage() || {
  cart: [],
  user: null,
  saved: [],
  ui: { cartOpen: false, searchOpen: false },
};

window.__store = window.__store || initial;

function writeStorage() {
  const { ui, ...rest } = window.__store;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(rest));
}

function emit() {
  window.dispatchEvent(new CustomEvent("halden:store"));
}

function subscribe(fn) {
  window.addEventListener("halden:store", fn);
  return () => window.removeEventListener("halden:store", fn);
}

/* mutation helpers */
const Store = {
  addToCart(item) {
    const cart = [...window.__store.cart];
    const existing = cart.find(
      (l) => l.id === item.id && l.upholstery === item.upholstery && l.leg === item.leg
    );
    if (existing) existing.qty += item.qty || 1;
    else cart.push({ ...item, qty: item.qty || 1 });
    window.__store = { ...window.__store, cart };
    writeStorage();
    emit();
  },
  updateQty(idx, qty) {
    const cart = [...window.__store.cart];
    if (qty <= 0) cart.splice(idx, 1);
    else cart[idx] = { ...cart[idx], qty };
    window.__store = { ...window.__store, cart };
    writeStorage();
    emit();
  },
  removeFromCart(idx) {
    const cart = [...window.__store.cart];
    cart.splice(idx, 1);
    window.__store = { ...window.__store, cart };
    writeStorage();
    emit();
  },
  clearCart() {
    window.__store = { ...window.__store, cart: [] };
    writeStorage();
    emit();
  },
  signIn(user) {
    window.__store = { ...window.__store, user };
    writeStorage();
    emit();
  },
  signOut() {
    window.__store = { ...window.__store, user: null };
    writeStorage();
    emit();
  },
  toggleSaved(id) {
    let saved = [...window.__store.saved];
    if (saved.includes(id)) saved = saved.filter((s) => s !== id);
    else saved.push(id);
    window.__store = { ...window.__store, saved };
    writeStorage();
    emit();
  },
  setUI(patch) {
    window.__store = { ...window.__store, ui: { ...window.__store.ui, ...patch } };
    emit();
  },
};

/* hook */
function useStore(selector = (s) => s) {
  return useSyncExternalStore(
    subscribe,
    () => selector(window.__store),
    () => selector(window.__store)
  );
}

/* derived: subtotal */
function cartSubtotal() {
  return window.__store.cart.reduce((sum, l) => sum + l.price * l.qty, 0);
}

function formatPrice(n) {
  return "$" + n.toLocaleString("en-US");
}

Object.assign(window, { Store, useStore, cartSubtotal, formatPrice });
