﻿// Saraya Events — Cart layer: provider, money math (VAT / delivery / discount),
// cart drawer, and the header cart button. Persists to localStorage.

const { useState: useStateCart, useEffect: useEffectCart, useContext: useContextCart, useCallback: useCbCart } = React;

const CART_KEY = 'saraya_cart_v1';

/* money formatter — AED, no decimals unless needed */
function money(n) {
  const v = Math.round((Number(n) || 0) * 100) / 100;
  return 'AED ' + v.toLocaleString('en-AE', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
}
window.money = money;

function loadCart() {
  try { const c = JSON.parse(localStorage.getItem(CART_KEY) || '{}'); return { items: c.items || [], code: c.code || '' }; }
  catch (e) { return { items: [], code: '' }; }
}

function CartProvider({ children }) {
  const init = loadCart();
  const [items, setItems] = useStateCart(init.items);
  const [code, setCode] = useStateCart(init.code);
  const [open, setOpen] = useStateCart(false);

  useEffectCart(() => { localStorage.setItem(CART_KEY, JSON.stringify({ items, code })); }, [items, code]);

  const add = useCbCart((product, qty, meta) => {
    qty = qty || 1;
    setItems((prev) => {
      const ex = prev.find((x) => x.id === product.id);
      const snapshot = {
        id: product.id, name: product.name, price: Number(product.price) || 0,
        tone: product.tone, src: product.src, digital: !!product.digital, category: product.category,
        requestQuote: !!product.requestQuote, isSubscription: !!product.isSubscription,
      };
      if (ex) {
        const max = product.digital ? 1 : 99;
        return prev.map((x) => x.id === product.id ? { ...x, ...snapshot, qty: Math.min(max, x.qty + qty), meta: meta || x.meta } : x);
      }
      return [...prev, { ...snapshot, qty: product.digital ? 1 : qty, meta: meta || null }];
    });
  }, []);
  const setQty = useCbCart((id, q) => setItems((prev) => prev.map((x) => x.id === id ? { ...x, qty: Math.max(1, Math.min(x.digital ? 1 : 99, q)) } : x)), []);
  const remove = useCbCart((id) => setItems((prev) => prev.filter((x) => x.id !== id)), []);
  const clear = useCbCart(() => { setItems([]); setCode(''); }, []);
  const has = useCbCart((id) => items.some((x) => x.id === id), [items]);

  const applyCode = useCbCart((raw) => {
    const c = (raw || '').trim().toUpperCase();
    if (!c) { setCode(''); return { ok: true, msg: '' }; }
    const discounts = window.SARAYA?.STORE_CONFIG?.discounts || {}; if (discounts[c]) { setCode(c); return { ok: true, msg: 'Code applied' }; }
    return { ok: false, msg: 'Invalid code' };
  }, []);

  /* derived totals */
  const cfg = window.SARAYA?.STORE_CONFIG || { vatRate: 0.05, deliveryFee: 0, freeDeliveryOver: Infinity, discounts: {} };
  const count = items.reduce((a, b) => a + b.qty, 0);
  const subtotal = items.reduce((a, b) => a + b.price * b.qty, 0);
  const hasPhysical = items.some((x) => !x.digital);
  const allDigital = items.length > 0 && !hasPhysical;
  let discount = 0;
  const disc = cfg.discounts[code];
  if (disc) discount = disc.type === 'pct' ? Math.round(subtotal * disc.value) / 100 : Math.min(disc.value, subtotal);
  const delivery = hasPhysical ? (subtotal - discount >= cfg.freeDeliveryOver ? 0 : cfg.deliveryFee) : 0;
  const taxable = Math.max(0, subtotal - discount) + delivery;
  const vat = Math.round(taxable * cfg.vatRate * 100) / 100;
  const total = Math.max(0, subtotal - discount) + delivery + vat;

  const api = {
    items, count, open, setOpen, add, setQty, remove, clear, has,
    code, applyCode,
    totals: { subtotal, discount, delivery, vat, total, hasPhysical, allDigital },
  };
  return (
    <window.CartContext.Provider value={api}>
      {children}
      <CartDrawer />
    </window.CartContext.Provider>
  );
}
function useCart() { return useContextCart(window.CartContext); }

/* Header cart button (icon + count) */
function CartButton({ onDark }) {
  const cart = useCart();
  const { go } = useContextCart(window.NavContext);
  const col = onDark ? 'var(--ivory)' : 'var(--fg-primary)';
  return (
    <button onClick={() => cart.setOpen(true)} aria-label="Cart" style={{ position: 'relative', background: 'none', border: 'none', cursor: 'pointer', color: col, display: 'flex', alignItems: 'center', padding: 6 }}>
      <Icon name="shopping-bag" size={22} />
      {cart.count > 0 && <span style={{ position: 'absolute', top: -2, insetInlineEnd: -2, minWidth: 17, height: 17, padding: '0 4px', borderRadius: 999, background: 'var(--gold)', color: 'var(--espresso)', fontSize: 10.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{cart.count}</span>}
    </button>
  );
}

/* Slide-in cart drawer */
function CartDrawer() {
  const { lang } = useLang();
  const { go } = useContextCart(window.NavContext);
  const cart = useCart();
  if (!cart.open) return null;
  const T = cart.totals;
  const ar = lang === 'ar';
  const go2 = (r) => { cart.setOpen(false); go(r); };
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 130, display: 'flex', justifyContent: ar ? 'flex-start' : 'flex-end' }}>
      <div onClick={() => cart.setOpen(false)} style={{ position: 'absolute', inset: 0, background: 'var(--scrim)', animation: 'sarayaFade 200ms ease' }} />
      <aside style={{ position: 'relative', width: 'min(430px,100%)', height: '100%', background: 'var(--bg-canvas)', boxShadow: 'var(--shadow-deep)', display: 'flex', flexDirection: 'column', animation: 'sarayaSlideIn 320ms var(--ease-out)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>{ar ? 'سلة التسوّق' : 'Your Cart'}</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>{cart.count} {ar ? 'عنصر' : 'items'}</div>
          </div>
          <button onClick={() => cart.setOpen(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', display: 'flex', padding: 4 }}><Icon name="x" size={24} /></button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 24px' }}>
          {cart.items.length === 0 ? (
            <div style={{ textAlign: 'center', marginTop: 48, color: 'var(--fg-muted)' }}>
              <Icon name="shopping-bag" size={40} stroke={1} />
              <p style={{ fontSize: 14.5, marginTop: 12 }}>{ar ? 'سلتك فارغة.' : 'Your cart is empty.'}</p>
              <Button variant="secondary" size="sm" style={{ marginTop: 16 }} onClick={() => go2('store')}>{ar ? 'تصفح السوق' : 'Browse Marketplace'}</Button>
            </div>
          ) : cart.items.map((it) => (
            <div key={it.id} style={{ display: 'flex', gap: 13, padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
              <Img tone={it.tone} icon={it.digital ? 'download' : 'shopping-bag'} src={it.src} slot={'store:' + it.id} ratio="1/1" radius={10} plain style={{ width: 64, flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontWeight: 500, lineHeight: 1.2 }}>{it.name[lang] || it.name.en}</div>
                <div style={{ fontSize: 13, color: 'var(--gold-deep)', fontWeight: 600, marginTop: 2 }}>{money(it.price)}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8 }}>
                  {it.digital ? (
                    <span style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>{ar ? 'منتج رقمي' : 'Digital'}</span>
                  ) : (
                    <span style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--line-strong)', borderRadius: 8 }}>
                      <QtyBtn onClick={() => cart.setQty(it.id, it.qty - 1)} icon="minus" />
                      <span style={{ minWidth: 26, textAlign: 'center', fontSize: 14, fontWeight: 600 }}>{it.qty}</span>
                      <QtyBtn onClick={() => cart.setQty(it.id, it.qty + 1)} icon="plus" />
                    </span>
                  )}
                  <button onClick={() => cart.remove(it.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', display: 'flex', padding: 4, marginInlineStart: 'auto' }}><Icon name="trash-2" size={16} /></button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {cart.items.length > 0 && (
          <div style={{ padding: '16px 24px', borderTop: '1px solid var(--line)', background: 'var(--white)' }}>
            <Row label={ar ? 'المجموع الفرعي' : 'Subtotal'} value={money(T.subtotal)} />
            {T.discount > 0 && <Row label={ar ? 'الخصم' : 'Discount'} value={'− ' + money(T.discount)} accent />}
            {T.hasPhysical && <Row label={ar ? 'التوصيل' : 'Delivery'} value={T.delivery === 0 ? (ar ? 'مجاني' : 'Free') : money(T.delivery)} />}
            <Row label={ar ? 'ضريبة القيمة المضافة (٥٪)' : 'VAT (5%)'} value={money(T.vat)} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8, paddingTop: 10, borderTop: '1px solid var(--line)' }}>
              <span style={{ fontWeight: 600, fontSize: 15 }}>{ar ? 'الإجمالي' : 'Total'}</span>
              <span style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 600 }}>{money(T.total)}</span>
            </div>
            <div style={{ display: 'grid', gap: 8, marginTop: 14 }}>
              <Button variant="primary" full icon="lock" onClick={() => go2('checkout')}>{ar ? 'إتمام الشراء' : 'Proceed to Checkout'}</Button>
              <div style={{ display: 'flex', gap: 8 }}>
                <Button variant="secondary" size="sm" full onClick={() => go2('store')}>{ar ? 'متابعة التسوّق' : 'Continue Shopping'}</Button>
                <Button variant="whatsapp" size="sm" icon="message-circle" href={window.SARAYA.waLink('Hello Saraya Events, I need help with my cart.')} target="_blank">{ar ? 'دعم' : 'Support'}</Button>
              </div>
            </div>
          </div>
        )}
      </aside>
    </div>
  );
}
function QtyBtn({ onClick, icon }) {
  return <button onClick={onClick} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '10px 12px', minWidth: 40, minHeight: 40 }}><Icon name={icon} size={14} /></button>;
}
function Row({ label, value, accent }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, padding: '3px 0', color: accent ? 'var(--success)' : 'var(--fg-secondary)' }}>
      <span>{label}</span><span style={{ fontWeight: 500 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { CartProvider, useCart, CartButton, CartDrawer, money });
