// admin.jsx — admin panel: products CRUD, orders, stats, customers

function AdminLayout({ route, setRoute, lang, children }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const items = [
    { id: 'admin-products',  label: t('المنتجات', 'Products'),   icon: <I.box /> },
    { id: 'admin-orders',    label: t('الطلبات', 'Orders'),      icon: <I.receipt /> },
    { id: 'admin-stats',     label: t('الإحصائيات', 'Analytics'), icon: <I.chart /> },
    { id: 'admin-customers', label: t('العملاء', 'Customers'),   icon: <I.users /> },
    { id: 'admin-settings',  label: t('الإعدادات', 'Settings'),  icon: <I.settings /> },
  ];
  return (
    <div className="admin">
      <aside className="admin-side">
        <div className="sect">{t('لوحة التحكم', 'Dashboard')}</div>
        {items.map(it => (
          <a key={it.id} className={'admin-nav' + (route === it.id ? ' on' : '')}
             onClick={() => setRoute(it.id)}>
            {it.icon}{it.label}
          </a>
        ))}
        <div style={{ flex: 1 }} />
        <div className="sect">{t('متجرك', 'Your store')}</div>
        <a className="admin-nav" onClick={() => setRoute('home')}>
          ↗ {t('عرض المتجر', 'View storefront')}
        </a>
      </aside>
      <main className="admin-main">{children}</main>
    </div>
  );
}

