/* eslint-disable */
/* Shell — shared chrome + state for every page (header, footer, cart drawer,
   VIP popup, AI Stylist, floating FAB, persistent cart in localStorage).
   Each page renders <Shell><PageContent/></Shell>. */
const LOCAL_CART_KEY = "DROP_LOCAL_CART_V1";

function loadLocalCart() {
  try { return JSON.parse(localStorage.getItem(LOCAL_CART_KEY) || "[]"); }
  catch { return []; }
}
function saveLocalCart(cart) {
  try { localStorage.setItem(LOCAL_CART_KEY, JSON.stringify(cart)); } catch {}
}

function useCart() {
  const [cart, setCart] = React.useState(loadLocalCart);
  React.useEffect(() => { saveLocalCart(cart); }, [cart]);

  // Pick the first available variant from a normalized product object so
  // quick-add (no explicit variant) still hits the Shopify Cart API.
  const pickVariant = (p) => {
    if (!p?.variants?.length) return null;
    return p.variants.find(v => v.availableForSale) || p.variants[0];
  };

  const add = (p, qty = 1, variant = null) => {
    const v = variant || pickVariant(p);
    const lineKey = (v?.id || p.id) + "";
    setCart(c => {
      const idx = c.findIndex(i => (i.variantId || i.id) + "" === lineKey);
      if (idx >= 0) {
        const copy = [...c]; copy[idx] = {...copy[idx], qty: copy[idx].qty + qty}; return copy;
      }
      return [...c, {
        ...p,
        qty,
        variantId: v?.id || null,
        variantTitle: v?.title || null,
        unitPrice: v?.price?.amount ? parseFloat(v.price.amount) : p.price,
      }];
    });
    // Sync to Shopify cart whenever we have a real variant id. If we don't
    // (e.g. mock catalog), fall back to handle-based variant lookup so the
    // Shopify cart still gets seeded — otherwise checkout falls through.
    const sync = async () => {
      if (!window.Shopify?.isConfigured?.()) return;
      let variantId = v?.id;
      if (!variantId && p?.handle) {
        try {
          const fetched = await window.Shopify.getProduct(p.handle);
          variantId = pickVariant(fetched)?.id;
        } catch (e) { /* swallow — local cart stays valid */ }
      }
      if (variantId) {
        try { await window.Shopify.cart.add(variantId, qty); } catch (e) { /* no-op */ }
      }
    };
    sync();
    if (window.dropTrack) window.dropTrack("add_to_cart", { id: p.id, name: p.name, price: p.price });
  };
  const remove = idx => setCart(c => c.filter((_, i) => i !== idx));
  const setQty = (idx, qty) => setCart(c => c.map((i, j) => j === idx ? {...i, qty: Math.max(1, qty)} : i));
  const count = cart.reduce((s, i) => s + i.qty, 0);
  const subtotal = cart.reduce((s, i) => s + (i.unitPrice || i.price) * i.qty, 0);
  return { cart, add, remove, setQty, count, subtotal };
}

function Shell({ children, page }) {
  const { cart, add, remove, setQty, count, subtotal } = useCart();
  const [cartOpen, setCartOpen] = React.useState(false);
  const [active, setActive] = React.useState(null);
  const [aiOpen, setAiOpen] = React.useState(false);

  // Expose actions globally so non-React code (config, page scripts) can hook in.
  React.useEffect(() => {
    window.Drop = {
      addToCart: (p, qty, variant) => { add(p, qty, variant); setActive(null); setCartOpen(true); },
      openCart: () => setCartOpen(true),
      openAI: () => setAiOpen(true),
      openProduct: (p) => setActive(p),
    };
  }, [add]);

  return (
    <React.Fragment>
      <Header
        cartCount={count}
        onCart={() => setCartOpen(true)}
        onSearch={() => {}}
        onAI={() => setAiOpen(true)}
      />
      {children}
      <Footer />
      <ProductDetail product={active} onAdd={(p, qty, variant) => { add(p, qty, variant); setActive(null); setCartOpen(true); }} onClose={() => setActive(null)} />
      <CartDrawer open={cartOpen} items={cart} subtotal={subtotal} onClose={() => setCartOpen(false)} onRemove={remove} onQty={setQty} />
      <AIStylist open={aiOpen} onClose={() => setAiOpen(false)} onAdd={(p, qty) => { add(p, qty); setAiOpen(false); setCartOpen(true); }} onView={(p) => { setAiOpen(false); setActive(p); }} />
      {/* React VipPopup disabled 2026-05-10: Klaviyo's "Email & SMS Popup"
          form XwiJxN auto-injects via klaviyo.js — two popups was the bug.
          Klaviyo wins on conversion (behavioral triggers, native flow
          integration, built-in form analytics). To revert: uncomment
          <VipPopup /> and set Klaviyo form XwiJxN to draft in dashboard
          OR via PATCH /api/forms/XwiJxN/ with status=draft. */}
      {/* <VipPopup /> */}
      <button className="ai-fab" onClick={() => setAiOpen(true)} aria-label="AI Stylist">
        <span className="ai-dot"></span>
        <span>Style with AI</span>
      </button>
    </React.Fragment>
  );
}
window.Shell = Shell;
window.useCart = useCart;
