// Saraya Events — Orders & fulfilment layer.
//   • OrdersAPI: localStorage-backed orders (create / list / update status).
//   • Digital files: stored in IndexedDB so admin can attach a real download.
//   • AdminOrdersPanel: dashboard stats + order list + detail + status control.
// No backend required; see DEV NOTE in checkout.jsx for the payment gateway.

const { useState: useStateOrd, useEffect: useEffectOrd, useContext: useCtxOrd } = React;

const ORDERS_KEY = 'saraya_orders_v1';

const ORDER_STATUSES = [
  { id: 'new',         label: 'New Order',          tone: 'info' },
  { id: 'pending',     label: 'Pending Payment',    tone: 'warning' },
  { id: 'paid',        label: 'Payment Received',   tone: 'success' },
  { id: 'confirmed',   label: 'Confirmed',          tone: 'success' },
  { id: 'prep',        label: 'In Preparation',     tone: 'info' },
  { id: 'out',         label: 'Out for Delivery',   tone: 'info' },
  { id: 'done',        label: 'Delivered / Completed', tone: 'success' },
  { id: 'cancelled',   label: 'Cancelled',          tone: 'error' },
  { id: 'refunded',    label: 'Refunded',           tone: 'error' },
];
const statusMeta = (id) => ORDER_STATUSES.find((s) => s.id === id) || ORDER_STATUSES[0];

const OrdersAPI = {
  list() { try { return JSON.parse(localStorage.getItem(ORDERS_KEY) || '[]'); } catch (e) { return []; } },
  _save(arr) { localStorage.setItem(ORDERS_KEY, JSON.stringify(arr)); },
  create(order) {
    const arr = OrdersAPI.list();
    const d = new Date();
    const num = 'SE-' + d.toISOString().slice(2, 10).replace(/-/g, '') + '-' + String(arr.length + 1).padStart(4, '0');
    const full = Object.assign({ id: 'o' + Date.now().toString(36), number: num, createdAt: d.toISOString(), status: order.payment && order.payment.status === 'paid' ? 'paid' : 'new' }, order);
    arr.unshift(full); OrdersAPI._save(arr); return full;
  },
  get(id) { return OrdersAPI.list().find((o) => o.id === id || o.number === id) || null; },
  setStatus(id, status) { const a = OrdersAPI.list(); const o = a.find((x) => x.id === id); if (o) { o.status = status; OrdersAPI._save(a); } return o; },
};
window.OrdersAPI = OrdersAPI;
window.ORDER_STATUSES = ORDER_STATUSES;
window.statusMeta = statusMeta;

/* ---- digital file store (IndexedDB) ---- */
const FILE_DB = 'saraya_files_db', FILE_STORE = 'files';
function fileDbOpen() {
  return new Promise((res, rej) => { let r; try { r = indexedDB.open(FILE_DB, 1); } catch (e) { return rej(e); }
    r.onupgradeneeded = () => { if (!r.result.objectStoreNames.contains(FILE_STORE)) r.result.createObjectStore(FILE_STORE); };
    r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
}
async function saveDigitalFile(productId, file) {
  const db = await fileDbOpen();
  return new Promise((res, rej) => { const tx = db.transaction(FILE_STORE, 'readwrite');
    tx.objectStore(FILE_STORE).put({ name: file.name, type: file.type, blob: file }, productId);
    tx.oncomplete = () => res(true); tx.onerror = () => rej(tx.error); });
}
async function getDigitalFile(productId) {
  const db = await fileDbOpen();
  return new Promise((res) => { const tx = db.transaction(FILE_STORE, 'readonly');
    const r = tx.objectStore(FILE_STORE).get(productId); r.onsuccess = () => res(r.result || null); r.onerror = () => res(null); });
}
async function hasDigitalFile(productId) { return !!(await getDigitalFile(productId)); }
async function downloadDigitalFile(productId, fallbackName) {
  const rec = await getDigitalFile(productId);
  if (!rec) return false;
  const a = document.createElement('a'); a.href = URL.createObjectURL(rec.blob); a.download = rec.name || fallbackName || 'download';
  document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 1500); return true;
}
function pickDigitalFile(productId, onDone) {
  const input = document.createElement('input'); input.type = 'file';
  input.style.position = 'fixed'; input.style.left = '-9999px';
  input.onchange = async () => { const f = input.files && input.files[0]; if (f) { try { await saveDigitalFile(productId, f); onDone && onDone(f.name); } catch (e) { onDone && onDone(null, e); } } input.remove(); };
  document.body.appendChild(input); input.click();
}
Object.assign(window, { saveDigitalFile, getDigitalFile, hasDigitalFile, downloadDigitalFile, pickDigitalFile });

/* ---- Status pill ---- */
function StatusPill({ status, small }) {
  const m = statusMeta(status);
  const map = { info: ['var(--info-bg)', 'var(--info)'], success: ['var(--success-bg)', 'var(--success)'], warning: ['var(--warning-bg)', 'var(--warning)'], error: ['var(--error-bg)', 'var(--error)'] };
  const [bg, fg] = map[m.tone] || map.info;
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: small ? '2px 9px' : '4px 12px', borderRadius: 999, background: bg, color: fg, fontSize: small ? 11 : 12.5, fontWeight: 600, whiteSpace: 'nowrap' }}>{m.label}</span>;
}