// ── Products ───────────────────────────────────────────────
function AdminProducts({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [products, setProducts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [q, setQ] = React.useState('');
  const [familyFilter, setFamilyFilter] = React.useState('all');
  const [edit, setEdit] = React.useState(null);    // product being edited (modal)
  const [creating, setCreating] = React.useState(false);

  const load = React.useCallback(() => {
    setLoading(true);
    apiGet('products').then(d => { setProducts(Array.isArray(d) ? d : []); setLoading(false); });
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const filtered = products.filter(p => {
    if (familyFilter !== 'all' && p.family !== familyFilter) return false;
    if (q && !p.name_ar.includes(q) && !p.name_en.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  const save = async (p) => {
    if (creating) await apiPost('products', p);
    else await apiPut('products', p.id, p);
    setEdit(null); setCreating(false);
    load();
  };
  const del = async (id) => {
    if (!confirm(t('حذف المنتج؟', 'Delete this product?'))) return;
    await apiDel('products', id);
    load();
  };

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('الإدارة · 01', 'Manage · 01')}</div>
          <h1 className="h-display">{t('المنتجات', 'Products')}</h1>
          <div className="sub">{products.length} {t('منتج', 'products')} · {products.filter(p => p.stock < 10).length} {t('مخزون منخفض', 'low stock')}</div>
        </div>
        <div className="actions">
          <div className="search-box">
            <I.search />
            <input placeholder={t('بحث…', 'Search…')} value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
          <select className="btn ghost" style={{ padding: '0 18px' }} value={familyFilter} onChange={(e) => setFamilyFilter(e.target.value)}>
            <option value="all">{t('كل العائلات', 'All families')}</option>
            {SCENT_FAMILIES.map(f => <option key={f.id} value={f.id}>{lang === 'ar' ? f.ar : f.en}</option>)}
          </select>
          <button className="btn" onClick={() => { setEdit({ id: '', name_ar: '', name_en: '', family: 'oud', price: 500, sizes: [{ml:30,price:280},{ml:50,price:500},{ml:100,price:900}], stock: 20, rating: 4.5, top_ar:'', heart_ar:'', base_ar:'', year: 2026, origin: '', concentration: 'EDP', tone: '#3D2A1E', image: '' }); setCreating(true); }}>
            <I.plus /> {t('منتج جديد', 'New product')}
          </button>
        </div>
      </div>

      <div style={{ overflowX: 'auto' }}>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 60 }}></th>
              <th>{t('المنتج', 'Product')}</th>
              <th>{t('العائلة', 'Family')}</th>
              <th>{t('التركيز', 'Concentration')}</th>
              <th>{t('المخزون', 'Stock')}</th>
              <th>{t('السعر', 'Price')}</th>
              <th>{t('التقييم', 'Rating')}</th>
              <th style={{ textAlign: 'end' }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(p => {
              const fam = SCENT_FAMILIES.find(f => f.id === p.family);
              const stockClass = p.stock < 8 ? 'crit' : p.stock < 15 ? 'low' : '';
              return (
                <tr key={p.id}>
                  <td><div className="mono" style={{ color: 'var(--ink-3)' }}>N°{String(p.id).padStart(3, '0')}</div></td>
                  <td>
                    <div className="cell-product">
                      <div className="mini-img" style={{ overflow: 'hidden' }}>
                        {p.image
                          ? <img src={p.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                          : <div className="mini-bottle" style={{ background: `linear-gradient(170deg, ${p.tone}, color-mix(in oklab, ${p.tone} 55%, #000))` }} />}
                      </div>
                      <div>
                        <div className="nm-ar">{p.name_ar}</div>
                        <div className="nm-en">{p.name_en}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: fam.tone }} />
                      {lang === 'ar' ? fam.ar : fam.en}
                    </span>
                  </td>
                  <td><span className="mono">{p.concentration}</span></td>
                  <td>
                    <div className={'stock-bar ' + stockClass}>
                      <div className="stock-bar-track">
                        <div className="stock-bar-fill" style={{ width: `${Math.min(100, p.stock * 2)}%` }} />
                      </div>
                      <span>{p.stock}</span>
                    </div>
                  </td>
                  <td><span className="serif-en" style={{ fontSize: 16 }}>{p.price}</span> <span style={{ fontSize: 10, color: 'var(--ink-3)' }}>AED</span></td>
                  <td><I.star /> <span className="tabular">{p.rating}</span></td>
                  <td>
                    <div className="actions-cell">
                      <button className="icon-btn-sm" onClick={() => { setEdit(p); setCreating(false); }}><I.edit /></button>
                      <button className="icon-btn-sm danger" onClick={() => del(p.id)}><I.trash /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {edit && <ProductEditor product={edit} onSave={save} onClose={() => { setEdit(null); setCreating(false); }} lang={lang} creating={creating} />}
    </>
  );
}

function ProductEditor({ product, onSave, onClose, lang, creating }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [p, setP] = React.useState(product);
  const [uploading, setUploading] = React.useState(false);
  const fileRef = React.useRef();
  const upd = (k, v) => setP(prev => ({ ...prev, [k]: v }));
  const updSize = (i, k, v) => {
    setP(prev => { const sizes = [...prev.sizes]; sizes[i] = { ...sizes[i], [k]: Number(v) }; return { ...prev, sizes }; });
  };
  const onFile = async (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    setUploading(true);
    const r = await apiUpload(f);
    setUploading(false);
    if (r && r.url) upd('image', r.url);
    else alert((r && r.error) || (lang === 'ar' ? 'فشل رفع الصورة' : 'Upload failed'));
    e.target.value = '';
  };
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" style={{ gridTemplateColumns: '320px 1fr', maxWidth: 960 }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-l" style={{ background: `color-mix(in oklab, ${p.tone} 14%, var(--bg-2))`, padding: 32, flexDirection: 'column', gap: 16, justifyContent: 'flex-start' }}>
          <div className="eyebrow">{t('معاينة', 'Preview')}</div>
          <div className="pdp-bottle" style={{ width: '70%', height: 280, margin: '0 auto', overflow: 'hidden', background: p.image ? '#0000' : `linear-gradient(170deg, ${p.tone} 0%, color-mix(in oklab, ${p.tone} 55%, #000) 100%)` }}>
            {p.image
              ? <img src={p.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit' }} />
              : <div className="pdp-label" style={{ fontSize: 10 }}>ISTABRAQ<br /><span style={{ fontSize: 13 }}>{p.name_en || 'NAME'}</span></div>}
          </div>
          <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
          <button className="btn ghost sm" style={{ width: '100%' }} onClick={() => fileRef.current && fileRef.current.click()} disabled={uploading}>
            <I.upload /> {uploading ? t('جارٍ الرفع…', 'Uploading…') : (p.image ? t('تغيير الصورة', 'Change image') : t('رفع صورة', 'Upload image'))}
          </button>
          {p.image && <button className="btn ghost sm" style={{ width: '100%' }} onClick={() => upd('image', '')}>{t('إزالة الصورة', 'Remove image')}</button>}
          <div className="field" style={{ marginTop: 4 }}>
            <label>{t('لون البطاقة (إن لم توجد صورة)', 'Card tone (if no image)')}</label>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {SCENT_FAMILIES.map(f => (
                <button key={f.id} onClick={() => upd('tone', f.tone)}
                        style={{ width: 28, height: 28, borderRadius: '50%', border: p.tone === f.tone ? '2px solid var(--ink)' : '1px solid var(--line)', background: f.tone }} />
              ))}
            </div>
          </div>
        </div>
        <div className="modal-r" style={{ padding: 32 }}>
          <button className="modal-x" onClick={onClose}><I.close /></button>
          <div className="eyebrow">{creating ? t('منتج جديد', 'New product') : t('تعديل منتج', 'Edit product')}</div>
          <h2 className="h-display" style={{ fontSize: 28, lineHeight: 1, margin: '4px 0 8px' }}>{p.name_ar || t('بلا اسم', 'Untitled')}</h2>

          <div className="co-grid">
            <div className="field"><label>{t('الاسم بالعربي', 'Name (Arabic)')}</label><input value={p.name_ar} onChange={(e) => upd('name_ar', e.target.value)} /></div>
            <div className="field"><label>{t('الاسم بالإنجليزي', 'Name (English)')}</label><input value={p.name_en} onChange={(e) => upd('name_en', e.target.value)} /></div>
            <div className="field"><label>{t('العائلة', 'Family')}</label>
              <select value={p.family} onChange={(e) => upd('family', e.target.value)}>
                {SCENT_FAMILIES.map(f => <option key={f.id} value={f.id}>{f.ar} · {f.en}</option>)}
              </select>
            </div>
            <div className="field"><label>{t('التركيز', 'Concentration')}</label>
              <select value={p.concentration} onChange={(e) => upd('concentration', e.target.value)}>
                <option>EDT</option><option>EDP</option><option>Parfum</option><option>Extrait</option>
              </select>
            </div>
            <div className="field"><label>{t('بلد المصدر', 'Origin')}</label><input value={p.origin} onChange={(e) => upd('origin', e.target.value)} placeholder="e.g. Mysore" /></div>
            <div className="field"><label>{t('سنة الإصدار', 'Year')}</label><input value={p.year} type="number" onChange={(e) => upd('year', +e.target.value)} /></div>
            <div className="field span-2"><label>{t('النوتات العليا', 'Top notes')}</label><input value={p.top_ar} onChange={(e) => upd('top_ar', e.target.value)} /></div>
            <div className="field span-2"><label>{t('قلب العطر', 'Heart notes')}</label><input value={p.heart_ar} onChange={(e) => upd('heart_ar', e.target.value)} /></div>
            <div className="field span-2"><label>{t('نوتات القاعدة', 'Base notes')}</label><input value={p.base_ar} onChange={(e) => upd('base_ar', e.target.value)} /></div>
            <div className="field"><label>{t('السعر الأساسي', 'Base price (AED)')}</label><input type="number" value={p.price} onChange={(e) => upd('price', +e.target.value)} /></div>
            <div className="field"><label>{t('المخزون', 'Stock')}</label><input type="number" value={p.stock} onChange={(e) => upd('stock', +e.target.value)} /></div>
          </div>

          <div style={{ marginTop: 24 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>{t('الأحجام والأسعار', 'Sizes & prices')}</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
              {p.sizes.map((s, i) => (
                <div key={s.ml} className="field" style={{ background: 'var(--bg-2)', padding: 12, borderRadius: 4 }}>
                  <label style={{ fontSize: 10 }}>{s.ml}ml · {t('السعر', 'Price')}</label>
                  <input type="number" value={s.price} onChange={(e) => updSize(i, 'price', e.target.value)} style={{ fontSize: 18, fontFamily: 'var(--f-en-head)', fontStyle: 'italic' }} />
                </div>
              ))}
            </div>
          </div>

          <div className="modal-actions">
            <button className="btn ghost" onClick={onClose}>{t('إلغاء', 'Cancel')}</button>
            <button className="btn" onClick={() => onSave(p)}>{creating ? t('إنشاء المنتج', 'Create') : t('حفظ التغييرات', 'Save')}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Orders ─────────────────────────────────────────────────
function AdminOrders({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [orders, setOrders] = React.useState([]);
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [view, setView] = React.useState(null);
  const [invoice, setInvoice] = React.useState(null);
  const load = () => apiGet('orders').then(d => setOrders(Array.isArray(d) ? d : []));
  React.useEffect(() => { load(); }, []);
  const filtered = orders.filter(o => statusFilter === 'all' || o.status === statusFilter);
  const setStatus = (id, status) => {
    setOrders(prev => prev.map(o => o.id === id ? { ...o, status } : o));
    setView(v => v && v.id === id ? { ...v, status } : v);
    apiPut('orders', id, { status });
  };
  const del = async (id) => {
    if (!confirm(t('حذف هذا الطلب نهائيًا؟', 'Delete this order permanently?'))) return;
    await apiDel('orders', id); setView(null); load();
  };
  const totalSales = orders.reduce((s, o) => s + (o.total || 0), 0);

  const tabs = [
    { id: 'all',       label: t('الكل', 'All'),             count: orders.length },
    { id: 'pending',   label: t('قيد الانتظار', 'Pending'),  count: orders.filter(o => o.status === 'pending').length },
    { id: 'shipped',   label: t('تم الشحن', 'Shipped'),     count: orders.filter(o => o.status === 'shipped').length },
    { id: 'delivered', label: t('تم التسليم', 'Delivered'), count: orders.filter(o => o.status === 'delivered').length },
    { id: 'cancelled', label: t('ملغية', 'Cancelled'),      count: orders.filter(o => o.status === 'cancelled').length },
  ];

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('الإدارة · 02', 'Manage · 02')}</div>
          <h1 className="h-display">{t('الطلبات', 'Orders')}</h1>
          <div className="sub">{orders.length} {t('طلب · إجمالي المبيعات', 'orders · total sales')} AED {totalSales.toLocaleString()}</div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 24, borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
        {tabs.map(tab => (
          <button key={tab.id} className="btn ghost sm"
                  style={{ borderRadius: 0, border: 'none', borderBottom: '2px solid ' + (statusFilter === tab.id ? 'var(--accent)' : 'transparent'), color: statusFilter === tab.id ? 'var(--ink)' : 'var(--ink-3)', padding: '10px 14px' }}
                  onClick={() => setStatusFilter(tab.id)}>
            {tab.label} <span style={{ marginInlineStart: 4, fontSize: 10, padding: '2px 6px', borderRadius: 999, background: 'var(--bg-2)' }}>{tab.count}</span>
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
          <div className="serif-en" style={{ fontSize: 26 }}>{t('لا طلبات بعد', 'No orders yet')}</div>
          <div style={{ marginTop: 6, fontSize: 13 }}>{t('ستظهر طلبات الزبائن هنا تلقائيًّا', 'Customer orders will appear here automatically')}</div>
        </div>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table className="table">
            <thead>
              <tr>
                <th>{t('رقم الطلب', 'Order')}</th><th>{t('العميل', 'Customer')}</th><th>{t('المدينة', 'City')}</th>
                <th>{t('التاريخ', 'Date')}</th><th>{t('العناصر', 'Items')}</th><th>{t('المجموع', 'Total')}</th>
                <th>{t('الحالة', 'Status')}</th><th style={{ textAlign: 'end' }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(o => (
                <tr key={o.id} style={{ cursor: 'pointer' }} onClick={() => setView(o)}>
                  <td><span className="mono">{o.id}</span></td>
                  <td><div style={{ fontWeight: 500 }}>{o.customer}</div><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{o.phone || o.email}</div></td>
                  <td>{o.city}</td>
                  <td className="mono" style={{ color: 'var(--ink-3)' }}>{o.date}</td>
                  <td className="tabular">{o.items}</td>
                  <td className="serif-en" style={{ fontSize: 16 }}>AED {o.total.toLocaleString()}</td>
                  <td onClick={e => e.stopPropagation()}>
                    <select className={'status-pill ' + o.status}
                            style={{ border: 'none', outline: 'none', cursor: 'pointer', padding: '3px 14px', fontFamily: 'inherit' }}
                            value={o.status} onChange={(e) => setStatus(o.id, e.target.value)}>
                      <option value="pending">{t('قيد الانتظار', 'Pending')}</option>
                      <option value="shipped">{t('تم الشحن', 'Shipped')}</option>
                      <option value="delivered">{t('تم التسليم', 'Delivered')}</option>
                      <option value="cancelled">{t('ملغية', 'Cancelled')}</option>
                    </select>
                  </td>
                  <td onClick={e => e.stopPropagation()}>
                    <div className="actions-cell">
                      <button className="icon-btn-sm" title={t('تفاصيل', 'Details')} onClick={() => setView(o)}><I.arrow /></button>
                      <button className="icon-btn-sm danger" title={t('حذف', 'Delete')} onClick={() => del(o.id)}><I.trash /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {view && <OrderDetail order={view} lang={lang} onClose={() => setView(null)} onStatus={setStatus} onDelete={del} onInvoice={() => setInvoice(view)} />}
      {invoice && <OrderInvoice order={invoice} lang={lang} onClose={() => setInvoice(null)} />}
    </>
  );
}

const PAY_M = { card: ['بطاقة', 'Card'], apple: ['Apple Pay', 'Apple Pay'], cod: ['الدفع عند الاستلام', 'Cash on delivery'], mada: ['مدى', 'Mada'], bank: ['حوالة', 'Bank'] };

function OrderDetail({ order, lang, onClose, onStatus, onDelete, onInvoice }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const items = order.line_items || [];
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" style={{ gridTemplateColumns: '1fr', maxWidth: 640 }} onClick={e => e.stopPropagation()}>
        <div className="modal-r" style={{ padding: 32 }}>
          <button className="modal-x" onClick={onClose}><I.close /></button>
          <div className="eyebrow">{t('تفاصيل الطلب', 'Order details')}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, margin: '4px 0 18px' }}>
            <h2 className="h-display" style={{ fontSize: 30 }}><span className="mono">{order.id}</span></h2>
            <select className={'status-pill ' + order.status} style={{ border: 'none', cursor: 'pointer', padding: '4px 14px', fontFamily: 'inherit' }}
                    value={order.status} onChange={e => onStatus(order.id, e.target.value)}>
              <option value="pending">{t('قيد الانتظار', 'Pending')}</option>
              <option value="shipped">{t('تم الشحن', 'Shipped')}</option>
              <option value="delivered">{t('تم التسليم', 'Delivered')}</option>
              <option value="cancelled">{t('ملغية', 'Cancelled')}</option>
            </select>
          </div>

          <div className="co-grid" style={{ gap: '14px 24px' }}>
            <div><div className="eyebrow" style={{ marginBottom: 4 }}>{t('العميل', 'Customer')}</div><div style={{ fontWeight: 500 }}>{order.customer}</div></div>
            <div><div className="eyebrow" style={{ marginBottom: 4 }}>{t('التاريخ', 'Date')}</div><div className="mono">{order.date}</div></div>
            <div><div className="eyebrow" style={{ marginBottom: 4 }}>{t('الجوّال', 'Phone')}</div><div className="mono" dir="ltr">{order.phone || '—'}</div></div>
            <div><div className="eyebrow" style={{ marginBottom: 4 }}>{t('البريد', 'Email')}</div><div style={{ fontSize: 13, wordBreak: 'break-all' }}>{order.email || '—'}</div></div>
            <div className="span-2"><div className="eyebrow" style={{ marginBottom: 4 }}>{t('العنوان', 'Address')}</div><div>{[order.address, order.city, order.emirate].filter(Boolean).join('، ')}</div></div>
            <div><div className="eyebrow" style={{ marginBottom: 4 }}>{t('طريقة الدفع', 'Payment')}</div><div>{PAY_M[order.pay_method] ? (lang === 'ar' ? PAY_M[order.pay_method][0] : PAY_M[order.pay_method][1]) : order.pay_method}</div></div>
          </div>

          <div className="eyebrow" style={{ margin: '22px 0 10px' }}>{t('المنتجات المطلوبة', 'Items ordered')}</div>
          <table className="table" style={{ fontSize: 13 }}>
            <thead><tr><th>{t('المنتج', 'Product')}</th><th>{t('الحجم', 'Size')}</th><th>{t('الكمية', 'Qty')}</th><th style={{ textAlign: 'end' }}>{t('المجموع', 'Total')}</th></tr></thead>
            <tbody>
              {items.map((it, i) => (
                <tr key={i}>
                  <td>{lang === 'ar' ? it.name_ar : it.name_en}</td>
                  <td className="mono">{it.size}ml</td>
                  <td className="tabular">{it.qty}</td>
                  <td style={{ textAlign: 'end' }} className="serif-en">AED {(it.price * it.qty).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>

          <div style={{ marginTop: 16, marginInlineStart: 'auto', maxWidth: 280 }}>
            <div className="summary-row"><span>{t('المجموع الفرعي', 'Subtotal')}</span><span className="tabular">{(order.subtotal || 0).toLocaleString()} AED</span></div>
            <div className="summary-row"><span>{t('الشحن', 'Shipping')}</span><span className="tabular">{order.shipping ? order.shipping + ' AED' : t('مجاناً', 'Free')}</span></div>
            <div className="summary-row"><span>{t('الضريبة', 'VAT')}</span><span className="tabular">{(order.vat || 0).toLocaleString()} AED</span></div>
            <div className="summary-row total"><span className="ar">{t('الإجمالي', 'Total')}</span><span className="serif-en">AED {order.total.toLocaleString()}</span></div>
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
            <button className="btn ghost" onClick={() => onDelete(order.id)} style={{ color: 'var(--danger)' }}><I.trash /> {t('حذف الطلب', 'Delete')}</button>
            <button className="btn" onClick={onInvoice}><I.invoice /> {t('تصدير فاتورة', 'Export invoice')}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function OrderInvoice({ order, lang, onClose }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const items = order.line_items || [];
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="invoice-doc" onClick={e => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose}><I.close /></button>
        <div className="inv-head">
          <div>
            <div className="brand-mark">{t('استبرق', 'ISTABRAQ')}</div>
            <div className="brand-mark-en">{t('عطور هندية · دبي', 'Indian perfumery · Dubai')}</div>
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--ink-3)' }}>VAT TRN: 100123456700003<br />hello@istabraq.store</div>
          </div>
          <div style={{ textAlign: 'end' }}>
            <div className="eyebrow" style={{ fontSize: 13, letterSpacing: '0.3em' }}>{t('فاتورة', 'INVOICE')}</div>
            <div className="serif-en" style={{ fontSize: 26, marginTop: 4 }}>{order.id}</div>
            <div style={{ marginTop: 8, fontSize: 12 }}><span style={{ color: 'var(--ink-3)' }}>{t('التاريخ:', 'Date:')}</span> <span className="mono">{order.date}</span></div>
          </div>
        </div>
        <hr className="fine" />
        <div className="inv-parties">
          <div><div className="eyebrow">{t('من', 'From')}</div><div style={{ fontWeight: 500, marginTop: 6 }}>{t('استبرق للعطور', 'Istabraq Perfumery')}</div><div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Dubai · UAE</div></div>
          <div><div className="eyebrow">{t('إلى', 'Bill to')}</div>
            <div style={{ fontWeight: 500, marginTop: 6 }}>{order.customer}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }} dir="ltr">{order.phone}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{order.email}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{[order.address, order.city, order.emirate].filter(Boolean).join('، ')}</div>
          </div>
        </div>
        <table className="inv-items">
          <thead><tr><th>{t('الوصف', 'Description')}</th><th style={{ textAlign: 'center' }}>{t('الكمية', 'Qty')}</th><th style={{ textAlign: 'end' }}>{t('السعر', 'Unit')}</th><th style={{ textAlign: 'end' }}>{t('المجموع', 'Amount')}</th></tr></thead>
          <tbody>
            {items.map((it, i) => (
              <tr key={i}>
                <td><div style={{ fontWeight: 500 }}>{lang === 'ar' ? it.name_ar : it.name_en}</div><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{it.concentration} · {it.size}ml</div></td>
                <td style={{ textAlign: 'center' }} className="tabular">{it.qty}</td>
                <td style={{ textAlign: 'end' }} className="tabular">{it.price.toLocaleString()}</td>
                <td style={{ textAlign: 'end' }} className="serif-en">AED {(it.price * it.qty).toLocaleString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="inv-totals">
          <div className="row"><span>{t('المجموع الفرعي', 'Subtotal')}</span><span className="tabular">AED {(order.subtotal || 0).toLocaleString()}</span></div>
          <div className="row"><span>{t('الشحن', 'Shipping')}</span><span className="tabular">{order.shipping ? 'AED ' + order.shipping : t('مجاناً', 'Free')}</span></div>
          <div className="row"><span>{t('ضريبة القيمة المضافة (٥٪)', 'VAT (5%)')}</span><span className="tabular">AED {(order.vat || 0).toLocaleString()}</span></div>
          <div className="row total"><span>{t('الإجمالي', 'Total')}</span><span className="serif-en">AED {order.total.toLocaleString()}</span></div>
        </div>
        <div className="inv-foot">
          <div className="eyebrow">{t('طريقة الدفع', 'Payment')}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 6 }}>{PAY_M[order.pay_method] ? (lang === 'ar' ? PAY_M[order.pay_method][0] : PAY_M[order.pay_method][1]) : order.pay_method} · {t('شكراً لطلبك من استبرق', 'Thank you for your order')}</div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 28, justifyContent: 'flex-end' }} className="no-print">
          <button className="btn ghost" onClick={onClose}>{t('إغلاق', 'Close')}</button>
          <button className="btn" onClick={() => window.print()}><I.print /> {t('طباعة / PDF', 'Print / PDF')}</button>
        </div>
      </div>
    </div>
  );
}

// ── Stats / Analytics ──────────────────────────────────────
function AdminStats({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [stats, setStats] = React.useState(null);
  const [fin, setFin] = React.useState(null);
  const [products, setProducts] = React.useState([]);
  React.useEffect(() => {
    apiGet('stats').then(setStats);
    apiGet('finance').then(setFin);
    apiGet('products').then(d => setProducts(Array.isArray(d) ? d : []));
  }, []);

  if (!stats || !fin) return <div style={{ padding: 60, textAlign: 'center' }}><div className="boot-bar" style={{ margin: '0 auto' }}><span /></div></div>;

  const series = fin.series.slice(-14).map(s => s.rev);
  const max = Math.max(1, ...series);
  const peak = Math.max(...series);
  const peakIdx = series.indexOf(peak);

  const cards = [
    { lbl: t('الإيرادات', 'Revenue'), val: `AED ${(stats.revenue / 1000).toFixed(1)}K` },
    { lbl: t('الطلبات', 'Orders'), val: String(stats.orders) },
    { lbl: t('العملاء', 'Customers'), val: String(stats.customers) },
    { lbl: t('متوسط قيمة الطلب', 'Avg order value'), val: `AED ${stats.aov}` },
  ];

  const fsplit = (stats.family_split || []).filter(x => x.value > 0);
  const total = fsplit.reduce((s, x) => s + x.value, 0) || 1;
  let acc = 0;
  const r = 70, circ = 2 * Math.PI * r;
  const lowStock = [...products].sort((a, b) => a.stock - b.stock).slice(0, 6);

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('الإدارة · 03', 'Manage · 03')}</div>
          <h1 className="h-display">{t('الإحصائيات', 'Analytics')}</h1>
          <div className="sub">{t('من بياناتك الفعلية', 'From your real data')}</div>
        </div>
      </div>

      <div className="stat-cards">
        {cards.map((c, i) => (
          <div key={i} className="stat-card">
            <div className="lbl">{c.lbl}</div>
            <div className="val">{c.val}</div>
          </div>
        ))}
      </div>

      <div className="chart-grid">
        <div className="chart-card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <h3>{t('الإيرادات اليومية · AED', 'Daily revenue · AED')}</h3>
            <div className="eyebrow" style={{ fontSize: 10 }}>peak: {peak.toLocaleString()} AED</div>
          </div>
          <div className="bar-chart">
            {series.map((v, i) => (
              <div key={i} className={'bar' + (i === peakIdx && peak > 0 ? ' peak' : '')}
                   style={{ height: `${(v / max) * 100}%` }} title={`AED ${v}`} />
            ))}
          </div>
          <div style={{ marginTop: 12, fontSize: 10, color: 'var(--ink-3)' }}>{t('آخر ١٤ يوماً', 'Last 14 days')}</div>
        </div>

        <div className="chart-card">
          <h3>{t('المبيعات حسب العائلة', 'Sales by family')}</h3>
          {fsplit.length === 0 ? (
            <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>{t('تظهر بعد أول عملية بيع', 'appears after the first sale')}</div>
          ) : (
            <div className="donut-wrap">
              <div className="donut">
                <svg viewBox="0 0 160 160">
                  <circle cx="80" cy="80" r={r} fill="none" stroke="var(--line)" strokeWidth="18" />
                  {fsplit.map((s) => {
                    const fam = SCENT_FAMILIES.find(f => f.id === s.id) || { tone: '#8C4A2B' };
                    const len = (s.value / total) * circ;
                    const seg = (
                      <circle key={s.id} cx="80" cy="80" r={r} fill="none" stroke={fam.tone} strokeWidth="18"
                              strokeDasharray={`${len} ${circ - len}`} strokeDashoffset={-acc} />
                    );
                    acc += len + 2;
                    return seg;
                  })}
                </svg>
                <div className="donut-center"><div className="big">100%</div><div className="lbl">{t('المبيعات', 'sales')}</div></div>
              </div>
              <div className="donut-legend">
                {fsplit.map(s => {
                  const fam = SCENT_FAMILIES.find(f => f.id === s.id) || { tone: '#8C4A2B', ar: s.id, en: s.id };
                  return (
                    <div key={s.id} className="donut-legend-row">
                      <span className="swatch" style={{ background: fam.tone }} />
                      <span>{lang === 'ar' ? fam.ar : fam.en}</span>
                      <span className="pct">{Math.round(s.value / total * 100)}%</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="chart-card" style={{ marginTop: 16 }}>
        <h3>{t('المخزون · الأقل توفّراً', 'Inventory · lowest stock')}</h3>
        {products.length === 0 ? (
          <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>{t('أضف منتجات من قسم المنتجات', 'Add products in the Products section')}</div>
        ) : (
          <table className="table" style={{ border: 'none' }}>
            <thead><tr><th>{t('المنتج', 'Product')}</th><th>{t('العائلة', 'Family')}</th><th>{t('السعر', 'Price')}</th><th>{t('المخزون', 'Stock')}</th></tr></thead>
            <tbody>
              {lowStock.map(p => {
                const fam = SCENT_FAMILIES.find(f => f.id === p.family);
                return (
                  <tr key={p.id}>
                    <td>
                      <div className="cell-product">
                        <div className="mini-img"><div className="mini-bottle" style={{ background: `linear-gradient(170deg, ${p.tone}, color-mix(in oklab, ${p.tone} 55%, #000))` }} /></div>
                        <div><div className="nm-ar">{lang === 'ar' ? p.name_ar : p.name_en}</div><div className="nm-en">{lang === 'ar' ? p.name_en : p.name_ar}</div></div>
                      </div>
                    </td>
                    <td style={{ fontSize: 13 }}>{fam ? (lang === 'ar' ? fam.ar : fam.en) : '—'}</td>
                    <td className="serif-en" style={{ fontSize: 16 }}>AED {p.price.toLocaleString()}</td>
                    <td>
                      <div className={'stock-bar ' + (p.stock < 8 ? 'crit' : p.stock < 15 ? 'low' : '')}>
                        <div className="stock-bar-track"><div className="stock-bar-fill" style={{ width: `${Math.min(100, p.stock * 2)}%` }} /></div>
                        <span>{p.stock}</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </>
  );
}

// ── Customers ──────────────────────────────────────────────
function AdminCustomers({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [CUSTOMERS, setCustomers] = React.useState([]);
  React.useEffect(() => { apiGet('customers').then(d => setCustomers(Array.isArray(d) ? d : [])); }, []);
  const vip = CUSTOMERS.filter(c => c.tier === 'VIP').length;
  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('الإدارة · 04', 'Manage · 04')}</div>
          <h1 className="h-display">{t('العملاء', 'Customers')}</h1>
          <div className="sub">{CUSTOMERS.length} {t('عميل', 'customers')} · {vip} VIP</div>
        </div>
      </div>
      <div style={{ overflowX: 'auto' }}>
        <table className="table">
          <thead>
            <tr>
              <th>{t('الاسم', 'Name')}</th>
              <th>{t('البريد', 'Email')}</th>
              <th>{t('الطلبات', 'Orders')}</th>
              <th>{t('الإنفاق', 'Spent')}</th>
              <th>{t('المستوى', 'Tier')}</th>
              <th style={{ textAlign: 'end' }}></th>
            </tr>
          </thead>
          <tbody>
            {CUSTOMERS.map(c => (
              <tr key={c.id}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--f-ar-head)', fontSize: 14 }}>
                      {c.name[0]}
                    </div>
                    <span style={{ fontWeight: 500 }}>{c.name}</span>
                  </div>
                </td>
                <td className="mono" style={{ color: 'var(--ink-3)' }}>{c.email}</td>
                <td className="tabular">{c.orders}</td>
                <td className="serif-en" style={{ fontSize: 16 }}>AED {c.spent.toLocaleString()}</td>
                <td><span className={'status-pill ' + (c.tier === 'VIP' ? 'delivered' : c.tier === 'Member' ? 'shipped' : 'pending')}>{c.tier}</span></td>
                <td><div className="actions-cell"><button className="icon-btn-sm"><I.arrow /></button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function AdminSettings({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [s, setS] = React.useState(null);
  const [saved, setSaved] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => { apiGet('settings').then(d => setS(d || {})); }, []);
  const upd = (k, v) => { setS({ ...s, [k]: v }); setSaved(false); };
  const save = async () => {
    setBusy(true);
    await apiPut('settings', null, s);
    setBusy(false); setSaved(true);
  };
  if (!s) return <div style={{ padding: 60, textAlign: 'center' }}><div className="boot-bar" style={{ margin: '0 auto' }}><span /></div></div>;

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('الإدارة · 05', 'Manage · 05')}</div>
          <h1 className="h-display">{t('الإعدادات', 'Settings')}</h1>
          <div className="sub">{t('بيانات المتجر، الشحن، الضريبة وبوابة الدفع', 'Store, shipping, tax & payment')}</div>
        </div>
        <div className="actions">
          {saved && <span style={{ alignSelf: 'center', color: 'var(--success)', fontSize: 13 }}>{t('تم الحفظ ✓', 'Saved ✓')}</span>}
          <button className="btn" onClick={save} disabled={busy}>{busy ? '…' : t('حفظ التغييرات', 'Save changes')}</button>
        </div>
      </div>
      <div style={{ maxWidth: 760, display: 'flex', flexDirection: 'column', gap: 24 }}>
        <div className="chart-card">
          <h3>{t('بيانات المتجر', 'Store info')}</h3>
          <div className="co-grid">
            <div className="field"><label>{t('اسم المتجر (عربي)', 'Store name (AR)')}</label><input value={s.store_name_ar || ''} onChange={e => upd('store_name_ar', e.target.value)} /></div>
            <div className="field"><label>{t('اسم المتجر (إنجليزي)', 'Store name (EN)')}</label><input value={s.store_name_en || ''} onChange={e => upd('store_name_en', e.target.value)} /></div>
            <div className="field"><label>{t('البريد', 'Email')}</label><input value={s.contact_email || ''} onChange={e => upd('contact_email', e.target.value)} /></div>
            <div className="field"><label>{t('الهاتف', 'Phone')}</label><input value={s.contact_phone || ''} onChange={e => upd('contact_phone', e.target.value)} /></div>
            <div className="field span-2"><label>{t('العنوان', 'Address')}</label><input value={s.address || ''} onChange={e => upd('address', e.target.value)} /></div>
            <div className="field"><label>{t('الرقم الضريبي TRN', 'Tax TRN')}</label><input value={s.trn || ''} onChange={e => upd('trn', e.target.value)} /></div>
            <div className="field"><label>{t('العملة', 'Currency')}</label>
              <select value={s.currency || 'AED'} onChange={e => upd('currency', e.target.value)}><option>AED</option><option>SAR</option><option>USD</option></select>
            </div>
          </div>
        </div>
        <div className="chart-card">
          <h3>{t('الشحن والضريبة', 'Shipping & tax')}</h3>
          <div className="co-grid">
            <div className="field"><label>{t('نسبة الضريبة ٪', 'VAT rate %')}</label><input type="number" value={s.vat_rate || ''} onChange={e => upd('vat_rate', e.target.value)} /></div>
            <div className="field"><label>{t('شحن مجاني فوق (AED)', 'Free shipping over (AED)')}</label><input type="number" value={s.free_ship_over || ''} onChange={e => upd('free_ship_over', e.target.value)} /></div>
            <div className="field"><label>{t('قيمة الشحن (AED)', 'Flat shipping (AED)')}</label><input type="number" value={s.flat_shipping || ''} onChange={e => upd('flat_shipping', e.target.value)} /></div>
          </div>
        </div>
        <div className="chart-card">
          <h3>{t('بوابة الدفع', 'Payment gateway')}</h3>
          <div className="co-grid">
            <div className="field"><label>{t('المزوّد', 'Provider')}</label>
              <select value={s.pay_gateway || ''} onChange={e => upd('pay_gateway', e.target.value)}>
                <option value="">{t('— غير مفعّل —', '— not enabled —')}</option>
                <option value="tap">Tap Payments</option>
                <option value="telr">Telr</option>
                <option value="paytabs">PayTabs</option>
                <option value="stripe">Stripe</option>
              </select>
            </div>
            <div className="field"><label>{t('وضع الاختبار', 'Test mode')}</label>
              <select value={s.pay_test_mode || '1'} onChange={e => upd('pay_test_mode', e.target.value)}><option value="1">{t('تجريبي', 'Test')}</option><option value="0">{t('مباشر', 'Live')}</option></select>
            </div>
            <div className="field span-2"><label>{t('المفتاح العام (Publishable)', 'Publishable key')}</label><input value={s.pay_publishable || ''} onChange={e => upd('pay_publishable', e.target.value)} placeholder="pk_..." /></div>
            <div className="field span-2"><label>{t('المفتاح السري (Secret)', 'Secret key')}</label><input type="password" value={s.pay_secret || ''} onChange={e => upd('pay_secret', e.target.value)} placeholder="sk_..." /></div>
          </div>
          <div style={{ marginTop: 12, fontSize: 12, color: 'var(--ink-3)' }}>{t('أدخل مفاتيح حسابك من المزوّد لتفعيل الدفع بالبطاقة عند الشراء.', 'Enter your provider keys to enable card payment at checkout.')}</div>
        </div>
      </div>
    </>
  );
}

// ── Site appearance / content editor ───────────────────────
function AdminSite({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [s, setS] = React.useState(null);
  const [saved, setSaved] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const fileRef = React.useRef();
  React.useEffect(() => { apiGet('settings').then(d => setS(d || {})); }, []);
  const upd = (k, v) => { setS(prev => ({ ...prev, [k]: v })); setSaved(false); };
  const save = async () => { setBusy(true); await apiPut('settings', null, s); setBusy(false); setSaved(true); };
  const onFile = async (e) => {
    const f = e.target.files && e.target.files[0]; if (!f) return;
    setUploading(true); const r = await apiUpload(f); setUploading(false);
    if (r && r.url) upd('hero_image', r.url); else alert((r && r.error) || 'upload failed');
    e.target.value = '';
  };
  if (!s) return <div style={{ padding: 60, textAlign: 'center' }}><div className="boot-bar" style={{ margin: '0 auto' }}><span /></div></div>;

  return (
    <>
      <div className="admin-head">
        <div>
          <div className="eyebrow">{t('الإدارة · 06', 'Manage · 06')}</div>
          <h1 className="h-display">{t('الموقع والمظهر', 'Site & appearance')}</h1>
          <div className="sub">{t('عدّل صورة الواجهة والنصوص واللون — تظهر مباشرة في المتجر', 'Edit hero image, text and color — reflects on the storefront')}</div>
        </div>
        <div className="actions">
          {saved && <span style={{ alignSelf: 'center', color: 'var(--success)', fontSize: 13 }}>{t('تم الحفظ ✓', 'Saved ✓')}</span>}
          <button className="btn" onClick={save} disabled={busy}>{busy ? '…' : t('حفظ ونشر', 'Save & publish')}</button>
        </div>
      </div>

      <div style={{ maxWidth: 760, display: 'flex', flexDirection: 'column', gap: 24 }}>
        <div className="chart-card">
          <h3>{t('صورة الواجهة (Hero)', 'Hero image')}</h3>
          <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start', flexWrap: 'wrap' }}>
            <div style={{ width: 220, height: 150, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {s.hero_image
                ? <img src={s.hero_image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                : <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t('لا صورة (عرض افتراضي)', 'No image (default render)')}</span>}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
              <button className="btn ghost sm" onClick={() => fileRef.current && fileRef.current.click()} disabled={uploading}>
                <I.upload /> {uploading ? t('جارٍ الرفع…', 'Uploading…') : t('رفع صورة', 'Upload image')}
              </button>
              {s.hero_image && <button className="btn ghost sm" onClick={() => upd('hero_image', '')}>{t('إزالة', 'Remove')}</button>}
            </div>
          </div>
        </div>

        <div className="chart-card">
          <h3>{t('نصوص الواجهة', 'Hero text')}</h3>
          <div className="co-grid">
            <div className="field span-2"><label>{t('العنوان (عربي)', 'Title (AR)')}</label><input value={s.hero_title_ar || ''} onChange={e => upd('hero_title_ar', e.target.value)} /></div>
            <div className="field span-2"><label>{t('العنوان (إنجليزي)', 'Title (EN)')}</label><input value={s.hero_title_en || ''} onChange={e => upd('hero_title_en', e.target.value)} /></div>
            <div className="field span-2"><label>{t('الوصف (عربي)', 'Subtitle (AR)')}</label><input value={s.hero_sub_ar || ''} onChange={e => upd('hero_sub_ar', e.target.value)} /></div>
            <div className="field span-2"><label>{t('الوصف (إنجليزي)', 'Subtitle (EN)')}</label><input value={s.hero_sub_en || ''} onChange={e => upd('hero_sub_en', e.target.value)} /></div>
          </div>
        </div>

        <div className="chart-card">
          <h3>{t('اللون والمظهر', 'Color & layout')}</h3>
          <div className="co-grid">
            <div className="field"><label>{t('لون الهوية (Accent)', 'Accent color')}</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <input type="color" value={s.accent || '#B97A5E'} onChange={e => upd('accent', e.target.value)} style={{ width: 46, height: 34, padding: 0, border: '1px solid var(--line)', borderRadius: 8, background: 'none' }} />
                <input value={s.accent || ''} onChange={e => upd('accent', e.target.value)} style={{ flex: 1 }} />
              </div>
            </div>
            <div className="field"><label>{t('عرض محرّك الذكاء الاصطناعي', 'Show AI console')}</label>
              <select value={String(s.show_ai ?? '1')} onChange={e => upd('show_ai', e.target.value)}>
                <option value="1">{t('نعم', 'Yes')}</option><option value="0">{t('لا', 'No')}</option>
              </select>
            </div>
          </div>
          <div style={{ marginTop: 10, display: 'flex', gap: 8 }}>
            {['#B97A5E','#7E8B5E','#C08274','#9A8C72','#C46A4B','#8A8B6C'].map(c => (
              <button key={c} onClick={() => upd('accent', c)} title={c}
                      style={{ width: 26, height: 26, borderRadius: '50%', background: c, border: (s.accent||'').toLowerCase() === c.toLowerCase() ? '2px solid var(--ink)' : '1px solid var(--line)' }} />
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

window.AdminLayout = AdminLayout;
window.AdminProducts = AdminProducts;
window.AdminOrders = AdminOrders;
window.AdminStats = AdminStats;
window.AdminCustomers = AdminCustomers;
window.AdminSettings = AdminSettings;
window.AdminSite = AdminSite;
