// ============================================================
// Saraya Events — Admin Dashboard
//
// Phase 1 scope:
//   • Platform stats overview
//   • Vendor approval queue (approve / reject / suspend)
//   • Subscription management (view, give free access, downgrade)
//   • Payout management (approve / hold / release)
//   • Complaint queue
//   • Subscription tier editor (names, prices, limits)
//   • User list
// ============================================================

const {
  useState: useStateAD,
  useEffect: useEffectAD,
  useCallback: useCallbackAD,
} = React;

/* ---------- Stat card ---------- */
function AdminStat({ icon, label, value, tone }) {
  const colors = {
    gold:    { bg: 'var(--cream)',  fg: 'var(--gold-deep)' },
    success: { bg: '#F0FDF4',      fg: '#16A34A' },
    warning: { bg: '#FFFBEB',      fg: '#D97706' },
    danger:  { bg: '#FEF2F2',      fg: '#B91C1C' },
  };
  const c = colors[tone] || colors.gold;
  return (
    <div style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', padding: '18px 20px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <span style={{ display: 'inline-flex', width: 36, height: 36, borderRadius: 10, background: c.bg, alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={18} style={{ color: c.fg }} />
        </span>
        <span style={{ fontSize: 12, color: 'var(--fg-secondary)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{label}</span>
      </div>
      <p style={{ fontSize: 30, fontWeight: 700, fontFamily: 'var(--font-display)', margin: 0 }}>{value ?? '—'}</p>
    </div>
  );
}

const COMPLAINT_TYPE_LABELS = {
  booking_issue: 'Booking issue',
  rental_issue: 'Rental issue',
  service_issue: 'Service issue',
  vendor_issue: 'Vendor issue',
  payment_issue: 'Payment issue',
  delivery_issue: 'Delivery issue',
  order_issue: 'Order issue',
  quality_issue: 'Quality issue',
  vendor_conduct: 'Vendor conduct',
  billing_dispute: 'Billing dispute',
  other: 'Other',
};

/* ---------- Status badge ---------- */
function StatusBadge({ status }) {
  const MAP = {
    active:               { bg: '#DCFCE7', fg: '#16A34A' },
    approved:             { bg: '#DCFCE7', fg: '#16A34A' },
    pending_approval:     { bg: '#FEF3C7', fg: '#D97706' },
    payment_pending:      { bg: '#DBEAFE', fg: '#1D4ED8' },
    package_pending:      { bg: '#F3E8FF', fg: '#7C3AED' },
    registered:           { bg: '#F3F4F6', fg: '#6B7280' },
    suspended:            { bg: '#FEE2E2', fg: '#B91C1C' },
    deactivated:          { bg: '#F3F4F6', fg: '#9CA3AF' },
    // legacy statuses (kept for backward compatibility)
    agreement_accepted:   { bg: '#D1FAE5', fg: '#059669' },
    under_review:         { bg: '#FEF3C7', fg: '#D97706' },
    documents_submitted:  { bg: '#DBEAFE', fg: '#1D4ED8' },
    pending:              { bg: '#FEF3C7', fg: '#D97706' },
    approved_payout:      { bg: '#D1FAE5', fg: '#059669' },
    on_hold:              { bg: '#FEE2E2', fg: '#B91C1C' },
    paid:                 { bg: '#DCFCE7', fg: '#16A34A' },
    open:                 { bg: '#DBEAFE', fg: '#1D4ED8' },
    resolved:             { bg: '#DCFCE7', fg: '#16A34A' },
  };
  const s = MAP[status] || { bg: '#F3F4F6', fg: '#6B7280' };
  return (
    <span style={{ padding: '3px 10px', borderRadius: 20, background: s.bg, color: s.fg, fontSize: 12, fontWeight: 600, textTransform: 'capitalize' }}>
      {(status || '').replace(/_/g, ' ')}
    </span>
  );
}

/* ---------- Section wrapper ---------- */
function AdminSection({ title, desc, children, action }) {
  return (
    <div style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
        <div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, margin: 0 }}>{title}</h2>
          {desc && <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: '3px 0 0' }}>{desc}</p>}
        </div>
        {action}
      </div>
      <div style={{ padding: '0' }}>{children}</div>
    </div>
  );
}

