/* eslint-disable */
/* Global shop state — cart, wishlist, compare, garage, recently-viewed.
   Persists to localStorage so reloads keep state.
   Exposed as window.useShop() — a single hook that returns { cart, wishlist, compare, garage, recents, ...actions }. */

const { useState: useState_s, useEffect: useEffect_s, useCallback: useCallback_s } = React;

const LS_KEY = "fcp.shop.v1";

function loadState() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return null;
    const v = JSON.parse(raw);
    if (typeof v !== "object" || v === null) return null;
    return v;
  } catch { return null; }
}

function saveState(s) {
  try { localStorage.setItem(LS_KEY, JSON.stringify(s)); } catch {}
}

const DEFAULT_STATE = {
  cart: [],          // [{ id, qty }]
  wishlist: [],      // [id]
  compare: [],       // [id]    (max 3)
  garage: [],        // [{ id, display, kind, ... }]
  activeVehicle: null,
  recents: [],       // [id]  (max 8)
};

function useShop() {
  const [state, setState] = useState_s(() => {
    const saved = loadState();
    return { ...DEFAULT_STATE, ...(saved || {}) };
  });

  useEffect_s(() => { saveState(state); }, [state]);

  // ----- CART -----
  const addToCart = useCallback_s((id, qty = 1) => {
    setState(s => {
      const ex = s.cart.find(c => c.id === id);
      const cart = ex
        ? s.cart.map(c => c.id === id ? { ...c, qty: c.qty + qty } : c)
        : [...s.cart, { id, qty }];
      return { ...s, cart };
    });
  }, []);
  const setCartQty = useCallback_s((id, qty) => {
    setState(s => ({
      ...s,
      cart: qty <= 0 ? s.cart.filter(c => c.id !== id) : s.cart.map(c => c.id === id ? { ...c, qty } : c),
    }));
  }, []);
  const removeFromCart = useCallback_s((id) => {
    setState(s => ({ ...s, cart: s.cart.filter(c => c.id !== id) }));
  }, []);
  const clearCart = useCallback_s(() => setState(s => ({ ...s, cart: [] })), []);

  // ----- WISHLIST -----
  const toggleWishlist = useCallback_s((id) => {
    setState(s => ({
      ...s,
      wishlist: s.wishlist.includes(id) ? s.wishlist.filter(x => x !== id) : [...s.wishlist, id],
    }));
  }, []);

  // ----- COMPARE -----
  const toggleCompare = useCallback_s((id) => {
    setState(s => {
      if (s.compare.includes(id)) return { ...s, compare: s.compare.filter(x => x !== id) };
      if (s.compare.length >= 3) return { ...s, compare: [...s.compare.slice(1), id] };
      return { ...s, compare: [...s.compare, id] };
    });
  }, []);
  const clearCompare = useCallback_s(() => setState(s => ({ ...s, compare: [] })), []);

  // ----- GARAGE -----
  const addVehicle = useCallback_s((v) => {
    const id = v.id || `v-${Date.now()}`;
    const veh = { ...v, id };
    setState(s => {
      const existing = s.garage.find(g => g.display === veh.display);
      const garage = existing ? s.garage : [veh, ...s.garage].slice(0, 6);
      return { ...s, garage, activeVehicle: veh };
    });
  }, []);
  const setActiveVehicle = useCallback_s((id) => {
    setState(s => {
      const v = s.garage.find(g => g.id === id);
      return { ...s, activeVehicle: v || null };
    });
  }, []);
  const removeVehicle = useCallback_s((id) => {
    setState(s => {
      const garage = s.garage.filter(g => g.id !== id);
      const activeVehicle = s.activeVehicle && s.activeVehicle.id === id ? (garage[0] || null) : s.activeVehicle;
      return { ...s, garage, activeVehicle };
    });
  }, []);
  const clearActiveVehicle = useCallback_s(() => setState(s => ({ ...s, activeVehicle: null })), []);

  // ----- RECENTS -----
  const pushRecent = useCallback_s((id) => {
    setState(s => {
      const recents = [id, ...s.recents.filter(x => x !== id)].slice(0, 8);
      return { ...s, recents };
    });
  }, []);

  // ----- DERIVED -----
  const getPart = (id) => (window.PARTS_DATA || []).find(p => p.id === id);
  const cartItems = state.cart.map(c => ({ ...c, part: getPart(c.id) })).filter(c => c.part);
  const cartCount = state.cart.reduce((a, c) => a + c.qty, 0);
  const cartSubtotal = cartItems.reduce((a, c) => a + (c.part.price * c.qty), 0);
  const wishlistItems = state.wishlist.map(getPart).filter(Boolean);
  const compareItems = state.compare.map(getPart).filter(Boolean);
  const recentItems = state.recents.map(getPart).filter(Boolean);

  return {
    // state
    cart: state.cart,
    cartItems, cartCount, cartSubtotal,
    wishlist: state.wishlist, wishlistItems,
    compare: state.compare, compareItems,
    garage: state.garage, activeVehicle: state.activeVehicle,
    recents: state.recents, recentItems,
    // actions
    addToCart, setCartQty, removeFromCart, clearCart,
    toggleWishlist,
    toggleCompare, clearCompare,
    addVehicle, setActiveVehicle, removeVehicle, clearActiveVehicle,
    pushRecent,
  };
}

window.useShop = useShop;