/* ---- Admin Orders dashboard (modal) ---- */
function AdminOrdersPanel({ onClose }) {
  const [orders, setOrders] = useStateOrd(() => OrdersAPI.list());
  const [sel, setSel] = useStateOrd(null);
  const refresh = () => setOrders(OrdersAPI.list());

  const totalSales = orders.filter((o) => ['paid', 'confirmed', 'prep', 'out', 'done'].includes(o.status)).reduce((a, b) => a + (b.totals ? b.totals.total : 0), 0);
  const pending = orders.filter((o) => ['new', 'pending'].includes(o.status)).length;
  const digitalSold = orders.reduce((a, o) => a + (o.items || []).filter((i) => i.digital).reduce((x, i) => x + i.qty, 0), 0);

  const setStatus = (id, s) => { OrdersAPI.setStatus(id, s); refresh(); setSel((p) => p && p.id === id ? Object.assign({}, p, { status: s }) : p); };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 290, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'var(--scrim)' }} />
      <div style={{ position: 'relative', width: 'min(960px,100%)', height: 'min(88vh,820px)', display: 'flex', flexDirection: 'column', background: 'var(--bg-canvas)', borderRadius: 18, boxShadow: 'var(--shadow-deep)', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 22px', borderBottom: '1px solid var(--line)', background: 'var(--white)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="package" size={20} style={{ color: 'var(--gold-deep)' }} />
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500 }}>Orders</h3>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', display: 'flex', padding: 4 }}><Icon name="x" size={22} /></button>
        </div>

        {/* dashboard stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(150px,1fr))', gap: 12, padding: '16px 22px', background: 'var(--bg-muted)' }}>
          <Stat label="Total sales" value={money(totalSales)} icon="trending-up" />
          <Stat label="Total orders" value={orders.length} icon="shopping-bag" />
          <Stat label="Pending" value={pending} icon="clock" />
          <Stat label="Digital sold" value={digitalSold} icon="download" />
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 22px 22px' }}>
          {orders.length === 0 ? (
            <div style={{ textAlign: 'center', color: 'var(--fg-muted)', marginTop: 48 }}>
              <Icon name="inbox" size={40} stroke={1} /><p style={{ marginTop: 12, fontSize: 14 }}>No orders yet. Orders placed at checkout will appear here.</p>
            </div>
          ) : !sel ? (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
              <thead><tr style={{ textAlign: 'start', color: 'var(--fg-muted)', fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                {['Order', 'Customer', 'Total', 'Status', ''].map((h, i) => <th key={i} style={{ textAlign: i === 4 ? 'end' : 'start', padding: '10px 8px', borderBottom: '1px solid var(--line)', fontWeight: 600 }}>{h}</th>)}
              </tr></thead>
              <tbody>
                {orders.map((o) => (
                  <tr key={o.id} style={{ borderBottom: '1px solid var(--line)' }}>
                    <td style={{ padding: '12px 8px' }}><div style={{ fontWeight: 600 }}>{o.number}</div><div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>{new Date(o.createdAt).toLocaleDateString()}</div></td>
                    <td style={{ padding: '12px 8px' }}>{o.customer ? o.customer.name : '—'}<div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>{o.customer ? o.customer.phone : ''}</div></td>
                    <td style={{ padding: '12px 8px', fontWeight: 600 }}>{money(o.totals ? o.totals.total : 0)}</td>
                    <td style={{ padding: '12px 8px' }}><StatusPill status={o.status} small /></td>
                    <td style={{ padding: '12px 8px', textAlign: 'end' }}><button onClick={() => setSel(o)} style={linkBtn}>View</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <OrderDetail order={sel} onBack={() => setSel(null)} onStatus={setStatus} />
          )}
        </div>
      </div>
    </div>
  );
}
const linkBtn = { background: 'none', border: '1px solid var(--line-strong)', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 500, color: 'var(--fg-primary)' };

function Stat({ label, value, icon }) {
  return (
    <div style={{ background: 'var(--white)', borderRadius: 12, padding: '14px 16px', border: '1px solid var(--line)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, color: 'var(--fg-muted)', fontSize: 12 }}><Icon name={icon} size={15} />{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, marginTop: 4 }}>{value}</div>
    </div>
  );
}

function OrderDetail({ order, onBack, onStatus }) {
  const o = order; const f = o.fulfilment || {}; const c = o.customer || {};
  return (
    <div>
      <button onClick={onBack} style={{ ...linkBtn, marginBottom: 14, display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="arrow-left" size={14} />All orders</button>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>{o.number}</h4>
          <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>{new Date(o.createdAt).toLocaleString()}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>Status</span>
          <Select value={o.status} onChange={(e) => onStatus(o.id, e.target.value)} style={{ width: 'auto' }}>
            {ORDER_STATUSES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
          </Select>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(230px,1fr))', gap: 18, marginTop: 20 }}>
        <Box title="Customer">
          <KV k="Name" v={c.name} /><KV k="Mobile" v={c.phone} /><KV k="Email" v={c.email} />
        </Box>
        <Box title={o.totals && o.totals.allDigital ? 'Delivery (digital — none)' : 'Delivery / Event'}>
          {o.address && <KV k="Address" v={o.address} />}{o.emirate && <KV k="Emirate" v={o.emirate} />}
          {f.deliveryDate && <KV k="Delivery" v={f.deliveryDate + ' · ' + (f.deliveryTime || '')} />}
          {f.eventDate && <KV k="Event" v={f.eventDate + ' · ' + (f.eventTime || '')} />}
          {f.recipientName && <KV k="Recipient" v={f.recipientName + ' · ' + (f.recipientPhone || '')} />}
          {f.giftMessage && <KV k="Gift note" v={f.giftMessage} />}
          {!o.address && !f.deliveryDate && !f.eventDate && <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>—</div>}
        </Box>
        <Box title="Payment">
          <KV k="Method" v={o.payment ? o.payment.methodLabel : '—'} />
          <KV k="Status" v={o.payment ? (o.payment.status === 'paid' ? 'Paid' : 'Awaiting') : '—'} />
        </Box>
      </div>

      <Box title="Items" style={{ marginTop: 18 }}>
        {(o.items || []).map((it) => (
          <div key={it.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13.5, borderBottom: '1px solid var(--line)' }}>
            <span>{(it.name.en || it.name)} {it.digital ? '· (digital)' : ''} × {it.qty}</span>
            <span style={{ fontWeight: 600 }}>{money(it.price * it.qty)}</span>
          </div>
        ))}
        {o.totals && <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 10, fontWeight: 700 }}><span>Total</span><span>{money(o.totals.total)}</span></div>}
      </Box>
      {o.notes && <Box title="Notes" style={{ marginTop: 18 }}><div style={{ fontSize: 13.5 }}>{o.notes}</div></Box>}
    </div>
  );
}
function Box({ title, children, style }) {
  return <div style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 12, padding: '14px 16px', ...style }}>
    <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--gold-deep)', marginBottom: 10 }}>{title}</div>{children}</div>;
}
function KV({ k, v }) { if (!v) return null; return <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '3px 0', fontSize: 13 }}><span style={{ color: 'var(--fg-muted)' }}>{k}</span><span style={{ fontWeight: 500, textAlign: 'end' }}>{v}</span></div>; }

Object.assign(window, { AdminOrdersPanel, StatusPill, OrdersAPI });

/* ====================================================
   MY ORDERS — customer-facing order tracking page
   Route: #my-orders  (already wired in app.jsx)
   ==================================================== */
function MyOrdersPage() {
  const db   = window.SarayaDB;
  const auth = window.useAuth ? window.useAuth() : {};
  const user = auth.user;
  let lang = 'en';
  try { lang = useCtxOrd(window.LangContext)?.lang || localStorage.getItem('saraya_lang') || 'en'; } catch (e) {}
  const ar = lang === 'ar';

  const [orders,     setOrders]     = useStateOrd([]);
  const [loading,    setLoading]    = useStateOrd(true);
  const [sel,        setSel]        = useStateOrd(null);
  const [confirming, setConfirming] = useStateOrd(null);

  useEffectOrd(() => {
    if (!db || !user) { setLoading(false); return; }
    (async () => {
      const { data } = await db
        .from('orders')
        .select('id, reference, type, status, subtotal, total_amount, delivery_fee, vat_amount, discount_amount, notes, delivery_address, created_at, customer_confirmed_at, vendor_profiles!vendor_id(trade_name, trade_name_ar), order_items(id, name_en, name_ar, unit_price, quantity, line_total)')
        .eq('customer_id', user.id)
        .order('created_at', { ascending: false });
      setOrders(data || []);
      setLoading(false);
    })();
  }, [db, user]);

  const confirmDelivery = async (orderId) => {
    setConfirming(orderId);
    const now = new Date().toISOString();
    await db.from('orders').update({ customer_confirmed_at: now, status: 'done' }).eq('id', orderId);
    setOrders((prev) => prev.map((o) => o.id === orderId ? { ...o, status: 'done', customer_confirmed_at: now } : o));
    setSel((p) => p && p.id === orderId ? { ...p, status: 'done', customer_confirmed_at: now } : p);
    setConfirming(null);
  };

  const STATUS_DISPLAY = {
    processing: { label: ar ? 'قيد المعالجة' : 'Processing',       bg: '#EFF6FF', fg: '#2563EB' },
    pending:    { label: ar ? 'في الانتظار'   : 'Pending',          bg: '#FEF9C3', fg: '#A16207' },
    paid:       { label: ar ? 'تم الدفع'      : 'Paid',             bg: '#DCFCE7', fg: '#15803D' },
    confirmed:  { label: ar ? 'مؤكد'          : 'Confirmed',        bg: '#DCFCE7', fg: '#15803D' },
    prep:       { label: ar ? 'قيد التحضير'   : 'In Preparation',   bg: '#EFF6FF', fg: '#2563EB' },
    out:        { label: ar ? 'خارج للتوصيل'  : 'Out for Delivery', bg: '#DBEAFE', fg: '#1D4ED8' },
    done:       { label: ar ? 'مكتمل'         : 'Delivered',        bg: '#DCFCE7', fg: '#15803D' },
    delivered:  { label: ar ? 'تم التوصيل'    : 'Delivered',        bg: '#DCFCE7', fg: '#15803D' },
    cancelled:  { label: ar ? 'ملغى'          : 'Cancelled',        bg: '#FEE2E2', fg: '#B91C1C' },
    refunded:   { label: ar ? 'مسترد'         : 'Refunded',         bg: '#FEE2E2', fg: '#B91C1C' },
  };
  const getBadge = (status) => STATUS_DISPLAY[status] || { label: status, bg: '#F3F4F6', fg: '#374151' };
  const fmtAED  = (n) => 'AED ' + Number(n || 0).toLocaleString('en-AE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const fmtDate = (d) => new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' });

  const cardStyle = { background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' };
  const backBtn = { display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 20, padding: '8px 16px', borderRadius: 8, border: '1.5px solid var(--line-strong)', background: 'transparent', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 500, color: 'var(--fg-primary)' };

  if (!user) return (
    React.createElement('main', { style: { paddingTop: 120, paddingBottom: 80, minHeight: '70vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16 } },
      React.createElement(Icon, { name: 'lock', size: 36, stroke: 1, style: { color: 'var(--fg-muted)' } }),
      React.createElement('p', { style: { fontSize: 15, color: 'var(--fg-muted)' } }, ar ? 'يرجى تسجيل الدخول لعرض طلباتك.' : 'Please sign in to view your orders.')
    )
  );

  return (
    <main style={{ paddingTop: 100, paddingBottom: 80, minHeight: '70vh' }}>
      <div style={{ maxWidth: 860, margin: '0 auto', padding: '0 20px' }}>

        <div style={{ marginBottom: 28 }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 500, margin: '0 0 6px' }}>
            {ar ? 'طلباتي' : 'My Orders'}
          </h1>
          <p style={{ color: 'var(--fg-secondary)', fontSize: 14, margin: 0 }}>
            {ar ? 'تتبع حالة طلباتك وتاريخ مشترياتك.' : 'Track your orders and purchase history.'}
          </p>
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: '60px 0', color: 'var(--fg-muted)' }}>
            <Icon name="loader" size={32} style={{ animation: 'spin 1s linear infinite', color: 'var(--gold)' }} />
          </div>

        ) : orders.length === 0 ? (
          <div style={{ ...cardStyle, textAlign: 'center', padding: '60px 24px' }}>
            <Icon name="shopping-bag" size={48} stroke={1} style={{ color: 'var(--fg-muted)' }} />
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginTop: 16, marginBottom: 8 }}>
              {ar ? 'لا توجد طلبات بعد' : 'No orders yet'}
            </h3>
            <p style={{ color: 'var(--fg-secondary)', fontSize: 14, margin: '0 0 24px' }}>
              {ar ? 'ستظهر هنا طلباتك بعد إتمام أول عملية شراء.' : 'Your orders will appear here after your first purchase.'}
            </p>
            <button onClick={() => { location.hash = '#store'; }} style={{ padding: '10px 24px', borderRadius: 8, background: 'var(--gold)', color: '#fff', border: 'none', fontWeight: 600, cursor: 'pointer', fontSize: 14, fontFamily: 'var(--font-body)' }}>
              {ar ? 'تصفح المتجر' : 'Browse the Store'}
            </button>
          </div>

        ) : !sel ? (
          <div style={{ display: 'grid', gap: 12 }}>
            {orders.map((o) => {
              const b = getBadge(o.status);
              const vp = o.vendor_profiles;
              const items = o.order_items || [];
              return (
                <div key={o.id} style={cardStyle}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, padding: '16px 20px', borderBottom: '1px solid var(--line)' }}>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{o.reference || '#' + o.id.slice(0, 8).toUpperCase()}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 2 }}>
                        {fmtDate(o.created_at)}{vp && <span> · {ar ? (vp.trade_name_ar || vp.trade_name) : vp.trade_name}</span>}
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</span>
                      <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--gold-deep)' }}>{fmtAED(o.total_amount)}</span>
                    </div>
                  </div>
                  <div style={{ padding: '12px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
                    <div style={{ fontSize: 13, color: 'var(--fg-secondary)' }}>
                      {items.slice(0, 2).map((it, i) => (
                        <span key={it.id}>{ar ? (it.name_ar || it.name_en) : it.name_en} × {it.quantity}{i < Math.min(items.length, 2) - 1 ? ', ' : ''}</span>
                      ))}
                      {items.length > 2 && <span style={{ color: 'var(--fg-muted)' }}> +{items.length - 2} {ar ? 'أخرى' : 'more'}</span>}
                      {items.length === 0 && <span style={{ color: 'var(--fg-muted)' }}>—</span>}
                    </div>
                    <button onClick={() => setSel(o)} style={{ padding: '7px 16px', borderRadius: 8, border: '1.5px solid var(--line-strong)', background: 'transparent', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 500, color: 'var(--fg-primary)' }}>
                      {ar ? 'عرض التفاصيل' : 'View Details'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>

        ) : (
          <div>
            <button onClick={() => setSel(null)} style={backBtn}>
              <Icon name={ar ? 'arrow-right' : 'arrow-left'} size={14} />
              {ar ? 'كل الطلبات' : 'All Orders'}
            </button>
            <div style={cardStyle}>
              <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
                <div>
                  <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500, margin: '0 0 4px' }}>
                    {sel.reference || '#' + sel.id.slice(0, 8).toUpperCase()}
                  </h2>
                  <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
                    {fmtDate(sel.created_at)}{sel.vendor_profiles && <span> · {ar ? (sel.vendor_profiles.trade_name_ar || sel.vendor_profiles.trade_name) : sel.vendor_profiles.trade_name}</span>}
                  </div>
                </div>
                {(() => { const b = getBadge(sel.status); return <span style={{ padding: '6px 16px', borderRadius: 20, fontSize: 13, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</span>; })()}
              </div>

              <div style={{ padding: '0 24px' }}>
                <div style={{ padding: '16px 0 10px', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)' }}>{ar ? 'المنتجات' : 'Items'}</div>
                {(sel.order_items || []).map((it) => (
                  <div key={it.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderTop: '1px solid var(--line)', gap: 12 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{ar ? (it.name_ar || it.name_en) : it.name_en}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 2 }}>{ar ? 'الكمية' : 'Qty'}: {it.quantity} · {fmtAED(it.unit_price)} {ar ? 'للوحدة' : 'each'}</div>
                    </div>
                    <div style={{ fontWeight: 700, fontSize: 14, flexShrink: 0 }}>{fmtAED(it.line_total)}</div>
                  </div>
                ))}
              </div>

              <div style={{ padding: '12px 24px 16px', background: 'var(--bg-tint)', borderTop: '1px solid var(--line)' }}>
                {Number(sel.discount_amount) > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, padding: '4px 0', color: 'var(--fg-secondary)' }}>
                    <span>{ar ? 'الخصم' : 'Discount'}</span><span style={{ color: '#16A34A' }}>−{fmtAED(sel.discount_amount)}</span>
                  </div>
                )}
                {Number(sel.delivery_fee) > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, padding: '4px 0', color: 'var(--fg-secondary)' }}>
                    <span>{ar ? 'رسوم التوصيل' : 'Delivery Fee'}</span><span>{fmtAED(sel.delivery_fee)}</span>
                  </div>
                )}
                {Number(sel.vat_amount) > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, padding: '4px 0', color: 'var(--fg-secondary)' }}>
                    <span>{ar ? 'ضريبة القيمة المضافة (5%)' : 'VAT (5%)'}</span><span>{fmtAED(sel.vat_amount)}</span>
                  </div>
                )}
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 16, fontWeight: 700, padding: '10px 0 0', marginTop: 4, borderTop: '1.5px solid var(--line)' }}>
                  <span>{ar ? 'المجموع الكلي' : 'Total'}</span>
                  <span style={{ color: 'var(--gold-deep)' }}>{fmtAED(sel.total_amount)}</span>
                </div>
              </div>

              {sel.delivery_address && (
                <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)', marginBottom: 6 }}>{ar ? 'عنوان التوصيل' : 'Delivery Address'}</div>
                  <div style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
                    {typeof sel.delivery_address === 'string' ? sel.delivery_address : [sel.delivery_address.line1, sel.delivery_address.line2, sel.delivery_address.city, sel.delivery_address.emirate].filter(Boolean).join(', ')}
                  </div>
                </div>
              )}

              {sel.notes && (
                <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)', marginBottom: 6 }}>{ar ? 'ملاحظات' : 'Notes'}</div>
                  <div style={{ fontSize: 13.5, color: 'var(--fg-secondary)' }}>{sel.notes}</div>
                </div>
              )}

              {['confirmed', 'prep', 'out'].includes(sel.status) && !sel.customer_confirmed_at && (
                <div style={{ padding: '16px 24px', borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap', background: '#F0FDF4' }}>
                  <div style={{ flex: 1, fontSize: 13.5, color: '#166534', lineHeight: 1.6 }}>
                    {ar ? 'هل استلمت طلبك؟ أكّد الاستلام حتى يتم الإفراج عن الدفع للبائع.' : 'Did you receive your order? Confirm delivery to release payment to the vendor.'}
                  </div>
                  <button onClick={() => confirmDelivery(sel.id)} disabled={confirming === sel.id} style={{ padding: '10px 22px', borderRadius: 8, background: '#16A34A', color: '#fff', border: 'none', fontWeight: 600, cursor: confirming === sel.id ? 'not-allowed' : 'pointer', fontSize: 14, fontFamily: 'var(--font-body)', opacity: confirming === sel.id ? 0.7 : 1, flexShrink: 0 }}>
                    {confirming === sel.id ? (ar ? 'جارٍ...' : 'Confirming…') : (ar ? 'تأكيد الاستلام' : 'Confirm Delivery')}
                  </button>
                </div>
              )}
              {sel.customer_confirmed_at && (
                <div style={{ padding: '12px 24px', borderTop: '1px solid var(--line)', background: '#F0FDF4', display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, color: '#15803D' }}>
                  <Icon name="check-circle" size={16} />
                  {ar ? 'أكّدت استلام هذا الطلب بتاريخ ' + fmtDate(sel.customer_confirmed_at) : 'You confirmed delivery on ' + fmtDate(sel.customer_confirmed_at)}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </main>
  );
}
window.MyOrdersPage = MyOrdersPage;
