/* ============================================================
   Global store: routing, cart, wishlist, orders, toasts
   ============================================================ */
const Store = createContext(null);
const useStore = () => useContext(Store);

const LS = 'gaf_state_v2';
function loadState() {
  try { return JSON.parse(localStorage.getItem(LS)) || {}; } catch { return {}; }
}

function StoreProvider({ children }) {
  const saved = loadState();
  const _CUR = BB.BRAND.currency;
  const [route, setRoute] = useState({ page: 'home', params: {} });
  const [currency, setCurrency] = useState([_CUR.primary.code, _CUR.secondary.code].includes(saved.currency) ? saved.currency : _CUR.primary.code);
  const [cart, setCart] = useState(Array.isArray(saved.cart) ? saved.cart : []); // [{id, qty}]
  const [wish, setWish] = useState(saved.wish || []);
  const [drawer, setDrawer] = useState(false);
  const [toasts, setToasts] = useState([]);
  const [orders, setOrders] = useState(saved.orders || []);

  useEffect(() => {
    localStorage.setItem(LS, JSON.stringify({ currency, cart, wish, orders }));
  }, [currency, cart, wish, orders]);

  const nav = (page, params = {}) => {
    setRoute({ page, params });
    window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    setDrawer(false);
  };

  const toast = (msg, icon = 'check') => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, msg, icon }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 2600);
  };

  const fmt = (ngn) => BB.money(ngn, currency);

  const addToCart = (prod, qty = 1) => {
    setCart(c => c.some(x => x.id === prod.id)
      ? c.map(x => x.id === prod.id ? { ...x, qty: Math.min(x.qty + qty, prod.stock || 99) } : x)
      : [...c, { id: prod.id, qty }]);
    toast(`Added to bag · ${prod.name}`, 'bag');
  };
  const setQty = (id, qty) => setCart(c => c.map(x => {
    if (x.id !== id) return x;
    const p = BB.products.find(pp => pp.id === id);
    return { ...x, qty: Math.max(1, Math.min(qty, (p && p.stock) || 99)) };
  }));
  const removeFromCart = (id) => setCart(c => c.filter(x => x.id !== id));
  const clearCart = () => setCart([]);

  const toggleWish = (id) => setWish(w => w.includes(id) ? w.filter(x => x !== id) : [...w, id]);

  const cartLines = cart
    .map(line => ({ ...line, product: BB.products.find(p => p.id === line.id) }))
    .filter(l => l.product)
    .map(l => ({ ...l, total: l.product.price * l.qty }));
  const cartCount = cartLines.reduce((n, l) => n + l.qty, 0);
  const subtotal = cartLines.reduce((n, l) => n + l.total, 0);

  const shipFor = (zoneId) => {
    const S = BB.BRAND.shipping;
    const zone = S.zones.find(z => z.id === zoneId) || S.zones[0];
    return { zone, fee: subtotal >= S.free && zone.id !== 'intl' ? 0 : zone.fee };
  };

  const placeOrder = (details) => {
    const num = BB.BRAND.orderPrefix + Date.now().toString().slice(-6);
    const record = {
      num, date: new Date().toISOString(),
      lines: cartLines.map(l => ({ name: l.product.name, qty: l.qty, unit: l.product.unit, total: l.total })),
      subtotal, ...details,
    };
    setOrders(o => [record, ...o]);
    clearCart();
    return record;
  };

  const value = {
    route, nav, currency, setCurrency, fmt,
    cart, cartLines, cartCount, subtotal, shipFor,
    addToCart, setQty, removeFromCart, clearCart,
    wish, toggleWish, drawer, setDrawer, toast, toasts, orders, placeOrder,
  };
  return <Store.Provider value={value}>{children}</Store.Provider>;
}

function Toasts() {
  const { toasts } = useStore();
  return (
    <div style={{ position: 'fixed', bottom: 26, left: '50%', transform: 'translateX(-50%)', zIndex: 200, display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'center', pointerEvents: 'none' }}>
      {toasts.map(t => (
        <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'var(--ink)', color: 'var(--cream)', padding: '13px 22px', borderRadius: 100, boxShadow: 'var(--shadow-lg)', animation: 'scaleIn .35s cubic-bezier(.2,.8,.2,1)', fontSize: 14, letterSpacing: '.02em', maxWidth: 'min(92vw, 520px)' }}>
          {I[t.icon] && I[t.icon]({ width: 17, height: 17, style: { color: 'var(--accent-soft)' } })}
          {t.msg}
        </div>
      ))}
    </div>
  );
}