/* ---------- Table ---------- */
function AdminTable({ cols, rows, emptyMsg }) {
  if (!rows || rows.length === 0) {
    return (
      <div style={{ padding: '32px 22px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>
        {emptyMsg || 'No records'}
      </div>
    );
  }
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
        <thead>
          <tr style={{ background: 'var(--bg-tint)' }}>
            {cols.map((c) => (
              <th key={c.key} style={{ padding: '10px 16px', textAlign: 'start', fontWeight: 600, fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-secondary)', borderBottom: '1px solid var(--line)', whiteSpace: 'nowrap' }}>
                {c.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr key={row.id || i} style={{ borderBottom: '1px solid var(--line)', transition: 'background 120ms' }}
              onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bg-tint)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = ''; }}>
              {cols.map((c) => (
                <td key={c.key} style={{ padding: '12px 16px', verticalAlign: 'middle', whiteSpace: c.wrap ? 'normal' : 'nowrap' }}>
                  {c.render ? c.render(row) : (row[c.key] ?? '—')}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- Confirm dialog ---------- */
function ConfirmDialog({ msg, onOk, onCancel, dangerous }) {
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(42,31,26,0.5)', padding: 16 }}>
      <div style={{ background: 'var(--white)', borderRadius: 16, padding: '28px', maxWidth: 380, width: '100%', boxShadow: 'var(--shadow-deep)' }}>
        <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--fg-primary)', marginBottom: 20 }}>{msg}</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onCancel}>Cancel</Button>
          <Button variant={dangerous ? 'danger' : 'primary'} onClick={onOk}>Confirm</Button>
        </div>
      </div>
    </div>
  );
}

/* ---- Placeholder panel for sections not yet backed by live data ---- */
function AdminPlaceholder({ title, desc, items, note }) {
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={{ padding: '16px 20px', borderRadius: 12, background: '#FFFBEB', border: '1.5px solid #FCD34D', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <Icon name="construction" size={18} style={{ color: '#D97706', flexShrink: 0, marginTop: 2 }} />
        <div>
          <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>Backend Required</div>
          <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>{note || 'This section requires Supabase tables and RLS policies to be configured. The UI is ready — connect the data source to activate.'}</div>
        </div>
      </div>
      {items && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(220px,1fr))', gap: 12 }}>
          {items.map((item, i) => (
            <div key={i} style={{ padding: '18px 20px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <span style={{ display: 'inline-flex', width: 32, height: 32, borderRadius: 8, background: 'var(--cream)', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={item.icon} size={16} style={{ color: 'var(--gold-deep)' }} />
                </span>
                <span style={{ fontWeight: 600, fontSize: 13.5 }}>{item.label}</span>
              </div>
              <p style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.5, margin: 0 }}>{item.desc}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}



/* ============================================================
   ADMIN MARKETPLACE LISTINGS APPROVAL
   ============================================================ */
function AdminListingsApproval() {
  const db = window.SarayaDB;
  const [listType, setListType] = window.React.useState('products');
  const [items, setItems]       = window.React.useState([]);
  const [loading, setLoading]   = window.React.useState(true);
  const [busyId, setBusyId]     = window.React.useState('');
  const [filterActive, setFilterActive] = window.React.useState('all'); const [filterStatus, setFilterStatus] = window.React.useState('all');

  const TABLE = listType === 'products' ? 'products' : listType === 'rentals' ? 'rentals' : 'services';

  const load = async () => {
    if (!db) return;
    setLoading(true);
    let q = db.from(TABLE).select('*, vendor_profiles(trade_name)').order('created_at', { ascending: false }).limit(100);
    const { data, error } = await q;
    if (!error && data) setItems(data);
    setLoading(false);
  };

  window.React.useEffect(() => { load(); }, [listType]);

  const toggle = async (id, field, current) => {
    setBusyId(id + field);
    await db.from(TABLE).update({ [field]: !current }).eq('id', id);
    setItems((prev) => prev.map((it) => it.id === id ? { ...it, [field]: !current } : it));
    setBusyId('');
  };
  const setStatus = async (id, status) => { setBusyId(id + 'status'); await db.from(TABLE).update({ status }).eq('id', id); setItems((prev) => prev.map((it) => it.id === id ? { ...it, status } : it)); setBusyId(''); };

  const filtered = items.filter((it) => {
    if (filterActive === 'active') return it.is_active !== false;
    if (filterActive === 'inactive') return it.is_active === false;
    if (filterStatus !== 'all' && (it.status || 'approved') !== filterStatus) return false;
    return true;
  });

  const priceCol = listType === 'products' ? 'price' : listType === 'rentals' ? 'price_per_day' : 'base_price';
  const typeColors = { products: '#1B2A4A', rentals: '#2D7D78', services: '#B8965A' };
  const typeLabel  = { products: 'Product', rentals: 'Rental', services: 'Service' };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {/* Type tabs */}
      <div style={{ display: 'flex', gap: 0, borderRadius: 10, overflow: 'hidden', border: '1px solid var(--line)', width: 'fit-content' }}>
        {['products','rentals','services'].map((t) => (
          <button key={t} onClick={() => setListType(t)} style={{ padding: '8px 18px', border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: 13, background: listType === t ? 'var(--espresso)' : 'var(--white)', color: listType === t ? 'var(--ivory)' : 'var(--fg-primary)', borderInlineEnd: t !== 'services' ? '1px solid var(--line)' : 'none' }}>
            {t.charAt(0).toUpperCase() + t.slice(1)}
          </button>
        ))}
      </div>
      {/* Status filter */}
      <div style={{ display: 'flex', gap: 8 }}>
        {[['all','All'],['active','Active'],['inactive','Inactive / Draft']].map(([v,l]) => (
          <button key={v} onClick={() => setFilterActive(v)} style={{ padding: '5px 12px', borderRadius: 20, border: '1px solid var(--line)', cursor: 'pointer', fontSize: 12.5, fontWeight: filterActive===v ? 700 : 400, background: filterActive===v ? 'var(--espresso)' : 'var(--white)', color: filterActive===v ? 'var(--ivory)' : 'var(--fg-primary)' }}>
            {l}
          </button>
        ))}
        <span style={{ fontSize: 12, color: 'var(--fg-muted)', alignSelf: 'center' }}>{filtered.length} listing{filtered.length !== 1 ? 's' : ''}</span>
      </div>
      {/* Status filter */}
      <div style={{ display: 'flex', gap: 8 }}>
        {[['all','All'],['pending','Pending Review'],['approved','Approved'],['rejected','Rejected']].map(([v,l]) => (
          <button key={v} onClick={() => setFilterStatus(v)} style={{ padding: '5px 12px', borderRadius: 20, border: '1px solid var(--line)', cursor: 'pointer', fontSize: 12.5, fontWeight: filterStatus===v ? 700 : 400, background: filterStatus===v ? 'var(--espresso)' : 'var(--white)', color: filterStatus===v ? 'var(--ivory)' : 'var(--fg-primary)' }}>
            {l}
          </button>
        ))}
        <span style={{ fontSize: 12, color: 'var(--fg-muted)', alignSelf: 'center' }}>{filtered.length} listing{filtered.length !== 1 ? 's' : ''}</span>
      </div>
      
      {loading ? (
        <div style={{ textAlign: 'center', padding: 40, color: 'var(--fg-muted)' }}><Icon name="loader" size={28} style={{ animation: 'sarayaSpin 1s linear infinite' }} /></div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: 32, textAlign: 'center', background: 'var(--white)', borderRadius: 12, border: '1px dashed var(--line)', color: 'var(--fg-muted)', fontSize: 14 }}>
          No {listType} found.
        </div>
      ) : (
        <div style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-tint)', borderBottom: '1px solid var(--line)' }}>
                {['Image','Name','Vendor','Price','Status','Active','Popular','Actions'].map((h) => (
                  <th key={h} style={{ padding: '10px 14px', textAlign: 'start', fontWeight: 600, fontSize: 11.5, color: 'var(--fg-secondary)', textTransform: 'uppercase', letterSpacing: '.05em', whiteSpace: 'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((it, idx) => {
                const imgSrc = (it.images && it.images[0]) || it.src || it.cover_image_url || null;
                const price = it[priceCol];
                const isActive = it.is_active !== false;
                const isPopular = it.is_popular || false;
                const vendorName = (it.vendor_profiles && it.vendor_profiles.trade_name) || '—';
                return (
                  <tr key={it.id} style={{ borderBottom: idx < filtered.length-1 ? '1px solid var(--line)' : 'none', background: isActive ? 'transparent' : 'var(--bg-tint,#f9f9fb)' }}>
                    <td style={{ padding: '10px 14px' }}>
                      {imgSrc ? (
                        <img src={imgSrc} alt="" style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 8, border: '1px solid var(--line)', display: 'block' }} />
                      ) : (
                        <div style={{ width: 48, height: 48, borderRadius: 8, background: 'var(--gold-tint,#fdf8f0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <Icon name="image" size={20} style={{ color: 'var(--gold-deep)' }} />
                        </div>
                      )}
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <div style={{ fontWeight: 600, maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.name_en}</div>
                      {it.name_ar && <div style={{ fontSize: 11.5, color: 'var(--fg-secondary)', direction: 'rtl', textAlign: 'start' }}>{it.name_ar}</div>}
                      <span style={{ display: 'inline-block', padding: '1px 7px', borderRadius: 10, fontSize: 10.5, fontWeight: 700, background: typeColors[listType] + '1A', color: typeColors[listType], marginTop: 3 }}>{typeLabel[listType]}</span>{it.status && it.status !== 'approved' && <span style={{ display: 'inline-block', marginInlineStart: 6, padding: '1px 7px', borderRadius: 10, fontSize: 10.5, fontWeight: 700, background: it.status === 'pending' ? '#FEF3C7' : '#FEE2E2', color: it.status === 'pending' ? '#92400E' : '#991B1B' }}>{it.status === 'pending' ? 'Pending Review' : 'Rejected'}</span>}
                    </td>
                    <td style={{ padding: '10px 14px', color: 'var(--fg-secondary)', fontSize: 12.5 }}>{vendorName}</td>
                    <td style={{ padding: '10px 14px', whiteSpace: 'nowrap' }}>{price ? `AED ${Number(price).toLocaleString()}` : '—'}</td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{ display: 'inline-flex', padding: '3px 9px', borderRadius: 20, fontSize: 11.5, fontWeight: 700, background: isActive ? '#DCFCE7' : '#F3F4F6', color: isActive ? '#16A34A' : '#6B7280' }}>
                        {isActive ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <button onClick={() => toggle(it.id, 'is_active', isActive)} disabled={busyId === it.id+'is_active'} title={isActive ? 'Deactivate' : 'Activate'} style={{ width: 32, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer', position: 'relative', background: isActive ? '#16A34A' : '#D1D5DB', transition: 'background 200ms' }}>
                        <span style={{ position: 'absolute', top: 2, left: isActive ? 14 : 2, width: 16, height: 16, borderRadius: 8, background: '#fff', transition: 'left 200ms', display: 'block' }} />
                      </button>
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      {listType === 'products' && (
                        <button onClick={() => toggle(it.id, 'is_popular', isPopular)} disabled={busyId === it.id+'is_popular'} title={isPopular ? 'Unfeature' : 'Feature'} style={{ width: 32, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer', position: 'relative', background: isPopular ? '#B8965A' : '#D1D5DB', transition: 'background 200ms' }}>
                          <span style={{ position: 'absolute', top: 2, left: isPopular ? 14 : 2, width: 16, height: 16, borderRadius: 8, background: '#fff', transition: 'left 200ms', display: 'block' }} />
                        </button>
                      )}
                      {listType !== 'products' && <span style={{ color: 'var(--fg-muted)', fontSize: 12 }}>—</span>}
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <div style={{ display: 'flex', gap: 6, flexWrap: 'nowrap' }}>
                        <Button variant="primary" small onClick={() => toggle(it.id, 'is_active', !true)} style={{ display: isActive ? 'none' : undefined }}>
                          Activate
                        </Button>
                        <button onClick={() => toggle(it.id, 'is_active', isActive)} style={{ padding: '4px 10px', borderRadius: 7, border: '1px solid var(--line)', background: 'var(--white)', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: isActive ? 'var(--error,#dc2626)' : '#16A34A' }}>
                          {isActive ? 'Deactivate' : 'Activate'}
                        </button>
                        {it.status && it.status !== 'approved' && <button onClick={() => setStatus(it.id, 'approved')} disabled={busyId === it.id+'status'} style={{ padding: '4px 10px', borderRadius: 7, border: 'none', background: '#16A34A', color: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 600 }}>
                          Approve
                        </button>}

                        {it.status === 'pending' && <button onClick={() => setStatus(it.id, 'rejected')} disabled={busyId === it.id+'status'} style={{ padding: '4px 10px', borderRadius: 7, border: '1px solid var(--line)', background: 'var(--white)', color: '#dc2626', cursor: 'pointer', fontSize: 12, fontWeight: 600 }}>
                          Reject
                        </button>}
                      
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

/* ============================================================
   ADMIN PLATFORM IMAGE CMS
   ============================================================ */
function AdminPlatformImageCMS() {
  const db = window.SarayaDB;
  const [images, setImages]         = window.React.useState([]);
  const [loading, setLoading]       = window.React.useState(true);
  const [tableExists, setTableExists] = window.React.useState(null);
  const [uploading, setUploading]   = window.React.useState('');
  const [showAddForm, setShowAddForm] = window.React.useState(false);
  const [newImg, setNewImg]         = window.React.useState({ page_key: 'home', section_key: 'hero', image_url: '', image_alt_en: '', title_en: '' });

  const PAGE_KEYS    = ['home','store','rental','service','showroom','global'];
  const SECTION_KEYS = ['hero','banner','category','promo','logo'];

  const load = async () => {
    if (!db) { setLoading(false); return; }
    try {
      const { data, error } = await db.from('platform_images').select('*').order('page_key').order('image_order');
      if (error && error.code === '42P01') { setTableExists(false); setLoading(false); return; }
      setTableExists(true);
      if (!error && data) setImages(data);
    } catch (_e) { setTableExists(false); }
    setLoading(false);
  };

  window.React.useEffect(() => { load(); }, []);

  const toggleActive = async (id, current) => {
    await db.from('platform_images').update({ is_active: !current }).eq('id', id);
    setImages((prev) => prev.map((im) => im.id === id ? { ...im, is_active: !current } : im));
  };

  const deleteImage = async (id) => {
    if (!window.confirm('Delete this platform image?')) return;
    await db.from('platform_images').delete().eq('id', id);
    setImages((prev) => prev.filter((im) => im.id !== id));
  };

  const handleFileUpload = async (e, existingId) => {
    const file = e.target.files && e.target.files[0];
    if (!file || !window.SarayaService) return;
    setUploading(existingId || 'new');
    const { url, error } = await window.SarayaService.storage.uploadListingImage('platform', file);
    if (!error && url) {
      if (existingId) {
        await db.from('platform_images').update({ image_url: url }).eq('id', existingId);
        setImages((prev) => prev.map((im) => im.id === existingId ? { ...im, image_url: url } : im));
      } else {
        setNewImg((p) => ({ ...p, image_url: url }));
      }
    }
    setUploading('');
    e.target.value = '';
  };

  const addImage = async () => {
    if (!newImg.image_url) { alert('Please upload or enter an image URL first.'); return; }
    const { data, error } = await db.from('platform_images').insert({ ...newImg, is_active: true, image_order: 1 }).select();
    if (!error && data) { setImages((prev) => [...prev, data[0]]); setShowAddForm(false); setNewImg({ page_key: 'home', section_key: 'hero', image_url: '', image_alt_en: '', title_en: '' }); }
  };

  if (loading) return <div style={{ textAlign: 'center', padding: 32, color: 'var(--fg-muted)' }}><Icon name="loader" size={24} style={{ animation: 'sarayaSpin 1s linear infinite' }} /></div>;

  if (tableExists === false) return (
    <div style={{ padding: '20px 24px', borderRadius: 12, background: '#FFFBEB', border: '1.5px solid #FCD34D' }}>
      <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="alert-triangle" size={16} style={{ color: '#D97706' }} /> Migration Required</div>
      <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: '0 0 12px', lineHeight: 1.6 }}>
        The <code>platform_images</code> table does not exist yet. Run the Supabase migration (Task 34) to enable this CMS. Once the migration runs, this panel will activate automatically.
      </p>
      <code style={{ display: 'block', background: '#1B2A4A', color: '#E5C98C', padding: '12px 16px', borderRadius: 8, fontSize: 12, lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
        {`-- Migration: create platform_images table\nCREATE TABLE platform_images (\n  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n  page_key text NOT NULL,\n  section_key text NOT NULL,\n  image_url text NOT NULL,\n  image_alt_en text, image_alt_ar text,\n  title_en text, title_ar text,\n  is_active boolean DEFAULT true,\n  image_order int DEFAULT 1,\n  uploaded_by uuid,\n  created_at timestamptz DEFAULT now(),\n  updated_at timestamptz DEFAULT now()\n);\nALTER TABLE platform_images ENABLE ROW LEVEL SECURITY;\nCREATE POLICY "Public reads active" ON platform_images FOR SELECT USING (is_active = true);\nCREATE POLICY "Admin full access" ON platform_images USING (true) WITH CHECK (true);`}
      </code>
    </div>
  );

  const grouped = PAGE_KEYS.reduce((acc, k) => { acc[k] = images.filter((im) => im.page_key === k); return acc; }, {});

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Button variant="primary" small onClick={() => setShowAddForm(!showAddForm)}>
          <Icon name="plus" size={14} /> Add Platform Image
        </Button>
      </div>

      {/* Add image form */}
      {showAddForm && (
        <div style={{ padding: '20px 22px', borderRadius: 14, border: '1.5px solid var(--gold-deep)', background: 'var(--gold-tint,#fdf8f0)' }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 14 }}>Add New Platform Image</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
            <div>
              <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-secondary)', display: 'block', marginBottom: 4 }}>Page</label>
              <select value={newImg.page_key} onChange={(e) => setNewImg((p) => ({ ...p, page_key: e.target.value }))} style={{ width: '100%', padding: '8px 10px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13 }}>
                {PAGE_KEYS.map((k) => <option key={k} value={k}>{k}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-secondary)', display: 'block', marginBottom: 4 }}>Section</label>
              <select value={newImg.section_key} onChange={(e) => setNewImg((p) => ({ ...p, section_key: e.target.value }))} style={{ width: '100%', padding: '8px 10px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13 }}>
                {SECTION_KEYS.map((k) => <option key={k} value={k}>{k}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-secondary)', display: 'block', marginBottom: 4 }}>Alt Text (EN)</label>
              <input value={newImg.image_alt_en} onChange={(e) => setNewImg((p) => ({ ...p, image_alt_en: e.target.value }))} placeholder="Image description" style={{ width: '100%', padding: '8px 10px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13, boxSizing: 'border-box' }} />
            </div>
            <div>
              <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-secondary)', display: 'block', marginBottom: 4 }}>Title (EN)</label>
              <input value={newImg.title_en} onChange={(e) => setNewImg((p) => ({ ...p, title_en: e.target.value }))} placeholder="Optional headline" style={{ width: '100%', padding: '8px 10px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13, boxSizing: 'border-box' }} />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14 }}>
            {newImg.image_url && <img src={newImg.image_url} alt="" style={{ width: 64, height: 64, objectFit: 'cover', borderRadius: 8, border: '1px solid var(--line)' }} />}
            <div>
              <input value={newImg.image_url} onChange={(e) => setNewImg((p) => ({ ...p, image_url: e.target.value }))} placeholder="https:// image URL" style={{ width: 260, padding: '8px 10px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13, display: 'block', marginBottom: 6 }} />
              <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: uploading==='new'?'not-allowed':'pointer', fontSize: 12.5, color: 'var(--gold-deep)', fontWeight: 600 }}>
                <Icon name="upload" size={13} /> {uploading==='new' ? 'Uploading…' : 'Or upload file'}
                <input type="file" accept="image/*" onChange={(e) => handleFileUpload(e, null)} disabled={uploading==='new'} style={{ display: 'none' }} />
              </label>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="primary" small onClick={addImage}>Save Image</Button>
            <Button variant="secondary" small onClick={() => setShowAddForm(false)}>Cancel</Button>
          </div>
        </div>
      )}

      {/* Existing images grouped by page */}
      {PAGE_KEYS.map((page) => grouped[page].length === 0 ? null : (
        <div key={page} style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', background: 'var(--bg-tint)', borderBottom: '1px solid var(--line)', fontWeight: 700, fontSize: 13.5, color: 'var(--fg-primary)', textTransform: 'capitalize' }}>
            {page} page
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-canvas,#f7f5f0)', borderBottom: '1px solid var(--line)' }}>
                {['Preview','Section','Title / Alt','Active','Actions'].map((h) => (
                  <th key={h} style={{ padding: '9px 14px', textAlign: 'start', fontWeight: 600, fontSize: 11.5, color: 'var(--fg-secondary)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {grouped[page].map((im, idx) => (
                <tr key={im.id} style={{ borderBottom: idx < grouped[page].length-1 ? '1px solid var(--line)' : 'none' }}>
                  <td style={{ padding: '10px 14px' }}>
                    <img src={im.image_url} alt={im.image_alt_en || ''} style={{ width: 72, height: 48, objectFit: 'cover', borderRadius: 7, border: '1px solid var(--line)', display: 'block' }} onError={(e) => { e.target.style.display='none'; }} />
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{ padding: '3px 9px', borderRadius: 10, background: '#E3F0FB', color: '#1B2A4A', fontSize: 12, fontWeight: 700 }}>{im.section_key}</span>
                    <span style={{ fontSize: 11, color: 'var(--fg-muted)', display: 'block', marginTop: 3 }}>Order: {im.image_order}</span>
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{im.title_en || '—'}</div>
                    <div style={{ fontSize: 12, color: 'var(--fg-secondary)', marginTop: 2 }}>{im.image_alt_en || 'No alt text'}</div>
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <button onClick={() => toggleActive(im.id, im.is_active)} style={{ width: 32, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer', position: 'relative', background: im.is_active ? '#16A34A' : '#D1D5DB', transition: 'background 200ms' }}>
                      <span style={{ position: 'absolute', top: 2, left: im.is_active ? 14 : 2, width: 16, height: 16, borderRadius: 8, background: '#fff', transition: 'left 200ms', display: 'block' }} />
                    </button>
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ display: 'flex', gap: 6 }}>
                      <label style={{ padding: '4px 10px', borderRadius: 7, border: '1px solid var(--gold-deep)', background: 'var(--gold-tint,#fdf8f0)', cursor: uploading===im.id?'not-allowed':'pointer', fontSize: 12, fontWeight: 600, color: 'var(--gold-deep)' }}>
                        {uploading===im.id ? 'Uploading…' : 'Replace'}
                        <input type="file" accept="image/*" onChange={(e) => handleFileUpload(e, im.id)} disabled={uploading===im.id} style={{ display: 'none' }} />
                      </label>
                      <button onClick={() => deleteImage(im.id)} style={{ padding: '4px 10px', borderRadius: 7, border: '1px solid var(--error,#dc2626)', background: 'var(--error-bg,#fef2f2)', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: 'var(--error,#dc2626)' }}>Delete</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}

      {images.length === 0 && (
        <div style={{ textAlign: 'center', padding: 40, background: 'var(--white)', borderRadius: 14, border: '1px dashed var(--line)', color: 'var(--fg-muted)', fontSize: 14 }}>
          No platform images yet. Click "Add Platform Image" to upload the first one.
        </div>
      )}
    </div>
  );
}

/* ============================================================
   MAIN ADMIN DASHBOARD PAGE
   ============================================================ */
function AdminDashboardPage() {
  const db = window.SarayaDB;
  const { isAdmin, user, openAuthModal, loading: authLoading } = useAuth();
  const { lang } = useLang();
  const { go } = useNav();
  const ar = lang === 'ar';

  const [activeTab, setActiveTab] = useStateAD(() => {
    const stored = localStorage.getItem('saraya_admin_tab');
    if (stored) { localStorage.removeItem('saraya_admin_tab'); return stored; }
    return 'overview';
  });
  const [stats, setStats]           = useStateAD(null);
  const [vendors, setVendors]       = useStateAD([]);
  const [payouts, setPayouts]       = useStateAD([]);
  const [complaints, setComplaints]  = useStateAD([]);
  const [viewingComplaint, setViewingComplaint] = useStateAD(null);
  const [tiers, setTiers]           = useStateAD([]);
  const [orders, setOrders]         = useStateAD([]);
  const [leads, setLeads]           = useStateAD([]);
  const [rfqs, setRfqs]             = useStateAD([]);
  const [loading, setLoading]       = useStateAD(true);
  const [confirm, setConfirm]       = useStateAD(null);
  const [tierEdit, setTierEdit]     = useStateAD(null);
  const [tierBusy, setTierBusy]     = useStateAD(false);
  const [busyId, setBusyId]         = useStateAD('');

  // Register global so AdminBar can switch tabs without full navigation
  useEffectAD(() => {
    window.setAdminDashboardTab = (tab) => setActiveTab(tab);
    return () => { window.setAdminDashboardTab = null; };
  }, []);

  const load = useCallbackAD(async () => {
    if (!db) { setLoading(false); return; }
    setLoading(true);

    // Safe fetch wrapper — never rejects; returns default on any error
    const safe = (promise, fallback = { data: [], count: 0 }) =>
      promise.then((res) => res.error ? fallback : res).catch(() => fallback);

    try {
      const [vendorRes, payoutRes, complaintRes, tierRes, prodCount, rentCount, svcCount, orderRes, leadRes, rfqRes, custCount, subCount] = await Promise.all([
        safe(db.from('vendor_profiles').select('*, profiles(display_name, phone)').order('created_at', { ascending: false })),
        safe(db.from('payouts').select('*, vendor_profiles(trade_name), orders(reference)').order('created_at', { ascending: false }).limit(100)),
        safe(db.from('complaints').select('*, orders(reference)').order('created_at', { ascending: false }).limit(50)),
        safe(db.from('subscription_tiers').select('*').order('sort_order')),
        safe(db.from('products').select('id', { count: 'exact', head: true }), { count: 0 }),
        safe(db.from('rentals').select('id', { count: 'exact', head: true }), { count: 0 }),
        safe(db.from('services').select('id', { count: 'exact', head: true }), { count: 0 }),
        safe(db.from('orders').select('id, reference, total_amount, status, created_at, profiles!customer_id(display_name)').order('created_at', { ascending: false }).limit(50)),
        safe(db.from('leads').select('*').order('created_at', { ascending: false }).limit(100)),
        safe(db.from('rfq_requests').select('*').order('created_at', { ascending: false }).limit(50)),
        safe(db.from('profiles').select('id', { count: 'exact', head: true }).eq('role', 'customer'), { count: 0 }),
        safe(db.from('subscriptions').select('id', { count: 'exact', head: true }).in('status', ['trialing','active']), { count: 0 }),
      ]);

      const allVendors = vendorRes.data || [];
      const allPayouts = payoutRes.data || [];
      const allOrders  = orderRes.data  || [];

      setVendors(allVendors);
      setPayouts(allPayouts);
      setComplaints(complaintRes.data || []);
      setTiers(tierRes.data || []);
      setOrders(allOrders);
      setLeads(leadRes.data || []);
      setRfqs(rfqRes.data || []);

      setStats({
        totalVendors:     allVendors.length,
        activeVendors:    allVendors.filter((v) => ['active','approved'].includes(v.status)).length,
        pendingApproval:  allVendors.filter((v) => ['pending_approval','agreement_accepted','under_review'].includes(v.status)).length,
        pendingPayouts:   allPayouts.filter((p) => p.status === 'pending').reduce((s, p) => s + Number(p.amount), 0),
        heldPayouts:      allPayouts.filter((p) => p.status === 'on_hold').reduce((s, p) => s + Number(p.amount), 0),
        totalProducts:    prodCount.count  || 0,
        totalRentals:     rentCount.count  || 0,
        totalServices:    svcCount.count   || 0,
        pendingOrders:    allOrders.filter((o) => o.status === 'pending').length,
        totalRevenue:     allOrders.reduce((s, o) => s + Number(o.total_amount || 0), 0),
        totalLeads:       (leadRes.data || []).length,
        openRfqs:         (rfqRes.data || []).filter((r) => r.status === 'open').length,
        openComplaints:   (complaintRes.data || []).filter((c) => c.status === 'open').length,
        totalCustomers:   custCount.count  || 0,
        activeSubsc:      subCount.count   || 0,
      });
    } catch (e) {
      console.error('AdminDashboard load error:', e);
      // Show empty stats rather than a blank screen
      setStats({ totalVendors:0, activeVendors:0, pendingApproval:0, pendingPayouts:0, heldPayouts:0, totalProducts:0, totalRentals:0, totalServices:0, pendingOrders:0, totalRevenue:0, totalLeads:0, openRfqs:0, openComplaints:0, totalCustomers:0, activeSubsc:0 });
    } finally {
      setLoading(false);
    }
  }, [db]);

  useEffectAD(() => { load(); }, [load]);

  /* ---- vendor status actions ---- */
  const setVendorStatus = async (vendorId, status, reason) => {
    setBusyId(vendorId);
    const update = { status };
    if (reason) update.rejection_reason = reason;
    await db.from('vendor_profiles').update(update).eq('id', vendorId);
    await sarayaNotify(vendorId, 'vendor_status', `Your vendor account status has changed to: ${status}`);
    await sarayaLogActivity({ action: `vendor_${status}`, entityType: 'vendor', entityId: vendorId, details: { reason } });
    setBusyId('');
    load();
  };

  /* ---- payout actions ---- */
  const setPayoutStatus = async (payoutId, status, note) => {
    setBusyId(payoutId);
    const update = { status };
    if (status === 'approved') update.approved_by = user.id, update.approved_at = new Date().toISOString();
    if (status === 'paid')     update.paid_at = new Date().toISOString();
    if (note) update.notes = note;
    await db.from('payouts').update(update).eq('id', payoutId);
    setBusyId('');
    load();
  };

  /* ---- give free subscription ---- */
  const giveFreeAccess = async (vendorId, tierId) => {
    await db.from('subscriptions').upsert({
      vendor_id: vendorId,
      tier_id: tierId,
      status: 'active',
      is_free_access: true,
      current_period_start: new Date().toISOString(),
      current_period_end: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
    }, { onConflict: 'vendor_id' });
    load();
  };

  /* ---- tier save ---- */
  const saveTier = async (e) => {
    e.preventDefault();
    if (!tierEdit || !db) return;
    setTierBusy(true);
    if (tierEdit.id) {
      await db.from('subscription_tiers').update(tierEdit).eq('id', tierEdit.id);
    } else {
      await db.from('subscription_tiers').insert({ ...tierEdit, sort_order: tiers.length + 1 });
    }
    setTierBusy(false);
    setTierEdit(null);
    load();
  };

  /* ---- guard ---- */
  if (!window.supabaseConfigured) {
    return (
      <main style={{ paddingTop: 120, minHeight: '60vh' }}>
        <Container narrow style={{ textAlign: 'center' }}>
          <Icon name="database" size={44} stroke={1} style={{ color: 'var(--fg-muted)' }} />
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500, marginTop: 14 }}>Database Not Configured</h2>
          <p style={{ color: 'var(--fg-secondary)', marginTop: 8 }}>Fill in src/config.js with your Supabase credentials.</p>
        </Container>
      </main>
    );
  }

  if (authLoading) {
    return (
      <main style={{ paddingTop: 120, minHeight: '60vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: 36, height: 36, border: '3px solid var(--line)', borderTopColor: 'var(--gold)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
      </main>
    );
  }

  if (!user) {
    return (
      <main style={{ paddingTop: 120, minHeight: '60vh' }}>
        <Container narrow style={{ textAlign: 'center' }}>
          <Icon name="lock" size={44} stroke={1} style={{ color: 'var(--fg-muted)' }} />
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500, marginTop: 14 }}>Please Sign In</h2>
          <Button variant="primary" style={{ marginTop: 18 }} onClick={() => openAuthModal('login')}>Sign In</Button>
        </Container>
      </main>
    );
  }

  if (!isAdmin) {
    return (
      <main style={{ paddingTop: 120, minHeight: '60vh' }}>
        <Container narrow style={{ textAlign: 'center' }}>
          <Icon name="shield-off" size={44} stroke={1} style={{ color: 'var(--fg-muted)' }} />
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500, marginTop: 14 }}>Admin Access Required</h2>
        </Container>
      </main>
    );
  }

  const TABS = [
    { key: 'overview',    icon: 'layout-dashboard', label: 'Overview' },
    { key: 'orders',      icon: 'package',          label: 'Orders',       badge: stats?.pendingOrders || 0 },
    { key: 'rfqs',        icon: 'file-text',        label: 'RFQs',         badge: stats?.openRfqs || 0 },
    { key: 'leads',       icon: 'inbox',            label: 'Leads' },
    { key: 'vendors',     icon: 'store',            label: 'Vendors',      badge: stats?.pendingApproval || 0 },
    { key: 'marketplace', icon: 'shopping-bag',     label: 'Marketplace' },
    { key: 'payouts',     icon: 'banknote',         label: 'Payouts' },
    { key: 'complaints',  icon: 'alert-circle',     label: 'Complaints',   badge: stats?.openComplaints || 0 },
    { key: 'finance',     icon: 'credit-card',      label: 'Finance' },
    { key: 'marketing',   icon: 'megaphone',        label: 'Marketing' },
    { key: 'content',     icon: 'file-edit',        label: 'Content' },
    { key: 'tiers',       icon: 'layers',           label: 'Sub. Tiers' },
    { key: 'subscriptions', icon: 'repeat',           label: 'Subscriptions' },
    { key: 'users',       icon: 'users',            label: 'Users' },
    { key: 'activity',    icon: 'activity',         label: 'Activity Log' },
    { key: 'tools',       icon: 'wrench',           label: 'Tools' },
  ];

  return (
    <main style={{ paddingTop: 80, minHeight: '100vh', background: 'var(--bg-canvas)' }}>
      <div className="saraya-vd-shell" style={{ display: 'flex', maxWidth: 1400, margin: '0 auto', padding: '0 16px', gap: 0 }}>

        {/* Sidebar */}
        <aside className="saraya-vd-sidebar" style={{ width: 220, flexShrink: 0, paddingTop: 20, paddingBottom: 40, paddingRight: 16 }}>
          <div style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', overflow: 'hidden', position: 'sticky', top: 90 }}>
            <div style={{ padding: '18px 16px 12px', borderBottom: '1px solid var(--line)' }}>
              <Badge tone="gold">Admin</Badge>
              <p style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500, margin: '6px 0 0', color: 'var(--fg-primary)' }}>Platform Control</p>
            </div>
            <nav style={{ padding: '8px 8px' }}>
              {TABS.map((t) => (
                <button key={t.key} onClick={() => setActiveTab(t.key)} style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '9px 12px', borderRadius: 8, border: 'none', marginBottom: 2,
                  background: activeTab === t.key ? 'var(--espresso)' : 'transparent',
                  color: activeTab === t.key ? 'var(--white)' : 'var(--fg-secondary)',
                  fontFamily: 'var(--font-body)', fontSize: 13.5,
                  fontWeight: activeTab === t.key ? 600 : 400,
                  cursor: 'pointer', transition: 'all 160ms', textAlign: 'left',
                }}>
                  <Icon name={t.icon} size={15} style={{ flexShrink: 0 }} />
                  <span style={{ flex: 1 }}>{t.label}</span>
                  {t.badge > 0 && (
                    <span style={{ display: 'inline-flex', minWidth: 20, height: 20, borderRadius: 10, background: '#EF4444', color: '#fff', fontSize: 11, fontWeight: 700, alignItems: 'center', justifyContent: 'center', padding: '0 5px' }}>
                      {t.badge}
                    </span>
                  )}
                </button>
              ))}
            </nav>
            <div style={{ padding: '12px 16px', borderTop: '1px solid var(--line)' }}>
              <Button variant="secondary" icon="refresh-cw" onClick={load} style={{ width: '100%', justifyContent: 'center' }}>Refresh</Button>
            </div>
          </div>
        </aside>

        {/* Main content */}
        <div style={{ flex: 1, minWidth: 0, paddingTop: 20, paddingBottom: 40 }}>

        {loading ? (
          <div style={{ textAlign: 'center', padding: 80, color: 'var(--fg-muted)' }}>
            <Icon name="loader" size={36} style={{ animation: 'sarayaSpin 1s linear infinite' }} />
            <p style={{ marginTop: 16, fontSize: 14 }}>Loading platform data…</p>
          </div>
        ) : (
          <>
            {/* OVERVIEW */}
            {activeTab === 'overview' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(180px,1fr))', gap: 14 }}>
                  <AdminStat icon="store"          label="Total Vendors"      value={stats.totalVendors} />
                  <AdminStat icon="user-check"     label="Pending Approval"   value={stats.pendingApproval}  tone="warning" />
                  <AdminStat icon="users"          label="Total Customers"    value={stats.totalCustomers} />
                  <AdminStat icon="inbox"          label="New Leads"          value={stats.totalLeads} />
                  <AdminStat icon="file-text"      label="Open RFQs"          value={stats.openRfqs}         tone={stats.openRfqs > 0 ? 'warning' : 'gold'} />
                  <AdminStat icon="package"        label="Pending Orders"     value={stats.pendingOrders}    tone={stats.pendingOrders > 0 ? 'warning' : 'gold'} />
                  <AdminStat icon="repeat"         label="Active Subscriptions" value={stats.activeSubsc}    tone="success" />
                  <AdminStat icon="alert-circle"   label="Open Complaints"    value={stats.openComplaints}   tone={stats.openComplaints > 0 ? 'danger' : 'gold'} />
                  <AdminStat icon="banknote"       label="Pending Payouts"    value={'AED ' + stats.pendingPayouts.toFixed(0)} tone="warning" />
                  <AdminStat icon="trending-up"    label="Total Revenue"      value={'AED ' + stats.totalRevenue.toFixed(0)} tone="success" />
                  <AdminStat icon="shopping-bag"   label="Products"           value={stats.totalProducts} />
                  <AdminStat icon="archive"        label="Rental Items"       value={stats.totalRentals} />
                </div>

                {/* Action alerts */}
                <div style={{ display: 'grid', gap: 10 }}>
                  {stats.pendingApproval > 0 && (
                    <div onClick={() => setActiveTab('vendors')} style={{ padding: '14px 18px', borderRadius: 10, background: '#FFFBEB', border: '1.5px solid #FCD34D', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
                      <Icon name="alert-triangle" size={18} style={{ color: '#D97706' }} />
                      <span style={{ fontWeight: 600, fontSize: 14 }}>{stats.pendingApproval} vendor{stats.pendingApproval !== 1 ? 's' : ''} awaiting approval</span>
                      <Icon name="chevron-right" size={15} style={{ marginInlineStart: 'auto', color: '#D97706' }} />
                    </div>
                  )}
                  {stats.openRfqs > 0 && (
                    <div onClick={() => setActiveTab('rfqs')} style={{ padding: '14px 18px', borderRadius: 10, background: '#EFF6FF', border: '1.5px solid #93C5FD', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
                      <Icon name="file-text" size={18} style={{ color: '#1D4ED8' }} />
                      <span style={{ fontWeight: 600, fontSize: 14 }}>{stats.openRfqs} open RFQ request{stats.openRfqs !== 1 ? 's' : ''}</span>
                      <Icon name="chevron-right" size={15} style={{ marginInlineStart: 'auto', color: '#1D4ED8' }} />
                    </div>
                  )}
                  {stats.openComplaints > 0 && (
                    <div onClick={() => setActiveTab('complaints')} style={{ padding: '14px 18px', borderRadius: 10, background: '#FEF2F2', border: '1.5px solid #FCA5A5', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
                      <Icon name="alert-circle" size={18} style={{ color: '#B91C1C' }} />
                      <span style={{ fontWeight: 600, fontSize: 14 }}>{stats.openComplaints} open complaint{stats.openComplaints !== 1 ? 's' : ''}</span>
                      <Icon name="chevron-right" size={15} style={{ marginInlineStart: 'auto', color: '#B91C1C' }} />
                    </div>
                  )}
                </div>

                {/* Quick nav grid */}
                <div>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, marginBottom: 14 }}>Quick Access</h3>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(180px,1fr))', gap: 10 }}>
                    {[
                      { tab: 'orders',      icon: 'package',      label: 'Orders & Bookings' },
                      { tab: 'rfqs',        icon: 'file-text',    label: 'RFQ Requests' },
                      { tab: 'leads',       icon: 'inbox',        label: 'Leads & Inquiries' },
                      { tab: 'vendors',     icon: 'store',        label: 'Vendor Management' },
                      { tab: 'marketplace', icon: 'shopping-bag', label: 'Marketplace Listings' },
                      { tab: 'payouts',     icon: 'banknote',     label: 'Vendor Payouts' },
                      { tab: 'finance',     icon: 'credit-card',  label: 'Finance & Payments' },
                      { tab: 'marketing',   icon: 'megaphone',    label: 'Marketing' },
                      { tab: 'content',     icon: 'file-edit',    label: 'Content & Pages' },
                      { tab: 'tiers',       icon: 'layers',       label: 'Subscription Tiers' },
                      { tab: 'users',       icon: 'users',        label: 'Users & Roles' },
                      { tab: 'tools',       icon: 'wrench',       label: 'Developer Tools' },
                    ].map((q) => (
                      <button key={q.tab} onClick={() => setActiveTab(q.tab)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 10, background: 'var(--white)', border: '1px solid var(--line)', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-primary)', transition: 'all 120ms', textAlign: 'left' }}
                        onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--gold)'; e.currentTarget.style.background = 'var(--cream)'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.background = 'var(--white)'; }}>
                        <Icon name={q.icon} size={16} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
                        {q.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* VENDORS */}
            {activeTab === 'vendors' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection title="Vendor Approvals" desc="Review and approve vendor applications.">
                  <AdminTable
                    emptyMsg="No vendors yet"
                    cols={[
                      { key: 'trade_name', label: 'Business' },
                      { key: 'status',     label: 'Status', render: (r) => <StatusBadge status={r.status} /> },
                      { key: 'city',       label: 'City' },
                      { key: 'created_at', label: 'Registered', render: (r) => new Date(r.created_at).toLocaleDateString() },
                      {
                        key: 'actions', label: 'Actions',
                        render: (r) => (
                          <div style={{ display: 'flex', gap: 6 }}>
                            {r.status === 'pending_approval' && (
                              <>
                                <Button variant="primary"   small loading={busyId === r.id} onClick={() => setConfirm({ msg: `Approve "${r.trade_name}"?`, onOk: () => { setConfirm(null); setVendorStatus(r.id, 'approved'); } })}>Approve</Button>
                                <Button variant="secondary" small loading={busyId === r.id} onClick={() => { const reason = window.prompt('Rejection reason:'); if (reason) setVendorStatus(r.id, 'registered', reason); }}>Reject</Button>
                              </>
                            )}
                            {/* Legacy statuses — kept for any vendors created before the new flow */}
                            {(r.status === 'documents_submitted' || r.status === 'under_review') && (
                              <>
                                <Button variant="primary"   small loading={busyId === r.id} onClick={() => setVendorStatus(r.id, 'approved')}>Approve</Button>
                                <Button variant="secondary" small loading={busyId === r.id} onClick={() => { const reason = window.prompt('Rejection reason:'); if (reason) setVendorStatus(r.id, 'registered', reason); }}>Reject</Button>
                              </>
                            )}
                            {(r.status === 'active' || r.status === 'approved') && (
                              <Button variant="ghost" small danger onClick={() => setConfirm({ msg: `Suspend "${r.trade_name}"?`, dangerous: true, onOk: () => { setConfirm(null); setVendorStatus(r.id, 'suspended'); } })}>Suspend</Button>
                            )}
                            {r.status === 'suspended' && (
                              <Button variant="secondary" small onClick={() => setVendorStatus(r.id, 'approved')}>Reinstate</Button>
                            )}
                            {/* Give free access */}
                            {tiers.length > 0 && (
                              <Button variant="ghost" small onClick={() => giveFreeAccess(r.id, tiers[0].id)} title="Give free Starter access">Free Sub</Button>
                            )}
                          </div>
                        ),
                      },
                    ]}
                    rows={vendors}
                  />
                </AdminSection>
              </div>
            )}

            {/* PAYOUTS */}
            {activeTab === 'payouts' && (
              <AdminSection title="Payout Management" desc="Approve, hold, or release vendor payouts.">
                <AdminTable
                  emptyMsg="No payouts yet"
                  cols={[
                    { key: 'id',       label: 'ID',     render: (r) => <code style={{ fontSize: 11 }}>{r.id.slice(0, 8)}…</code> },
                    { key: 'vendor',   label: 'Vendor', render: (r) => r.vendor_profiles?.trade_name || '—' },
                    { key: 'order',    label: 'Order',  render: (r) => r.orders?.reference || '—' },
                    { key: 'amount',   label: 'Amount', render: (r) => `AED ${Number(r.amount).toFixed(2)}` },
                    { key: 'status',   label: 'Status', render: (r) => <StatusBadge status={r.status} /> },
                    { key: 'hold_reason', label: 'Hold Reason', wrap: true },
                    {
                      key: 'actions', label: 'Actions',
                      render: (r) => (
                        <div style={{ display: 'flex', gap: 6 }}>
                          {r.status === 'pending' && (
                            <>
                              <Button variant="primary"   small loading={busyId === r.id} onClick={() => { setBusyId(r.id); setPayoutStatus(r.id, 'approved'); }}>Approve</Button>
                              <Button variant="ghost"     small danger onClick={() => { const reason = window.prompt('Hold reason:'); if (reason !== null) setPayoutStatus(r.id, 'on_hold', reason); }}>Hold</Button>
                            </>
                          )}
                          {r.status === 'approved' && (
                            <Button variant="primary" small loading={busyId === r.id} onClick={() => setPayoutStatus(r.id, 'paid')}>Mark Paid</Button>
                          )}
                          {r.status === 'on_hold' && (
                            <Button variant="secondary" small loading={busyId === r.id} onClick={() => setPayoutStatus(r.id, 'approved')}>Release</Button>
                          )}
                        </div>
                      ),
                    },
                  ]}
                  rows={payouts}
                />
              </AdminSection>
            )}

            {/* COMPLAINTS */}
            {activeTab === 'complaints' && (
              <AdminSection title="Complaints" desc="Manage complaints and disputes submitted via the complaint form. WhatsApp is not used for official case handling.">
                <AdminTable
                  emptyMsg="No complaints yet"
                  cols={[
                    { key: 'reference', label: 'Ref' },
                    { key: 'created_at', label: 'Date', render: (r) => r.created_at ? new Date(r.created_at).toLocaleDateString() : '—' },
                    { key: 'submitted_by', label: 'Submitted By', render: (r) => r.contact_name || r.profiles?.display_name || '—' },
                    { key: 'filed_by_role', label: 'User Type', render: (r) => ({ customer: 'Customer', vendor: 'Vendor' }[r.filed_by_role] || 'Other') },
                    { key: 'complaint_type', label: 'Type', render: (r) => COMPLAINT_TYPE_LABELS[r.complaint_type] || r.complaint_type || '—' },
                    { key: 'related', label: 'Related', render: (r) => r.orders?.reference || r.related_reference || '—' },
                    { key: 'status', label: 'Status', render: (r) => <StatusBadge status={r.status} /> },
                    {
                      key: 'actions', label: 'Actions',
                      render: (r) => (
                        <div style={{ display: 'flex', gap: 6 }}>
                          <Button variant="secondary" small onClick={() => setViewingComplaint(r)}>View</Button>
                          {r.status !== 'resolved' && r.status !== 'closed' && (
                            <>
                              <Button variant="secondary" small onClick={async () => {
                                const notes = window.prompt('Resolution notes:');
                                if (notes === null) return;
                                await db.from('complaints').update({ status: 'resolved', resolution_notes: notes, resolved_at: new Date().toISOString(), resolved_by: user.id }).eq('id', r.id);
                                if (r.payout_held) {
                                  await db.from('payouts').update({ status: 'approved', hold_reason: null }).eq('order_id', r.order_id);
                                }
                                load();
                              }}>Resolve</Button>
                              <Button variant="ghost" small danger onClick={async () => {
                                await db.from('complaints').update({ status: 'rejected' }).eq('id', r.id);
                                load();
                              }}>Reject</Button>
                            </>
                          )}
                        </div>
                      ),
                    },
                  ]}
                  rows={complaints}
                />
              </AdminSection>
            )}

            {viewingComplaint && (
              <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 20 }} onClick={() => setViewingComplaint(null)}>
                <div style={{ background: '#fff', borderRadius: 14, padding: 28, maxWidth: 560, width: '100%', maxHeight: '85vh', overflowY: 'auto' }} onClick={(e) => e.stopPropagation()}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
                    <h3 style={{ margin: 0, fontSize: 19, fontWeight: 700 }}>Complaint {viewingComplaint.reference}</h3>
                    <button onClick={() => setViewingComplaint(null)} style={{ border: 'none', background: 'none', fontSize: 22, cursor: 'pointer', color: '#6B7280', lineHeight: 1 }}>&times;</button>
                  </div>
                  <div style={{ display: 'grid', gap: 10, fontSize: 14 }}>
                    <div><strong>Status:</strong> <StatusBadge status={viewingComplaint.status} /></div>
                    <div><strong>Submitted:</strong> {viewingComplaint.created_at ? new Date(viewingComplaint.created_at).toLocaleString() : '—'}</div>
                    <div><strong>Last updated:</strong> {viewingComplaint.updated_at ? new Date(viewingComplaint.updated_at).toLocaleString() : '—'}</div>
                    <div><strong>Submitted by:</strong> {viewingComplaint.contact_name || viewingComplaint.profiles?.display_name || '—'}</div>
                    <div><strong>User type:</strong> {({ customer: 'Customer', vendor: 'Vendor' }[viewingComplaint.filed_by_role] || 'Other')}</div>
                    <div><strong>Email:</strong> {viewingComplaint.contact_email || '—'}</div>
                    <div><strong>Phone:</strong> {viewingComplaint.contact_phone || '—'}</div>
                    <div><strong>Complaint type:</strong> {COMPLAINT_TYPE_LABELS[viewingComplaint.complaint_type] || viewingComplaint.complaint_type || '—'}</div>
                    <div><strong>Related order/listing/vendor:</strong> {viewingComplaint.orders?.reference || viewingComplaint.related_reference || '—'}</div>
                    <div><strong>Description:</strong><div style={{ marginTop: 4, padding: 10, background: '#F9FAFB', borderRadius: 8, whiteSpace: 'pre-wrap' }}>{viewingComplaint.description}</div></div>
                    {viewingComplaint.attachment_url && (
                      <div>
                        <strong>Attachment:</strong>{' '}
                        <Button variant="secondary" small onClick={async () => {
                          const { data } = await db.storage.from('complaint-attachments').createSignedUrl(viewingComplaint.attachment_url, 300);
                          if (data?.signedUrl) window.open(data.signedUrl, '_blank');
                        }}>Open attachment</Button>
                      </div>
                    )}
                    <div style={{ marginTop: 6 }}>
                      <label style={{ fontWeight: 600, fontSize: 12.5, textTransform: 'uppercase', color: '#6B7280', display: 'block', marginBottom: 6 }}>Update Status</label>
                      <select
                        value={viewingComplaint.status}
                        onChange={async (e) => {
                          const newStatus = e.target.value;
                          await db.from('complaints').update({ status: newStatus }).eq('id', viewingComplaint.id);
                          setViewingComplaint({ ...viewingComplaint, status: newStatus });
                          load();
                        }}
                        style={{ padding: '8px 12px', borderRadius: 8, border: '1px solid #D1D5DB', fontSize: 14 }}
                      >
                        <option value="open">New</option>
                        <option value="under_review">Under Review</option>
                        <option value="awaiting_customer_response">Waiting for Customer</option>
                        <option value="awaiting_vendor_response">Waiting for Vendor</option>
                        <option value="resolved">Resolved</option>
                        <option value="closed">Closed</option>
                        <option value="escalated">Escalated</option>
                        <option value="rejected">Rejected</option>
                      </select>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* SUBSCRIPTION MANAGEMENT */}
            {activeTab === 'subscriptions' && (
              <AdminSubscriptionsTab db={db} vendors={vendors} tiers={tiers} />
            )}

            {/* SUBSCRIPTION TIERS */}
            {activeTab === 'tiers' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection
                  title="Subscription Tiers"
                  desc="Edit tier names, prices, and limits. Changes take effect immediately."
                  action={
                    <Button variant="primary" icon="plus" onClick={() => setTierEdit({
                      name: '', name_ar: '', description_en: '', description_ar: '',
                      price_monthly: 0, max_listings: 20, rfq_responses_per_month: 10,
                      can_create_discounts: false, featured_placement: false, banner_eligibility: false,
                      priority_support: false, analytics_level: 'basic', is_active: true,
                    })}>New Tier</Button>
                  }
                >
                  <AdminTable
                    emptyMsg="No tiers configured"
                    cols={[
                      { key: 'name',         label: 'Name' },
                      { key: 'price_monthly', label: 'Price/mo', render: (r) => `AED ${r.price_monthly}` },
                      { key: 'max_listings', label: 'Max Listings' },
                      { key: 'rfq_responses_per_month', label: 'RFQ/mo', render: (r) => r.rfq_responses_per_month ?? '∞' },
                      { key: 'featured_placement', label: 'Featured', render: (r) => r.featured_placement ? '✓' : '—' },
                      { key: 'is_active', label: 'Active', render: (r) => r.is_active ? <span style={{ color: '#16A34A', fontWeight: 600 }}>Yes</span> : <span style={{ color: '#9CA3AF' }}>No</span> },
                      {
                        key: 'actions', label: 'Edit',
                        render: (r) => (
                          <Button variant="ghost" small icon="pencil" onClick={() => setTierEdit({ ...r })}>Edit</Button>
                        ),
                      },
                    ]}
                    rows={tiers}
                  />
                </AdminSection>

                {/* Tier edit form */}
                {tierEdit && (
                  <div style={{ position: 'fixed', inset: 0, zIndex: 400, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, background: 'rgba(42,31,26,0.5)' }}>
                    <div style={{ background: 'var(--white)', borderRadius: 20, padding: '28px', maxWidth: 560, width: '100%', maxHeight: '90vh', overflowY: 'auto', boxShadow: 'var(--shadow-deep)' }}>
                      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginBottom: 20 }}>{tierEdit.id ? 'Edit Tier' : 'New Tier'}</h3>
                      <form onSubmit={saveTier} style={{ display: 'grid', gap: 14 }}>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                          <Field label="Name (EN)"><TextInput value={tierEdit.name} onChange={(e) => setTierEdit((p) => ({ ...p, name: e.target.value }))} required /></Field>
                          <Field label="Name (AR)"><TextInput value={tierEdit.name_ar || ''} onChange={(e) => setTierEdit((p) => ({ ...p, name_ar: e.target.value }))} dir="rtl" /></Field>
                          <Field label="Price / Month (AED)"><TextInput type="number" value={tierEdit.price_monthly} onChange={(e) => setTierEdit((p) => ({ ...p, price_monthly: e.target.value }))} required /></Field>
                          <Field label="Max Listings"><TextInput type="number" value={tierEdit.max_listings} onChange={(e) => setTierEdit((p) => ({ ...p, max_listings: e.target.value }))} required /></Field>
                          <Field label="RFQ Responses / mo (blank = unlimited)"><TextInput type="number" value={tierEdit.rfq_responses_per_month ?? ''} onChange={(e) => setTierEdit((p) => ({ ...p, rfq_responses_per_month: e.target.value === '' ? null : parseInt(e.target.value) }))} placeholder="Leave blank for unlimited" /></Field>
                          <Field label="Analytics Level">
                            <select value={tierEdit.analytics_level} onChange={(e) => setTierEdit((p) => ({ ...p, analytics_level: e.target.value }))} style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
                              <option value="none">None</option>
                              <option value="basic">Basic</option>
                              <option value="advanced">Advanced</option>
                            </select>
                          </Field>
                        </div>
                        {[
                          { k: 'can_create_discounts',  l: 'Can Create Discounts' },
                          { k: 'featured_placement',    l: 'Featured Placement' },
                          { k: 'banner_eligibility',    l: 'Banner Eligibility' },
                          { k: 'priority_support',      l: 'Priority Support' },
                          { k: 'is_active',             l: 'Active' },
                        ].map((f) => (
                          <label key={f.k} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14 }}>
                            <input type="checkbox" checked={!!tierEdit[f.k]} onChange={(e) => setTierEdit((p) => ({ ...p, [f.k]: e.target.checked }))} style={{ width: 16, height: 16, accentColor: 'var(--gold-deep)' }} />
                            {f.l}
                          </label>
                        ))}
                        <Field label="Description (EN)">
                          <textarea value={tierEdit.description_en || ''} onChange={(e) => setTierEdit((p) => ({ ...p, description_en: e.target.value }))} rows={2} style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 14, resize: 'vertical', boxSizing: 'border-box' }} />
                        </Field>
                        <Field label="Description (AR)">
                          <textarea value={tierEdit.description_ar || ''} onChange={(e) => setTierEdit((p) => ({ ...p, description_ar: e.target.value }))} dir="rtl" rows={2} style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 14, resize: 'vertical', boxSizing: 'border-box' }} />
                        </Field>
                        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
                          <Button variant="ghost" onClick={() => setTierEdit(null)}>Cancel</Button>
                          <Button variant="primary" type="submit" loading={tierBusy}>Save Tier</Button>
                        </div>
                      </form>
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* ORDERS & BOOKINGS */}
            {activeTab === 'orders' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection title="Orders & Bookings" desc="All platform orders and service bookings.">
                  {orders.length > 0 ? (
                    <AdminTable
                      emptyMsg="No orders yet"
                      cols={[
                        { key: 'reference',    label: 'Reference', render: (r) => <code style={{ fontSize: 12 }}>{r.reference || r.id?.slice(0,8)}</code> },
                        { key: 'customer',     label: 'Customer',  render: (r) => r.profiles?.display_name || '—' },
                        { key: 'total_amount', label: 'Total',     render: (r) => 'AED ' + Number(r.total_amount || 0).toFixed(2) },
                        { key: 'status',       label: 'Status',    render: (r) => <StatusBadge status={r.status} /> },
                        { key: 'created_at',   label: 'Date',      render: (r) => new Date(r.created_at).toLocaleDateString() },
                        { key: 'actions',      label: '',          render: (r) => (
                          <select
                            value={r.status}
                            onChange={async (e) => {
                              const newStatus = e.target.value;
                              await db.from('orders').update({ status: newStatus }).eq('id', r.id);
                              setOrders((prev) => prev.map((o) => o.id === r.id ? { ...o, status: newStatus } : o));
                              sarayaLogActivity(db, user, 'order_status_update', { order_id: r.id, status: newStatus });
                            }}
                            style={{ padding: '5px 8px', borderRadius: 6, border: '1px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 12, background: 'var(--white)', cursor: 'pointer' }}
                          >
                            {['processing','pending','paid','confirmed','prep','out','done','cancelled','refunded'].map((s) => (
                              <option key={s} value={s}>{s}</option>
                            ))}
                          </select>
                        )},
                      ]}
                      rows={orders}
                    />
                  ) : (
                    <AdminPlaceholder
                      note="Orders will appear here once customers place orders. Requires the 'orders' Supabase table with RLS."
                      items={[
                        { icon: 'package',     label: 'Pending Orders',    desc: 'New orders awaiting confirmation' },
                        { icon: 'check-circle',label: 'Confirmed Orders',  desc: 'Orders accepted by vendors' },
                        { icon: 'truck',       label: 'In Progress',       desc: 'Orders being fulfilled' },
                        { icon: 'calendar',    label: 'Bookings',          desc: 'Service and venue bookings' },
                      ]}
                    />
                  )}
                </AdminSection>
              </div>
            )}

            {/* RFQ REQUESTS */}
            {activeTab === 'rfqs' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection title="RFQ Requests" desc="Quote requests submitted by customers.">
                  {rfqs.length > 0 ? (
                    <AdminTable
                      emptyMsg="No RFQ requests yet"
                      cols={[
                        { key: 'id',         label: 'ID',       render: (r) => <code style={{ fontSize: 11 }}>{r.id?.slice(0,8)}</code> },
                        { key: 'name',       label: 'Customer', render: (r) => r.name || r.customer_name || '—' },
                        { key: 'event_type', label: 'Event Type' },
                        { key: 'budget',     label: 'Budget' },
                        { key: 'status',     label: 'Status',   render: (r) => <StatusBadge status={r.status || 'open'} /> },
                        { key: 'created_at', label: 'Date',     render: (r) => new Date(r.created_at).toLocaleDateString() },
                      ]}
                      rows={rfqs}
                    />
                  ) : (
                    <AdminPlaceholder
                      note="RFQ requests from the Request Quote form will appear here. Requires the 'rfq_requests' Supabase table."
                      items={[
                        { icon: 'file-text',   label: 'Open RFQs',       desc: 'New quote requests needing response' },
                        { icon: 'send',        label: 'Sent to Vendors',  desc: 'RFQs forwarded for vendor responses' },
                        { icon: 'check',       label: 'Quoted',           desc: 'RFQs with vendor quotes ready' },
                        { icon: 'x-circle',    label: 'Closed/Declined',  desc: 'Completed or declined requests' },
                      ]}
                    />
                  )}
                </AdminSection>
              </div>
            )}

            {/* LEADS & INQUIRIES */}
            {activeTab === 'leads' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection title="Leads & Inquiries" desc="All leads captured from website forms, WhatsApp, and Request Quote modal.">
                  {leads.length > 0 ? (
                    <AdminTable
                      emptyMsg="No leads yet"
                      cols={[
                        { key: 'name',       label: 'Name' },
                        { key: 'phone',      label: 'Phone' },
                        { key: 'email',      label: 'Email' },
                        { key: 'lead_type',  label: 'Type',   render: (r) => <StatusBadge status={r.lead_type || r.leadType || 'inquiry'} /> },
                        { key: 'source',     label: 'Source', render: (r) => r.source || '—' },
                        { key: 'message',    label: 'Message', wrap: true, render: (r) => (r.message || '').slice(0, 80) + ((r.message || '').length > 80 ? '…' : '') },
                        { key: 'created_at', label: 'Date',   render: (r) => new Date(r.created_at).toLocaleDateString() },
                      ]}
                      rows={leads}
                    />
                  ) : (
                    <AdminPlaceholder
                      note="Leads from the Request Quote modal and contact forms are saved here via window.saveLead(). Requires the 'leads' Supabase table."
                      items={[
                        { icon: 'users',       label: 'Customer Leads', desc: 'Enquiries from potential customers' },
                        { icon: 'store',       label: 'Vendor Leads',   desc: 'Vendor partnership inquiries' },
                        { icon: 'phone',       label: 'WhatsApp Leads', desc: 'Contacts via WhatsApp button' },
                        { icon: 'mail',        label: 'Email Leads',    desc: 'Contacts via email forms' },
                      ]}
                    />
                  )}
                </AdminSection>
              </div>
            )}

            {/* MARKETPLACE */}
            {activeTab === 'marketplace' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(180px,1fr))', gap: 14 }}>
                  <AdminStat icon="shopping-bag" label="Total Products" value={stats?.totalProducts} />
                  <AdminStat icon="archive"      label="Rental Items"   value={stats?.totalRentals} />
                  <AdminStat icon="briefcase"    label="Services"       value={stats?.totalServices} />
                  <AdminStat icon="store"        label="Active Vendors" value={stats?.activeVendors} tone="success" />
                </div>
                <AdminSection title="Marketplace Listings" desc="Products, rental items, and services across all vendors. Toggle active/inactive and feature listings.">
                  <AdminListingsApproval />
                </AdminSection>
                <AdminSection title="Virtual Showroom Subscriptions" desc="Manage showroom access for vendors.">
                  <AdminPlaceholder note="Virtual Showroom subscriptions will appear here. Requires the 'subscriptions' table with showroom_tier field." />
                </AdminSection>
              </div>
            )}

            {/* FINANCE */}
            {activeTab === 'finance' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(200px,1fr))', gap: 14 }}>
                  <AdminStat icon="trending-up"  label="Total Revenue"      value={'AED ' + (stats?.totalRevenue || 0).toFixed(0)} tone="success" />
                  <AdminStat icon="banknote"     label="Pending Payouts"    value={'AED ' + (stats?.pendingPayouts || 0).toFixed(0)} tone="warning" />
                  <AdminStat icon="alert-circle" label="Held Payouts"       value={'AED ' + (stats?.heldPayouts || 0).toFixed(0)}    tone="danger" />
                  <AdminStat icon="repeat"       label="Active Subscriptions" value={stats?.activeSubsc} tone="success" />
                </div>
                <AdminSection title="Payments" desc="All payment transactions across the platform.">
                  <AdminPlaceholder
                    note="Payment records from Stripe will appear here once the Stripe webhook is configured. Requires the 'payments' Supabase table."
                    items={[
                      { icon: 'credit-card', label: 'All Payments',    desc: 'Stripe payment transactions' },
                      { icon: 'percent',     label: 'Commissions',     desc: 'Platform commission per order' },
                      { icon: 'rotate-ccw', label: 'Refunds',          desc: 'Refund requests and status' },
                      { icon: 'zap',        label: 'Stripe Settings',  desc: 'Stripe keys, webhooks, and config' },
                    ]}
                  />
                </AdminSection>
                <AdminSection title="Stripe Settings">
                  <div style={{ padding: '16px 22px' }}>
                    <div style={{ display: 'grid', gap: 12, fontSize: 14 }}>
                      {[
                        { label: 'Publishable Key', key: 'STRIPE_PUBLISHABLE_KEY', desc: 'Frontend key — safe to expose. Set in src/config.js.' },
                        { label: 'Secret Key',      key: 'STRIPE_SECRET_KEY',      desc: 'NEVER put in frontend. Use Supabase Edge Function or backend server only.' },
                        { label: 'Webhook Secret',  key: 'STRIPE_WEBHOOK_SECRET',  desc: 'Validates Stripe webhook events. Server-side only.' },
                      ].map((item) => (
                        <div key={item.key} style={{ padding: '12px 16px', borderRadius: 10, background: 'var(--bg-canvas)', border: '1px solid var(--line)' }}>
                          <div style={{ fontWeight: 600, marginBottom: 3 }}>{item.label}</div>
                          <code style={{ fontSize: 12, color: 'var(--fg-secondary)' }}>{item.key}</code>
                          <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', margin: '4px 0 0' }}>{item.desc}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                </AdminSection>
              </div>
            )}

            {/* MARKETING */}
            {activeTab === 'marketing' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection title="Platform Image CMS" desc="Manage hero images, banners, and promotional visuals for all pages. Backed by the platform_images table.">
                  <AdminPlatformImageCMS />
                </AdminSection>
                <AdminSection title="Customer Leads" desc="Leads submitted by customers via quote forms and inquiries.">
                  <AdminTable emptyMsg="No customer leads yet" cols={[
                    { key: 'name',       label: 'Name' },
                    { key: 'phone',      label: 'Phone' },
                    { key: 'source',     label: 'Source' },
                    { key: 'created_at', label: 'Date', render: (r) => new Date(r.created_at).toLocaleDateString() },
                  ]} rows={leads.filter((l) => (l.lead_type || l.leadType || '').includes('customer'))} />
                </AdminSection>
                <AdminSection title="Vendor Leads" desc="Vendor partnership and application inquiries.">
                  <AdminTable emptyMsg="No vendor leads yet" cols={[
                    { key: 'name',       label: 'Business / Name' },
                    { key: 'phone',      label: 'Phone' },
                    { key: 'source',     label: 'Source' },
                    { key: 'created_at', label: 'Date', render: (r) => new Date(r.created_at).toLocaleDateString() },
                  ]} rows={leads.filter((l) => (l.lead_type || l.leadType || '').includes('vendor'))} />
                </AdminSection>
              </div>
            )}

            {/* CONTENT */}
            {activeTab === 'content' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <div style={{ padding: '16px 20px', borderRadius: 12, background: '#EFF6FF', border: '1.5px solid #93C5FD', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <Icon name="info" size={18} style={{ color: '#1D4ED8', flexShrink: 0, marginTop: 2 }} />
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 3 }}>Content Editing Mode</div>
                    <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
                      Toggle <strong>Content Editing Mode</strong> in the left Admin sidebar to edit images and text inline on any page. Use the pencil icon on any element to edit it directly.
                    </div>
                  </div>
                </div>
                <AdminSection title="Page Content" desc="Content sections for each page of the platform.">
                  <AdminPlaceholder
                    note="Page-level content management requires a 'content_blocks' Supabase table. Currently, content is edited via Content Editing Mode and saved to browser localStorage / exported via Data Export."
                    items={[
                      { icon: 'home',        label: 'Home Page',          desc: 'Hero, features, testimonials, CTA sections' },
                      { icon: 'shopping-bag',label: 'Marketplace',        desc: 'Marketplace header and category banners' },
                      { icon: 'archive',     label: 'Rentals',            desc: 'Rental page headers and featured categories' },
                      { icon: 'monitor',     label: 'Virtual Showroom',   desc: 'Showroom intro and vendor spotlights' },
                    ]}
                  />
                </AdminSection>
                <AdminSection title="Legal Pages" desc="Terms, privacy policy, cancellation and complaints policies.">
                  <div style={{ padding: '12px 22px', display: 'grid', gap: 10 }}>
                    {[
                      { label: 'Terms of Use',             route: 'terms',               icon: 'scale' },
                      { label: 'Privacy Policy',           route: 'privacy',             icon: 'shield' },
                      { label: 'Cancellation & Refund',    route: 'cancellation-refund', icon: 'rotate-ccw' },
                      { label: 'Complaints Policy',        route: 'complaints',          icon: 'alert-circle' },
                    ].map((p) => (
                      <div key={p.route} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 10, background: 'var(--bg-canvas)', border: '1px solid var(--line)' }}>
                        <Icon name={p.icon} size={16} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
                        <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{p.label}</span>
                        <button onClick={function() { location.hash = '#' + p.route; }} style={{ background: 'none', border: '1px solid var(--line)', borderRadius: 7, padding: '4px 12px', fontSize: 12.5, cursor: 'pointer', color: 'var(--fg-secondary)' }}>View</button>
                      </div>
                    ))}
                  </div>
                </AdminSection>
                <AdminSection title="Footer & Navigation" desc="Footer links, social links, and main navigation structure.">
                  <AdminPlaceholder note="Footer and navigation content is currently defined in chrome.jsx and data.js. A CMS-driven nav editor requires a 'navigation' Supabase table." />
                </AdminSection>
              </div>
            )}

            {/* USERS */}
            {activeTab === 'users' && (
              <AdminSection title="Users & Roles" desc="All registered users and their platform roles.">
                <div style={{ padding: '12px 22px 0', display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                  {[
                    { role: 'admin',    label: 'Admins',    color: '#7C3AED' },
                    { role: 'vendor',   label: 'Vendors',   color: '#D97706' },
                    { role: 'customer', label: 'Customers', color: '#16A34A' },
                  ].map((r) => (
                    <span key={r.role} style={{ padding: '4px 12px', borderRadius: 20, background: r.color + '18', color: r.color, fontSize: 12.5, fontWeight: 600 }}>
                      {r.label}
                    </span>
                  ))}
                </div>
                <UsersTable db={db} />
              </AdminSection>
            )}

            {activeTab === 'activity' && (
              <AdminActivityLog db={db} />
            )}

            {activeTab === 'tools' && (
              <div style={{ display: 'grid', gap: 20 }}>
                <AdminSection title="Developer Tools" desc="One-time data operations, migrations, and utilities.">
                  <DataMigrationTool db={db} />
                </AdminSection>
                <AdminSection title="Demo & Test Accounts" desc="Setup instructions for development/demo accounts.">
                  <div style={{ padding: '16px 22px', display: 'grid', gap: 12 }}>
                    <div style={{ padding: '12px 16px', borderRadius: 10, background: '#FEF2F2', border: '1px solid #FCA5A5', fontSize: 13, color: '#B91C1C', fontWeight: 600 }}>
                      Development/demo only. Remove or change credentials before production.
                    </div>
                    {[
                      { role: 'Admin',    email: 'sales@sarayaevents.com',    purpose: 'Admin Dashboard + Admin Mode access' },
                      { role: 'Vendor',   email: 'sarayaeventsllc@gmail.com', purpose: 'Vendor Dashboard, listings, RFQs' },
                      { role: 'Customer', email: 'sales@sarayaevents.com',    purpose: 'Customer browsing, orders, complaints' },
                    ].map((a) => (
                      <div key={a.role} style={{ padding: '12px 16px', borderRadius: 10, background: 'var(--bg-canvas)', border: '1px solid var(--line)' }}>
                        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 6 }}>
                          <StatusBadge status={a.role.toLowerCase()} />
                          <code style={{ fontSize: 12 }}>{a.email}</code>
                          <code style={{ fontSize: 12, color: 'var(--fg-muted)' }}>SarayaDemo123!</code>
                        </div>
                        <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)' }}>{a.purpose}</div>
                      </div>
                    ))}
                    <p style={{ fontSize: 12.5, color: 'var(--fg-secondary)', margin: 0 }}>
                      Create these accounts in your Supabase Auth dashboard, then set their <code>role</code> in the <code>profiles</code> table. See <code>src/project/DEMO_ACCOUNTS.md</code> for full instructions.
                    </p>
                  </div>
                </AdminSection>
                <AdminSection title="Reset Local Changes" desc="Clear browser-stored content edits and overrides.">
                  <div style={{ padding: '16px 22px' }}>
                    <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', marginBottom: 16 }}>
                      Clears only content saved to <em>this browser</em> via Content Editing Mode. Does not affect Supabase data or other users.
                    </p>
                    <button onClick={function() {
                      if (window.confirm('Clear all local content overrides? This cannot be undone.')) {
                        localStorage.removeItem('saraya_overrides_v1');
                        window.location.reload();
                      }
                    }} style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'8px 16px', borderRadius:8, background:'none', border:'1px solid var(--line)', cursor:'pointer', fontSize:13.5, color:'var(--fg)' }}>
                      Reset Local Content
                    </button>
                  </div>
                </AdminSection>
              </div>
            )}
          </>
        )}
        </div> {/* end main content */}
      </div> {/* end flex wrapper */}

      {confirm && (
        <ConfirmDialog
          msg={confirm.msg}
          dangerous={confirm.dangerous}
          onOk={confirm.onOk}
          onCancel={() => setConfirm(null)}
        />
      )}
    </main>
  );
}
window.AdminDashboardPage = AdminDashboardPage;

/* ---- Users sub-component (separate to keep load lazy) ---- */
function UsersTable({ db }) {
  const [rows, setRows] = useStateAD([]);
  const [loaded, setLoaded] = useStateAD(false);

  useEffectAD(() => {
    if (!db) return;
    db.from('profiles').select('*').order('created_at', { ascending: false }).limit(200)
      .then(({ data }) => { setRows(data || []); setLoaded(true); });
  }, [db]);

  if (!loaded) return <div style={{ padding: '32px', textAlign: 'center', color: 'var(--fg-muted)' }}><Icon name="loader" size={24} /></div>;

  return (
    <AdminTable
      emptyMsg="No users yet"
      rows={rows}
      cols={[
        { key: 'id',           label: 'ID',      render: (r) => <code style={{ fontSize: 11 }}>{r.id.slice(0, 8)}…</code> },
        { key: 'display_name', label: 'Name' },
        { key: 'role',         label: 'Role',    render: (r) => <StatusBadge status={r.role} /> },
        { key: 'phone',        label: 'Phone' },
        { key: 'created_at',   label: 'Joined',  render: (r) => new Date(r.created_at).toLocaleDateString() },
      ]}
    />
  );
}

/* ---- One-time data migration / seed tool ---- */
function DataMigrationTool({ db }) {
  const [vendorId, setVendorId] = useStateAD('');
  const [vendors, setVendors]   = useStateAD([]);
  const [result, setResult]     = useStateAD(null);
  const [running, setRunning]   = useStateAD(false);

  useEffectAD(() => {
    if (!db) return;
    db.from('vendor_profiles').select('id, trade_name').eq('status', 'active')
      .then(({ data }) => setVendors(data || []));
  }, [db]);

  const runSeed = async () => {
    if (!vendorId) { alert('Select a vendor to assign the seeded products to.'); return; }
    if (!window.SarayaService) { alert('SarayaService not loaded.'); return; }
    if (!window.confirm('This will insert all data.js products into Supabase under the selected vendor. Run only once. Continue?')) return;
    setRunning(true); setResult(null);
    const res = await window.SarayaService.seedFromDataJs(vendorId);
    setResult(res);
    setRunning(false);
  };

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div style={{ padding: '20px 22px', borderRadius: 14, border: '1px solid var(--gold-light)', background: 'var(--cream)' }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 10 }}>
          <Icon name="alert-triangle" size={18} style={{ color: 'var(--gold-deep)' }} />
          <strong style={{ fontSize: 14 }}>Seed data.js Products → Supabase</strong>
        </div>
        <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.6, marginBottom: 18 }}>
          Imports all existing <code>data.js</code> products into the <code>products</code> table. Run once after Supabase is configured. Assigns all products to the selected vendor.
        </p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <select value={vendorId} onChange={(e) => setVendorId(e.target.value)}
            style={{ padding: '9px 12px', borderRadius: 9, border: '1px solid var(--line-strong)', fontFamily: 'var(--font-body)', fontSize: 14, minWidth: 220 }}>
            <option value="">— Select a vendor —</option>
            {vendors.map((v) => <option key={v.id} value={v.id}>{v.trade_name}</option>)}
          </select>
          <Button variant="primary" onClick={runSeed} disabled={running || !vendorId}>
            {running ? 'Running…' : 'Run Seed'}
          </Button>
        </div>
        {result && (
          <div style={{ marginTop: 14, padding: '10px 14px', borderRadius: 9, background: result.error ? 'var(--error-bg,#fef2f2)' : '#DCFCE7', color: result.error ? '#dc2626' : '#16a34a', fontSize: 13.5 }}>
            {result.error
              ? `Error: ${result.error}`
              : `Done — ${result.inserted} inserted, ${result.skipped} skipped (duplicates or missing category).`}
          </div>
        )}
      </div>
    </div>
  );
}

/* ---- Activity Logs component ---- */
function AdminActivityLog({ db }) {
  const [logs, setLogs]       = useStateAD([]);
  const [loading, setLoading] = useStateAD(true);
  const [filter, setFilter]   = useStateAD('');

  useEffectAD(() => {
    if (!db) return;
    db.from('activity_logs')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(200)
      .then(({ data }) => { setLogs(data || []); setLoading(false); });
  }, [db]);

  const filtered = filter ? logs.filter((l) => l.action?.includes(filter) || l.actor_label?.includes(filter) || l.entity_label?.includes(filter)) : logs;

  return (
    <AdminSection title="Admin Activity Log" desc="All admin and vendor actions logged in chronological order.">
      <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
        <input
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          placeholder="Filter by action, actor, or entity…"
          style={{ flex: 1, padding: '9px 14px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 13.5, background: 'var(--white)', color: 'var(--fg-primary)' }}
        />
        {filter && <button onClick={() => setFilter('')} style={{ padding: '9px 14px', borderRadius: 8, border: '1px solid var(--line)', background: 'var(--white)', cursor: 'pointer', fontSize: 13.5, color: 'var(--fg-muted)' }}>Clear</button>}
      </div>
      {loading && <div style={{ padding: '32px', textAlign: 'center', color: 'var(--fg-muted)' }}><Icon name="loader" size={22} /></div>}
      {!loading && (
        <AdminTable
          emptyMsg="No activity logged yet."
          rows={filtered}
          cols={[
            { key: 'created_at',  label: 'When',   render: (r) => new Date(r.created_at).toLocaleString('en-AE', { dateStyle: 'short', timeStyle: 'short' }) },
            { key: 'actor_label', label: 'Actor',  render: (r) => <span style={{ fontSize: 12.5 }}>{r.actor_label || '—'}<br/><span style={{ color: 'var(--fg-muted)', fontSize: 11 }}>{r.actor_role}</span></span> },
            { key: 'action',      label: 'Action', render: (r) => <code style={{ fontSize: 12, background: 'var(--cream)', padding: '2px 7px', borderRadius: 4 }}>{r.action}</code> },
            { key: 'entity',      label: 'Entity', render: (r) => r.entity_type ? `${r.entity_type}: ${r.entity_label || r.entity_id?.slice(0, 8) || ''}` : '—' },
            { key: 'ip_address',  label: 'IP',     render: (r) => <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{r.ip_address || '—'}</span> },
          ]}
        />
      )}
    </AdminSection>
  );
}


/* ---- Admin Subscriptions Management Tab ---- */
function AdminSubscriptionsTab({ db, vendors, tiers }) {
  const [subs, setSubs]               = useStateAD([]);
  const [settings, setSettings]       = useStateAD({});
  const [loading, setLoading]         = useStateAD(true);
  const [filterStatus, setFilterStatus] = useStateAD('all');
  const [filterPkg, setFilterPkg]     = useStateAD('all');
  const [showExpiring, setShowExpiring] = useStateAD(false);
  const [promoBusy, setPromoBusy]     = useStateAD(false);
  const [busyId, setBusyId]           = useStateAD('');
  const [selectedSub, setSelectedSub] = useStateAD(null); // for override modal
  const [overrideMode, setOverrideMode] = useStateAD(''); // 'extend'|'assign'|'cancel'
  const [overrideDays, setOverrideDays] = useStateAD(30);
  const [overridePkg, setOverridePkg] = useStateAD(2);
  const [overrideNote, setOverrideNote] = useStateAD('');

  const loadData = useCallbackAD(async () => {
    if (!db) return;
    setLoading(true);
    try {
      const [{ data: subData }, { data: settData }] = await Promise.all([
        db.from('subscriptions')
          .select('*, subscription_tiers(*), vendor_profiles(trade_name, status, whatsapp)')
          .in('status', ['trialing', 'active', 'restricted', 'expired', 'cancelled'])
          .order('created_at', { ascending: false }),
        db.from('platform_settings')
          .select('key, value')
          .in('key', ['launch_promotion_active', 'launch_trial_days', 'default_trial_package_level']),
      ]);
      setSubs(subData || []);
      const settObj = {};
      (settData || []).forEach((s) => { settObj[s.key] = s.value; });
      setSettings(settObj);
    } catch (e) { console.error(e); }
    setLoading(false);
  }, [db]);

  useEffectAD(() => { loadData(); }, [loadData]);

  const promoActive = settings['launch_promotion_active'] === true || settings['launch_promotion_active'] === 'true';

  const togglePromo = async () => {
    setPromoBusy(true);
    const newVal = !promoActive;
    await db.from('platform_settings')
      .update({ value: newVal, updated_at: new Date().toISOString() })
      .eq('key', 'launch_promotion_active');
    await sarayaLogActivity({ action: 'platform_setting_update', entityType: 'setting', entityLabel: 'launch_promotion_active', details: { value: newVal } });
    await loadData();
    setPromoBusy(false);
  };

  const doOverride = async () => {
    if (!selectedSub) return;
    setBusyId(selectedSub.id);
    try {
      if (overrideMode === 'extend') {
        const newEnd = new Date((selectedSub.trial_end_date ? new Date(selectedSub.trial_end_date) : new Date()).getTime() + overrideDays * 86400000);
        await db.from('subscriptions').update({
          trial_end_date: newEnd.toISOString(),
          status: 'trialing',
          is_trial_active: true,
          notes: overrideNote || null,
          package_changed_at: new Date().toISOString(),
        }).eq('id', selectedSub.id);
        await sarayaLogActivity({ action: 'trial_extended', entityType: 'subscription', entityId: selectedSub.id, entityLabel: selectedSub.vendor_profiles?.trade_name, details: { days: overrideDays, new_end: newEnd.toISOString(), note: overrideNote } });
      } else if (overrideMode === 'assign') {
        const tier = tiers.find((t) => t.package_level === overridePkg);
        if (!tier) { alert('Tier not found'); setBusyId(''); return; }
        await db.from('subscriptions').update({
          tier_id: tier.id,
          status: 'active',
          is_trial_active: false,
          is_free_access: true,
          current_period_start: new Date().toISOString(),
          current_period_end: new Date(Date.now() + overrideDays * 86400000).toISOString(),
          admin_override: 'free_access',
          notes: overrideNote || null,
          package_changed_at: new Date().toISOString(),
        }).eq('id', selectedSub.id);
        await sarayaLogActivity({ action: 'package_assigned', entityType: 'subscription', entityId: selectedSub.id, entityLabel: selectedSub.vendor_profiles?.trade_name, details: { pkg: overridePkg, days: overrideDays, note: overrideNote } });
      } else if (overrideMode === 'cancel') {
        await db.from('subscriptions').update({
          status: 'restricted',
          is_trial_active: false,
          notes: overrideNote || null,
          package_changed_at: new Date().toISOString(),
        }).eq('id', selectedSub.id);
        await db.from('vendor_profiles').update({ status: 'active' }).eq('id', selectedSub.vendor_id);
        await sarayaLogActivity({ action: 'trial_cancelled', entityType: 'subscription', entityId: selectedSub.id, entityLabel: selectedSub.vendor_profiles?.trade_name, details: { note: overrideNote } });
      }
    } catch (e) { console.error(e); }
    setSelectedSub(null);
    setOverrideMode('');
    setOverrideNote('');
    setBusyId('');
    loadData();
  };

  const now = new Date();
  const in7days = new Date(now.getTime() + 7 * 86400000);

  // Build vendor lookup from subs (subs have vendor_id)
  // Also add vendors with NO subscription
  const vendorSubMap = {};
  subs.forEach((s) => { if (s.vendor_id) vendorSubMap[s.vendor_id] = s; });

  const rows = vendors
    .filter((v) => ['active', 'approved', 'agreement_accepted'].includes(v.status))
    .map((v) => {
      const sub = vendorSubMap[v.id] || null;
      const tier = sub?.subscription_tiers || null;
      const trialEnd = sub?.trial_end_date ? new Date(sub.trial_end_date) : null;
      const trialDaysLeft = trialEnd ? Math.max(0, Math.ceil((trialEnd - now) / 86400000)) : null;
      const isTrial = sub?.is_trial_active && sub?.status === 'trialing';
      const isExpiringSoon = isTrial && trialEnd && trialEnd <= in7days && trialEnd >= now;
      const effectiveStatus = !sub ? 'no_sub'
        : sub.status === 'trialing' && trialEnd && trialEnd < now ? 'trial_expired'
        : sub.status;
      return { ...v, sub, tier, trialEnd, trialDaysLeft, isTrial, isExpiringSoon, effectiveStatus };
    });

  const filtered = rows.filter((r) => {
    if (showExpiring && !r.isExpiringSoon) return false;
    if (filterStatus !== 'all' && r.effectiveStatus !== filterStatus) return false;
    if (filterPkg !== 'all' && String(r.tier?.package_level ?? '0') !== filterPkg) return false;
    return true;
  });

  const statusColor = { trialing: '#D97706', active: '#16A34A', restricted: '#DC2626', trial_expired: '#DC2626', expired: '#9CA3AF', cancelled: '#9CA3AF', no_sub: '#6B7280' };
  const statusLabel = { trialing: 'Trial', active: 'Active', restricted: 'Restricted', trial_expired: 'Trial Expired', expired: 'Expired', cancelled: 'Cancelled', no_sub: 'No Plan' };

  const inputStyle = { padding: '9px 12px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 13.5, background: 'var(--white)', color: 'var(--fg-primary)', outline: 'none' };
  const labelStyle = { fontSize: 12.5, fontWeight: 600, color: 'var(--fg-secondary)', marginBottom: 5, display: 'block' };

  return (
    <div style={{ display: 'grid', gap: 20 }}>

      {/* Launch Promotion Toggle */}
      <div style={{ padding: '18px 22px', borderRadius: 14, border: '1.5px solid var(--gold-light)', background: 'var(--cream)', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <Icon name="zap" size={20} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--fg-primary)', marginBottom: 2 }}>Launch Promotion</div>
          <div style={{ fontSize: 13, color: 'var(--fg-secondary)' }}>
            When <strong>ON</strong>, new approved vendors automatically receive a {settings['launch_trial_days'] || 60}-day free trial on Package 2 (Growth). Currently: <strong style={{ color: promoActive ? '#16A34A' : '#DC2626' }}>{promoActive ? 'ACTIVE' : 'INACTIVE'}</strong>
          </div>
        </div>
        <button
          onClick={togglePromo}
          disabled={promoBusy}
          style={{
            padding: '10px 22px', borderRadius: 10, border: 'none', cursor: promoBusy ? 'not-allowed' : 'pointer',
            fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600,
            background: promoActive ? '#FEF2F2' : '#F0FDF4',
            color: promoActive ? '#DC2626' : '#16A34A',
            transition: 'all 160ms',
          }}
        >
          {promoBusy ? 'Saving…' : promoActive ? 'Turn OFF Promo' : 'Turn ON Promo'}
        </button>
      </div>

      {/* Stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(160px,1fr))', gap: 12 }}>
        {[
          { label: 'Trial Active',   value: rows.filter((r) => r.isTrial).length,                               color: '#D97706' },
          { label: 'Paid Active',    value: rows.filter((r) => r.effectiveStatus === 'active' && !r.sub?.is_free_access).length, color: '#16A34A' },
          { label: 'Free Access',    value: rows.filter((r) => r.sub?.is_free_access).length,                   color: '#2563EB' },
          { label: 'Expiring ≤7d',   value: rows.filter((r) => r.isExpiringSoon).length,                        color: '#DC2626' },
          { label: 'Restricted',     value: rows.filter((r) => ['restricted','trial_expired','no_sub'].includes(r.effectiveStatus)).length, color: '#9CA3AF' },
        ].map((s) => (
          <div key={s.label} style={{ background: 'var(--white)', borderRadius: 12, border: '1px solid var(--line)', padding: '14px 16px', textAlign: 'center' }}>
            <div style={{ fontSize: 24, fontWeight: 700, color: s.color }}>{s.value}</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <AdminSection title="Vendor Subscriptions" desc="Manage packages, trials, and overrides for all active vendors.">
        <div style={{ padding: '12px 20px 0', display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <select value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)} style={{ ...inputStyle, minWidth: 150 }}>
            <option value="all">All Statuses</option>
            <option value="trialing">Trial Active</option>
            <option value="active">Paid/Free Active</option>
            <option value="restricted">Restricted</option>
            <option value="trial_expired">Trial Expired</option>
            <option value="no_sub">No Subscription</option>
          </select>
          <select value={filterPkg} onChange={(e) => setFilterPkg(e.target.value)} style={{ ...inputStyle, minWidth: 150 }}>
            <option value="all">All Packages</option>
            <option value="1">Package 1 – Starter</option>
            <option value="2">Package 2 – Growth</option>
            <option value="3">Package 3 – Premium</option>
            <option value="0">No Package</option>
          </select>
          <button
            onClick={() => setShowExpiring((v) => !v)}
            style={{ padding: '9px 14px', borderRadius: 8, border: `1.5px solid ${showExpiring ? '#DC2626' : 'var(--line)'}`, fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, background: showExpiring ? '#FEF2F2' : 'var(--white)', color: showExpiring ? '#DC2626' : 'var(--fg-secondary)', cursor: 'pointer' }}
          >
            <Icon name="clock" size={13} style={{ marginRight: 5 }} />Expiring Soon
          </button>
          {(filterStatus !== 'all' || filterPkg !== 'all' || showExpiring) && (
            <button onClick={() => { setFilterStatus('all'); setFilterPkg('all'); setShowExpiring(false); }} style={{ padding: '9px 12px', borderRadius: 8, border: '1px solid var(--line)', background: 'var(--white)', fontSize: 13, color: 'var(--fg-muted)', cursor: 'pointer' }}>Clear</button>
          )}
          <span style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginLeft: 'auto' }}>{filtered.length} vendor{filtered.length !== 1 ? 's' : ''}</span>
        </div>

        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)' }}><Icon name="loader" size={22} /></div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
              <thead>
                <tr style={{ borderBottom: '2px solid var(--line)' }}>
                  {['Vendor', 'Package', 'Status', 'Trial / Expiry', 'Days Left', 'Stripe', 'Actions'].map((h) => (
                    <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12.5, whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 && (
                  <tr><td colSpan={7} style={{ padding: '32px', textAlign: 'center', color: 'var(--fg-muted)' }}>No vendors match the selected filters.</td></tr>
                )}
                {filtered.map((r) => (
                  <tr key={r.id} style={{ borderBottom: '1px solid var(--line)', background: r.isExpiringSoon ? '#FFFBEB' : 'var(--white)', transition: 'background 120ms' }}>
                    <td style={{ padding: '10px 14px' }}>
                      <div style={{ fontWeight: 600, color: 'var(--fg-primary)' }}>{r.trade_name}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>{r.sub?.vendor_id?.slice(0,8) || r.id?.slice(0,8)}</div>
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      {r.tier ? (
                        <span style={{ padding: '3px 9px', borderRadius: 6, background: 'var(--cream)', color: 'var(--gold-deep)', fontSize: 12, fontWeight: 600 }}>
                          P{r.tier.package_level} — {r.tier.name}
                        </span>
                      ) : <span style={{ color: 'var(--fg-muted)' }}>—</span>}
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{ padding: '3px 9px', borderRadius: 6, background: (statusColor[r.effectiveStatus] || '#9CA3AF') + '18', color: statusColor[r.effectiveStatus] || '#9CA3AF', fontSize: 12, fontWeight: 600 }}>
                        {statusLabel[r.effectiveStatus] || r.effectiveStatus}
                      </span>
                      {r.sub?.is_free_access && <span style={{ marginLeft: 5, padding: '2px 7px', borderRadius: 6, background: '#EFF6FF', color: '#2563EB', fontSize: 11, fontWeight: 600 }}>FREE</span>}
                    </td>
                    <td style={{ padding: '10px 14px', fontSize: 12.5, color: 'var(--fg-secondary)', whiteSpace: 'nowrap' }}>
                      {r.trialEnd ? new Date(r.trialEnd).toLocaleDateString('en-AE') : '—'}
                    </td>
                    <td style={{ padding: '10px 14px', textAlign: 'center' }}>
                      {r.isTrial && r.trialDaysLeft !== null ? (
                        <span style={{ fontWeight: 700, color: r.trialDaysLeft <= 7 ? '#DC2626' : r.trialDaysLeft <= 14 ? '#D97706' : '#16A34A', fontSize: 13 }}>
                          {r.trialDaysLeft}d
                        </span>
                      ) : <span style={{ color: 'var(--fg-muted)' }}>—</span>}
                    </td>
                    <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--fg-muted)' }}>
                      {r.sub?.stripe_sub_id
                        ? <span style={{ color: '#16A34A', fontWeight: 600 }}>✓ {r.sub.stripe_sub_id.slice(0,12)}…</span>
                        : <span style={{ color: '#9CA3AF' }}>No Stripe</span>}
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                        <button
                          disabled={busyId === r.id}
                          onClick={() => { setSelectedSub(r.sub ? { ...r.sub, vendor_profiles: { trade_name: r.trade_name } } : { vendor_id: r.id, id: null, vendor_profiles: { trade_name: r.trade_name } }); setOverrideMode('extend'); setOverrideDays(30); setOverrideNote(''); }}
                          style={{ padding: '5px 10px', borderRadius: 7, border: '1px solid var(--line)', background: 'var(--white)', fontSize: 12, cursor: 'pointer', color: '#D97706', fontWeight: 600 }}
                        >+Trial</button>
                        <button
                          disabled={busyId === r.id}
                          onClick={() => { setSelectedSub(r.sub ? { ...r.sub, vendor_profiles: { trade_name: r.trade_name } } : { vendor_id: r.id, id: null, vendor_profiles: { trade_name: r.trade_name } }); setOverrideMode('assign'); setOverridePkg(2); setOverrideDays(365); setOverrideNote(''); }}
                          style={{ padding: '5px 10px', borderRadius: 7, border: '1px solid var(--line)', background: 'var(--white)', fontSize: 12, cursor: 'pointer', color: '#2563EB', fontWeight: 600 }}
                        >Assign</button>
                        {(r.isTrial || r.effectiveStatus === 'active') && (
                          <button
                            disabled={busyId === r.id}
                            onClick={() => { setSelectedSub(r.sub ? { ...r.sub, vendor_profiles: { trade_name: r.trade_name } } : { vendor_id: r.id, id: null, vendor_profiles: { trade_name: r.trade_name } }); setOverrideMode('cancel'); setOverrideNote(''); }}
                            style={{ padding: '5px 10px', borderRadius: 7, border: '1px solid #FCA5A5', background: '#FEF2F2', fontSize: 12, cursor: 'pointer', color: '#DC2626', fontWeight: 600 }}
                          >Restrict</button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </AdminSection>

      {/* Override Modal */}
      {selectedSub && overrideMode && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}
          onClick={(e) => { if (e.target === e.currentTarget) { setSelectedSub(null); setOverrideMode(''); } }}>
          <div style={{ background: 'var(--white)', borderRadius: 18, padding: '28px 30px', maxWidth: 440, width: '100%', boxShadow: '0 20px 60px rgba(0,0,0,0.25)' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, marginBottom: 6 }}>
              {overrideMode === 'extend' ? 'Extend / Grant Trial' : overrideMode === 'assign' ? 'Assign Package' : 'Restrict Vendor'}
            </div>
            <div style={{ fontSize: 13.5, color: 'var(--fg-secondary)', marginBottom: 20 }}>
              Vendor: <strong>{selectedSub.vendor_profiles?.trade_name || selectedSub.vendor_id}</strong>
            </div>

            {overrideMode === 'extend' && (
              <div style={{ display: 'grid', gap: 14 }}>
                <div>
                  <label style={labelStyle}>Extend Trial by (days)</label>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {[7, 14, 30, 60].map((d) => (
                      <button key={d} onClick={() => setOverrideDays(d)}
                        style={{ flex: 1, padding: '8px 0', borderRadius: 8, border: `1.5px solid ${overrideDays === d ? 'var(--gold-deep)' : 'var(--line)'}`, background: overrideDays === d ? 'var(--cream)' : 'var(--white)', color: overrideDays === d ? 'var(--gold-deep)' : 'var(--fg-secondary)', fontWeight: 600, fontSize: 13, cursor: 'pointer' }}
                      >{d}d</button>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {overrideMode === 'assign' && (
              <div style={{ display: 'grid', gap: 14 }}>
                <div>
                  <label style={labelStyle}>Package</label>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {[{l:1,n:'Starter'},{l:2,n:'Growth'},{l:3,n:'Premium'}].map((p) => (
                      <button key={p.l} onClick={() => setOverridePkg(p.l)}
                        style={{ flex: 1, padding: '8px 0', borderRadius: 8, border: `1.5px solid ${overridePkg === p.l ? 'var(--gold-deep)' : 'var(--line)'}`, background: overridePkg === p.l ? 'var(--cream)' : 'var(--white)', color: overridePkg === p.l ? 'var(--gold-deep)' : 'var(--fg-secondary)', fontWeight: 600, fontSize: 12.5, cursor: 'pointer' }}
                      >P{p.l}<br/><span style={{ fontSize: 11, fontWeight: 400 }}>{p.n}</span></button>
                    ))}
                  </div>
                </div>
                <div>
                  <label style={labelStyle}>Duration (days of free access)</label>
                  <input type="number" value={overrideDays} onChange={(e) => setOverrideDays(Number(e.target.value))} min={1} style={{ ...inputStyle, width: '100%' }} />
                </div>
              </div>
            )}

            {overrideMode === 'cancel' && (
              <div style={{ padding: '12px 16px', borderRadius: 10, background: '#FEF2F2', border: '1px solid #FCA5A5', fontSize: 13.5, color: '#DC2626', marginBottom: 4 }}>
                This vendor will be set to <strong>Restricted</strong> — they can log in and view their dashboard but cannot publish listings, respond to RFQs, or appear in the marketplace until they subscribe.
              </div>
            )}

            <div style={{ marginTop: 16 }}>
              <label style={labelStyle}>Admin Note (optional)</label>
              <textarea value={overrideNote} onChange={(e) => setOverrideNote(e.target.value)}
                placeholder="Internal note saved to subscription log…"
                rows={2}
                style={{ ...inputStyle, width: '100%', resize: 'vertical', boxSizing: 'border-box' }}
              />
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
              <button onClick={() => { setSelectedSub(null); setOverrideMode(''); }}
                style={{ flex: 1, padding: '10px 0', borderRadius: 9, border: '1px solid var(--line)', background: 'var(--white)', fontSize: 14, cursor: 'pointer', color: 'var(--fg-secondary)', fontWeight: 600 }}
              >Cancel</button>
              <button onClick={doOverride} disabled={!!busyId}
                style={{ flex: 1, padding: '10px 0', borderRadius: 9, border: 'none', fontSize: 14, cursor: busyId ? 'not-allowed' : 'pointer', fontWeight: 700,
                  background: overrideMode === 'cancel' ? '#DC2626' : 'var(--espresso)', color: 'var(--white)' }}
              >{busyId ? 'Saving…' : overrideMode === 'extend' ? 'Extend Trial' : overrideMode === 'assign' ? 'Assign Package' : 'Restrict Vendor'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---- sarayaLogActivity — call from anywhere after an admin action ---- */
async function sarayaLogActivity({ action, entityType, entityId, entityLabel, details }) {
  const db = window.SarayaDB;
  if (!db) return;
  const { data: { user } } = await db.auth.getUser().catch(() => ({ data: {} }));
  if (!user) return;
  const { data: profile } = await db.from('profiles').select('display_name, role').eq('id', user.id).single().catch(() => ({ data: null }));
  await db.from('activity_logs').insert({
    actor_id:     user.id,
    actor_role:   profile?.role || 'unknown',
    actor_label:  profile?.display_name || user.email,
    action,
    entity_type:  entityType || null,
    entity_id:    entityId   || null,
    entity_label: entityLabel || null,
    details:      details     || {},
  }).catch(() => {});
}
window.sarayaLogActivity = sarayaLogActivity;
