// 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(PRODUCTS);
  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 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 = (p) => {
    if (creating) {
      setProducts([{ ...p, id: 'p' + String(products.length + 1).padStart(2, '0') }, ...products]);
    } else {
      setProducts(products.map(x => x.id === p.id ? p : x));
    }
    setEdit(null); setCreating(false);
  };
  const del = (id) => {
    if (!confirm(t('حذف المنتج؟', 'Delete this product?'))) return;
    setProducts(products.filter(p => p.id !== id));
  };

  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' }); 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°{p.id.slice(1)}</div></td>
                  <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">{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 upd = (k, v) => setP({ ...p, [k]: v });
  const updSize = (i, k, v) => {
    const sizes = [...p.sizes];
    sizes[i] = { ...sizes[i], [k]: Number(v) };
    setP({ ...p, sizes });
  };
  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, background: `linear-gradient(170deg, ${p.tone} 0%, color-mix(in oklab, ${p.tone} 55%, #000) 100%)`, margin: '0 auto' }}>
            <div className="pdp-label" style={{ fontSize: 10 }}>
              ISTABRAQ<br /><span style={{ fontSize: 13 }}>{p.name_en || 'NAME'}</span>
            </div>
          </div>
          <button className="btn ghost sm" style={{ width: '100%' }}>
            <I.upload /> {t('رفع صورة', 'Upload image')}
          </button>
          <div className="field" style={{ marginTop: 4 }}>
            <label>{t('لون البطاقة', 'Card tone')}</label>
            <div style={{ display: 'flex', gap: 6 }}>
              {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 style={{ display: 'flex', gap: 8, marginTop: 32, justifyContent: 'flex-end' }}>
            <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(ORDERS);
  const [statusFilter, setStatusFilter] = React.useState('all');
  const filtered = orders.filter(o => statusFilter === 'all' || o.status === statusFilter);
  const setStatus = (id, status) => setOrders(orders.map(o => o.id === id ? { ...o, status } : o));

  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 },
  ];

  const statusLabel = (s) => ({
    pending: t('قيد الانتظار', 'Pending'),
    shipped: t('تم الشحن', 'Shipped'),
    delivered: t('تم التسليم', 'Delivered'),
    cancelled: t('ملغية', 'Cancelled'),
  })[s];

  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('طلب · 18,420 AED مبيعات هذا الأسبوع', 'orders · AED 18,420 this week')}</div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 24, borderBottom: '1px solid var(--line)', paddingBottom: 0 }}>
        {tabs.map(tab => (
          <button key={tab.id}
                  className="btn ghost sm"
                  style={{
                    borderRadius: 0, border: 'none',
                    borderBottom: '2px solid ' + (statusFilter === tab.id ? 'var(--ink)' : '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>

      <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}>
                <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.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>
                  <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>
                  <div className="actions-cell">
                    <button className="icon-btn-sm"><I.arrow /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ── Stats ──────────────────────────────────────────────────
function AdminStats({ lang }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const max = Math.max(...REVENUE_SERIES);
  const totalRev = REVENUE_SERIES.reduce((a, b) => a + b, 0);
  const peakIdx = REVENUE_SERIES.indexOf(max);

  const cards = [
    { lbl: t('الإيرادات (14 يوم)', 'Revenue · 14d'), val: `AED ${(totalRev / 1000).toFixed(1)}K`, delta: '+12.4%', up: true },
    { lbl: t('الطلبات', 'Orders'),                    val: '142', delta: '+8.1%', up: true },
    { lbl: t('متوسط قيمة الطلب', 'Avg order value'),  val: 'AED 612', delta: '+4.2%', up: true },
    { lbl: t('معدل التحويل', 'Conversion'),            val: '3.8%', delta: '−0.4%', up: false },
  ];

  // donut
  const total = FAMILY_SPLIT.reduce((s, x) => s + x.pct, 0);
  let acc = 0;
  const r = 70, circ = 2 * Math.PI * r;

  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('آخر ١٤ يوماً', 'Last 14 days')}</div>
        </div>
        <div className="actions">
          <select className="btn ghost" style={{ padding: '0 18px' }}>
            <option>{t('آخر ١٤ يوم', 'Last 14 days')}</option>
            <option>{t('هذا الشهر', 'This month')}</option>
            <option>{t('آخر ٣٠ يوماً', 'Last 30 days')}</option>
          </select>
        </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 className={'delta ' + (c.up ? 'up' : 'down')}>
              {c.up ? <I.trendUp /> : <I.trendDown />} {c.delta} {t('vs الأسبوع السابق', 'vs last period')}
            </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: {max.toLocaleString()} AED</div>
          </div>
          <div className="bar-chart">
            {REVENUE_SERIES.map((v, i) => (
              <div key={i} className={'bar' + (i === peakIdx ? ' peak' : '')}
                   style={{ height: `${(v / max) * 100}%` }} title={`Day ${i + 1}: AED ${v}`} />
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--f-en-body)' }}>
            <span>May 5</span><span>May 12</span><span>May 18</span>
          </div>
        </div>

        <div className="chart-card">
          <h3>{t('المبيعات حسب العائلة', 'Sales by family')}</h3>
          <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" />
                {FAMILY_SPLIT.map((s, i) => {
                  const fam = SCENT_FAMILIES.find(f => f.id === s.id);
                  const len = (s.pct / 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; // 2px gap
                  return seg;
                })}
              </svg>
              <div className="donut-center">
                <div className="big">100%</div>
                <div className="lbl">{t('المبيعات', 'sales')}</div>
              </div>
            </div>
            <div className="donut-legend">
              {FAMILY_SPLIT.map(s => {
                const fam = SCENT_FAMILIES.find(f => f.id === 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">{s.pct}%</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* top products */}
      <div className="chart-card" style={{ marginTop: 16 }}>
        <h3>{t('الأكثر مبيعاً هذا الأسبوع', 'Top products this week')}</h3>
        <table className="table" style={{ border: 'none' }}>
          <thead>
            <tr>
              <th>{t('المنتج', 'Product')}</th>
              <th>{t('وحدات مباعة', 'Units sold')}</th>
              <th>{t('الإيرادات', 'Revenue')}</th>
              <th>{t('المخزون المتبقي', 'Stock left')}</th>
            </tr>
          </thead>
          <tbody>
            {[0, 10, 4, 8, 18].map((i, j) => {
              const p = PRODUCTS[i];
              const units = [42, 38, 31, 27, 24][j];
              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 className="tabular">{units}</td>
                  <td className="serif-en" style={{ fontSize: 16 }}>AED {(units * 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;
  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('عميل · 3 VIP', 'customers · 3 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;
  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 data & payment gateways')}</div>
        </div>
      </div>
      <div style={{ maxWidth: 720, display: 'flex', flexDirection: 'column', gap: 32 }}>
        <div className="chart-card">
          <h3>{t('بيانات المتجر', 'Store info')}</h3>
          <div className="co-grid">
            <div className="field span-2"><label>{t('اسم المتجر', 'Store name')}</label><input defaultValue="استبرق · Istabraq" /></div>
            <div className="field"><label>{t('العملة الافتراضية', 'Currency')}</label><select defaultValue="AED"><option>AED</option><option>SAR</option><option>USD</option></select></div>
            <div className="field"><label>{t('الضريبة', 'Tax')}</label><input defaultValue="5%" /></div>
          </div>
        </div>
        <div className="chart-card">
          <h3>{t('بوابات الدفع', 'Payment gateways')}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              ['Stripe',     t('متصل', 'Connected'),     true],
              ['Apple Pay',  t('متصل', 'Connected'),     true],
              ['Mada',       t('متصل', 'Connected'),     true],
              ['PayPal',     t('غير متصل', 'Not connected'), false],
            ].map(([name, status, on]) => (
              <div key={name} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 0', borderTop: '1px solid var(--line-2)' }}>
                <div>
                  <div style={{ fontWeight: 500 }}>{name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{status}</div>
                </div>
                <button className={on ? 'btn ghost sm' : 'btn sm'}>{on ? t('إدارة', 'Manage') : t('ربط', 'Connect')}</button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

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