/* Small +/- stepper used in the drawer, cart and PDP. */
function QtyStepper({ value, onChange, max = 99, unit }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 2, border: '1.5px solid var(--line)', borderRadius: 100, background: 'var(--ivory)', padding: 3 }}>
      <button onClick={() => onChange(value - 1)} disabled={value <= 1} aria-label="Decrease"
        style={{ width: 34, height: 34, borderRadius: 100, display: 'grid', placeItems: 'center', fontSize: 18, lineHeight: 1, color: value <= 1 ? 'var(--ink-faint)' : 'var(--ink)', cursor: value <= 1 ? 'not-allowed' : 'pointer' }}>−</button>
      <span style={{ minWidth: unit ? 76 : 34, textAlign: 'center', fontSize: 14, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
        {value}{unit ? ` ${unit}${value !== 1 ? 's' : ''}` : ''}
      </span>
      <button onClick={() => onChange(value + 1)} disabled={value >= max} aria-label="Increase"
        style={{ width: 34, height: 34, borderRadius: 100, display: 'grid', placeItems: 'center', fontSize: 18, lineHeight: 1, color: value >= max ? 'var(--ink-faint)' : 'var(--ink)', cursor: value >= max ? 'not-allowed' : 'pointer' }}>+</button>
    </div>
  );
}

function CartDrawer() {
  const { drawer, setDrawer, cartLines, removeFromCart, setQty, nav, cartCount, subtotal, fmt } = useStore();
  return (
    <>
      <div onClick={() => setDrawer(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(33,26,17,.38)', backdropFilter: 'blur(3px)', zIndex: 150, opacity: drawer ? 1 : 0, pointerEvents: drawer ? 'auto' : 'none', transition: 'opacity .4s' }} />
      <aside style={{ position: 'fixed', top: 0, right: 0, height: '100%', width: 'min(440px, 100vw)', background: 'var(--cream)', zIndex: 151, boxShadow: 'var(--shadow-lg)', transform: drawer ? 'none' : 'translateX(100%)', transition: 'transform .5s cubic-bezier(.2,.8,.2,1)', display: 'flex', flexDirection: 'column' }}>
        <header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '24px 28px', borderBottom: '1px solid var(--line)' }}>
          <h3 style={{ fontSize: 26 }}>Your Bag <span style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-soft)' }}>({cartCount})</span></h3>
          <button className="icobtn" onClick={() => setDrawer(false)} aria-label="Close" style={{ marginRight: -10 }}><I.close width={22} height={22} /></button>
        </header>
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 28px' }}>
          {cartLines.length === 0 && (
            <div style={{ textAlign: 'center', padding: '70px 0', color: 'var(--ink-soft)' }}>
              <I.bag width={42} height={42} style={{ opacity: .35, margin: '0 auto 14px' }} />
              <p style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--ink)' }}>Your bag is empty</p>
              <button className="btn btn-primary btn-sm" style={{ marginTop: 20 }} onClick={() => { setDrawer(false); nav('shop'); }}>Shop fabrics</button>
            </div>
          )}
          {cartLines.map(l => (
            <div key={l.id} style={{ display: 'flex', gap: 14, padding: '18px 0', borderBottom: '1px solid var(--line)' }}>
              <Ph src={l.product.img} label="" style={{ width: 76, height: 76, borderRadius: 'var(--r-sm)', flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <span className="cat-tag" style={{ fontSize: 9.5 }}>{BB.catOf(l.product)?.short}</span>
                <p style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 17, lineHeight: 1.15 }}>{l.product.name}</p>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginTop: 8, flexWrap: 'wrap' }}>
                  <QtyStepper value={l.qty} max={l.product.stock} onChange={q => setQty(l.id, q)} />
                  <strong style={{ fontSize: 14.5, fontVariantNumeric: 'tabular-nums' }}>{fmt(l.total)}</strong>
                </div>
                <button onClick={() => removeFromCart(l.id)} className="link-u" style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 8 }}>Remove</button>
              </div>
            </div>
          ))}
        </div>
        {cartLines.length > 0 && (
          <footer style={{ padding: '20px 28px 26px', borderTop: '1px solid var(--line)', background: 'var(--ivory)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
              <span style={{ fontSize: 14, color: 'var(--ink-soft)' }}>Subtotal</span>
              <strong style={{ fontFamily: 'var(--serif)', fontSize: 24 }}>{fmt(subtotal)}</strong>
            </div>
            <p style={{ fontSize: 12, color: 'var(--ink-faint)', marginBottom: 16 }}>Delivery calculated at checkout.</p>
            <button className="btn btn-accent btn-block" onClick={() => { setDrawer(false); nav('checkout'); }}>Checkout</button>
            <button className="btn btn-block" style={{ marginTop: 8, color: 'var(--ink-soft)' }} onClick={() => { setDrawer(false); nav('cart'); }}>View bag</button>
          </footer>
        )}
      </aside>
    </>
  );
}

Object.assign(window, { Store, useStore, StoreProvider, Toasts, CartDrawer, QtyStepper });
