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

const LS = 'bb_state_v1';
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(saved.cart || []);          // [{id, qty, opts}]
  const [wish, setWish] = useState(saved.wish || []);          // [id]
  const [drawer, setDrawer] = useState(false);
  const [toasts, setToasts] = useState([]);
  const [orders, setOrders] = useState(saved.orders || []);
  const [user,   setUser]   = useState(saved.user   || null);  // { firstName, lastName, email, phone }

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

  // routing helpers
  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);
  };

  // cart ops
  const addToCart = (prod, qty = 1, opts = {}) => {
    setCart(c => {
      const key = JSON.stringify(opts);
      const i = c.findIndex(x => x.id === prod.id && JSON.stringify(x.opts || {}) === key);
      if (i >= 0) { const n = [...c]; n[i] = { ...n[i], qty: n[i].qty + qty }; return n; }
      return [...c, { id: prod.id, qty, opts }];
    });
    toast(`Added to bag · ${prod.name}`, 'bag');
  };
  const setQty = (idx, qty) => setCart(c => qty <= 0 ? c.filter((_, i) => i !== idx) : c.map((x, i) => i === idx ? { ...x, qty } : x));
  const removeItem = (idx) => setCart(c => c.filter((_, i) => i !== idx));
  const clearCart = () => setCart([]);

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

  const cartCount = cart.reduce((s, x) => s + x.qty, 0);
  const cartLines = cart.map((line, idx) => {
    const p = BB.products.find(p => p.id === line.id);
    return { ...line, idx, product: p, lineTotal: p ? p.price * line.qty : 0 };
  }).filter(l => l.product);
  const subtotal = cartLines.reduce((s, l) => s + l.lineTotal, 0);

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

  /* ---- Auth helpers ---- */
  const signIn = (email, password) => {
    // In production replace with a real API call.
    // For now: accept any stored user whose email matches.
    const stored = JSON.parse(localStorage.getItem('hpn_users') || '[]');
    const match  = stored.find(u => u.email.toLowerCase() === email.toLowerCase() && u.password === password);
    if (match) { const { password: _, ...safe } = match; setUser(safe); return true; }
    return false;
  };
  const signUp = (data) => {
    const users = JSON.parse(localStorage.getItem('hpn_users') || '[]');
    users.push(data);
    localStorage.setItem('hpn_users', JSON.stringify(users));
    const { password: _, ...safe } = data;
    setUser(safe);
  };
  const signOut = () => { setUser(null); };

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

  const value = {
    route, nav, currency, setCurrency, money,
    cart, cartLines, cartCount, subtotal, addToCart, setQty, removeItem, clearCart,
    wish, toggleWish, drawer, setDrawer, toast, toasts, orders, placeOrder,
    user, signIn, signUp, signOut,
  };
  return <Store.Provider value={value}>{children}</Store.Provider>;
}

/* ---------- Toasts ---------- */
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' }}>
          {I[t.icon] && I[t.icon]({ width: 17, height: 17, style: { color: 'var(--gold-soft)' } })}
          {t.msg}
        </div>
      ))}
    </div>
  );
}

/* ---------- Cart drawer ---------- */
function CartDrawer() {
  const { drawer, setDrawer, cartLines, subtotal, setQty, removeItem, money, nav, cartCount } = useStore();
  return (
    <>
      <div onClick={() => setDrawer(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(42,17,51,.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 onClick={() => setDrawer(false)} aria-label="Close"><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>
              <p style={{ fontSize: 14, marginTop: 6 }}>Beautiful things await.</p>
              <button className="btn btn-primary btn-sm" style={{ marginTop: 20 }} onClick={() => { setDrawer(false); nav('shop'); }}>Browse the shop</button>
            </div>
          )}
          {cartLines.map(l => (
            <div key={l.idx} style={{ display: 'flex', gap: 14, padding: '18px 0', borderBottom: '1px solid var(--line)' }}>
              <Ph src={l.product.img} label={l.product.name} variant={l.product.ph} style={{ width: 76, height: 90, borderRadius: 'var(--r-sm)', flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ fontFamily: 'var(--serif)', fontSize: 18, lineHeight: 1.15 }}>{l.product.name}</p>
                {Object.keys(l.opts || {}).length > 0 && <p style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 3 }}>{Object.values(l.opts).join(' · ')}</p>}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4, border: '1px solid var(--line)', borderRadius: 100, padding: '3px' }}>
                    <button onClick={() => setQty(l.idx, l.qty - 1)} style={{ width: 26, height: 26, display: 'grid', placeItems: 'center', borderRadius: 100 }}><I.minus width={14} height={14} /></button>
                    <span style={{ minWidth: 18, textAlign: 'center', fontSize: 14 }}>{l.qty}</span>
                    <button onClick={() => setQty(l.idx, l.qty + 1)} style={{ width: 26, height: 26, display: 'grid', placeItems: 'center', borderRadius: 100 }}><I.plus width={14} height={14} /></button>
                  </div>
                  <span style={{ fontWeight: 500 }}>{money(l.lineTotal)}</span>
                </div>
              </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', fontSize: 15, marginBottom: 4 }}><span className="muted">Subtotal</span><span style={{ fontFamily: 'var(--serif)', fontSize: 24 }}>{money(subtotal)}</span></div>
            <p style={{ fontSize: 12, color: 'var(--ink-faint)', marginBottom: 16 }}>Shipping & taxes calculated at checkout.</p>
            <button className="btn btn-gold 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 full bag</button>
          </footer>
        )}
      </aside>
    </>
  );
}

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