// ============================================================
// Saraya Events — Vendor Dashboard
//
// Phase 1 scope:
//   • Profile status display (approval pipeline)
//   • Trade document upload
//   • Vendor agreement acceptance
//   • Subscription tier display
//   • Listing count summary (products / rentals / services)
//   • Payout summary
//   • Quick-link placeholders for Phase 2 CRUD
// ============================================================

const {
  useState: useStateVD,
  useEffect: useEffectVD,
  useCallback: useCallbackVD,
  useRef: useRefVD,
} = React;

/* ---------- Status pipeline bar ---------- */
const VENDOR_STATUSES = [
  { key: 'registered',       label: { en: 'Registered',       ar: 'مسجّل' } },
  { key: 'package_pending',  label: { en: 'Package Pending',  ar: 'باقة معلقة' } },
  { key: 'payment_pending',  label: { en: 'Payment Pending',  ar: 'دفع معلق' } },
  { key: 'pending_approval', label: { en: 'Pending Approval', ar: 'بانتظار الموافقة' } },
  { key: 'approved',         label: { en: 'Approved',         ar: 'معتمد' } },
];

function StatusPipeline({ currentStatus, ar }) {
  const idx = VENDOR_STATUSES.findIndex((s) => s.key === currentStatus);
  return (
    <div className="saraya-vd-pipeline" style={{ display: 'flex', alignItems: 'center', gap: 0, overflowX: 'auto', paddingBottom: 4 }}>
      {VENDOR_STATUSES.map((s, i) => {
        const done    = i < idx;
        const active  = i === idx;
        const pending = i > idx;
        return (
          <React.Fragment key={s.key}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, minWidth: 90, flex: 1 }}>
              <div style={{
                width: 32, height: 32, borderRadius: '50%', border: '2px solid',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: done ? 'var(--gold)' : active ? 'var(--cream)' : 'var(--white)',
                borderColor: done || active ? 'var(--gold)' : 'var(--line)',
                transition: 'all 200ms',
              }}>
                {done
                  ? <Icon name="check" size={15} style={{ color: 'var(--white)' }} />
                  : <span style={{ width: 10, height: 10, borderRadius: '50%', background: active ? 'var(--gold)' : 'var(--line)' }} />}
              </div>
              <span style={{
                fontSize: 11, fontWeight: active ? 700 : 500, letterSpacing: '0.06em',
                textTransform: 'uppercase', textAlign: 'center', lineHeight: 1.3,
                color: done || active ? 'var(--fg-primary)' : 'var(--fg-muted)',
              }}>
                {ar ? s.label.ar : s.label.en}
              </span>
            </div>
            {i < VENDOR_STATUSES.length - 1 && (
              <div style={{ flex: 0, width: 24, height: 2, background: done ? 'var(--gold)' : 'var(--line)', margin: '0 0 22px', transition: 'background 200ms' }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* ---------- Stat card ---------- */
function VDStat({ icon, label, value, sub }) {
  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: 'var(--cream)', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={18} style={{ color: 'var(--gold-deep)' }} />
        </span>
        <span style={{ fontSize: 12.5, color: 'var(--fg-secondary)', fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</span>
      </div>
      <p style={{ fontSize: 28, fontWeight: 700, fontFamily: 'var(--font-display)', margin: 0, color: 'var(--fg-primary)' }}>{value}</p>
      {sub && <p style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{sub}</p>}
    </div>
  );
}

/* ---------- Coming-soon placeholder ---------- */
function VDPlaceholder({ icon, title, desc, items }) {
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={{ padding: '20px 22px', borderRadius: 14, background: 'var(--cream)', border: '1.5px solid var(--gold-light)', display: 'flex', gap: 16, alignItems: 'flex-start' }}>
        <span style={{ display: 'inline-flex', width: 44, height: 44, borderRadius: 12, background: 'var(--white)', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={icon} size={22} style={{ color: 'var(--gold-deep)' }} />
        </span>
        <div>
          <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 5 }}>{title}</div>
          <div style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.65 }}>{desc}</div>
        </div>
      </div>
      {items && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(200px,1fr))', gap: 12 }}>
          {items.map(function(item, i) {
            return (
              <div key={i} style={{ padding: '14px 16px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <Icon name={item.icon} size={15} style={{ color: 'var(--gold-deep)' }} />
                  <span style={{ fontWeight: 600, fontSize: 13 }}>{item.label}</span>
                </div>
                <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', margin: 0, lineHeight: 1.5 }}>{item.desc}</p>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ---------- Document upload section ---------- */
function DocumentUpload({ vendorId, existingDocs, onUploaded, ar }) {
  const db = window.SarayaDB;
  const [uploading, setUploading] = useStateVD(false);
  const [msg, setMsg] = useStateVD('');
  const inputRef = useRefVD(null);

  const DOC_TYPES = [
    { key: 'trade_license',    label: { en: 'Trade License',     ar: 'الرخصة التجارية' }, required: true },
    { key: 'emirates_id',      label: { en: 'Emirates ID',       ar: 'الهوية الإماراتية' }, required: true },
    { key: 'bank_letter',      label: { en: 'Bank Letter / IBAN Certificate', ar: 'خطاب البنك / شهادة الآيبان' }, required: true },
    { key: 'vat_certificate',  label: { en: 'VAT Certificate (optional)', ar: 'شهادة ضريبة القيمة المضافة (اختياري)' } },
  ];

  const handleFile = async (docType, file) => {
    if (!file || !db) return;
    setUploading(true); setMsg('');
    const ext  = file.name.split('.').pop();
    const path = `${vendorId}/${docType}-${Date.now()}.${ext}`;
    const { error: upErr } = await db.storage.from('vendor-documents').upload(path, file, { upsert: true });
    if (upErr) { setMsg(upErr.message); setUploading(false); return; }
    // vendor-documents is a PRIVATE bucket (KYC docs). Store the object path and
    // open via a short-lived signed URL — public URLs 404 ("Bucket not found").
    const { error: docErr } = await db.from('vendor_documents').upsert({
      vendor_id: vendorId, doc_type: docType,
      file_url: path, file_name: file.name,
    }, { onConflict: 'vendor_id,doc_type' });
    if (docErr) { setMsg(docErr.message); setUploading(false); return; }
    // Only advance status to 'pending_approval' if vendor is not already further along
    const STATUSES_ORDER = ['registered', 'package_pending', 'payment_pending', 'pending_approval', 'approved'];
    const { data: vp } = await db.from('vendor_profiles').select('status').eq('id', vendorId).single();
    const currentIdx = STATUSES_ORDER.indexOf(vp?.status);
    const targetIdx  = STATUSES_ORDER.indexOf('pending_approval');
    if (currentIdx < targetIdx) {
      await db.from('vendor_profiles').update({ status: 'pending_approval' }).eq('id', vendorId);
    }
    setUploading(false);
    setMsg(ar ? 'تم رفع الملف بنجاح' : 'Document uploaded successfully');
    onUploaded && onUploaded();
  };

  const viewDoc = async (fileUrl) => {
    if (!fileUrl || !db) return;
    const path = fileUrl.includes('/vendor-documents/') ? fileUrl.split('/vendor-documents/')[1] : fileUrl;
    const { data, error } = await db.storage.from('vendor-documents').createSignedUrl(path, 300);
    if (error) { setMsg(error.message); return; }
    window.open(data.signedUrl, '_blank', 'noopener');
  };

  return (
    <div style={{ display: 'grid', gap: 12 }}>
      {uploading && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 8, background: 'var(--cream)', border: '1px solid var(--gold-light)', fontSize: 13, color: 'var(--fg-secondary)' }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ animation: 'sarayaSpin 1s linear infinite', color: 'var(--gold-deep)' }}>
            <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
          </svg>
          {ar ? 'جارٍ رفع الملف...' : 'Uploading document…'}
        </div>
      )}
      {DOC_TYPES.map((dt) => {
        const existing = existingDocs.find((d) => d.doc_type === dt.key);
        return (
          <div key={dt.key} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 16px', borderRadius: 10,
            border: existing ? '1.5px solid var(--gold)' : '1.5px dashed var(--line)',
            background: existing ? 'var(--cream)' : 'var(--white)',
            opacity: uploading ? 0.6 : 1,
            pointerEvents: uploading ? 'none' : 'auto',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name={existing ? 'file-check' : 'file-up'} size={18} style={{ color: existing ? 'var(--gold-deep)' : 'var(--fg-muted)' }} />
              <span style={{ fontSize: 13.5, fontWeight: 500 }}>{ar ? dt.label.ar : dt.label.en}{dt.required && <span style={{ color: 'var(--error)', fontWeight: 700 }}> *</span>}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {existing && (
              <button type="button" onClick={() => viewDoc(existing.file_url)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 8, fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-body)', background: 'transparent', color: 'var(--gold-deep)', border: '1.5px solid var(--gold)', cursor: 'pointer' }}>
                <Icon name="eye" size={14} />{ar ? 'عرض' : 'View'}
              </button>
            )}
            <label style={{ cursor: uploading ? 'not-allowed' : 'pointer' }}>
              <input
                type="file"
                accept=".pdf,.jpg,.jpeg,.png"
                style={{ display: 'none' }}
                onChange={(e) => handleFile(dt.key, e.target.files[0])}
                disabled={uploading}
              />
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 14px',
                borderRadius: 8, fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-body)',
                background: existing ? 'transparent' : 'var(--gold)', color: existing ? 'var(--gold-deep)' : 'var(--white)',
                border: existing ? '1.5px solid var(--gold)' : 'none',
                cursor: uploading ? 'not-allowed' : 'pointer',
              }}>
                <Icon name={existing ? 'repeat' : 'upload'} size={14} />
                {existing ? (ar ? 'استبدال' : 'Replace') : (ar ? 'رفع' : 'Upload')}
              </span>
            </label>
            </div>
          </div>
        );
      })}
      {msg && <p style={{ fontSize: 13, color: msg.includes('success') || msg.includes('نجاح') ? 'var(--success, #16a34a)' : '#B91C1C', marginTop: 4 }}>{msg}</p>}
    </div>
  );
}

/* ---------- Agreement section ---------- */
function AgreementSection({ vendorId, alreadySigned, signedAt, version, tradeName, onSign, ar }) {
  const db = window.SarayaDB;
  const [agreed, setAgreed] = useStateVD(false);
  const [busy, setBusy] = useStateVD(false);

  const AGREEMENT_VERSION = (window.SarayaAgreement && window.SarayaAgreement.VERSION) || '2.0';
  const AGREEMENT_TEXT_EN = `
Saraya Events Marketplace Vendor Agreement — v${AGREEMENT_VERSION}

By accepting this agreement, you confirm:
1. You are an authorised representative of the registered business entity.
2. You are solely responsible for the quality, accuracy, delivery, installation, warranty, and after-sales service of all products, rentals, and services listed under your account.
3. Saraya Events operates as an intermediary platform connecting buyers and sellers. Saraya is not responsible for disputes arising from product quality, late delivery, or service failures — these are the vendor's responsibility.
4. You agree to the platform commission rate as defined in your subscription tier.
5. Payouts will be held until customer confirmation of delivery/completion or expiry of the 3-day dispute window, whichever is earlier.
6. Saraya reserves the right to suspend or deactivate accounts that breach platform policies or receive repeated complaints.
7. You agree to maintain a valid trade license for the duration of your subscription.
  `.trim();

  const sign = async () => {
    if (!agreed || !db) return;
    setBusy(true);
    let ok = false;
    // Prefer the server-side record — it captures the acceptance IP + version
    // for a binding electronic-signature record.
    try {
      const { data, error } = await db.functions.invoke('sign-agreement', { body: { version: AGREEMENT_VERSION } });
      if (!error && data && data.ok) ok = true;
    } catch (e) { /* fall back below */ }
    if (!ok) {
      const r = await db.from('vendor_profiles').update({
        agreement_version: AGREEMENT_VERSION,
        agreement_signed_at: new Date().toISOString(),
        status: 'agreement_accepted',
      }).eq('id', vendorId);
      ok = !r.error;
    }
    setBusy(false);
    if (ok) onSign && onSign();
  };

  if (alreadySigned) {
    const signedLabel = signedAt ? new Date(signedAt).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' }) : null;
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderRadius: 10, background: 'var(--cream)', border: '1.5px solid var(--gold)', flexWrap: 'wrap' }}>
        <Icon name="badge-check" size={20} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
        <span style={{ fontSize: 13.5, color: 'var(--fg-primary)', flex: 1, minWidth: 180 }}>
          {ar ? 'وقّعت على اتفاقية البائع' : 'You have signed the Vendor Agreement'}
          {signedLabel ? <span style={{ color: 'var(--fg-muted)' }}> · v{version || '1.0'} · {signedLabel}</span> : null}
        </span>
        <button
          type="button"
          onClick={() => window.SarayaAgreement && window.SarayaAgreement.downloadDoc({ tradeName, signedAt, version: version || '1.0' })}
          style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 14px', borderRadius: 8, border: '1px solid var(--gold)', background: 'var(--white)', color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, cursor: 'pointer', whiteSpace: 'nowrap' }}>
          <Icon name="download" size={15} />{ar ? 'تنزيل الاتفاقية' : 'Download agreement'}
        </button>
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gap: 14 }}>
      <div dir={ar ? 'rtl' : 'ltr'} style={{
        maxHeight: 280, overflowY: 'auto', padding: '16px 18px',
        borderRadius: 10, border: '1px solid var(--line)',
        background: 'var(--bg-tint)', fontSize: 12.5, lineHeight: 1.75,
        color: 'var(--fg-secondary)', fontFamily: 'var(--font-body)', whiteSpace: 'pre-wrap',
        textAlign: ar ? 'right' : 'left',
      }}>
        {(window.SarayaAgreement ? (ar ? window.SarayaAgreement.TEXT_AR : window.SarayaAgreement.TEXT_EN) : AGREEMENT_TEXT_EN)}
      </div>
      <button
        type="button"
        onClick={() => window.SarayaAgreement && window.SarayaAgreement.downloadDoc({ tradeName, version: AGREEMENT_VERSION })}
        style={{ alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 13px', borderRadius: 8, border: '1px solid var(--line)', background: 'var(--white)', color: 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12.5, cursor: 'pointer' }}>
        <Icon name="download" size={14} />{ar ? 'تنزيل النسخة الكاملة (عربي/إنجليزي)' : 'Download full agreement (EN/AR)'}
      </button>
      <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer' }}>
        <input
          type="checkbox"
          checked={agreed}
          onChange={(e) => setAgreed(e.target.checked)}
          style={{ width: 17, height: 17, marginTop: 2, accentColor: 'var(--gold-deep)', flexShrink: 0 }}
        />
        <span style={{ fontSize: 13.5, lineHeight: 1.55 }}>
          {ar
            ? 'أوافق على شروط اتفاقية البائع وأتفهم مسؤولياتي كبائع في منصة سرايا.'
            : 'I agree to the Vendor Agreement and understand my responsibilities as a seller on the Saraya platform.'}
        </span>
      </label>
      <Button variant="primary" onClick={sign} loading={busy} disabled={!agreed || busy}>
        {ar ? 'توقيع الاتفاقية' : 'Sign Agreement'}
      </Button>
    </div>
  );
}

/* ---------- Quick action card ---------- */
function QuickCard({ icon, title, description, cta, onClick, badge }) {
  return (
    <div style={{
      background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)',
      padding: '20px', display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <span style={{ display: 'inline-flex', width: 40, height: 40, borderRadius: 11, background: 'var(--cream)', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={20} style={{ color: 'var(--gold-deep)' }} />
        </span>
        {badge != null && (
          <span style={{ padding: '3px 10px', borderRadius: 20, background: 'var(--cream)', fontSize: 12, fontWeight: 700, color: 'var(--gold-deep)', border: '1px solid var(--gold-light)' }}>
            {badge}
          </span>
        )}
      </div>
      <div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, margin: 0, marginBottom: 4 }}>{title}</h3>
        <p style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.55, margin: 0 }}>{description}</p>
      </div>
      <Button variant="secondary" onClick={onClick} style={{ alignSelf: 'flex-start', marginTop: 4 }}>{cta}</Button>
    </div>
  );
}

/* ============================================================
   VENDOR LISTINGS CRUD (Phase 2)
   Products / Rentals / Services — create, edit, delete with image upload
   ============================================================ */

const LISTING_TYPES = ['products', 'rentals', 'services'];

const AVAIL_OPTS = [
  { value: 'in', label: 'In stock' }, { value: 'order', label: 'Made to order' },
  { value: 'soon', label: 'Coming soon' }, { value: 'out', label: 'Unavailable' },
];
const PRICING_TYPE_OPTS = [
  { value: 'fixed', label: 'Fixed price' }, { value: 'hourly', label: 'Per hour' },
  { value: 'per_person', label: 'Per person' }, { value: 'package', label: 'Package' },
  { value: 'custom_quote', label: 'Custom quote (no price displayed)' },
];

/* ── Shared field wrapper ── */
function VDField({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
      <label style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--fg-secondary)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{label}</label>
      {children}
    </div>
  );
}
const VDInput = ({ style, ...p }) => (
  <input {...p} style={{ padding: '10px 12px', borderRadius: 9, border: '1px solid var(--line-strong)', fontFamily: 'var(--font-body)', fontSize: 14, outline: 'none', background: 'var(--white)', width: '100%', boxSizing: 'border-box', ...style }} />
);
const VDTextarea = ({ style, ...p }) => (
  <textarea {...p} rows={3} style={{ padding: '10px 12px', borderRadius: 9, border: '1px solid var(--line-strong)', fontFamily: 'var(--font-body)', fontSize: 14, outline: 'none', background: 'var(--white)', width: '100%', resize: 'vertical', boxSizing: 'border-box', ...style }} />
);
const VDSelect = ({ options, style, ...p }) => (
  <select {...p} style={{ padding: '10px 12px', borderRadius: 9, border: '1px solid var(--line-strong)', fontFamily: 'var(--font-body)', fontSize: 14, outline: 'none', background: 'var(--white)', width: '100%', cursor: 'pointer', boxSizing: 'border-box', ...style }}>
    {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
  </select>
);

/* ── Listing form modal (shared for products / rentals / services) ── */
function ListingFormModal({ type, initial, vendorId, categories, onSave, onClose, ar, canDiscount }) {
  const isEdit = !!initial;
  const db     = window.SarayaDB;
  const cat0   = (categories[0] && categories[0].id) || '';

  /* ── Blank forms ── */
  const blankProduct = {
    name_en: '', name_ar: '', category_id: cat0,
    price: '', sale_price: '', stock_quantity: '',
    description_en: '', description_ar: '',
    availability: 'in', is_digital: false, is_popular: false, is_new: false, is_active: true,
    images: [], coverIdx: 0, meta: { city: '' },
  };
  const blankRental = {
    name_en: '', name_ar: '', category_id: cat0,
    price_per_day: '', price_per_week: '', price_per_event: '',
    deposit_amount: '', min_order_qty: 20, delivery_fee: '', min_rental_days: 1, stock_quantity: '',
    description_en: '', description_ar: '', is_active: true,
    images: [], coverIdx: 0, meta: { condition: 'excellent', delivery_available: false },
  };
  const blankService = {
    name_en: '', name_ar: '', category_id: cat0,
    pricing_type: 'fixed', base_price: '',
    description_en: '', description_ar: '', is_active: true,
    images: [], coverIdx: 0, meta: { duration: '', service_area: 'all_uae', lead_time_days: '' },
  };
  const blank = type === 'products' ? blankProduct : type === 'rentals' ? blankRental : blankService;

  const [form, setForm] = useStateVD(() => {
    if (!isEdit) {
      try {
        const _dk = 'saraya_draft_' + type;
        const _raw = window.localStorage.getItem(_dk);
        if (_raw) { const _d = JSON.parse(_raw); if (_d && _d.t && (Date.now() - _d.t < 86400000) && _d.form) return { ...blank, ..._d.form, meta: { ...(blank.meta || {}), ...(_d.form.meta || {}) } }; }
      } catch (e) {}
      return blank;
    }
    /* Only pull real column/form fields from the loaded row -- spreading the
       full normalized object (which also carries derived-only helper fields
       like _dbId, tone, name/desc objects, salePrice, etc.) sent those
       non-column keys straight into the Supabase update() payload and made
       PostgREST reject every edit-save with a 'column not found' error. */
    const picked = {};
    Object.keys(blank).forEach((k) => {
      if (k !== 'meta' && initial[k] !== undefined) picked[k] = initial[k];
    });
    return { ...blank, ...picked, meta: { ...(blank.meta || {}), ...(initial.meta || {}) } };
  });
  const _draftKey = 'saraya_draft_' + type;
  useEffectVD(() => {
    if (isEdit) return;
    try { window.localStorage.setItem(_draftKey, JSON.stringify({ t: Date.now(), form: form })); } catch (e) {}
  }, [form]);
  const [saving,       setSaving]       = useStateVD(false);
  const [err,          setErr]          = useStateVD(null);
  const [uploadingImg, setUploadingImg] = useStateVD(false);
  const [uploadingFile, setUploadingFile] = useStateVD(false);
  const [fitFrame,     setFitFrame]     = useStateVD(true); // crop uploads to fill the card frame

  /* ── Rental availability calendar ── */
  const [blockedDates, setBlockedDates] = useStateVD(() => new Set());
  const [calMonth,     setCalMonth]     = useStateVD(() => { const d = new Date(); return { y: d.getFullYear(), m: d.getMonth() }; });
  const [loadingAvail, setLoadingAvail] = useStateVD(false);

  useEffectVD(() => {
    if (type !== 'rentals' || !isEdit || !initial || !initial.id || !db) return;
    setLoadingAvail(true);
    db.from('rental_availability').select('blocked_date').eq('rental_id', initial.id)
      .then(({ data }) => {
        if (data) setBlockedDates(new Set(data.map((r) => r.blocked_date)));
        setLoadingAvail(false);
      });
  }, []);

  const toggleDate = (dateStr) => setBlockedDates((prev) => {
    const next = new Set(prev);
    next.has(dateStr) ? next.delete(dateStr) : next.add(dateStr);
    return next;
  });
  const prevCal = () => setCalMonth(({ y, m }) => m === 0 ? { y: y - 1, m: 11 } : { y, m: m - 1 });
  const nextCal = () => setCalMonth(({ y, m }) => m === 11 ? { y: y + 1, m: 0 } : { y, m: m + 1 });

  /* ── Service availability (per-vendor shared calendar) ── */
  const [svcWorkDays, setSvcWorkDays]       = useStateVD([0, 1, 2, 3, 4, 5, 6]);
  const [svcCapacity, setSvcCapacity]       = useStateVD(1);
  const [svcBlocked,  setSvcBlocked]        = useStateVD(() => new Set());
  const [svcAvailLoading, setSvcAvailLoading] = useStateVD(false);
  const svcAvail = window.SarayaService && window.SarayaService.availability;

  useEffectVD(() => {
    if (type !== 'services' || !vendorId || !svcAvail) return;
    setSvcAvailLoading(true);
    Promise.all([svcAvail.getSettings(vendorId), svcAvail.listBlocked(vendorId)])
      .then(([s, blocked]) => {
        setSvcWorkDays((s && s.working_days) || [0, 1, 2, 3, 4, 5, 6]);
        setSvcCapacity((s && s.daily_capacity) || 1);
        setSvcBlocked(new Set(blocked || []));
        setSvcAvailLoading(false);
      })
      .catch(() => setSvcAvailLoading(false));
  }, [type, vendorId]);

  const saveSvcSettings = (workDays, cap) => { if (vendorId && svcAvail) svcAvail.saveSettings(vendorId, { working_days: workDays, daily_capacity: cap }); };
  const toggleWorkDay = (dowIdx) => setSvcWorkDays((prev) => {
    const next = prev.includes(dowIdx) ? prev.filter((x) => x !== dowIdx) : prev.concat(dowIdx).sort((a, b) => a - b);
    saveSvcSettings(next, svcCapacity);
    return next;
  });
  const toggleSvcBlocked = (dateStr) => {
    if (!vendorId || !svcAvail) return;
    const has = svcBlocked.has(dateStr);
    setSvcBlocked((prev) => { const n = new Set(prev); has ? n.delete(dateStr) : n.add(dateStr); return n; });
    has ? svcAvail.unblock(vendorId, dateStr) : svcAvail.block(vendorId, dateStr, null);
  };

  /* ── Load existing images from listing_images on edit ── */
  useEffectVD(() => {
    if (!isEdit || !initial || !initial.id || !db) return;
    const ltSingle = type === 'products' ? 'product' : type === 'rentals' ? 'rental' : 'service';
    db.from('listing_images')
      .select('image_url, image_order, is_cover')
      .eq('listing_id', initial.id)
      .eq('listing_type', ltSingle)
      .order('image_order')
      .then(({ data, error: _e }) => {
        if (_e || !data || data.length === 0) return;
        const urls = data.map((r) => r.image_url);
        const ci = data.findIndex((r) => r.is_cover);
        setForm((p) => ({ ...p, images: urls, coverIdx: ci >= 0 ? ci : 0 }));
      });
  }, []);

  /* ── Helpers ── */
  const set     = (k, v) => setForm((p) => ({ ...p, [k]: v }));
  const setMeta = (k, v) => setForm((p) => ({ ...p, meta: { ...(p.meta || {}), [k]: v } }));
  const rentalCfg = (type === 'rentals' && window.RENTAL_CATEGORIES_CONFIG) || [];
  const findMainCatId = (catId) => {
    const row = categories.find((c) => c.id === catId);
    const byRow = row && rentalCfg.find((m) => m.subcategories.some((s) => s.dbSubSlug === row.slug));
    if (byRow) return byRow.id;
    return (rentalCfg[0] && rentalCfg[0].id) || '';
  };
  const [mainCatId, setMainCatId] = useStateVD(() => findMainCatId(form.category_id));
  const subCatOptions = (() => {
    const mc = rentalCfg.find((m) => m.id === mainCatId);
    if (!mc) return [];
    return mc.subcategories.map((s) => categories.find((c) => c.slug === s.dbSubSlug)).filter(Boolean)
    .map((c) => ({ value: c.id, label: (ar ? c.name_ar || c.name_en : c.name_en) || c.slug }));
  })();
  const handleMainCatChange = (newMainId) => {
    setMainCatId(newMainId);
    const mc2 = rentalCfg.find((m) => m.id === newMainId);
    const firstRow = mc2 && mc2.subcategories.map((s) => categories.find((c) => c.slug === s.dbSubSlug)).find(Boolean);
    if (firstRow) set('category_id', firstRow.id);
  };

  /* ── Multi-image upload (up to 5) ── */
  const MAX_IMAGES = 5;
  const handleImageFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (!window.SarayaService) { setErr('Storage not available'); return; }
    if ((form.images || []).length >= MAX_IMAGES) {
      setErr(ar ? `الحد الأقصى ${MAX_IMAGES} صور` : `Maximum ${MAX_IMAGES} images allowed`);
      return;
    }
    setUploadingImg(true);
    const { url, error } = await window.SarayaService.storage.uploadListingImage(vendorId, file);
    if (error) { setErr(error); } else {
      setForm((p) => ({ ...p, images: [...(p.images || []), url] }));
    }
    setUploadingImg(false);
    e.target.value = '';
  };

  const removeImage = (idx) => {
    setForm((p) => {
      const imgs = (p.images || []).filter((_, i) => i !== idx);
      const ci = p.coverIdx >= imgs.length ? Math.max(0, imgs.length - 1) : p.coverIdx;
      return { ...p, images: imgs, coverIdx: ci };
    });
  };

  const setCover = (idx) => set('coverIdx', idx);

  // Secure digital-file upload → PRIVATE 'digital-files' bucket; path in meta.digital_file
  const handleDigitalFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (!window.SarayaService || !window.SarayaService.storage || !window.SarayaService.storage.uploadDigitalFile) { setErr('Storage not available'); return; }
    if (file.size > 50 * 1024 * 1024) { setErr(ar ? 'الحد الأقصى لحجم الملف 50 ميجابايت' : 'Maximum file size is 50 MB'); e.target.value = ''; return; }
    setUploadingFile(true); setErr(null);
    const res = await window.SarayaService.storage.uploadDigitalFile(vendorId, initial && initial.id, file);
    if (res.error) { setErr(res.error); } else {
      setMeta('digital_file', { path: res.path, name: res.name, type: res.type, size: res.size });
    }
    setUploadingFile(false);
    e.target.value = '';
  };
  const removeDigitalFile = () => setMeta('digital_file', null);

  /* ── Validation ── */
  const validate = () => {
    if (!form.name_en.trim())                                       return ar ? 'الاسم بالإنجليزية مطلوب' : 'English name is required';
    if (categories.length > 0 && !form.category_id)                return ar ? 'الفئة مطلوبة' : 'Category is required';
    if (form.category_id && categories.length > 0 && !categories.some((c) => c.id === form.category_id))
      return ar ? 'الفئة المختارة غير صالحة لهذا النوع من القوائم' : 'Selected category is not valid for this listing type';
    if (form.category_id) {
      const chosenCat = categories.find((c) => c.id === form.category_id);
      const excluded = type === 'products' ? (window.MARKETPLACE_EXCLUDED_LABELS || [])
                     : type === 'services' ? (window.SERVICE_EXCLUDED_LABELS || [])
                     : [];
      if (chosenCat && excluded.includes(chosenCat.name_en))
        return ar ? 'هذه الفئة غير متاحة للاستخدام' : 'This category is not available for use';
    }
    if (type === 'products' && !(Number(form.price) > 0))          return ar ? 'السعر مطلوب ويجب أن يكون أكبر من صفر' : 'Price is required (must be > 0)';
    if (type === 'rentals'  && !(Number(form.price_per_day) > 0))  return ar ? 'سعر اليوم مطلوب ويجب أن يكون أكبر من صفر' : 'Price per day is required (must be > 0)';
    if (type === 'services' && form.pricing_type !== 'custom_quote'
        && !(Number(form.base_price) > 0))                         return ar ? 'السعر الأساسي مطلوب' : 'Base price is required (must be > 0)';
    if (!form.images || form.images.length === 0)                  return ar ? 'صورة الغلاف مطلوبة' : 'At least one listing image is required';
    return null;
  };

  /* ── Submit ── */
  const handleSubmit = async () => {
    const validErr = validate();
    if (validErr) { setErr(validErr); return; }
    setSaving(true); setErr(null);
    const svc = window.SarayaService;
    let result;
    let savedId = isEdit ? initial.id : null;
    // Strip UI-only fields before sending to DB
    const { coverIdx: _coverIdx, ...formData } = form;
    const payload = { ...formData, vendor_id: vendorId };

    if (type === 'products') {
      payload.price          = Number(payload.price) || 0;
      payload.sale_price     = payload.sale_price   ? Number(payload.sale_price)   : null;
      payload.stock_quantity = payload.stock_quantity !== '' ? Number(payload.stock_quantity) : null;
      result = isEdit ? await svc.products.update(initial.id, payload) : await svc.products.create(payload);
      if (!savedId && result && result.data) savedId = (Array.isArray(result.data) ? result.data[0] : result.data).id;
    } else if (type === 'rentals') {
      payload.price_per_day   = Number(payload.price_per_day) || 0;
      payload.price_per_week  = payload.price_per_week  ? Number(payload.price_per_week)  : null;
      payload.price_per_event = payload.price_per_event ? Number(payload.price_per_event) : null;
      payload.deposit_amount  = payload.deposit_amount  ? Number(payload.deposit_amount)  : null;
      payload.min_order_qty   = Math.max(1, Math.floor(Number(payload.min_order_qty)) || 20);
      payload.delivery_fee    = Math.max(0, Number(payload.delivery_fee) || 0);
      payload.min_rental_days = 1;
      payload.stock_quantity  = payload.stock_quantity !== '' ? Number(payload.stock_quantity)  : null;
      result = isEdit ? await svc.rentals.update(initial.id, payload) : await svc.rentals.create(payload);
      if (!savedId && result && result.data) savedId = (Array.isArray(result.data) ? result.data[0] : result.data).id;
    } else {
      payload.base_price = payload.pricing_type === 'custom_quote' ? null : (Number(payload.base_price) || 0);
      result = isEdit ? await svc.services.update(initial.id, payload) : await svc.services.create(payload);
      if (!savedId && result && result.data) savedId = (Array.isArray(result.data) ? result.data[0] : result.data).id;
    }

    /* Sync rental_availability blocked dates */
    if (type === 'rentals' && savedId && db) {
      await db.from('rental_availability').delete().eq('rental_id', savedId);
      if (blockedDates.size > 0) {
        const rows = Array.from(blockedDates).map((d) => ({ rental_id: savedId, blocked_date: d, reason: 'blocked' }));
        await db.from('rental_availability').insert(rows);
      }
    }

    /* Sync listing_images table */
    if (savedId && db && form.images && form.images.length > 0) {
      const ltSingle = type === 'products' ? 'product' : type === 'rentals' ? 'rental' : 'service';
      const ci = form.coverIdx || 0;
      try {
        await db.from('listing_images').delete().eq('listing_id', savedId).eq('listing_type', ltSingle);
        const imgRows = form.images.map((imgUrl, i) => ({
          listing_id: savedId, listing_type: ltSingle, vendor_id: vendorId,
          image_url: imgUrl, image_order: i + 1, is_cover: i === ci,
          alt_text: form.name_en || '',
        }));
        await db.from('listing_images').insert(imgRows);
      } catch (_imgErr) { /* listing_images table may not exist yet */ }
    }

    setSaving(false);
    if (result && result.error) {
      const _raw = typeof result.error === 'string' ? result.error : (result.error.message || 'Save failed');
      const _friendly = /LISTING_LIMIT_REACHED/i.test(_raw)
        ? (ar ? 'لقد وصلت إلى الحد الأقصى لعدد القوائم في باقتك. رقِّ باقتك أو أرشِف قائمة حالية لإضافة المزيد.' : 'You have reached the listing limit for your plan. Upgrade your plan or archive an existing listing to add more.')
        : _raw;
      setErr(_friendly); return;
    }
    try { if (!isEdit) window.localStorage.removeItem(_draftKey); } catch (e) {}
    onSave();
  };

  /* ── Section header helper ── */
  const SectionHead = ({ icon, label }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 7, paddingBottom: 6, borderBottom: '1px solid var(--line)', marginTop: 4 }}>
      <Icon name={icon} size={14} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
      <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--fg-secondary)', textTransform: 'uppercase', letterSpacing: '.07em' }}>{label}</span>
    </div>
  );

  const labelType = type === 'products' ? (ar ? 'المنتج' : 'Product') : type === 'rentals' ? (ar ? 'الإيجار' : 'Rental') : (ar ? 'الخدمة' : 'Service');

  // ── Digital Products ──────────────────────────────────────────────
  // A marketplace product whose category is "Digital Products" (slug 'digital')
  // is delivered online: physical fields (stock, availability, city, delivery)
  // do not apply. Detected from the selected category, kept in sync with is_digital.
  const _selCat = (categories || []).find((c) => c.id === form.category_id);
  const isDigitalProduct = type === 'products' && ((_selCat && _selCat.slug === 'digital') || !!form.is_digital);
  useEffectVD(() => {
    if (type === 'products' && _selCat && _selCat.slug === 'digital' && !form.is_digital) set('is_digital', true);
  }, [form.category_id]);
  const DIGITAL_TYPE_OPTS = [
    { value: 'invitation_template', label: ar ? 'قالب دعوة' : 'Invitation Template' },
    { value: 'canva_template',      label: ar ? 'قالب Canva قابل للتعديل' : 'Editable Canva Template' },
    { value: 'printable_sign',      label: ar ? 'لافتة قابلة للطباعة' : 'Printable Event Sign' },
    { value: 'seating_plan',        label: ar ? 'قالب مخطط الجلوس' : 'Seating Plan Template' },
    { value: 'menu_place_card',     label: ar ? 'قالب قائمة/بطاقة مكان' : 'Menu / Place Card Template' },
    { value: 'checklist_planner',   label: ar ? 'قائمة تحقق/مخطط فعالية' : 'Event Checklist / Planner' },
    { value: 'social_invitation',   label: ar ? 'دعوة لوسائل التواصل' : 'Social Media Invitation' },
    { value: 'gift_card_design',    label: ar ? 'تصميم بطاقة هدية رقمية' : 'Digital Gift Card Design' },
    { value: 'other_digital',       label: ar ? 'ملف رقمي آخر' : 'Other Digital File' },
  ];
  const DIGITAL_DELIVERY_OPTS = [
    { value: 'instant',  label: ar ? 'تنزيل فوري بعد الدفع' : 'Instant download after payment' },
    { value: 'manual',   label: ar ? 'يرسل البائع الملف يدويًا' : 'Vendor sends file manually' },
    { value: 'custom',   label: ar ? 'تصميم مخصص يُسلَّم لاحقًا' : 'Custom design delivered later' },
  ];
  const DIGITAL_TIMEFRAME_OPTS = [
    { value: 'instant', label: ar ? 'فوري' : 'Instant' },
    { value: '24h',     label: ar ? 'خلال 24 ساعة' : 'Within 24 hours' },
    { value: '2_3d',    label: ar ? '2–3 أيام عمل' : '2–3 business days' },
    { value: 'custom',  label: ar ? 'مدة مخصصة' : 'Custom timeframe' },
  ];
  const DIGITAL_USAGE_OPTS = [
    { value: 'personal',      label: ar ? 'للاستخدام الشخصي فقط' : 'Personal use only' },
    { value: 'commercial',    label: ar ? 'يُسمح بالاستخدام التجاري' : 'Commercial use allowed' },
    { value: 'editable',      label: ar ? 'قالب قابل للتعديل' : 'Editable template' },
    { value: 'non_editable',  label: ar ? 'ملف نهائي غير قابل للتعديل' : 'Non-editable final file' },
    { value: 'no_resale',     label: ar ? 'يُمنع إعادة البيع' : 'No resale allowed' },
    { value: 'custom',        label: ar ? 'شروط مخصصة من البائع' : 'Vendor custom terms' },
  ];

  /* ── Calendar data ── */
  const todayStr     = new Date().toISOString().slice(0, 10);
  const { y: cY, m: cM } = calMonth;
  const calDays = (() => {
    const first = new Date(cY, cM, 1);
    const last  = new Date(cY, cM + 1, 0);
    const cells = [];
    for (let i = 0; i < first.getDay(); i++) cells.push(null);
    for (let d = 1; d <= last.getDate(); d++) cells.push(d);
    return cells;
  })();
  const calMonthLabel = new Date(cY, cM, 1).toLocaleString('en', { month: 'long', year: 'numeric' });

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,.45)', padding: '20px 16px' }}>
      <div style={{ background: 'var(--white)', borderRadius: 20, width: '100%', maxWidth: 680, maxHeight: '90vh', overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px 16px', borderBottom: '1px solid var(--line)', position: 'sticky', top: 0, background: 'var(--white)', zIndex: 1, borderRadius: '20px 20px 0 0' }}>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 500, margin: 0 }}>
            {isEdit ? (ar ? `تعديل ${labelType}` : `Edit ${labelType}`) : (ar ? `إضافة ${labelType}` : `Add ${labelType}`)}
          </h2>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 6, borderRadius: 8, color: 'var(--fg-secondary)' }}><Icon name="x" size={20} /></button>
        </div>

        {/* Body */}
        <div style={{ padding: '22px 24px', display: 'grid', gap: 16 }}>
          {err && <div style={{ padding: '10px 14px', borderRadius: 9, background: 'var(--error-bg, #fef2f2)', color: 'var(--error, #dc2626)', fontSize: 13.5 }}>{err}</div>}

          {/* ── Basic information ── */}
          <SectionHead icon="info" label={ar ? 'المعلومات الأساسية' : 'Basic Information'} />

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <VDField label={ar ? 'الاسم — إنجليزي *' : 'Name (EN) *'}>
              <VDInput value={form.name_en} onChange={(e) => set('name_en', e.target.value)} placeholder="e.g. Gold Velvet Sofa" />
            </VDField>
            <VDField label={ar ? 'الاسم — عربي' : 'Name (AR)'}>
              <VDInput value={form.name_ar} onChange={(e) => set('name_ar', e.target.value)} placeholder="مثال: أريكة مخمل ذهبي" dir="rtl" />
            </VDField>
          </div>

          <TranslateFieldControls enValue={form.name_en} arValue={form.name_ar} onSetEn={(v) => set('name_en', v)} onSetAr={(v) => set('name_ar', v)} ar={ar} />

          {categories.length > 0 && type !== 'rentals' && (
            <VDField label={ar ? 'الفئة *' : 'Category *'}>
              <VDSelect value={form.category_id} onChange={(e) => set('category_id', e.target.value)}
                options={categories
                  .filter((c) => !((window.SERVICE_EXCLUDED_LABELS || []).concat(type === 'services' ? [] : (window.MARKETPLACE_EXCLUDED_LABELS || []))).includes(c.name_en))
                  .map((c) => ({ value: c.id, label: (ar ? c.name_ar || c.name_en : c.name_en) || c.slug }))} />
            </VDField>
          )}
          {type === 'rentals' && rentalCfg.length > 0 && (
      <VDField label={ar ? 'الفئة الرئيسية *' : 'Main Category *'}>
        <VDSelect value={mainCatId} onChange={(e) => handleMainCatChange(e.target.value)}
          options={rentalCfg.map((m) => ({ value: m.id, label: ar ? m.label.ar : m.label.en }))} />
      </VDField>
      )}
          {type === 'rentals' && rentalCfg.length > 0 && (
      <VDField label={ar ? 'الفئة الفرعية *' : 'Subcategory *'}>
        <VDSelect value={form.category_id} onChange={(e) => set('category_id', e.target.value)}
          options={subCatOptions} />
      </VDField>
      )}

          {/* ── Pricing & Inventory ── */}
          <SectionHead icon="tag" label={ar ? 'التسعير والمخزون' : 'Pricing & Inventory'} />

          {type === 'products' && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: isDigitalProduct ? '1fr 1fr' : '1fr 1fr 1fr', gap: 12 }}>
                <VDField label={ar ? 'السعر (AED) *' : 'Price (AED) *'}>
                  <VDInput type="number" min="0" step="0.01" value={form.price} onChange={(e) => set('price', e.target.value)} placeholder="0.00" />
                </VDField>
                <VDField label={ar ? 'سعر التخفيض' : 'Sale Price'}>
                  <div style={{ position: 'relative' }}>
                    <VDInput
                      type="number"
                      min="0"
                      step="0.01"
                      value={form.sale_price || ''}
                      onChange={(e) => set('sale_price', e.target.value)}
                      placeholder={canDiscount ? '—' : (ar ? 'باقة Growth فأعلى' : 'Growth package+')}
                      disabled={!canDiscount}
                      title={!canDiscount ? (ar ? 'متاح ابتداءً من باقة Growth' : 'Available on Growth package or higher') : undefined}
                      style={!canDiscount ? { opacity: 0.6, cursor: 'not-allowed', background: 'var(--gray-50, #f9fafb)', paddingRight: 34 } : { paddingRight: 34 }}
                    />
                    {!canDiscount && (
                      <Icon name="lock" size={14} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-muted)' }} />
                    )}
                  </div>
                </VDField>
                {!isDigitalProduct && (
                  <VDField label={ar ? 'الكمية المتاحة' : 'Stock Qty'}>
                    <VDInput type="number" min="0" step="1" value={form.stock_quantity || ''} onChange={(e) => set('stock_quantity', e.target.value)} placeholder="∞ unlimited" />
                  </VDField>
                )}
              </div>
              {!isDigitalProduct && (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <VDField label={ar ? 'التوفّر' : 'Availability'}>
                    <VDSelect value={form.availability} onChange={(e) => set('availability', e.target.value)} options={AVAIL_OPTS} />
                  </VDField>
                  <VDField label={ar ? 'المدينة / الموقع' : 'City / Location'}>
                    <VDInput value={(form.meta && form.meta.city) || ''} onChange={(e) => setMeta('city', e.target.value)} placeholder="e.g. Dubai, Abu Dhabi" />
                  </VDField>
                </div>
              )}
              {isDigitalProduct && (
                <>
                  <SectionHead icon="download" label={ar ? 'التسليم الرقمي' : 'Digital Delivery'} />
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)', lineHeight: 1.5, marginTop: -4 }}>
                    {ar ? 'تُسلَّم المنتجات الرقمية عبر الإنترنت. ارفع صور المعاينة للعرض، والملف النهائي للتسليم إذا كان التنزيل فوريًا.' : 'Digital products are delivered online. Upload preview images for display, and the final file for delivery if instant download is enabled.'}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                    <VDField label={ar ? 'نوع المنتج الرقمي *' : 'Digital product type *'}>
                      <VDSelect value={(form.meta && form.meta.digital_type) || ''} onChange={(e) => setMeta('digital_type', e.target.value)} options={[{ value: '', label: ar ? 'اختر…' : 'Select…' }].concat(DIGITAL_TYPE_OPTS)} />
                    </VDField>
                    <VDField label={ar ? 'طريقة التسليم *' : 'Delivery method *'}>
                      <VDSelect value={(form.meta && form.meta.digital_delivery) || 'instant'} onChange={(e) => setMeta('digital_delivery', e.target.value)} options={DIGITAL_DELIVERY_OPTS} />
                    </VDField>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                    <VDField label={ar ? 'مدة التسليم' : 'Delivery timeframe'}>
                      <VDSelect value={(form.meta && form.meta.digital_timeframe) || ((form.meta && form.meta.digital_delivery) === 'instant' ? 'instant' : '24h')} onChange={(e) => setMeta('digital_timeframe', e.target.value)} options={DIGITAL_TIMEFRAME_OPTS} />
                    </VDField>
                    <VDField label={ar ? 'صيغة الملف' : 'File format'}>
                      <VDInput value={(form.meta && form.meta.digital_format) || ''} onChange={(e) => setMeta('digital_format', e.target.value)} placeholder={ar ? 'مثال: PDF، PNG، ZIP' : 'e.g. PDF, PNG, ZIP'} />
                    </VDField>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                    <VDField label={ar ? 'شروط الاستخدام' : 'Usage terms'}>
                      <VDSelect value={(form.meta && form.meta.digital_usage) || 'personal'} onChange={(e) => setMeta('digital_usage', e.target.value)} options={DIGITAL_USAGE_OPTS} />
                    </VDField>
                    <VDField label={ar ? 'التخصيص متاح؟' : 'Customization available?'}>
                      <VDSelect value={(form.meta && form.meta.digital_customization) || 'no'} onChange={(e) => setMeta('digital_customization', e.target.value)} options={[{ value: 'no', label: ar ? 'لا' : 'No' }, { value: 'yes', label: ar ? 'نعم' : 'Yes' }]} />
                    </VDField>
                  </div>
                  <VDField label={ar ? 'الملف النهائي (يلزم للتنزيل الفوري)' : 'Final file (required for instant download)'}>
                    {form.meta && form.meta.digital_file ? (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 9, border: '1px solid var(--line)', background: 'var(--white)' }}>
                        <Icon name="file-check-2" size={16} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
                        <span style={{ flex: 1, minWidth: 0, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{form.meta.digital_file.name}</span>
                        <button type="button" onClick={removeDigitalFile} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--error, #dc2626)', fontSize: 12, fontWeight: 600 }}>{ar ? 'إزالة' : 'Remove'}</button>
                      </div>
                    ) : (
                      <label style={{ display: 'inline-flex', alignItems: 'center', gap: 7, cursor: uploadingFile ? 'not-allowed' : 'pointer', fontSize: 13, color: 'var(--gold-deep)', fontWeight: 600, padding: '9px 14px', borderRadius: 8, border: '1.5px dashed var(--gold-deep)', background: 'var(--gold-tint,#fdf8f0)', opacity: uploadingFile ? 0.6 : 1 }}>
                        <Icon name="upload" size={15} />
                        {uploadingFile ? (ar ? 'جارٍ الرفع…' : 'Uploading…') : (ar ? 'رفع الملف' : 'Upload file')}
                        <input type="file" accept=".pdf,.png,.jpg,.jpeg,.zip,.docx,.pptx,.xlsx" onChange={handleDigitalFile} disabled={uploadingFile} style={{ display: 'none' }} />
                      </label>
                    )}
                    <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 6, lineHeight: 1.5, display: 'flex', alignItems: 'flex-start', gap: 6 }}>
                      <Icon name="shield" size={13} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 1 }} />
                      {ar ? 'يُخزَّن الملف بشكل آمن ولا يُتاح إلا بعد الدفع عبر رابط مؤقّت. الحد الأقصى 50 ميجابايت. صور المعاينة أدناه للعرض فقط.' : 'Stored securely and only released to the buyer after payment via a temporary link. Max 50 MB. Preview images below are for display only.'}
                    </div>
                  </VDField>
                </>
              )}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 18 }}>
                {[['is_popular', ar ? 'مميّز' : 'Popular'], ['is_new', ar ? 'جديد' : 'New Arrival']].concat(isDigitalProduct ? [] : [['is_digital', ar ? 'رقمي' : 'Digital Product']]).concat([['is_active', ar ? 'نشط' : 'Active']]).map(([k, l]) => (
                  <label key={k} style={{ display: 'flex', gap: 7, alignItems: 'center', cursor: 'pointer', fontSize: 13.5 }}>
                    <input type="checkbox" checked={!!form[k]} onChange={(e) => set(k, e.target.checked)} />{l}
                  </label>
                ))}
              </div>
            </>
          )}

          {type === 'rentals' && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                <VDField label={ar ? 'سعر/يوم (AED) *' : 'Price/day (AED) *'}>
                  <VDInput type="number" min="0" step="0.01" value={form.price_per_day} onChange={(e) => set('price_per_day', e.target.value)} placeholder="0.00" />
                </VDField>
                <VDField label={ar ? 'سعر/أسبوع' : 'Price/week'}>
                  <VDInput type="number" min="0" step="0.01" value={form.price_per_week || ''} onChange={(e) => set('price_per_week', e.target.value)} placeholder="—" />
                </VDField>
                <VDField label={ar ? 'سعر/فعالية' : 'Price/event'}>
                  <VDInput type="number" min="0" step="0.01" value={form.price_per_event || ''} onChange={(e) => set('price_per_event', e.target.value)} placeholder="—" />
                </VDField>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                <VDField label={ar ? 'وديعة (AED)' : 'Security Deposit'}>
                  <VDInput type="number" min="0" step="0.01" value={form.deposit_amount || ''} onChange={(e) => set('deposit_amount', e.target.value)} placeholder="—" />
                </VDField>
                <VDField label={ar ? 'الحد الأدنى للكمية' : 'Minimum Order Quantity'}>
                  <VDInput type="number" min="1" step="1" value={form.min_order_qty || ''} onChange={(e) => set('min_order_qty', e.target.value)} placeholder="20" />
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 4, lineHeight: 1.4 }}>{ar ? 'أقل كمية يمكن للعميل طلبها؛ تفرضها السلة عند الطلب.' : 'Smallest quantity a customer can order. Enforced in the cart.'}</div>
                </VDField>
                <VDField label={ar ? 'الوحدات المتاحة' : 'Units Available'}>
                  <VDInput type="number" min="0" step="1" value={form.stock_quantity || ''} onChange={(e) => set('stock_quantity', e.target.value)} placeholder="∞ unlimited" />
                </VDField>
                <VDField label={ar ? 'تكلفة التوصيل (AED)' : 'Delivery Cost (AED)'}>
                  <VDInput type="number" min="0" step="0.01" value={form.delivery_fee || ''} onChange={(e) => set('delivery_fee', e.target.value)} placeholder="0" />
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 4, lineHeight: 1.4 }}>{ar ? 'يُضاف إلى إجمالي الطلب عند الدفع.' : 'Added to the order total at checkout.'}</div>
                </VDField>
              </div>
            </>
          )}

          {type === 'services' && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <VDField label={ar ? 'نوع التسعير' : 'Pricing type'}>
                  <VDSelect value={form.pricing_type} onChange={(e) => set('pricing_type', e.target.value)} options={PRICING_TYPE_OPTS} />
                </VDField>
                {form.pricing_type !== 'custom_quote' && (
                  <VDField label={ar ? 'السعر الأساسي (AED) *' : 'Base price (AED) *'}>
                    <VDInput type="number" min="0" step="0.01" value={form.base_price || ''} onChange={(e) => set('base_price', e.target.value)} placeholder="0.00" />
                  </VDField>
                )}
              </div>
              {form.pricing_type !== 'custom_quote' && (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <VDField label={ar ? 'دفعة الحجز' : 'Booking payment'}>
                    <VDSelect
                      value={(form.meta && form.meta.deposit_type) || 'percent'}
                      onChange={(e) => setMeta('deposit_type', e.target.value)}
                      options={[
                        { value: 'percent', label: ar ? 'عربون — نسبة % من السعر' : 'Deposit — % of price' },
                        { value: 'fixed',   label: ar ? 'عربون — مبلغ ثابت (AED)' : 'Deposit — fixed AED amount' },
                        { value: 'full',    label: ar ? 'دفع كامل عند الحجز' : 'Full payment at booking' },
                      ]} />
                    <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 4, lineHeight: 1.4 }}>
                      {ar ? 'كيف يدفع العميل لتأكيد الحجز.' : 'How the customer pays to confirm a booking.'}
                    </div>
                  </VDField>
                  {((form.meta && form.meta.deposit_type) || 'percent') !== 'full' && (
                    <VDField label={((form.meta && form.meta.deposit_type) === 'fixed')
                      ? (ar ? 'مبلغ العربون (AED)' : 'Deposit amount (AED)')
                      : (ar ? 'نسبة العربون %' : 'Deposit percentage %')}>
                      <VDInput type="number" min="0" step={((form.meta && form.meta.deposit_type) === 'fixed') ? '0.01' : '1'}
                        value={(form.meta && form.meta.deposit_value != null && form.meta.deposit_value !== '') ? form.meta.deposit_value : ''}
                        onChange={(e) => setMeta('deposit_value', e.target.value)}
                        placeholder={((form.meta && form.meta.deposit_type) === 'fixed') ? 'e.g. 500' : 'e.g. 10'} />
                      <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 4, lineHeight: 1.4 }}>
                        {((form.meta && form.meta.deposit_type) === 'fixed')
                          ? (ar ? 'الحد الأدنى للدفع لتأكيد الحجز.' : 'Minimum amount paid to confirm the booking.')
                          : (ar ? 'نسبة من السعر تُدفع لتأكيد الحجز (الافتراضي 10٪).' : 'Percent of price paid to confirm the booking (default 10%).')}
                      </div>
                    </VDField>
                  )}
                </div>
              )}
            </>
          )}

          {/* ── Details & Specifications ── */}
          <SectionHead icon="settings-2" label={ar ? 'التفاصيل والمواصفات' : 'Details & Specifications'} />

          {type === 'rentals' && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <VDField label={ar ? 'حالة العنصر' : 'Item Condition'}>
                <VDSelect value={(form.meta && form.meta.condition) || 'excellent'} onChange={(e) => setMeta('condition', e.target.value)}
                  options={[
                    { value: 'new',       label: ar ? 'جديد'  : 'New'       },
                    { value: 'excellent', label: ar ? 'ممتاز' : 'Excellent'  },
                    { value: 'good',      label: ar ? 'جيد'   : 'Good'       },
                    { value: 'fair',      label: ar ? 'مقبول' : 'Fair'       },
                  ]} />
              </VDField>
              <VDField label="">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingTop: 22 }}>
                  <label style={{ display: 'flex', gap: 7, alignItems: 'center', cursor: 'pointer', fontSize: 13.5 }}>
                    <input type="checkbox" checked={!!(form.meta && form.meta.delivery_available)} onChange={(e) => setMeta('delivery_available', e.target.checked)} />
                    {ar ? 'توصيل متاح' : 'Delivery available'}
                  </label>
                  <label style={{ display: 'flex', gap: 7, alignItems: 'center', cursor: 'pointer', fontSize: 13.5 }}>
                    <input type="checkbox" checked={!!form.is_active} onChange={(e) => set('is_active', e.target.checked)} />
                    {ar ? 'نشط' : 'Active listing'}
                  </label>
                </div>
              </VDField>
            </div>
          )}

          {type === 'services' && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                <VDField label={ar ? 'مدة الخدمة' : 'Service Duration'}>
                  <VDInput value={(form.meta && form.meta.duration) || ''} onChange={(e) => setMeta('duration', e.target.value)} placeholder="e.g. 4 hours, Full day" />
                </VDField>
                <VDField label={ar ? 'منطقة الخدمة' : 'Service Area'}>
                  <VDSelect value={(form.meta && form.meta.service_area) || 'all_uae'} onChange={(e) => setMeta('service_area', e.target.value)}
                    options={[
                      { value: 'dubai',     label: ar ? 'دبي'          : 'Dubai'         },
                      { value: 'abu_dhabi', label: ar ? 'أبوظبي'       : 'Abu Dhabi'      },
                      { value: 'all_uae',   label: ar ? 'كل الإمارات'  : 'All UAE'        },
                      { value: 'on_site',   label: ar ? 'في الموقع فقط' : 'On-site only'  },
                    ]} />
                </VDField>
                <VDField label={ar ? 'وقت الإشعار (أيام)' : 'Lead time (days)'}>
                  <VDInput type="number" min="0" step="1" value={(form.meta && form.meta.lead_time_days) || ''} onChange={(e) => setMeta('lead_time_days', e.target.value)} placeholder="0" />
                </VDField>
              </div>
              <label style={{ display: 'flex', gap: 7, alignItems: 'center', cursor: 'pointer', fontSize: 13.5 }}>
                <input type="checkbox" checked={!!form.is_active} onChange={(e) => set('is_active', e.target.checked)} />
                {ar ? 'نشط' : 'Active listing'}
              </label>
            </>
          )}

          {/* ── Description ── */}
          <SectionHead icon="file-text" label={ar ? 'الوصف' : 'Description'} />

          <VDField label={ar ? 'الوصف — إنجليزي' : 'Description (EN)'}>
            <VDTextarea value={form.description_en || ''} onChange={(e) => set('description_en', e.target.value)} placeholder="Describe this listing in English…" />
          </VDField>
          <VDField label={ar ? 'الوصف — عربي' : 'Description (AR)'}>
            <VDTextarea value={form.description_ar || ''} onChange={(e) => set('description_ar', e.target.value)} placeholder="صف هذا الإدراج بالعربية…" dir="rtl" />
          </VDField>

          <TranslateFieldControls enValue={form.description_en} arValue={form.description_ar} onSetEn={(v) => set('description_en', v)} onSetAr={(v) => set('description_ar', v)} ar={ar} />

          {/* ── Rental Availability Calendar ── */}
          {type === 'rentals' && (
            <>
              <SectionHead icon="calendar-x" label={ar ? 'إدارة التوفّر — الأيام المحجوبة' : 'Availability — Blocked Dates'} />
              {loadingAvail ? (
                <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--fg-muted)' }}><Icon name="loader" size={22} style={{ animation: 'sarayaSpin 1s linear infinite' }} /></div>
              ) : (
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                    <button type="button" onClick={prevCal} style={{ border: '1px solid var(--line)', background: 'var(--white)', cursor: 'pointer', padding: '4px 12px', borderRadius: 7, fontSize: 18, lineHeight: 1, color: 'var(--fg-primary)' }}>‹</button>
                    <span style={{ fontWeight: 600, fontSize: 14 }}>{calMonthLabel}</span>
                    <button type="button" onClick={nextCal} style={{ border: '1px solid var(--line)', background: 'var(--white)', cursor: 'pointer', padding: '4px 12px', borderRadius: 7, fontSize: 18, lineHeight: 1, color: 'var(--fg-primary)' }}>›</button>
                  </div>
                  <div style={{ border: '1px solid var(--line)', borderRadius: 12, padding: '12px 8px', background: 'var(--bg-tint)' }}>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 3, marginBottom: 6 }}>
                      {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
                        <div key={d} style={{ textAlign: 'center', fontSize: 10.5, fontWeight: 700, color: 'var(--fg-muted)', padding: '2px 0' }}>{d}</div>
                      ))}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 3 }}>
                      {calDays.map((d, i) => {
                        if (!d) return <div key={'e' + i} />;
                        const dateStr  = cY + '-' + String(cM + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0');
                        const isBlocked = blockedDates.has(dateStr);
                        const isPast    = dateStr < todayStr;
                        const isToday   = dateStr === todayStr;
                        return (
                          <button key={dateStr} type="button" disabled={isPast} onClick={() => !isPast && toggleDate(dateStr)}
                            style={{ padding: '6px 2px', border: isToday ? '2px solid var(--gold)' : 'none', borderRadius: 7, cursor: isPast ? 'default' : 'pointer', fontSize: 12.5, fontWeight: isBlocked ? 700 : 400, textAlign: 'center', background: isBlocked ? '#FEE2E2' : isToday ? '#FFFBEB' : 'transparent', color: isBlocked ? '#DC2626' : isPast ? '#D1D5DB' : 'var(--fg-primary)', transition: 'background 100ms' }}>
                            {d}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                  <p style={{ fontSize: 12, color: 'var(--fg-muted)', margin: '8px 0 0' }}>
                    {ar
                      ? ('اضغط على تاريخ لتحديده كغير متاح. ' + (blockedDates.size > 0 ? blockedDates.size + ' يوم محجوب.' : 'لا توجد أيام محجوبة.'))
                      : ('Click dates to mark unavailable. ' + (blockedDates.size > 0 ? blockedDates.size + ' date' + (blockedDates.size !== 1 ? 's' : '') + ' blocked.' : 'No blocked dates.'))}
                  </p>
                </div>
              )}
            </>
          )}

          {/* ── Service Availability & Booking (per-vendor shared calendar) ── */}
          {type === 'services' && (
            <>
              <SectionHead icon="calendar-check" label={ar ? 'التوفّر والحجز' : 'Availability & Booking'} />
              <p style={{ fontSize: 12, color: 'var(--fg-muted)', margin: '-6px 0 12px' }}>
                {ar ? 'تُطبَّق هذه الإعدادات على كل خدماتك (تقويم مشترك). وقت الإشعار يُضبط بالأعلى.' : 'These settings apply to all your services (one shared calendar). Lead time is set in the fields above.'}
              </p>
              {svcAvailLoading ? (
                <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--fg-muted)' }}><Icon name="loader" size={22} style={{ animation: 'sarayaSpin 1s linear infinite' }} /></div>
              ) : (
                <>
                  <VDField label={ar ? 'أيام العمل' : 'Working days'}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      {[0, 1, 2, 3, 4, 5, 6].map((idx) => {
                        const on = svcWorkDays.includes(idx);
                        const lbl = (ar ? ['أحد', 'إثن', 'ثلا', 'أرب', 'خمي', 'جمع', 'سبت'] : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'])[idx];
                        return (
                          <button key={idx} type="button" onClick={() => toggleWorkDay(idx)}
                            style={{ minWidth: 44, padding: '7px 10px', borderRadius: 8, border: '1.5px solid ' + (on ? 'var(--gold)' : 'var(--line)'), background: on ? 'var(--gold-tint)' : 'var(--white)', color: on ? 'var(--gold-deep)' : 'var(--fg-muted)', fontWeight: on ? 700 : 500, fontSize: 12.5, cursor: 'pointer' }}>
                            {lbl}
                          </button>
                        );
                      })}
                    </div>
                  </VDField>
                  <VDField label={ar ? 'عدد الحجوزات في اليوم (السعة)' : 'Bookings per day (capacity)'}>
                    <VDInput type="number" min="1" step="1" value={svcCapacity}
                      onChange={(e) => setSvcCapacity(Math.max(1, parseInt(e.target.value, 10) || 1))}
                      onBlur={() => saveSvcSettings(svcWorkDays, svcCapacity)} />
                  </VDField>
                  <SectionHead icon="calendar-x" label={ar ? 'الأيام المحجوبة' : 'Blocked Dates'} />
                  {window.AvailabilityCalendar ? (
                    <window.AvailabilityCalendar mode="block" blocked={svcBlocked} onPick={toggleSvcBlocked} ar={ar} />
                  ) : null}
                  <p style={{ fontSize: 12, color: 'var(--fg-muted)', margin: '8px 0 0' }}>
                    {ar
                      ? ('اضغط على تاريخ لحجبه أو إتاحته. ' + (svcBlocked.size > 0 ? svcBlocked.size + ' يوم محجوب.' : 'لا توجد أيام محجوبة.'))
                      : ('Tap a date to block or open it. ' + (svcBlocked.size > 0 ? svcBlocked.size + ' date' + (svcBlocked.size !== 1 ? 's' : '') + ' blocked.' : 'No blocked dates.'))}
                  </p>
                </>
              )}
            </>
          )}

          {/* ── Listing images (up to 5) ── */}
          <SectionHead icon="image" label={ar ? 'صور القائمة *' : 'Listing Images *'} />
          <div>
            {form.images && form.images.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 12 }}>
                {form.images.map((imgUrl, idx) => (
                  <div key={idx} style={{ position: 'relative', width: 90, height: 90, borderRadius: 10, overflow: 'hidden', background: 'var(--gold-tint)', border: idx === (form.coverIdx || 0) ? '2.5px solid var(--gold-deep)' : '1.5px solid var(--line)', flexShrink: 0 }}>
                    <img src={imgUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
                    {idx === (form.coverIdx || 0) && (
                      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'rgba(184,150,90,0.92)', color: '#fff', fontSize: 9.5, fontWeight: 800, textAlign: 'center', padding: '2px 0', letterSpacing: '.05em' }}>
                        {ar ? 'غلاف' : 'COVER'}
                      </div>
                    )}
                    <div style={{ position: 'absolute', top: 3, right: 3, display: 'flex', gap: 3 }}>
                      {idx !== (form.coverIdx || 0) && (
                        <button type="button" onClick={() => setCover(idx)} title={ar ? 'تعيين كغلاف' : 'Set as cover'} style={{ width: 22, height: 22, borderRadius: 5, border: 'none', background: 'rgba(255,255,255,0.92)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
                          <Icon name="star" size={12} style={{ color: 'var(--gold-deep)' }} />
                        </button>
                      )}
                      <button type="button" onClick={() => removeImage(idx)} title={ar ? 'حذف' : 'Remove'} style={{ width: 22, height: 22, borderRadius: 5, border: 'none', background: 'rgba(220,38,38,0.85)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
                        <Icon name="x" size={12} style={{ color: '#fff' }} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
            {(!form.images || form.images.length < MAX_IMAGES) && (
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 7, cursor: uploadingImg ? 'not-allowed' : 'pointer', fontSize: 13, color: 'var(--gold-deep)', fontWeight: 600, padding: '8px 14px', borderRadius: 8, border: '1.5px dashed var(--gold-deep)', background: 'var(--gold-tint,#fdf8f0)', opacity: uploadingImg ? 0.6 : 1 }}>
                  <Icon name="upload" size={15} />
                  {uploadingImg ? (ar ? 'جارٍ الرفع…' : 'Uploading…') : (ar ? 'رفع صورة' : 'Upload image')}
                  <input type="file" accept="image/*" onChange={handleImageFile} disabled={uploadingImg} style={{ display: 'none' }} />
                </label>
                <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>
                  {(form.images || []).length}/{MAX_IMAGES} {ar ? 'صور' : 'images'}
                </span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--fg-muted)' }}>
                  <Icon name="check-circle" size={13} style={{ color: 'var(--gold-deep)' }} />
                  {ar ? 'تُعرض الصورة كاملة وموسّطة داخل الإطار' : 'Shown in full, centered — never cropped'}
                </span>
                {type === 'rentals' && (
                  <span style={{ flexBasis: '100%', fontSize: 12, color: 'var(--fg-muted)', lineHeight: 1.5 }}>
                    {ar
                      ? 'الحجم الموصى به لصورة الإيجار: 1200 × 1200 بكسل. ارفع صورة مربعة واضحة مع توسيط العنصر للحصول على أفضل نتيجة.'
                      : 'Recommended rental image size: 1200 × 1200 px. Upload a clear square image with the item centered for best results.'}
                  </span>
                )}
                {isDigitalProduct && (
                  <span style={{ flexBasis: '100%', fontSize: 12, color: 'var(--gold-deep)', fontWeight: 600, lineHeight: 1.5 }}>
                    {ar
                      ? 'صور المعاينة للعرض فقط — وليست الملف القابل للتنزيل.'
                      : 'Preview images are for display only — not the downloadable file.'}
                  </span>
                )}
              </div>
            )}
            {form.images && form.images.length > 1 && (
              <p style={{ fontSize: 12, color: 'var(--fg-muted)', margin: '8px 0 0' }}>
                {ar ? 'انقر ★ على الصورة لتعيينها كغلاف' : 'Click ★ on a thumbnail to set it as the cover image.'}
              </p>
            )}
          </div>

          {/* ── Variations / Options (optional) ── */}
          <SectionHead icon="list" label={ar ? 'الخيارات / التنويعات' : 'Variations / Options'} />
          {window.VariationEditor
            ? <window.VariationEditor value={(form.meta && form.meta.variations) || []} onChange={(v) => setMeta('variations', v)} ar={ar} vendorId={vendorId} />
            : <p style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{ar ? 'وحدة الخيارات غير محمّلة' : 'Options module not loaded.'}</p>}
        </div>

        {/* Footer */}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', padding: '16px 24px 20px', borderTop: '1px solid var(--line)', background: 'var(--bg-tint)', borderRadius: '0 0 20px 20px', position: 'sticky', bottom: 0 }}>
          <Button variant="secondary" onClick={onClose} disabled={saving}>{ar ? 'إلغاء' : 'Cancel'}</Button>
          <Button variant="primary" onClick={handleSubmit} disabled={saving || uploadingImg}>
            {saving ? (ar ? 'جارٍ الحفظ…' : 'Saving…') : (ar ? 'حفظ' : 'Save')}
          </Button>
        </div>
      </div>
    </div>
  );
}

/* ── Listings table + sub-tabs ── */
function VendorListingsTab({ vendorId, maxListings, currentCount, onCountsChange, initialType, ar, canDiscount, agreementSigned, onGoDocuments }) {
  const [listingType, setListingType] = useStateVD(initialType || 'products');
  const [items, setItems] = useStateVD([]);
  const [loading, setLoading] = useStateVD(true);
  const [categories, setCategories] = useStateVD([]);
  const [showModal, setShowModal] = useStateVD(false);
  const [editItem, setEditItem] = useStateVD(null);
  const [deleteTarget, setDeleteTarget] = useStateVD(null);
  const [deleting, setDeleting] = useStateVD(false);
  const [savedMsg, setSavedMsg] = useStateVD(null);
  const [selected, setSelected] = useStateVD(new Set());
  const [bulkBusy, setBulkBusy] = useStateVD(false);

  const svc = window.SarayaService;

  // Which listing types this vendor offers (drives which sub-tabs show).
  const dbVL = window.SarayaDB;
  const [offered, setOffered] = useStateVD(LISTING_TYPES);
  const [showTypeMgr, setShowTypeMgr] = useStateVD(false);
  useEffectVD(() => {
    if (!dbVL || !vendorId) return;
    dbVL.from('vendor_profiles').select('offered_types').eq('id', vendorId).maybeSingle()
      .then(({ data }) => { if (data && Array.isArray(data.offered_types) && data.offered_types.length) setOffered(data.offered_types); });
  }, [vendorId]);
  const shownTypes = LISTING_TYPES.filter((t) => offered.includes(t));
  useEffectVD(() => { if (shownTypes.length && !shownTypes.includes(listingType)) setListingType(shownTypes[0]); }, [offered]);
  const toggleOffered = async (t) => {
    const has = offered.includes(t);
    const next = has ? offered.filter((x) => x !== t) : LISTING_TYPES.filter((x) => offered.includes(x) || x === t);
    if (!next.length) return; // keep at least one type
    setOffered(next);
    if (dbVL && vendorId) await dbVL.from('vendor_profiles').update({ offered_types: next }).eq('id', vendorId);
  };

  const loadItems = useCallbackVD(async () => {
    if (!svc) { setLoading(false); return; }
    setLoading(true);
    const catType = listingType === 'products' ? 'product' : listingType === 'rentals' ? 'rental' : 'service';
    const [cats, listData] = await Promise.all([
      svc.categories.list(catType),
      listingType === 'products'
        ? svc.products.list({ vendorId, onlyActive: false })
        : listingType === 'rentals'
        ? svc.rentals.list({ vendorId, onlyActive: false })
        : svc.services.list({ vendorId, onlyActive: false }),
    ]);
    setCategories(cats);
    setItems(listData);
    setLoading(false);
  }, [listingType, vendorId]);

  useEffectVD(() => { loadItems(); }, [loadItems]);
  useEffectVD(() => { setSelected(new Set()); }, [listingType]);
  

  const openAdd = () => {
    if (!agreementSigned) {
      alert(ar ? 'يجب توقيع اتفاقية البائع قبل نشر أي قائمة. افتح تبويب "المستندات" لتوقيعها.' : 'Please sign the Vendor Agreement before publishing any listing. Open the Documents tab to sign it.');
      onGoDocuments && onGoDocuments();
      return;
    }
    // Combined count across ALL listing types (products + rentals + services),
    // not just the current sub-tab. maxListings === null/undefined => unlimited.
    if (maxListings != null && (currentCount != null ? currentCount : items.length) >= maxListings) {
      alert(ar ? `لقد وصلت إلى الحد الأقصى لعدد القوائم في باقتك (${maxListings}). رقِّ باقتك أو أرشِف قائمة حالية لإضافة المزيد.` : `You've reached your plan's listing limit (${maxListings}). Upgrade your plan or archive an existing listing to add more.`);
      return;
    }
    setEditItem(null);
    setShowModal(true);
  };

  const openEdit = (item) => { setEditItem(item); setShowModal(true); };

  const closeModal = () => { setShowModal(false); setEditItem(null); };

  const handleSaved = () => {
    closeModal();
    loadItems();
    onCountsChange && onCountsChange();
    setSavedMsg(ar ? 'تم حفظ التغييرات. القائمة الآن قيد المراجعة وستظهر للجميع بعد موافقة الفريق.' : 'Changes saved. This listing is now pending review and will reappear publicly once approved.');
    setTimeout(() => setSavedMsg(null), 7000);
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    if (listingType === 'products')      await svc.products.remove(deleteTarget);
    else if (listingType === 'rentals')  await svc.rentals.remove(deleteTarget);
    else                                 await svc.services.remove(deleteTarget);
    setDeleting(false);
    setDeleteTarget(null); loadItems(); onCountsChange && onCountsChange();
  };

  const svcForType = () => (listingType === 'products' ? svc.products : listingType === 'rentals' ? svc.rentals : svc.services);
  const toggleSelectAll = () => {
    setSelected((prev) => (prev.size === items.length ? new Set() : new Set(items.map((it) => it.id))));
  };
  const toggleSelectOne = (id) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };
  const handleBulkDelete = async () => {
    if (!selected.size) return;
    if (!window.confirm(ar ? `هل تريد حذف ${selected.size} عنصر؟ لا يمكن التراجع عن هذا الإجراء.` : `Delete ${selected.size} selected item(s)? This cannot be undone.`)) return;
    setBulkBusy(true);
    const s = svcForType();
    await Promise.all(Array.from(selected).map((id) => s.remove(id)));
    setBulkBusy(false);
    setSelected(new Set());
    loadItems(); onCountsChange && onCountsChange();
  };
  const handleBulkVisibility = async (makeActive) => {
    if (!selected.size) return;
    setBulkBusy(true);
    const s = svcForType();
    await Promise.all(Array.from(selected).map((id) => s.setActive(id, makeActive)));
    setBulkBusy(false);
    setSelected(new Set());
    loadItems();
  };

  const typeLabel = { products: ar ? 'المنتجات' : 'Products', rentals: ar ? 'الإيجار' : 'Rentals', services: ar ? 'الخدمات' : 'Services' };
  const typeLabelSingular = { products: ar ? 'منتج' : 'Product', rentals: ar ? 'إيجار' : 'Rental', services: ar ? 'خدمة' : 'Service' };
  const typeIcon = { products: 'shopping-bag', rentals: 'archive', services: 'briefcase' };

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      {savedMsg && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', borderRadius: 10, background: '#DCFCE7', border: '1px solid #86EFAC', color: '#166534', fontSize: 13.5, fontWeight: 600 }}>
          <Icon name="check-circle" size={18} />
          {savedMsg}
        </div>
      )}
      {!agreementSigned && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderRadius: 10, background: '#FEF3C7', border: '1px solid #FCD34D', color: '#92400E', fontSize: 13.5, flexWrap: 'wrap' }}>
          <Icon name="alert-triangle" size={18} style={{ flexShrink: 0 }} />
          <span style={{ flex: 1, minWidth: 200, lineHeight: 1.5 }}>
            {ar ? 'يجب توقيع اتفاقية البائع قبل نشر أي قائمة. لن تتمكن من إضافة منتجات أو إيجارات أو خدمات حتى توقّعها.' : 'You must sign the Vendor Agreement before publishing any listing. You can’t add products, rentals, or services until it’s signed.'}
          </span>
          <button type="button" onClick={() => onGoDocuments && onGoDocuments()}
            style={{ padding: '8px 14px', borderRadius: 8, border: 'none', background: 'var(--gold-deep)', color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, cursor: 'pointer', whiteSpace: 'nowrap' }}>
            {ar ? 'توقيع الآن' : 'Sign now'}
          </button>
        </div>
      )}
      {/* Sub-tabs — only the types this vendor offers */}
      {shownTypes.length > 1 && (
        <div style={{ display: 'flex', gap: 0, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', background: 'var(--white)' }}>
          {shownTypes.map((t, i) => (
            <button key={t} onClick={() => setListingType(t)}
              style={{ flex: 1, padding: '12px 8px', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, border: 'none', borderInlineEnd: i !== shownTypes.length - 1 ? '1px solid var(--line)' : 'none', background: listingType === t ? 'var(--espresso)' : 'transparent', color: listingType === t ? 'var(--ivory)' : 'var(--fg-primary)', transition: 'background 150ms' }}>
              {typeLabel[t]}
            </button>
          ))}
        </div>
      )}

      {/* What you offer — choose which type tabs appear */}
      <div>
        <button type="button" onClick={() => setShowTypeMgr((v) => !v)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontSize: 12.5, fontWeight: 600, padding: 0 }}>
          <Icon name="sliders-horizontal" size={14} />{ar ? 'ما الذي تقدّمه؟' : 'What you offer'}
          <Icon name={showTypeMgr ? 'chevron-up' : 'chevron-down'} size={14} />
        </button>
        {showTypeMgr && (
          <div style={{ marginTop: 10, padding: '14px 16px', borderRadius: 12, background: 'var(--cream)', border: '1px solid var(--line)' }}>
            <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', marginBottom: 10 }}>{ar ? 'اختر أنواع القوائم التي تقدّمها — تظهر تبويباتها فقط في القوائم والمخزون.' : 'Pick the listing types you offer — only those tabs show in Listings and Inventory.'}</div>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {LISTING_TYPES.map((t) => {
                const on = offered.includes(t);
                return (
                  <button key={t} type="button" onClick={() => toggleOffered(t)}
                    style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 14px', borderRadius: 999, border: '1.5px solid ' + (on ? 'var(--gold)' : 'var(--line)'), background: on ? 'var(--gold-tint)' : 'var(--white)', color: on ? 'var(--gold-deep)' : 'var(--fg-muted)', fontWeight: on ? 700 : 500, fontSize: 13, cursor: 'pointer' }}>
                    <Icon name={on ? 'check-circle' : 'circle'} size={15} />{typeLabel[t]}
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* Header row */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 500, margin: 0 }}>{typeLabel[listingType]}</h3>
          <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: '3px 0 0' }}>
            {items.length} / {maxListings} {ar ? 'إجمالي القوائم المستخدمة' : 'total listings used'}
          </p>
        </div>
        <Button variant="primary" onClick={openAdd} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
          <Icon name="plus" size={16} />
          {ar ? `إضافة ${typeLabelSingular[listingType]}` : `Add ${typeLabelSingular[listingType]}`}
        </Button>
      </div>

      {/* Listings table */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--fg-muted)' }}><Icon name="loader" size={28} style={{ animation: 'sarayaSpin 1s linear infinite' }} /></div>
      ) : items.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '52px 20px', background: 'var(--white)', borderRadius: 14, border: '1px dashed var(--line)' }}>
          <Icon name={typeIcon[listingType]} size={40} stroke={1} style={{ color: 'var(--fg-muted)' }} />
          <p style={{ marginTop: 12, color: 'var(--fg-secondary)', fontSize: 14 }}>
            {ar ? `لا توجد ${typeLabel[listingType]} بعد.` : `No ${typeLabel[listingType].toLowerCase()} yet.`}
          </p>
          <Button variant="secondary" onClick={openAdd} style={{ marginTop: 14 }}>
            {ar ? `إضافة ${typeLabelSingular[listingType]} الأول` : `Add your first ${typeLabelSingular[listingType].toLowerCase()}`}
          </Button>
        </div>
      ) : (
        <>
        {selected.size > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 10, padding: '10px 14px', background: '#FFF7ED', border: '1px solid #FED7AA', borderRadius: 10, marginBottom: 12 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: '#9A3412' }}>{ar ? `${selected.size} محدد` : `${selected.size} selected`}</span>
            <button disabled={bulkBusy} onClick={() => handleBulkVisibility(false)} style={{ padding: '6px 12px', borderRadius: 8, border: '1px solid #FED7AA', background: '#fff', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{ar ? 'إخفاء' : 'Hide'}</button>
            <button disabled={bulkBusy} onClick={() => handleBulkVisibility(true)} style={{ padding: '6px 12px', borderRadius: 8, border: '1px solid #FED7AA', background: '#fff', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{ar ? 'إظهار' : 'Unhide'}</button>
            <button disabled={bulkBusy} onClick={handleBulkDelete} style={{ padding: '6px 12px', borderRadius: 8, border: '1px solid #FCA5A5', background: '#fff', color: '#991B1B', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{ar ? 'حذف' : 'Delete'}</button>
            <button disabled={bulkBusy} onClick={() => setSelected(new Set())} style={{ padding: '6px 12px', borderRadius: 8, border: '1px solid var(--line)', background: '#fff', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{ar ? 'إلغاء التحديد' : 'Clear'}</button>
          </div>
        )}
        <div style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5, minWidth: 560 }}>
            <thead>
              <tr style={{ background: 'var(--bg-tint)', borderBottom: '1px solid var(--line)' }}>
                <th style={{ padding: '11px 16px', width: 36 }}>
                  <input type="checkbox" checked={items.length > 0 && selected.size === items.length} onChange={toggleSelectAll} />
                </th>
                <th style={{ padding: '11px 16px', textAlign: 'start', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>{ar ? 'اسم القائمة' : 'Name'}</th>
                {listingType !== 'rentals' && (
                  <th style={{ padding: '11px 16px', textAlign: 'start', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>{ar ? 'الفئة' : 'Category'}</th>
                )}
                <th style={{ padding: '11px 16px', textAlign: 'start', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>{ar ? 'السعر' : 'Price'}</th>
                <th style={{ padding: '11px 16px', textAlign: 'start', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>{ar ? 'الحالة' : 'Status'}</th>
                <th style={{ padding: '11px 16px', textAlign: 'end', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12 }}></th>
              </tr>
            </thead>
            <tbody>
              {items.map((item, idx) => {
                const price = item.price || item.pricePerDay || item.base_price || item.price_per_day || 0;
                const isActive = !item.hidden && item.is_active !== false;
                return (
                  <tr key={item.id} style={{ borderBottom: idx < items.length - 1 ? '1px solid var(--line)' : 'none' }}>
                    <td style={{ padding: '12px 16px' }}>
                      <input type="checkbox" checked={selected.has(item.id)} onChange={() => toggleSelectOne(item.id)} />
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        {item.src ? (
                          <img src={item.src} alt="" style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 10, border: '1px solid var(--line)', flexShrink: 0 }} />
                        ) : (
                          <div style={{ width: 60, height: 60, borderRadius: 10, background: 'var(--gold-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                            <Icon name={typeIcon[listingType]} size={22} style={{ color: 'var(--gold-deep)' }} />
                          </div>
                        )}
                        <div>
                          <p style={{ margin: 0, fontWeight: 600, fontSize: 14 }}>{item.name ? item.name.en : item.name_en}</p>
                          {(item.name && item.name.ar || item.name_ar) && (
                            <p style={{ margin: 0, fontSize: 12, color: 'var(--fg-secondary)', direction: 'rtl', textAlign: 'start' }}>{item.name ? item.name.ar : item.name_ar}</p>
                          )}
                        </div>
                      </div>
                    </td>
                    {listingType !== 'rentals' && (
                      <td style={{ padding: '12px 16px', color: 'var(--fg-secondary)', fontSize: 13 }}>
                        {(categories.find((c) => c.slug === item.category) || {})[ar ? 'name_ar' : 'name_en'] || '—'}
                      </td>
                    )}
                    <td style={{ padding: '12px 16px', color: 'var(--fg-secondary)' }}>
                      {price ? `AED ${Number(price).toLocaleString()}` : (ar ? 'حسب الطلب' : 'Custom')}
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{ display: 'inline-flex', padding: '3px 10px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: isActive ? '#DCFCE7' : '#F3F4F6', color: isActive ? '#16A34A' : '#6B7280' }}>
                        {isActive ? (ar ? 'نشط' : 'Active') : (ar ? 'مخفي' : 'Draft')}{item.status === 'pending' && <span style={{ display: 'inline-block', marginInlineStart: 6, padding: '3px 8px', borderRadius: 20, fontSize: 11, fontWeight: 600, background: '#FEF3C7', color: '#92400E' }}>{ar ? 'قيد المراجعة' : 'Pending Review'}</span>}{item.status === 'rejected' && <span style={{ display: 'inline-block', marginInlineStart: 6, padding: '3px 8px', borderRadius: 20, fontSize: 11, fontWeight: 600, background: '#FEE2E2', color: '#991B1B' }}>{ar ? 'مرفوض' : 'Rejected'}</span>}
                      </span>
                    </td>
                    <td style={{ padding: '12px 16px', textAlign: 'end' }}>
                      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                        <button onClick={() => openEdit(item)} title={ar ? 'تعديل' : 'Edit'} style={{ padding: '6px 10px', borderRadius: 8, border: '1px solid var(--line)', background: 'var(--white)', cursor: 'pointer', color: 'var(--fg-primary)', display: 'flex', alignItems: 'center', gap: 5, fontSize: 12.5 }}>
                          <Icon name="pencil" size={14} /> {ar ? 'تعديل' : 'Edit'}
                        </button>
                        <button onClick={() => setDeleteTarget(item.id)} title={ar ? 'حذف' : 'Delete'} style={{ padding: '6px 10px', borderRadius: 8, border: '1px solid var(--error, #dc2626)', background: 'var(--error-bg, #fef2f2)', cursor: 'pointer', color: 'var(--error, #dc2626)', display: 'flex', alignItems: 'center', gap: 5, fontSize: 12.5 }}>
                          <Icon name="trash-2" size={14} /> {ar ? 'حذف' : 'Delete'}
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        </div>
        </>
      )}

      {/* Add/Edit modal */}
      {showModal && (
        <ListingFormModal
          type={listingType}
          initial={editItem}
          vendorId={vendorId}
          categories={categories}
          onSave={handleSaved}
          onClose={closeModal}
          ar={ar}
          canDiscount={canDiscount}
        />
      )}

      {/* Delete confirm */}
      {deleteTarget && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9001, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,.45)', padding: '20px 16px' }}>
          <div style={{ background: 'var(--white)', borderRadius: 16, padding: '28px 28px 24px', maxWidth: 380, width: '100%' }}>
            <Icon name="alert-triangle" size={36} style={{ color: 'var(--error, #dc2626)' }} />
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, marginTop: 10, marginBottom: 6 }}>{ar ? 'حذف القائمة؟' : 'Delete this listing?'}</h3>
            <p style={{ color: 'var(--fg-secondary)', fontSize: 13.5, marginBottom: 22, lineHeight: 1.55 }}>
              {ar ? 'لا يمكن التراجع عن هذا الإجراء.' : 'This action cannot be undone.'}
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              <Button variant="secondary" onClick={() => setDeleteTarget(null)} disabled={deleting} style={{ flex: 1 }}>{ar ? 'إلغاء' : 'Cancel'}</Button>
              <button onClick={handleDelete} disabled={deleting} style={{ flex: 1, padding: '11px 18px', borderRadius: 10, border: 'none', background: '#DC2626', color: 'white', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, cursor: deleting ? 'not-allowed' : 'pointer' }}>
                {deleting ? (ar ? 'جارٍ الحذف…' : 'Deleting…') : (ar ? 'حذف' : 'Delete')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ============================================================
   MAIN VENDOR DASHBOARD PAGE
   ============================================================ */
function VendorDashboardPage() {
  const db = window.SarayaDB;
  const { user, profile, isVendor, openAuthModal, refreshProfile, loading: authLoading } = useAuth();
  const { lang, setLang } = useLang();
  const { go } = useNav();
  const ar = lang === 'ar';

  const [vp, setVp]             = useStateVD(null);
  const [docs, setDocs]         = useStateVD([]);
  const [sub, setSub]           = useStateVD(null);
  const [tier, setTier]         = useStateVD(null);
  const [counts, setCounts]     = useStateVD({ products: 0, rentals: 0, services: 0 });
  const [payouts, setPayouts]   = useStateVD({ pending: 0, total: 0 });
  const [loading, setLoading]   = useStateVD(true);
  const [activeTab, setActiveTab] = useStateVD('overview'); const [pendingListingType, setPendingListingType] = useStateVD(null);
  const [navOpen, setNavOpen] = useStateVD(false);
  const [toasts, setToasts] = useStateVD([]);
  const lastNotifAt = useRefVD(null);
  const dismissToast = useCallbackVD((id) => setToasts((prev) => prev.filter((x) => x.id !== id)), []);
  const pollNotifications = useCallbackVD(async () => {
    if (!db || !user || !window.SarayaService) return;
    const rows = await window.SarayaService.notifications.list(user.id, { limit: 10 });
    if (!rows || !rows.length) return;
    const newest = rows[0].created_at;
    if (lastNotifAt.current === null) { lastNotifAt.current = newest; return; }
    const fresh = rows.filter((r) => new Date(r.created_at) > new Date(lastNotifAt.current));
    if (fresh.length) {
      lastNotifAt.current = newest;
      const items = fresh.map((r) => ({ id: r.id, title: r.title, body: r.body }));
      items.forEach((it) => { setTimeout(() => dismissToast(it.id), 8000); });
      setToasts((prev) => [...prev, ...items].slice(-4));
    }
  }, [db, user, dismissToast]);
  useEffectVD(() => {
    if (!user) return;
    pollNotifications();
    const t = setInterval(pollNotifications, 25000);
    return () => clearInterval(t);
  }, [user, pollNotifications]);

  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    try {
      const [vpRes, docsRes, subRes, prodRes, rentRes, svcRes, payRes] = await Promise.all([
        db.from('vendor_profiles').select('*').eq('id', user.id).maybeSingle(),
        db.from('vendor_documents').select('*').eq('vendor_id', user.id),
        db.from('subscriptions').select('*, subscription_tiers!subscriptions_tier_id_fkey(*)').eq('vendor_id', user.id).eq('status', 'active').maybeSingle(),
        db.from('products').select('id', { count: 'exact', head: true }).eq('vendor_id', user.id),
        db.from('rentals').select('id', { count: 'exact', head: true }).eq('vendor_id', user.id),
        db.from('services').select('id', { count: 'exact', head: true }).eq('vendor_id', user.id),
        Promise.resolve(db.from('payouts').select('amount, status').eq('vendor_id', user.id)).catch(() => ({ data: [] })),
      ]);

      setVp(vpRes.data);
      setDocs(docsRes.data || []);
      if (subRes.data) {
        setSub(subRes.data);
        setTier(subRes.data.subscription_tiers);
      }
      setCounts({
        products: prodRes.count || 0,
        rentals:  rentRes.count || 0,
        services: svcRes.count || 0,
      });
      const allPayouts = (payRes && payRes.data) || [];
      setPayouts({
        pending: allPayouts.filter((p) => p.status === 'pending').reduce((s, p) => s + Number(p.amount), 0),
        total:   allPayouts.filter((p) => p.status === 'paid').reduce((s, p) => s + Number(p.amount), 0),
      });
    } catch(e) {
      console.error('VendorDashboard load error:', e);
    } finally {
      setLoading(false);
    }
  }, [db, user]);

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

  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 }}>
            {ar ? 'قاعدة البيانات غير مُفعّلة' : 'Database Not Configured'}
          </h2>
          <p style={{ color: 'var(--fg-secondary)', marginTop: 8, lineHeight: 1.6 }}>
            {ar ? 'يرجى ملء إعدادات Supabase في ملف src/config.js' : 'Please fill in the Supabase settings in src/config.js'}
          </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 }}>
            {ar ? 'يرجى تسجيل الدخول' : 'Please Sign In'}
          </h2>
          <Button variant="primary" style={{ marginTop: 18 }} onClick={() => openAuthModal('login')}>
            {ar ? 'تسجيل الدخول' : 'Sign In'}
          </Button>
        </Container>
      </main>
    );
  }

  if (!isVendor) {
    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 }}>
            {ar ? 'هذه الصفحة للبائعين فقط' : 'Vendors Only'}
          </h2>
          <Button variant="secondary" style={{ marginTop: 18 }} onClick={() => go('showroom')}>
            {ar ? 'انضم كبائع' : 'Become a Vendor'}
          </Button>
        </Container>
      </main>
    );
  }

  const totalListings    = counts.products + counts.rentals + counts.services;
  const maxListings      = tier?.max_listings ?? 20;
  const statusIdx        = VENDOR_STATUSES.findIndex((s) => s.key === (vp?.status || 'registered'));
  const isActive         = vp?.status === 'approved';
  const isSuspended      = vp?.status === 'suspended';
  const needsPackage     = vp?.status === 'package_pending';
  const needsPayment     = vp?.status === 'payment_pending';
  const needsProfile     = vp?.status === 'registered';
  const needsDocs        = vp?.status === 'documents_submitted';
  const needsAgreement   = vp?.status === 'agreement_pending';
  const isPendingApproval = vp?.status === 'pending_approval';

  // Subscription-derived state (used in JSX banners and passed to tabs)
  const _now = new Date();
  const trialEnd      = sub?.trial_end_date ? new Date(sub.trial_end_date) : null;
  const trialDaysLeft = trialEnd ? Math.max(0, Math.ceil((trialEnd - _now) / 86400000)) : 0;
  const isTrial       = !!(sub?.is_trial_active && sub?.status === 'trialing');
  const trialExpired  = sub?.status === 'trialing' && (!trialEnd || trialEnd < _now);
  const isRestricted  = sub?.status === 'restricted';
  const effectiveStatus = isTrial
    ? (trialDaysLeft > 0 ? 'trialing' : 'trial_expired')
    : (sub?.status || 'no_sub');
  const packageLevel  = tier?.package_level ?? 0;

  const TABS = [
    { key: 'overview',     group: 'main',      icon: 'layout-dashboard', label: { en: 'Overview',     ar: 'نظرة عامة' } },
    { key: 'profile',      group: 'setup',     icon: 'user',             label: { en: 'Store Profile', ar: 'ملف المتجر' } },
    { key: 'documents',    group: 'setup',     icon: 'file-text',        label: { en: 'Documents',    ar: 'الوثائق' } },
    { key: 'subscription', group: 'setup',     icon: 'credit-card',      label: { en: 'Subscription', ar: 'الاشتراك' } },
    { key: 'listings',     group: 'selling',   icon: 'package',          label: { en: 'Listings',     ar: 'القوائم' } },
    { key: 'inventory',    group: 'selling',   icon: 'boxes',            label: { en: 'Inventory',    ar: 'المخزون' } },
    { key: 'orders',       group: 'customers', icon: 'shopping-bag',     label: { en: 'Orders',       ar: 'الطلبات' } },
    { key: 'bookings',     group: 'customers', icon: 'calendar',         label: { en: 'Bookings',     ar: 'الحجوزات' } },
    { key: 'rfqs',         group: 'customers', icon: 'file-question',    label: { en: 'RFQs',         ar: 'عروض الأسعار' } },
    { key: 'leads',        group: 'customers', icon: 'inbox',            label: { en: 'Leads',        ar: 'العملاء المحتملون' } },
    { key: 'complaints',   group: 'customers', icon: 'alert-circle',     label: { en: 'Complaints',   ar: 'الشكاوى' } },
    { key: 'payouts',      group: 'money',     icon: 'banknote',         label: { en: 'Payments',     ar: 'المدفوعات' } },
    { key: 'analytics',    group: 'money',     icon: 'bar-chart-2',      label: { en: 'Analytics',    ar: 'الإحصائيات' } },
    { key: 'notifications', group: 'account',  icon: 'bell',             label: { en: 'Notifications', ar: 'الإشعارات' } },
    { key: 'support',      group: 'account',   icon: 'headset',          label: { en: 'Support', ar: 'الدعم' } },
    { key: 'settings',     group: 'account',   icon: 'settings',         label: { en: 'Settings',     ar: 'الإعدادات' } },
    { key: 'guide',        group: 'account',   icon: 'book-open',        label: { en: 'Vendor Guide', ar: 'دليل البائع' } },
  ];

  const NAV_GROUPS = [
    { id: 'main',      label: { en: '',           ar: '' } },
    { id: 'setup',     label: { en: 'Setup',      ar: 'الإعداد' } },
    { id: 'selling',   label: { en: 'Selling',    ar: 'البيع' } },
    { id: 'customers', label: { en: 'Customers',  ar: 'العملاء' } },
    { id: 'money',     label: { en: 'Money',      ar: 'المالية' } },
    { id: 'account',   label: { en: 'Account',    ar: 'الحساب' } },
  ];

  // Which tabs are accessible at the vendor's current package/subscription level
  const ALWAYS_OPEN = ['overview', 'profile', 'documents', 'subscription', 'settings', 'notifications', 'guide', 'support'];
  const tabAllowed = (key) => {
    if (ALWAYS_OPEN.includes(key)) return true;
    if (isRestricted || trialExpired) return false;
    const tab = TABS.find((t) => t.key === key);
    if (tab && tab.minPkg && packageLevel < tab.minPkg) return false;
    return true;
  };
  const activeTabMeta = TABS.find((t) => t.key === activeTab) || TABS[0];

  return (
    <main style={{ paddingTop: 100, minHeight: '100vh', background: 'var(--bg-canvas)' }}>
      {toasts.length > 0 && (
        <div style={{ position: 'fixed', top: 90, [ar ? 'left' : 'right']: 20, zIndex: 9999, display: 'grid', gap: 10, maxWidth: 340 }}>
          {toasts.map((t) => (
            <div
              key={t.id}
              onClick={() => { setActiveTab('notifications'); dismissToast(t.id); }}
              style={{ background: 'var(--white)', border: '1px solid var(--line)', borderInlineStart: '4px solid var(--gold)', borderRadius: 12, padding: '14px 16px', boxShadow: '0 8px 24px rgba(0,0,0,0.18)', cursor: 'pointer' }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{t.title || (ar ? 'إشعار جديد' : 'New notification')}</div>
                <button onClick={(e) => { e.stopPropagation(); dismissToast(t.id); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', fontSize: 16, lineHeight: 1, padding: 0 }}>×</button>
              </div>
              {t.body && <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', marginTop: 4, lineHeight: 1.5 }}>{t.body}</div>}
            </div>
          ))}
        </div>
      )}
      <Container wide>
        {/* Page header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 28 }}>
          <div>
            <Badge tone="gold">{ar ? 'لوحة البائع' : 'Vendor Dashboard'}</Badge>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(26px,4vw,38px)', fontWeight: 500, marginTop: 8, marginBottom: 4 }}>
              {vp?.trade_name || profile?.display_name || (ar ? 'حسابي' : 'My Account')}
            </h1>
            <p style={{ color: 'var(--fg-secondary)', fontSize: 14 }}>
              {ar ? 'حالة الحساب:' : 'Account status:'}{' '}
              <strong style={{ color: isActive ? 'var(--success)' : 'var(--gold-deep)', textTransform: 'capitalize' }}>
                {vp?.status?.replace(/_/g, ' ') || 'Registered'}
              </strong>
            </p>
          </div>
          <button onClick={() => setActiveTab('guide')} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '11px 20px', borderRadius: 10, background: 'var(--gold)', color: 'var(--espresso)', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap', boxShadow: 'var(--shadow-soft)' }}>
            <Icon name="book-open" size={17} />{ar ? 'دليل البائع' : 'Vendor Guide'}
          </button>
          {isSuspended && (
            <div style={{ padding: '10px 16px', borderRadius: 10, background: '#FEE2E2', border: '1px solid #FECACA', fontSize: 13, color: '#B91C1C', maxWidth: 360 }}>
              <strong style={{ display: 'block', marginBottom: 2 }}>{ar ? 'الحساب موقوف' : 'Account Suspended'}</strong>
              {ar ? 'تواصل مع فريق سرايا لمعرفة السبب واستعادة الحساب.' : 'Contact the Saraya team to understand the reason and reinstate your account.'}
            </div>
          )}
          {!isActive && !isSuspended && (
            <div style={{ padding: '10px 16px', borderRadius: 10, background: 'var(--cream)', border: '1px solid var(--gold-light)', fontSize: 13, color: 'var(--fg-secondary)', maxWidth: 360 }}>
              <strong style={{ color: 'var(--fg-primary)', display: 'block', marginBottom: 2 }}>
                {ar ? 'لتفعيل حسابك:' : 'To activate your account:'}
              </strong>
              {needsPackage && (
                <button onClick={() => { const el = document.getElementById('vd-pkg-banner'); if (el) el.scrollIntoView({ behavior: 'smooth' }); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, padding: 0, textDecoration: 'underline' }}>
                  {ar ? 'اختر باقة الاشتراك ↓' : 'Choose a subscription package ↓'}
                </button>
              )}
              {needsPayment && (ar ? 'أكمل الدفع للمتابعة ↓' : 'Complete your subscription payment ↓')}
              {isPendingApproval && (ar ? 'تم استلام الدفع — بانتظار موافقة فريق سرايا (2–3 أيام عمل)' : 'Payment received — awaiting Saraya team approval (2–3 business days)')}
              {needsProfile && (
                <button onClick={() => setActiveTab('profile')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, padding: 0, textDecoration: 'underline' }}>
                  {ar ? 'أكمل ملف شركتك للمتابعة ↓' : 'Complete your business profile to continue ↓'}
                </button>
              )}
            </div>
          )}
        </div>

        {/* Package selection banner — shown when vendor has not yet chosen a package */}
        {needsPackage && (
          <div id="vd-pkg-banner" style={{ background: 'var(--espresso)', color: 'var(--ivory)', borderRadius: 16, padding: '24px 28px', marginBottom: 24 }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 20, alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--gold-light)', margin: '0 0 8px' }}>
                  {ar ? 'الخطوة 2 من 3' : 'Step 2 of 3'}
                </p>
                <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, margin: '0 0 6px' }}>
                  {ar ? 'اختر باقة الموردين' : 'Choose Your Vendor Package'}
                </h2>
                <p style={{ fontSize: 13.5, color: 'rgba(250,246,240,0.75)', margin: 0 }}>
                  {ar ? 'اختر الباقة المناسبة لعملك لتبدأ بالإدراج وقبول الطلبات.' : 'Select the package that fits your business to start listing and receiving orders.'}
                </p>
              </div>
              <button onClick={() => window.openJoinVendorModal ? window.openJoinVendorModal() : go('showroom')} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '13px 24px', borderRadius: 10, background: 'var(--gold)', color: 'var(--espresso)', fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 700, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                <Icon name="briefcase" size={17} />
                {ar ? 'اختر باقتك الآن' : 'Choose Package Now'}
              </button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 12, marginTop: 20, paddingTop: 18, borderTop: '1px solid rgba(250,246,240,0.12)' }}>
              {(window.VENDOR_PACKAGES || []).map((pkg) => (
                <button key={pkg.id} onClick={() => go('showroom')} style={{ background: 'rgba(250,246,240,0.07)', border: '1px solid rgba(250,246,240,0.15)', borderRadius: 10, padding: '12px 16px', cursor: 'pointer', textAlign: 'start', color: 'var(--ivory)', fontFamily: 'var(--font-body)', transition: 'background 150ms' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                    <span style={{ fontSize: 14, fontWeight: 600 }}>{ar ? pkg.ar : pkg.en}</span>
                    {pkg.badge && <span style={{ fontSize: 10.5, background: 'var(--gold)', color: 'var(--espresso)', padding: '2px 8px', borderRadius: 20, fontWeight: 700 }}>{ar ? pkg.badge.ar : pkg.badge.en}</span>}
                  </div>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, color: 'var(--gold-light)' }}>AED {pkg.price}</span>
                  <span style={{ fontSize: 11, color: 'rgba(250,246,240,0.6)', marginInlineStart: 4 }}>/mo</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Payment pending banner */}
        {needsPayment && (
          <div style={{ background: 'linear-gradient(135deg, #1a3a5c 0%, #0f2340 100%)', color: 'var(--ivory)', borderRadius: 16, padding: '22px 26px', marginBottom: 24, display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#93C5FD', margin: '0 0 6px' }}>{ar ? 'الخطوة 3 من 3' : 'Step 3 of 3'}</p>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, margin: '0 0 4px' }}>{ar ? 'أكمل الدفع لتفعيل حسابك' : 'Complete Payment to Activate Your Account'}</h3>
              <p style={{ fontSize: 13, color: 'rgba(250,246,240,0.75)', margin: 0 }}>{ar ? 'الباقة المختارة في سلة التسوق وجاهزة للدفع.' : 'Your selected package is in the cart and ready for payment.'}</p>
            </div>
            <button onClick={() => go('checkout')} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '12px 22px', borderRadius: 10, background: '#3B82F6', color: '#fff', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap' }}>
              <Icon name="credit-card" size={16} />
              {ar ? 'الذهاب إلى الدفع' : 'Go to Checkout'}
            </button>
          </div>
        )}

        {/* Pending approval notice */}
        {isPendingApproval && (
          <div style={{ background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 16, padding: '20px 24px', marginBottom: 24, display: 'flex', gap: 14, alignItems: 'flex-start' }}>
            <Icon name="clock" size={22} style={{ color: '#D97706', flexShrink: 0, marginTop: 2 }} />
            <div>
              <strong style={{ fontSize: 15, color: '#92400E', display: 'block', marginBottom: 4 }}>{ar ? 'بانتظار موافقة سرايا' : 'Pending Saraya Approval'}</strong>
              <p style={{ fontSize: 13, color: '#78350F', margin: 0, lineHeight: 1.6 }}>
                {ar ? 'تم استلام دفعتك بنجاح. يراجع فريق سرايا حسابك خلال 2–3 أيام عمل. ستتلقى إشعارًا عند الموافقة.' : 'Your payment has been received. The Saraya team will review your account within 2–3 business days. You will be notified once approved.'}
              </p>
            </div>
          </div>
        )}

        {/* Status pipeline */}
        <div style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', padding: '20px 24px', marginBottom: 28 }}>
          <p style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 16 }}>
            {ar ? 'مسار الموافقة' : 'Approval Pipeline'}
          </p>
          <StatusPipeline currentStatus={vp?.status || 'registered'} ar={ar} />
        </div>

        <VendorActivationChecklist
          db={window.SarayaDB}
          vendorId={vp?.id}
          ar={ar}
          refreshKey={docs}
          go={setActiveTab}
          agreementSigned={!!vp?.agreement_signed_at}
          hasListing={(counts.products + counts.rentals + counts.services) > 0}
        />

        {/* Subscription status banner */}
        {(isTrial || isRestricted || sub) && (
          <div style={{
            marginBottom: 20, borderRadius: 14, padding: '14px 20px',
            background: isRestricted ? '#FEF2F2' : isTrial && trialDaysLeft <= 7 ? '#FFFBEB' : isTrial ? 'var(--cream)' : '#F0FDF4',
            border: isRestricted ? '1px solid #FECACA' : isTrial && trialDaysLeft <= 7 ? '1px solid #FDE68A' : isTrial ? '1px solid var(--gold-light)' : '1px solid #BBF7D0',
            display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 12,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <Icon name={isRestricted ? 'alert-triangle' : isTrial ? 'gift' : 'check-circle'} size={20}
                style={{ color: isRestricted ? '#DC2626' : isTrial ? '#D97706' : '#16A34A', flexShrink: 0 }} />
              <div>
                <div style={{ fontWeight: 700, fontSize: 14,
                  color: isRestricted ? '#DC2626' : isTrial && trialDaysLeft <= 7 ? '#B45309' : 'var(--fg-primary)' }}>
                  {isRestricted
                    ? (ar ? 'انتهت التجربة — مطلوب الاشتراك المدفوع' : 'Trial Expired — Paid Subscription Required')
                    : isTrial
                    ? (ar ? `التجربة المجانية · ${trialDaysLeft} يوم متبقٍ` : `Free Trial · ${trialDaysLeft} day${trialDaysLeft !== 1 ? 's' : ''} remaining`)
                    : (ar ? `اشتراك نشط — ${tier?.name || ''}` : `Active Subscription — ${tier?.name || ''}`)}
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-secondary)', marginTop: 2 }}>
                  {isRestricted
                    ? (ar ? 'اختر باقة مدفوعة لاستعادة الوصول الكامل.' : 'Choose a paid package to restore full dashboard access.')
                    : isTrial
                    ? (ar
                        ? `حزمة النمو مجانية حتى ${trialEnd ? trialEnd.toLocaleDateString('en-GB') : '—'}. اختر باقة مدفوعة قبل انتهائها.`
                        : `Growth Package (Pkg 2) free until ${trialEnd ? trialEnd.toLocaleDateString('en-GB') : '—'}. Choose a paid plan before it ends.`)
                    : `${effectiveStatus} · ${tier?.name || ''}`}
                </div>
              </div>
            </div>
            {(isRestricted || (isTrial && trialDaysLeft <= 14)) && (
              <button onClick={() => setActiveTab('subscription')}
                style={{ padding: '8px 18px', borderRadius: 9, border: 'none', cursor: 'pointer',
                  fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700,
                  background: isRestricted ? '#DC2626' : 'var(--gold)',
                  color: isRestricted ? '#fff' : 'var(--espresso)' }}>
                {ar ? 'اختر الباقة' : 'Choose Package'}
              </button>
            )}
          </div>
        )}

        {/* Sidebar + Content layout */}
        <div className="saraya-vd-shell" style={{ display: 'flex', gap: 24, alignItems: 'flex-start' }}>
          {/* Vertical sidebar */}
          <div className="saraya-vd-sidebar" style={{ width: 220, flexShrink: 0, background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', padding: '12px 8px', position: 'sticky', top: 90 }}>
            {/* Mobile-only toggle: shows current tab + hamburger, opens the nav list */}
            <button className="saraya-vd-navtoggle" onClick={() => setNavOpen((o) => !o)}
              style={{ width: '100%', alignItems: 'center', justifyContent: 'space-between', gap: 9,
                padding: '10px 12px', borderRadius: 9, border: '1px solid var(--line)', background: 'var(--cream)',
                cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, color: 'var(--fg-primary)' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <Icon name={activeTabMeta.icon} size={16} />
                {ar ? activeTabMeta.label.ar : activeTabMeta.label.en}
              </span>
              <Icon name={navOpen ? 'chevron-up' : 'menu'} size={18} />
            </button>
            <div className={'saraya-vd-navlist' + (navOpen ? ' open' : '')}>
            <div className="saraya-vd-navtitle" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--fg-muted)', padding: '6px 12px 10px' }}>
              {ar ? 'لوحة البائع' : 'Vendor Panel'}
            </div>
            {NAV_GROUPS.map((g) => {
              const groupTabs = TABS.filter((t) => t.group === g.id && (t.key !== 'guide' || isActive));
              if (!groupTabs.length) return null;
              return (
                <div key={g.id} style={{ marginTop: g.id === 'main' ? 0 : 4 }}>
                  {g.label.en ? (
                    <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-muted)', padding: '8px 12px 3px', opacity: 0.85 }}>
                      {ar ? g.label.ar : g.label.en}
                    </div>
                  ) : null}
                  {groupTabs.map((t) => {
                    const locked = !tabAllowed(t.key);
                    return (
                      <button key={t.key}
                        onClick={() => { if (!locked) setActiveTab(t.key); else setActiveTab('subscription'); setNavOpen(false); }}
                        title={locked ? (ar ? 'يتطلب ترقية الباقة' : 'Requires package upgrade') : undefined}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 9, width: '100%',
                          padding: '9px 12px', borderRadius: 8, border: 'none', textAlign: 'start',
                          background: activeTab === t.key ? 'var(--cream)' : 'none',
                          color: locked ? '#D1D5DB' : activeTab === t.key ? 'var(--fg-primary)' : 'var(--fg-secondary)',
                          fontFamily: 'var(--font-body)', fontSize: 13.5,
                          fontWeight: activeTab === t.key ? 600 : 400,
                          cursor: locked ? 'not-allowed' : 'pointer', transition: 'all 160ms',
                          borderInlineStart: activeTab === t.key ? '3px solid var(--gold)' : '3px solid transparent',
                          opacity: locked ? 0.55 : 1,
                        }}>
                        <Icon name={locked ? 'lock' : t.icon} size={15} />
                        <span style={{ flex: 1 }}>{ar ? t.label.ar : t.label.en}</span>
                        {t.minPkg && locked && (
                          <span style={{ fontSize: 9, fontWeight: 700, padding: '1px 5px', borderRadius: 20,
                            background: 'rgba(0,0,0,.10)', color: 'var(--fg-muted)' }}>
                            P{t.minPkg}+
                          </span>
                        )}
                      </button>
                    );
                  })}
                </div>
              );
            })}
            <div style={{ borderTop: '1px solid var(--line)', marginTop: 8, paddingTop: 8 }}>
              <button onClick={load} style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '9px 12px', borderRadius: 8, border: 'none', background: 'none', color: 'var(--fg-muted)', fontFamily: 'var(--font-body)', fontSize: 13, cursor: 'pointer' }}>
                <Icon name="refresh-cw" size={14} />
                {ar ? 'تحديث' : 'Refresh'}
              </button>
            </div>
            </div>
          </div>

          {/* Main content */}
          <div style={{ flex: 1, minWidth: 0 }}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: 60, color: 'var(--fg-muted)' }}>
            <Icon name="loader" size={32} style={{ animation: 'sarayaSpin 1s linear infinite' }} />
          </div>
        ) : (
          <>
            {/* OVERVIEW */}
            {activeTab === 'overview' && (
              <div style={{ display: 'grid', gap: 20 }}>
                {(() => {
                  const steps = [
                    { done: !!(vp && vp.trade_name),                          label: { en: 'Complete your store profile', ar: 'أكمل ملف متجرك' },   tab: 'profile' },
                    { done: !!(docs.length || (vp && vp.trade_license_number)), label: { en: 'Upload your trade licence',     ar: 'ارفع رخصتك التجارية' }, tab: 'documents' },
                    { done: totalListings > 0,                               label: { en: 'Publish your first listing',    ar: 'انشر أول قائمة' },     tab: 'listings' },
                    { done: isActive,                                        label: { en: 'Get approved by Saraya',        ar: 'احصل على موافقة سرايا' }, tab: null },
                  ];
                  const doneCount = steps.filter((s) => s.done).length;
                  if (doneCount === steps.length) return null;
                  return (
                    <div style={{ padding: '18px 22px', borderRadius: 14, background: 'linear-gradient(135deg,#FFFDF8,#FBF6EC)', border: '1.5px solid var(--gold)' }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
                        <div>
                          <strong style={{ fontSize: 16, display: 'block' }}>{ar ? 'ابدأ مع سرايا' : 'Get set up on Saraya'}</strong>
                          <span style={{ fontSize: 12.5, color: 'var(--fg-secondary)' }}>{doneCount}/{steps.length} {ar ? 'خطوات مكتملة' : 'steps complete'}</span>
                        </div>
                      </div>
                      <div style={{ height: 6, borderRadius: 20, background: 'rgba(0,0,0,.06)', margin: '12px 0 14px', overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: `${(doneCount / steps.length) * 100}%`, background: 'var(--gold)', borderRadius: 20, transition: 'width 300ms' }} />
                      </div>
                      <div style={{ display: 'grid', gap: 8 }}>
                        {steps.map((s, i) => (
                          <button key={i} disabled={s.done || !s.tab} onClick={() => { if (!s.done && s.tab) setActiveTab(s.tab); }}
                            style={{ display: 'flex', alignItems: 'center', gap: 10, textAlign: 'start', padding: '8px 10px', borderRadius: 9, border: 'none', background: s.done ? 'transparent' : 'var(--white)', cursor: (s.done || !s.tab) ? 'default' : 'pointer', width: '100%', opacity: s.done ? 0.75 : 1 }}>
                            <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 20, height: 20, borderRadius: '50%', background: s.done ? '#16A34A' : 'var(--cream)', color: s.done ? '#fff' : 'var(--fg-muted)', flexShrink: 0 }}>
                              <Icon name={s.done ? 'check' : 'circle'} size={12} />
                            </span>
                            <span style={{ flex: 1, fontSize: 13.5, textDecoration: s.done ? 'line-through' : 'none', color: s.done ? 'var(--fg-muted)' : 'var(--fg-primary)' }}>{ar ? s.label.ar : s.label.en}</span>
                            {!s.done && s.tab && <Icon name="chevron-right" size={15} style={{ color: 'var(--fg-muted)' }} />}
                          </button>
                        ))}
                      </div>
                    </div>
                  );
                })()}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(200px,1fr))', gap: 14 }}>
                  <VDStat icon="package"     label={ar ? 'القوائم' : 'Listings'}           value={totalListings}                         sub={`/ ${maxListings} ${ar ? 'الحد الأقصى' : 'max'}`} />
                  <VDStat icon="shopping-bag" label={ar ? 'المنتجات' : 'Products'}          value={counts.products}                       />
                  <VDStat icon="archive"      label={ar ? 'الإيجار' : 'Rentals'}            value={counts.rentals}                        />
                  <VDStat icon="briefcase"    label={ar ? 'الخدمات' : 'Services'}           value={counts.services}                       />
                  <VDStat icon="clock"        label={ar ? 'مدفوعات معلقة' : 'Pending Payout'} value={`AED ${payouts.pending.toFixed(2)}`} />
                  <VDStat icon="check-circle" label={ar ? 'إجمالي المدفوعات' : 'Total Paid'}  value={`AED ${payouts.total.toFixed(2)}`}  />
                </div>

                {/* Action cards */}
                {needsProfile && (
                  <div style={{ padding: '16px 20px', borderRadius: 12, background: '#EFF6FF', border: '1.5px solid #93C5FD', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                    <Icon name="user" size={20} style={{ color: '#2563EB', flexShrink: 0, marginTop: 2 }} />
                    <div>
                      <strong style={{ display: 'block', marginBottom: 4 }}>{ar ? 'أكمل ملف شركتك' : 'Complete Your Business Profile'}</strong>
                      <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: 0, lineHeight: 1.55 }}>
                        {ar
                          ? 'أضف اسم شركتك ومعلومات التواصل لإرسال طلبك إلى فريق سرايا للمراجعة.'
                          : 'Add your business name and contact info to submit your account for Saraya review.'}
                      </p>
                      <Button variant="primary" style={{ marginTop: 12 }} onClick={() => setActiveTab('profile')}>
                        {ar ? 'إكمال الملف الشخصي' : 'Complete Profile'}
                      </Button>
                    </div>
                  </div>
                )}

                {needsDocs && (
                  <div style={{ padding: '16px 20px', borderRadius: 12, background: '#FFFBEB', border: '1.5px solid #FCD34D', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                    <Icon name="alert-triangle" size={20} style={{ color: '#D97706', flexShrink: 0, marginTop: 2 }} />
                    <div>
                      <strong style={{ display: 'block', marginBottom: 4 }}>{ar ? 'الوثائق مطلوبة' : 'Documents Required'}</strong>
                      <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: 0, lineHeight: 1.55 }}>
                        {ar
                          ? 'ارفع رخصتك التجارية لتفعيل حسابك في سرايا.'
                          : 'Upload your trade license to activate your Saraya account.'}
                      </p>
                      <Button variant="primary" style={{ marginTop: 12 }} onClick={() => setActiveTab('documents')}>
                        {ar ? 'رفع الوثائق' : 'Upload Documents'}
                      </Button>
                    </div>
                  </div>
                )}

                {needsAgreement && (
                  <div style={{ padding: '16px 20px', borderRadius: 12, background: '#F0FDF4', border: '1.5px solid #86EFAC', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                    <Icon name="file-check-2" size={20} style={{ color: '#16A34A', flexShrink: 0, marginTop: 2 }} />
                    <div>
                      <strong style={{ display: 'block', marginBottom: 4 }}>{ar ? 'اتفاقية البائع جاهزة للتوقيع' : 'Vendor Agreement Ready'}</strong>
                      <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: 0, lineHeight: 1.55 }}>
                        {ar ? 'تمت الموافقة على ملفك. وقّع على الاتفاقية لتفعيل حسابك.' : 'Your profile has been approved. Sign the agreement to go live.'}
                      </p>
                      <Button variant="primary" style={{ marginTop: 12 }} onClick={() => setActiveTab('documents')}>
                        {ar ? 'مراجعة الاتفاقية' : 'Review Agreement'}
                      </Button>
                    </div>
                  </div>
                )}

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(min(280px,100%),1fr))', gap: 14 }}>
                  <QuickCard
                    icon="plus-square"
                    title={ar ? 'إضافة منتج' : 'Add a Product'}
                    description={ar ? 'أضف منتجًا جديدًا إلى كتالوجك' : 'List a new product in your catalogue'}
                    cta={ar ? 'إضافة منتج' : 'Add Product'}
                    onClick={() => { setPendingListingType('products'); setActiveTab('listings'); }}
                    badge={`${counts.products}/${maxListings}`}
                  />
                  <QuickCard
                    icon="calendar"
                    title={ar ? 'إضافة تأجير' : 'Add a Rental'}
                    description={ar ? 'أضف معدات أو ديكور للإيجار مع التقويم والأسعار' : 'List equipment or decor for rent with calendar and pricing'}
                    cta={ar ? 'إضافة تأجير' : 'Add Rental'}
                    onClick={() => { setPendingListingType('rentals'); setActiveTab('listings'); }}
                    badge={counts.rentals} /><QuickCard icon="briefcase" title={ar ? 'إضافة خدمة' : 'Add a Service'} description={ar ? 'أضف خدمة جديدة إلى قائمة عروضك' : 'List a new service you offer'} cta={ar ? 'إضافة خدمة' : 'Add Service'} onClick={() => { setPendingListingType('services'); setActiveTab('listings'); }} badge={counts.services}
                  />
                  <QuickCard
                    icon="clipboard-list"
                    title={ar ? 'طلبات عروض الأسعار' : 'RFQ Requests'}
                    description={ar ? 'اعرض سعرك على طلبات العملاء الجديدة' : 'Submit offers on new customer RFQ requests'}
                    cta={ar ? 'عرض الطلبات' : 'Browse RFQs'}
                    onClick={() => setActiveTab('rfqs')}
                  />
                </div>
              </div>
            )}

            {/* PROFILE */}
            {activeTab === 'profile' && <VendorProfileEditor vp={vp} onSaved={load} ar={ar} />}

            {/* DOCUMENTS */}
            {activeTab === 'documents' && (
              <div style={{ display: 'grid', gap: 28 }}>
                <Section title={ar ? 'رفع المستندات' : 'Document Upload'} desc={ar ? 'ارفع الرخصة التجارية والهوية الإماراتية وشهادة ضريبة القيمة المضافة للمراجعة.' : 'Upload your trade license, Emirates ID, and VAT certificate for review.'}>
                  <DocumentUpload vendorId={user.id} existingDocs={docs} onUploaded={load} ar={ar} />
                </Section>
                <AgreementSection vendorId={user.id} alreadySigned={!!vp?.agreement_signed_at} signedAt={vp?.agreement_signed_at} version={vp?.agreement_version} tradeName={vp?.trade_name} onSign={load} ar={ar} />
              </div>
            )}

            {/* SUBSCRIPTION */}
            {activeTab === 'subscription' && (
              <VendorSubscriptionTab sub={sub} tier={tier} isTrial={isTrial} trialDaysLeft={trialDaysLeft} trialEnd={trialEnd} trialExpired={trialExpired} isRestricted={isRestricted} effectiveStatus={effectiveStatus} packageLevel={packageLevel} vendorId={user.id} db={db} ar={ar} onRefresh={load} />
            )}

            {/* LISTINGS */}
            {activeTab === 'listings' && (
              <VendorListingsTab vendorId={user.id} maxListings={maxListings} currentCount={totalListings} onCountsChange={load} initialType={pendingListingType} ar={ar} canDiscount={tier?.can_create_discounts} agreementSigned={!!vp?.agreement_signed_at} onGoDocuments={() => setActiveTab('documents')} />
            )}

            {/* ORDERS */}
            {activeTab === 'orders' && (
              <VendorOrdersTab db={db} user={user} ar={ar} />
            )}

            {/* BOOKINGS */}
            {activeTab === 'bookings' && (
              <VendorBookingsTab db={db} user={user} ar={ar} />
            )}

            {/* RFQS */}
            {activeTab === 'rfqs' && (
              window.RFQBoardTab ? <window.RFQBoardTab db={db} user={user} ar={ar} tier={tier} /> : <VDPlaceholder icon="file-question" title={ar ? 'طلبات عروض الأسعار' : 'RFQs'} desc={ar ? 'لا توجد طلبات عروض أسعار مفتوحة حاليًا.' : 'No open RFQs right now.'} />
            )}

            {/* LEADS */}
            {activeTab === 'leads' && (
              <VendorLeadsTab db={db} user={user} ar={ar} />
            )}

            {/* COMPLAINTS */}
            {activeTab === 'complaints' && (
              <VendorComplaintsTab db={db} user={user} ar={ar} />
            )}

            {/* PAYOUTS */}
            {activeTab === 'payouts' && (
              <VendorPayoutsTab db={db} user={user} ar={ar} />
            )}

            {/* ANALYTICS */}
            {activeTab === 'analytics' && (
              <VendorAnalyticsTab db={db} user={user} ar={ar} tier={tier} />
            )}

            {/* INVENTORY */}
            {activeTab === 'inventory' && (
              <VendorInventoryTab db={db} user={user} ar={ar} />
            )}

            {/* NOTIFICATIONS */}
            {activeTab === 'notifications' && (
            <NotificationsTab db={db} user={user} ar={ar} />
          )}

            {/* SUPPORT / HELP — request a meeting with the Saraya team */}
            {activeTab === 'support' && <window.VendorMeetingSection ar={ar} />}

            {/* SETTINGS */}
            {activeTab === 'settings' && (
              <div style={{ display: 'grid', gap: 28 }}>
                <VendorSettingsTab db={db} user={user} profile={profile} refreshProfile={refreshProfile} ar={ar} lang={lang} setLang={setLang} tier={tier} />
                <Section title={ar ? 'خطر — حذف الحساب' : 'Danger Zone'} desc={ar ? 'إجراءات لا يمكن التراجع عنها.' : 'Irreversible account actions.'}>
                  <div style={{ padding: '12px 16px', borderRadius: 10, background: '#FEF2F2', border: '1px solid #FCA5A5', fontSize: 13, color: '#B91C1C', lineHeight: 1.6 }}>
                    {ar
                      ? 'لطلب تعليق الحساب أو حذفه، تواصل مع فريق سرايا عبر البريد الإلكتروني sales@sarayaevents.com.'
                      : 'To request account suspension or deletion, contact the Saraya team at sales@sarayaevents.com.'}
                  </div>
                </Section>
              </div>
            )}
          </>
        )}

            {/* VENDOR GUIDE — available to all vendors (any account status) */}
            {activeTab === 'guide' && (
              <div style={{ display: 'grid', gap: 24 }}>
                <Section
                  title={ar ? 'مرحباً بك في دليل البائع' : 'Welcome to your Vendor Guide'}
                  desc={ar ? 'دليل تدريبي مفصل لاستخدام كل قسم من لوحة تحكم البائع خطوة بخطوة، إلى جانب الشروط التي تحكم حسابك على المنصة.' : 'A detailed, step-by-step training guide for every section of your vendor dashboard, plus the terms that govern your account on the platform.'}
                />

                {[{"title":{"en":"Getting Set Up & Approved","ar":"الإعداد والحصول على الموافقة"},"desc":{"en":"The tabs that get your store live and keep your account and package current.","ar":"التبويبات التي تجهز متجرك للعمل وتُبقي حسابك وباقتك محدّثين."},"items":[{"title":{"en":"Overview","ar":"نظرة عامة"},"purpose":{"en":"Your home base when you log in. It shows exactly where your account stands in the approval pipeline, how many products, rentals, and services you currently have listed against your package limit, and your payout totals.","ar":"الصفحة الرئيسية عند تسجيل الدخول. تعرض موقعك بالضبط في مسار الموافقة، وعدد المنتجات والإيجارات والخدمات المدرجة حاليًا مقارنة بحد باقتك، وإجمالي مدفوعاتك."},"steps":{"en":["Check the Approval Pipeline bar at the top — it moves through Registered, Package Pending, Payment Pending, Pending Approval, and Approved as your application progresses.","Watch the Listings widget (e.g. \"28/25\") to see how close you are to your package’s listing limit.","Use the Pending Payout and Total Paid cards to track what Saraya owes you and what’s already been paid out.","Use the quick action cards (Add a Product, Add a Rental, Add a Service, Browse RFQs) to jump straight into common tasks without navigating the sidebar."],"ar":["تابع شريط مسار الموافقة أعلى الصفحة — يتنقل عبر: مسجل، الباقة معلقة، الدفع معلق، بانتظار الموافقة، ثم معتمد.","راقب مؤشر القوائم (مثل \"28/25\") لمعرفة مدى اقترابك من الحد الأقصى لباقتك.","استخدم بطاقتي \"المدفوعات المعلقة\" و\"إجمالي المدفوع\" لمتابعة مستحقاتك والمبالغ المدفوعة فعليًا.","استخدم بطاقات الإجراءات السريعة (إضافة منتج، إضافة إيجار، إضافة خدمة، تصفح عروض الأسعار) للانتقال مباشرة للمهام الشائعة دون التنقل عبر القائمة الجانبية."]},"tip":{"en":"If your account status is anything other than \"Approved\", some tabs will stay locked until you finish that step.","ar":"إذا كانت حالة حسابك غير \"معتمد\"، ستبقى بعض التبويبات مقفلة حتى تكمل تلك الخطوة."}},{"title":{"en":"Store Profile","ar":"ملف المتجر"},"purpose":{"en":"This is the public-facing information customers see about your business on the marketplace — get it right, since it’s often the first thing a customer checks before buying.","ar":"هذه هي المعلومات العامة التي يراها العملاء عن نشاطك التجاري في السوق — احرص على دقتها لأنها غالبًا أول ما يتحقق منه العميل قبل الشراء."},"steps":{"en":["Go to Store Profile and fill in your Trade Name in both English and Arabic — this appears on every listing card and your vendor page.","Write a clear business Description in both languages; keep it factual and specific about what you offer.","Select all applicable Business Categories (multi-select) so customers can find you under the right filters.","Add your WhatsApp number and website so customers and Saraya staff can reach you.","Enter your bank account or IBAN details accurately — this is where your payouts are sent, so double-check the digits."],"ar":["اذهب إلى ملف المتجر وأدخل الاسم التجاري باللغتين الإنجليزية والعربية — يظهر هذا في كل بطاقة قائمة وصفحة متجرك.","اكتب وصفًا واضحًا لنشاطك باللغتين، ويفضل أن يكون دقيقًا ومحددًا لما تقدمه.","اختر جميع الفئات التجارية المناسبة (اختيار متعدد) ليتمكن العملاء من إيجادك ضمن الفلاتر الصحيحة.","أضف رقم واتساب وموقعك الإلكتروني حتى يتمكن العملاء وفريق سرايا من التواصل معك.","أدخل بيانات حسابك البنكي أو الآيبان بدقة — فهذا هو المكان الذي تُرسل إليه مدفوعاتك، تحقق من الأرقام جيدًا."]},"tip":{"en":"Keep your WhatsApp number active and monitored — it’s usually the first way customers and Saraya staff reach you.","ar":"حافظ على تفعيل ومتابعة رقم الواتساب الخاص بك — فهو غالبًا أول وسيلة يتواصل بها معك العملاء وفريق سرايا."}},{"title":{"en":"Documents","ar":"الوثائق"},"purpose":{"en":"Saraya verifies every vendor’s trade license before approving a store, to protect customers and keep the marketplace credible.","ar":"تتحقق سرايا من الرخصة التجارية لكل بائع قبل اعتماد المتجر، لحماية العملاء والحفاظ على مصداقية السوق."},"steps":{"en":["Upload a clear, current copy of your trade license (PDF or image).","Add any other legal documents Saraya’s staff requests during review.","Check back here if your status shows \"documents submitted\" — staff will review and move you to the next pipeline stage."],"ar":["ارفع نسخة واضحة وسارية من رخصتك التجارية (PDF أو صورة).","أضف أي مستندات قانونية أخرى يطلبها فريق سرايا أثناء المراجعة.","تابع هذه الصفحة إذا كانت حالتك \"تم إرسال الوثائق\" — سيقوم الفريق بالمراجعة ونقلك للمرحلة التالية."]},"tip":{"en":"Blurry or expired documents are the most common reason approval gets delayed — upload a sharp, valid copy the first time.","ar":"الوثائق غير الواضحة أو منتهية الصلاحية هي السبب الأكثر شيوعًا لتأخر الموافقة — ارفع نسخة واضحة وسارية من أول مرة."}},{"title":{"en":"Subscription","ar":"الاشتراك"},"purpose":{"en":"Your package controls your listing limit, analytics depth, featured placement eligibility, and support level. This tab is also where you upgrade, downgrade, suspend, or resume your subscription yourself — no need to contact support for routine changes.","ar":"تحدد باقتك حد القوائم، وعمق الإحصائيات، وأهلية الظهور المميز، ومستوى الدعم. من هنا أيضًا يمكنك ترقية أو تخفيض أو إيقاف أو استئناف اشتراكك بنفسك دون الحاجة للتواصل مع الدعم لكل تغيير روتيني."},"steps":{"en":["Review your current package card to see your listing limit, analytics tier, and support level at a glance.","To upgrade, click \"Upgrade to [Package]\" — this takes effect immediately via secure checkout and unlocks the higher tier’s limits right away.","To downgrade, choose \"Request Downgrade\" — this is scheduled for your next billing cycle, so you keep your current benefits until then. You can cancel a pending downgrade any time before it takes effect.","To pause billing without losing your data, use \"Request Suspend\" — you can resume any time with \"Resume\"."],"ar":["راجع بطاقة باقتك الحالية لمعرفة حد القوائم ومستوى الإحصائيات والدعم بسرعة.","للترقية، اضغط \"ترقية إلى [الباقة]\" — يسري هذا فورًا عبر الدفع الآمن وتحصل على مزايا الباقة الأعلى مباشرة.","للتخفيض، اختر \"طلب تخفيض الباقة\" — يُجدول هذا لبداية دورة الفوترة القادمة، وتحتفظ بمزاياك الحالية حتى ذلك الحين. يمكنك إلغاء طلب التخفيض المعلق في أي وقت قبل سريانه.","لإيقاف الفوترة مؤقتًا دون فقدان بياناتك، استخدم \"طلب الإيقاف\" — ويمكنك الاستئناف في أي وقت عبر \"استئناف\"."]},"tip":{"en":"Downgrading may deactivate some listings if your count exceeds the new tier’s limit — trim your listings first if you’re close to it.","ar":"قد يؤدي التخفيض إلى تعطيل بعض قوائمك إذا تجاوز عددها حد الباقة الجديدة — قلّص قوائمك أولاً إذا كنت قريبًا من الحد الجديد."}}]},{"title":{"en":"Running Your Store Day to Day","ar":"إدارة متجرك يوميًا"},"desc":{"en":"The tabs you’ll use most once you’re live: listings, fulfilment, and customer demand.","ar":"التبويبات التي ستستخدمها أكثر بمجرد أن يصبح متجرك مباشرًا: القوائم والتنفيذ وطلب العملاء."},"items":[{"title":{"en":"Listings","ar":"القوائم"},"purpose":{"en":"Where you create and manage every product, rental, and service you sell. New and edited listings go through a quick admin review before they appear publicly.","ar":"من هنا تنشئ وتدير كل منتج وإيجار وخدمة تبيعها. تمر القوائم الجديدة والمعدّلة بمراجعة إدارية سريعة قبل ظهورها للجمهور."},"steps":{"en":["Use \"Add a Product\", \"Add a Rental\", or \"Add a Service\" to create a new listing with photos, pricing, and category.","Check the status badge on each listing — Pending means it’s awaiting admin approval, Approved means it’s live, Rejected means it needs changes.","Edit any listing at any time; substantial edits may be re-reviewed before going live again.","Keep an eye on your total listing count versus your package limit shown on Overview."],"ar":["استخدم \"إضافة منتج\" أو \"إضافة إيجار\" أو \"إضافة خدمة\" لإنشاء قائمة جديدة بالصور والأسعار والفئة.","تابع شارة الحالة على كل قائمة — \"معلق\" بانتظار موافقة الإدارة، \"معتمد\" أي أنها مباشرة الآن، \"مرفوض\" تحتاج تعديلات.","يمكنك تعديل أي قائمة في أي وقت؛ قد تحتاج التعديلات الجوهرية لمراجعة جديدة قبل الظهور مجددًا.","راقب إجمالي عدد قوائمك مقارنة بحد باقتك الظاهر في صفحة النظرة العامة."]},"tip":{"en":"Complete, accurate listings with real photos are approved faster and convert better with customers.","ar":"القوائم الكاملة والدقيقة مع صور حقيقية تُعتمد أسرع وتحقق تحويلات أفضل مع العملاء."}},{"title":{"en":"Orders","ar":"الطلبات"},"purpose":{"en":"Tracks every product order placed by customers so you can fulfil it correctly and on time.","ar":"تتابع كل طلب منتج يقدمه العملاء حتى تتمكن من تنفيذه بدقة وفي الوقت المناسب."},"steps":{"en":["Open an order to see the customer’s items, quantities, and delivery details.","Move the order through its statuses as you fulfil it: Processing → Confirmed → Preparing → Out for Delivery → Done.","Use Cancelled only when an order genuinely cannot be fulfilled, and follow up with the customer."],"ar":["افتح الطلب لعرض عناصر العميل والكميات وتفاصيل التوصيل.","حدّث حالة الطلب أثناء التنفيذ: قيد المعالجة ← مؤكد ← قيد التحضير ← خارج للتوصيل ← مكتمل.","استخدم حالة \"ملغى\" فقط عند تعذر تنفيذ الطلب فعليًا، وتابع مع العميل بعدها."]},"tip":{"en":"Keep order statuses current — customers get notified as status changes, so stale statuses create confusion and complaints.","ar":"حافظ على تحديث حالات الطلبات — يتم إشعار العملاء عند تغيّر الحالة، فالحالات القديمة تسبب ارتباكًا وشكاوى."}},{"title":{"en":"Bookings","ar":"الحجوزات"},"purpose":{"en":"Manages date-based bookings for your rentals and services, so you avoid accidentally double-booking the same item or time slot.","ar":"تدير الحجوزات المرتبطة بتواريخ لإيجاراتك وخدماتك، لتفادي حجز نفس العنصر أو الموعد مرتين بالخطأ."},"steps":{"en":["Review incoming bookings and confirm availability against your calendar.","Update booking status as the event date approaches and after it’s completed.","Block off dates in Inventory if an item becomes unavailable outside the booking flow (e.g. maintenance)."],"ar":["راجع الحجوزات الواردة وأكد التوفر بناءً على تقويمك.","حدّث حالة الحجز مع اقتراب تاريخ الفعالية وبعد اكتمالها.","احجب التواريخ في المخزون إذا أصبح العنصر غير متاح خارج تدفق الحجز (مثل الصيانة)."]},"tip":{"en":"Confirm bookings promptly — customers are comparing vendors, and slow responses lose bookings.","ar":"أكّد الحجوزات بسرعة — العملاء يقارنون بين البائعين، والرد البطيء يفقدك الحجز."}},{"title":{"en":"RFQs (Request a Quote)","ar":"عروض الأسعار (RFQ)"},"purpose":{"en":"Customers who need a custom quote (bulk orders, bespoke event packages, etc.) submit an RFQ that’s routed to relevant vendors. You respond with your own offer.","ar":"العملاء الذين يحتاجون عرض سعر مخصص (طلبات كبيرة، باقات فعاليات خاصة) يقدمون طلب عرض سعر يُوجَّه للبائعين المعنيين. أنت تردّ بعرضك الخاص."},"steps":{"en":["Open the RFQ Board to see incoming quote requests relevant to your categories.","Review the customer’s requirements and submit a competitive offer with your price and notes.","Track which RFQs you’ve already responded to and their status."],"ar":["افتح لوحة عروض الأسعار لمشاهدة الطلبات الواردة المتعلقة بفئاتك.","راجع متطلبات العميل وقدّم عرضًا تنافسيًا يتضمن السعر والملاحظات.","تابع العروض التي رددت عليها بالفعل وحالتها."]},"tip":{"en":"Starter package vendors have a monthly cap on RFQ responses — upgrade your package if you’re regularly hitting the limit.","ar":"بائعو الباقة الأساسية (Starter) لديهم حد شهري للردود على عروض الأسعار — رقّي باقتك إذا كنت تصل للحد بانتظام."}},{"title":{"en":"Leads","ar":"العملاء المحتملون"},"purpose":{"en":"Shows inbound customer inquiries routed to your store outside of a formal order, quote, or booking — a general \"I’m interested\" signal.","ar":"تعرض استفسارات العملاء الواردة الموجهة لمتجرك خارج إطار الطلب أو عرض السعر أو الحجز الرسمي — إشارة اهتمام عامة."},"steps":{"en":["Review new leads regularly and reach out to the customer promptly.","Use your Store Profile’s WhatsApp number as your primary follow-up channel."],"ar":["راجع العملاء المحتملين الجدد بانتظام وتواصل مع العميل بسرعة.","استخدم رقم الواتساب في ملف متجرك كقناة المتابعة الأساسية."]},"tip":{"en":"Fast follow-up on leads is one of the biggest drivers of conversion — check this tab daily.","ar":"المتابعة السريعة للعملاء المحتملين من أكبر عوامل زيادة التحويل — تحقق من هذا التبويب يوميًا."}},{"title":{"en":"Inventory","ar":"المخزون"},"purpose":{"en":"Tracks stock levels and date availability for your rentals and services so listings automatically reflect what you can actually fulfil.","ar":"يتابع مستويات المخزون وتوفر التواريخ لإيجاراتك وخدماتك حتى تعكس القوائم تلقائيًا ما يمكنك تنفيذه فعليًا."},"steps":{"en":["Set quantity or availability for each rental or service item.","Update stock after every booking or sale so customers don’t order something you can’t deliver."],"ar":["حدّد الكمية أو التوفر لكل عنصر إيجار أو خدمة.","حدّث المخزون بعد كل حجز أو عملية بيع حتى لا يطلب العميل شيئًا لا يمكنك توفيره."]},"tip":{"en":"Accurate inventory prevents the most common source of cancellations and complaints.","ar":"دقة المخزون تمنع أكثر أسباب الإلغاءات والشكاوى شيوعًا."}}]},{"title":{"en":"Support, Payments & Your Account","ar":"الدعم والمدفوعات وحسابك"},"desc":{"en":"Where issues get resolved, payouts get tracked, and your account preferences live.","ar":"حيث تُحل المشكلات، وتُتابع المدفوعات، وتوجد تفضيلات حسابك."},"items":[{"title":{"en":"Complaints","ar":"الشكاوى"},"purpose":{"en":"If a customer raises a formal complaint against your store, it appears here so you can respond directly. Saraya’s team also reviews and helps mediate unresolved complaints.","ar":"إذا قدّم عميل شكوى رسمية ضد متجرك، تظهر هنا لتتمكن من الرد مباشرة. يراجع فريق سرايا أيضًا الشكاوى غير المحلولة ويساعد في الوساطة."},"steps":{"en":["Open a complaint to see the customer’s issue and any order or booking it relates to.","Respond with your explanation or resolution as quickly as possible — Saraya aims to resolve complaints within 3 business days.","Escalate to Saraya support if you and the customer can’t reach a resolution yourselves."],"ar":["افتح الشكوى لعرض مشكلة العميل وأي طلب أو حجز مرتبط بها.","رد بتوضيحك أو حل المشكلة في أسرع وقت — تهدف سرايا لحل الشكاوى خلال 3 أيام عمل.","صعّد الأمر لدعم سرايا إذا تعذر التوصل لحل بينك وبين العميل."]},"tip":{"en":"You are responsible for product/service quality, delivery, and after-sales service — Saraya is an intermediary and does not assume that liability.","ar":"أنت المسؤول عن جودة المنتج أو الخدمة والتسليم وخدمة ما بعد البيع — سرايا منصة وسيطة ولا تتحمل هذه المسؤولية."}},{"title":{"en":"Payments","ar":"المدفوعات"},"purpose":{"en":"Shows what Saraya currently owes you (Pending Payout) and what’s already been paid out to your bank account (Total Paid).","ar":"تعرض ما تدين به سرايا لك حاليًا (المدفوعات المعلقة) وما تم دفعه بالفعل لحسابك البنكي (إجمالي المدفوع)."},"steps":{"en":["Check this tab regularly to reconcile your own sales records against what Saraya shows as pending or paid.","Make sure your bank/IBAN details in Store Profile are correct — payout issues are almost always caused by outdated bank details."],"ar":["تحقق من هذا التبويب بانتظام لمطابقة سجلات مبيعاتك مع ما تعرضه سرايا كمعلق أو مدفوع.","تأكد من صحة بيانات حسابك البنكي أو الآيبان في ملف المتجر — مشاكل الدفع غالبًا سببها بيانات بنكية قديمة."]},"tip":{"en":"Contact sales@sarayaevents.com if a payout looks delayed or incorrect.","ar":"تواصل مع sales@sarayaevents.com إذا بدت أي دفعة متأخرة أو غير صحيحة."}},{"title":{"en":"Analytics","ar":"الإحصائيات"},"purpose":{"en":"Gives you visibility into how your store and listings are performing. The depth of data available depends on your package tier — higher tiers unlock more detailed breakdowns.","ar":"تمنحك رؤية حول أداء متجرك وقوائمك. يعتمد عمق البيانات المتاحة على مستوى باقتك — الباقات الأعلى تفتح تفاصيل أعمق."},"steps":{"en":["Review your key metrics regularly to see what’s working (views, orders, conversion).","Use the data to decide which listings to promote, refresh, or retire."],"ar":["راجع مؤشراتك الرئيسية بانتظام لمعرفة ما ينجح (المشاهدات، الطلبات، التحويل).","استخدم البيانات لتقرر أي القوائم تروّج لها أو تحدّثها أو توقفها."]},"tip":{"en":"Upgrade your package if you need deeper analytics — Starter includes basic stats only.","ar":"رقّي باقتك إذا احتجت إحصائيات أعمق — باقة Starter تشمل إحصائيات أساسية فقط."}},{"title":{"en":"Notifications","ar":"الإشعارات"},"purpose":{"en":"Real-time alerts for anything that needs your attention: new orders, RFQs, bookings, complaints, and account or subscription updates.","ar":"تنبيهات فورية لكل ما يحتاج انتباهك: طلبات جديدة، عروض أسعار، حجوزات، شكاوى، وتحديثات الحساب أو الاشتراك."},"steps":{"en":["Check this tab regularly, or as soon as you see the notification badge.","Click through a notification to jump straight to the relevant order, RFQ, booking, or complaint."],"ar":["تحقق من هذا التبويب بانتظام أو فور ظهور شارة الإشعار.","اضغط على أي إشعار للانتقال مباشرة للطلب أو عرض السعر أو الحجز أو الشكوى المرتبطة به."]},"tip":{"en":"Make checking notifications a daily habit — most time-sensitive vendor tasks arrive here first.","ar":"اجعل مراجعة الإشعارات عادة يومية — معظم مهام البائع الحساسة للوقت تصل هنا أولاً."}},{"title":{"en":"Support (Book a Meeting)","ar":"الدعم (حجز اجتماع)"},"purpose":{"en":"Book a video or phone meeting with the Saraya team for onboarding, listing setup, store profile, subscription, or payment help — and track your requests in one place.","ar":"احجز اجتماعًا عبر الفيديو أو الهاتف مع فريق سرايا للمساعدة في الإعداد أو القوائم أو ملف المتجر أو الاشتراك أو الدفع — وتابع حالة طلباتك في مكان واحد."},"steps":{"en":["Open the Support tab and click \"Request Support Meeting\".","Choose a reason, a meeting type (Microsoft Teams, Zoom, or phone call), and a time slot — support hours are Sunday to Thursday, 1:00–4:00 PM UAE time.","Submit the request; you'll receive a confirmation email with a calendar invite, and the team confirms your slot shortly.","Track each request's status — Pending, Confirmed, Completed, or Cancelled — under \"Your meetings\" on the same tab."],"ar":["افتح تبويب الدعم واضغط «طلب اجتماع دعم».","اختر السبب ونوع الاجتماع (مايكروسوفت تيمز أو زوم أو مكالمة هاتفية) والموعد — ساعات الدعم من الأحد إلى الخميس، 1:00–4:00 مساءً بتوقيت الإمارات.","أرسل الطلب؛ ستصلك رسالة تأكيد مع دعوة تقويم، ويؤكد الفريق موعدك قريبًا.","تابع حالة كل طلب — قيد الانتظار، مؤكد، مكتمل، أو ملغى — ضمن «اجتماعاتك» في التبويب نفسه."]},"tip":{"en":"Use a meeting for anything a quick email can't solve — onboarding walk-throughs and payment/banking setup are the most common reasons vendors book.","ar":"استخدم الاجتماع لأي أمر لا تحله رسالة سريعة — جلسات الإعداد وإعداد الدفع والحسابات البنكية هي أكثر الأسباب شيوعًا لحجز اجتماع."}},{"title":{"en":"Settings","ar":"الإعدادات"},"purpose":{"en":"Manage your account-level preferences and, if needed, request account suspension or deletion.","ar":"إدارة تفضيلات حسابك، وعند الحاجة، طلب إيقاف أو حذف الحساب."},"steps":{"en":["Switch your dashboard language between English and Arabic.","Review your account details.","Use the Danger Zone only for irreversible actions — contact sales@sarayaevents.com to request suspension or deletion of your account."],"ar":["بدّل لغة لوحة التحكم بين الإنجليزية والعربية.","راجع تفاصيل حسابك.","استخدم \"منطقة الخطر\" فقط للإجراءات التي لا يمكن التراجع عنها — تواصل مع sales@sarayaevents.com لطلب إيقاف أو حذف حسابك."]},"tip":{"en":"Most day-to-day changes (business info, bank details) belong in Store Profile, not Settings.","ar":"معظم التغييرات اليومية (معلومات النشاط، البيانات البنكية) مكانها ملف المتجر وليس الإعدادات."}}]}].map((cluster, ci) => (
                  <Section
                    key={ci}
                    title={ar ? cluster.title.ar : cluster.title.en}
                    desc={ar ? cluster.desc.ar : cluster.desc.en}
                  >
                    <div style={{ display: 'grid', gap: 16 }}>
                      {cluster.items.map((it, ii) => (
                        <div key={ii} style={{ padding: '18px 20px', borderRadius: 12, background: 'var(--cream)', border: '1px solid var(--line)' }}>
                          <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 8 }}>{ar ? it.title.ar : it.title.en}</div>
                          <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.65, marginBottom: 12 }}>{ar ? it.purpose.ar : it.purpose.en}</div>
                          <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-muted)', marginBottom: 6 }}>{ar ? 'خطوات الاستخدام' : 'How to use it'}</div>
                          <ol style={{ margin: 0, paddingInlineStart: 20, display: 'grid', gap: 5 }}>
                            {(ar ? it.steps.ar : it.steps.en).map((s, si) => (
                              <li key={si} style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>{s}</li>
                            ))}
                          </ol>
                          <div style={{ marginTop: 12, padding: '10px 14px', borderRadius: 8, background: '#FFF7ED', border: '1px solid #FED7AA', fontSize: 12, color: '#9A3412', lineHeight: 1.55 }}>
                            <strong>{ar ? 'نصيحة: ' : 'Tip: '}</strong>{ar ? it.tip.ar : it.tip.en}
                          </div>
                        </div>
                      ))}
                    </div>
                  </Section>
                ))}

                <Section
                  title={ar ? 'الشروط والاتفاقيات' : 'Terms & Agreements'}
                  desc={ar ? 'باستخدامك لهذه المنصة كبائع، فإنك توافق على الشروط التالية. يرجى مراجعتها كاملة.' : 'By operating as a vendor on this platform, you agree to the following. Please review them in full.'}
                >
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
                    <a href="#vendor-agreement" style={{ padding: '10px 16px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13.5, fontWeight: 600, color: 'var(--fg-primary)', textDecoration: 'none' }}>{ar ? 'اتفاقية البائع' : 'Vendor Agreement'} →</a>
                    <a href="#vendor-terms" style={{ padding: '10px 16px', borderRadius: 8, border: '1px solid var(--line)', fontSize: 13.5, fontWeight: 600, color: 'var(--fg-primary)', textDecoration: 'none' }}>{ar ? 'شروط البائع والأحكام' : 'Vendor Terms & Conditions'} →</a>
                  </div>
                  <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 14, lineHeight: 1.6 }}>
                    {ar
                      ? 'ملخص سريع: أنت المسؤول الوحيد عن جودة منتجاتك وخدماتك، والتسليم، والتركيب، والضمان، وخدمة ما بعد البيع. سرايا للفعاليات منصة وسيطة فقط ولا تتحمل مسؤولية النزاعات التعاقدية بين البائع والعميل.'
                      : 'Quick summary: you are solely responsible for the quality, delivery, installation, warranty, and after-sales service of your products and services. Saraya Events is an intermediary platform only and does not assume liability for contractual disputes between vendor and customer.'}
                  </p>
                </Section>

                <Section
                  title={ar ? 'تحتاج مساعدة؟' : 'Need help?'}
                  desc={ar ? 'تواصل مع فريق سرايا في أي وقت.' : 'Reach the Saraya team any time.'}
                >
                  <div style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.9 }}>
                    <div>{ar ? 'البريد الإلكتروني: ' : 'Email: '}<a href="mailto:sales@sarayaevents.com" style={{ color: 'var(--fg-primary)', fontWeight: 600 }}>sales@sarayaevents.com</a></div>
                    <div>{ar ? 'واتساب: ' : 'WhatsApp: '}<a href="https://wa.me/971529692965" target="_blank" rel="noreferrer" style={{ color: 'var(--fg-primary)', fontWeight: 600 }}>{ar ? 'تواصل عبر واتساب' : 'Message us on WhatsApp'}</a></div>
                  </div>
                  <button onClick={() => setActiveTab('support')} style={{ marginTop: 14, display: 'inline-flex', alignItems: 'center', gap: 8, padding: '11px 18px', borderRadius: 10, background: 'var(--gold)', color: 'var(--espresso)', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700, border: 'none', cursor: 'pointer' }}>
                    <Icon name="calendar-plus" size={16} />{ar ? 'طلب اجتماع دعم' : 'Request a Support Meeting'}
                  </button>
                </Section>
              </div>
            )}
          </div>{/* end main content */}
        </div>{/* end sidebar+content flex */}
      </Container>
    </main>
  );
}
window.VendorDashboardPage = VendorDashboardPage;
window.ListingFormModal = ListingFormModal;

/* -------- Vendor Complaints Tab -------- */
function VendorComplaintsTab({ db, user, ar }) {
  const [items, setItems] = useStateVD([]);
  const [loading, setLoading] = useStateVD(true);
  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const { data } = await db.from('complaints').select('id, reference, subject, description, status, complaint_type, resolution_notes, created_at, orders(reference)').order('created_at', { ascending: false });
    setItems(data || []); setLoading(false);
  }, [db, user]);
  useEffectVD(() => { load(); }, [load]);
  const STATUS = { open:{en:'Open',ar:'مفتوحة',bg:'#FEE2E2',fg:'#B91C1C'}, in_review:{en:'In review',ar:'قيد المراجعة',bg:'#FEF9C3',fg:'#A16207'}, investigating:{en:'Investigating',ar:'قيد التحقيق',bg:'#FEF9C3',fg:'#A16207'}, resolved:{en:'Resolved',ar:'محلولة',bg:'#DCFCE7',fg:'#15803D'}, closed:{en:'Closed',ar:'مغلقة',bg:'#F3F4F6',fg:'#374151'}, escalated:{en:'Escalated',ar:'مُصعّدة',bg:'#FEE2E2',fg:'#B91C1C'} };
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year:'numeric', month:'short', day:'numeric' }) : '—';
  const cardS = { background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' };
  if (loading) return <div style={{ padding: '40px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;
  if (!items.length) return <VDPlaceholder icon="alert-circle" title={ar ? 'الشكاوى' : 'Complaints'} desc={ar ? 'لا توجد شكاوى على متجرك. تظهر هنا أي نزاعات يرفعها العملاء لتتمكن من متابعتها.' : 'No complaints against your store. Any customer disputes will appear here so you can track them.'} />;
  return (
    <div style={{ display: 'grid', gap: 10 }}>
      {items.map((c) => { const m = STATUS[c.status] || { en: c.status || '—', ar: c.status || '—', bg: '#F3F4F6', fg: '#374151' }; return (
        <div key={c.id} style={cardS}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{c.subject || (ar ? 'شكوى' : 'Complaint')}</div>
              <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 3 }}>{c.reference || ''}{c.orders && c.orders.reference ? ' · ' + (ar ? 'طلب ' : 'Order ') + c.orders.reference : ''}{c.complaint_type ? ' · ' + c.complaint_type : ''} · {fmtDate(c.created_at)}</div>
            </div>
            <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: m.bg, color: m.fg }}>{ar ? m.ar : m.en}</span>
          </div>
          {c.description && <div style={{ padding: '10px 18px', fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>{c.description}</div>}
          {c.resolution_notes && (
            <div style={{ padding: '10px 18px', fontSize: 12.5, color: '#15803D', background: '#F0FDF4', borderTop: '1px solid var(--line)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <Icon name="check-circle" size={14} style={{ flexShrink: 0, marginTop: 2 }} />
              <span>{ar ? 'الحل: ' : 'Resolution: '}{c.resolution_notes}</span>
            </div>
          )}
        </div>
      ); })}
      <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', margin: '4px 0 0', display: 'flex', gap: 8, alignItems: 'flex-start', lineHeight: 1.5 }}>
        <Icon name="info" size={14} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />
        {ar ? 'للرد على شكوى أو تصعيدها، تواصل مع فريق سرايا عبر sales@sarayaevents.com.' : 'To respond to or escalate a complaint, contact the Saraya team at sales@sarayaevents.com.'}
      </p>
    </div>
  );
}

/* -------- Vendor Payouts Tab -------- */
function VendorPayoutsTab({ db, user, ar }) {
  const [orders, setOrders] = useStateVD([]);
  const [payouts, setPayouts] = useStateVD([]);
  const [loading, setLoading] = useStateVD(true);
  const [connect, setConnect] = useStateVD(null);      // Connect payout status (null until loaded)
  const [connecting, setConnecting] = useStateVD(false);
  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const [oRes, pRes] = await Promise.all([
      db.from('orders').select('id, reference, status, paid_at, total_amount, vendor_payout_amount, commission_amount, created_at').eq('vendor_id', user.id).order('created_at', { ascending: false }),
      db.from('payouts').select('id, amount, status, bank_reference, paid_at, created_at, orders(reference)').eq('vendor_id', user.id).order('created_at', { ascending: false }),
    ]);
    setOrders(oRes.data || []); setPayouts(pRes.data || []);
    const [cfgRes, vpRes] = await Promise.all([
      db.from('platform_settings').select('value').eq('key', 'connect_enabled').maybeSingle(),
      db.from('vendor_profiles').select('connect_payouts_enabled, connect_details_submitted').eq('id', user.id).maybeSingle(),
    ]);
    setConnect({ enabled: !!(cfgRes.data && String(cfgRes.data.value) === 'true'), payouts_enabled: !!(vpRes.data && vpRes.data.connect_payouts_enabled), details_submitted: !!(vpRes.data && vpRes.data.connect_details_submitted) });
    setLoading(false);
  }, [db, user]);
  useEffectVD(() => { load(); }, [load]);
  const startConnect = useCallbackVD(async () => {
    setConnecting(true);
    try {
      const { data, error } = await db.functions.invoke('connect-onboard', { body: {} });
      if (error) window.alert((ar ? 'تعذر بدء الإعداد: ' : 'Could not start payout setup: ') + String(error));
      else if (data && data.url) { window.location.href = data.url; return; }
      else if (data && data.enabled === false) window.alert(data.message || (ar ? 'غير متاح بعد' : 'Not available yet'));
    } catch (e) { window.alert('Error: ' + (e && e.message ? e.message : e)); }
    setConnecting(false);
  }, [db, ar]);
  const fmtAED = (n) => 'AED ' + Number(n || 0).toFixed(2);
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year:'numeric', month:'short', day:'numeric' }) : '—';
  const cardS = { background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' };
  const PAY_STATUS = { paid:{en:'Paid',ar:'مدفوع',bg:'#DCFCE7',fg:'#15803D'}, pending:{en:'Pending',ar:'معلق',bg:'#FEF9C3',fg:'#A16207'}, hold:{en:'On hold',ar:'محجوز',bg:'#FEE2E2',fg:'#B91C1C'}, approved:{en:'Approved',ar:'معتمد',bg:'#EFF6FF',fg:'#2563EB'} };
  if (loading) return <div style={{ padding: '40px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;
  const earning = orders.filter((o) => o.paid_at && o.status !== 'refunded' && o.status !== 'cancelled');
  const earned = earning.reduce((s, o) => s + Number(o.vendor_payout_amount || 0), 0);
  const paidOut = payouts.filter((p) => p.status === 'paid').reduce((s, p) => s + Number(p.amount || 0), 0);
  const pending = Math.max(0, earned - paidOut);
  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 12 }}>
        {[
          { icon: 'wallet',   label: ar ? 'إجمالي الأرباح' : 'Total earned',   value: fmtAED(earned) },
          { icon: 'banknote', label: ar ? 'المدفوع'         : 'Paid out',       value: fmtAED(paidOut) },
          { icon: 'clock',    label: ar ? 'المستحق المعلق'   : 'Pending payout', value: fmtAED(pending) },
        ].map((k) => (
          <div key={k.icon} style={{ padding: '14px 16px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 8 }}>
              <Icon name={k.icon} size={14} style={{ color: 'var(--gold-deep)' }} />
              <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{k.label}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, color: 'var(--gold-deep)' }}>{k.value}</div>
          </div>
        ))}
      </div>

      {connect && connect.enabled && (
        <div style={{ ...cardS, padding: '16px 18px', display: 'flex', gap: 14, alignItems: 'flex-start', flexWrap: 'wrap', borderColor: connect.payouts_enabled ? '#BBF7D0' : 'var(--gold)' }}>
          <Icon name={connect.payouts_enabled ? 'check-circle' : 'zap'} size={20} style={{ color: connect.payouts_enabled ? '#15803D' : 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>{connect.payouts_enabled ? (ar ? 'المدفوعات التلقائية مفعّلة' : 'Automatic payouts active') : (ar ? 'فعّل المدفوعات التلقائية' : 'Set up automatic payouts')}</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', marginTop: 3, lineHeight: 1.5 }}>{connect.payouts_enabled ? (ar ? 'تُحوّل أرباحك تلقائيًا إلى حسابك بعد كل طلب مدفوع.' : 'Your earnings are transferred to your account automatically after each paid order.') : (ar ? 'اربط حسابك عبر Stripe لاستلام مستحقاتك تلقائيًا بدلاً من التحويل اليدوي.' : 'Connect your payout account via Stripe to receive earnings automatically instead of manual transfers.')}</div>
          </div>
          {!connect.payouts_enabled && (
            <button onClick={startConnect} disabled={connecting} style={{ padding: '9px 18px', borderRadius: 8, border: 'none', background: 'var(--gold)', color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, cursor: 'pointer', opacity: connecting ? 0.6 : 1, whiteSpace: 'nowrap' }}>{connecting ? '…' : (connect.details_submitted ? (ar ? 'متابعة الإعداد' : 'Finish setup') : (ar ? 'ربط الحساب' : 'Connect account'))}</button>
          )}
        </div>
      )}

      <p style={{ fontSize: 12.5, color: 'var(--fg-secondary)', margin: 0, display: 'flex', alignItems: 'flex-start', gap: 8, lineHeight: 1.5 }}>
        <Icon name="info" size={14} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />
        {ar ? 'تُصرف مستحقاتك بعد تأكيد العميل للتسليم أو انتهاء فترة النزاع. تأكد من صحة بيانات الآيبان في ملف المتجر.' : 'Payouts are released after the customer confirms delivery or the dispute window closes. Make sure your IBAN in Store Profile is correct.'}
      </p>

      <div style={cardS}>
        <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--line)', fontSize: 13, fontWeight: 700 }}>{ar ? 'سجل المدفوعات' : 'Payout history'}</div>
        {payouts.length === 0 ? (
          <div style={{ padding: '20px 18px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>{ar ? 'لا توجد مدفوعات بعد.' : 'No payouts recorded yet.'}</div>
        ) : payouts.map((p) => { const m = PAY_STATUS[p.status] || { en: p.status, ar: p.status, bg: '#F3F4F6', fg: '#374151' }; return (
          <div key={p.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '12px 18px', borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13.5 }}>{fmtAED(p.amount)}{p.orders && p.orders.reference ? <span style={{ color: 'var(--fg-muted)', fontWeight: 400 }}> · {p.orders.reference}</span> : null}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>{fmtDate(p.paid_at || p.created_at)}{p.bank_reference ? ' · ' + p.bank_reference : ''}</div>
            </div>
            <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: m.bg, color: m.fg }}>{ar ? m.ar : m.en}</span>
          </div>
        ); })}
      </div>

      <div style={cardS}>
        <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--line)', fontSize: 13, fontWeight: 700 }}>{ar ? 'الأرباح حسب الطلب' : 'Earnings by order'}</div>
        {earning.length === 0 ? (
          <div style={{ padding: '20px 18px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>{ar ? 'لا توجد أرباح بعد.' : 'No earnings yet.'}</div>
        ) : earning.map((o) => (
          <div key={o.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '12px 18px', borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13.5 }}>{o.reference}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>{fmtDate(o.paid_at)} · {ar ? 'إجمالي' : 'Total'} {fmtAED(o.total_amount)} · {ar ? 'عمولة' : 'Commission'} {fmtAED(o.commission_amount)}</div>
            </div>
            <span style={{ fontWeight: 700, fontSize: 14, color: 'var(--gold-deep)' }}>{fmtAED(o.vendor_payout_amount)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* -------- Vendor Leads Tab -------- */
function VendorLeadsTab({ db, user, ar }) {
  const [leads, setLeads] = useStateVD([]);
  const [loading, setLoading] = useStateVD(true);
  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const { data } = await db.from('lead_assignments').select('id, status, assigned_at, leads(id, name, phone, email, service, budget, event_date, message, source, created_at, lead_type)').eq('vendor_id', user.id).order('assigned_at', { ascending: false });
    setLeads((data || []).map((a) => Object.assign({}, a.leads || {}, { assignmentId: a.id, status: a.status, assigned_at: a.assigned_at })));
    setLoading(false);
  }, [db, user]);
  useEffectVD(() => { load(); }, [load]);
  const STATUS = { new:{en:'New',ar:'جديد',bg:'#EFF6FF',fg:'#2563EB'}, contacted:{en:'Contacted',ar:'تم التواصل',bg:'#FEF9C3',fg:'#A16207'}, quoted:{en:'Quoted',ar:'تم التسعير',bg:'#EFF6FF',fg:'#2563EB'}, won:{en:'Won',ar:'مكسوب',bg:'#DCFCE7',fg:'#15803D'}, lost:{en:'Lost',ar:'مفقود',bg:'#FEE2E2',fg:'#B91C1C'}, closed:{en:'Closed',ar:'مغلق',bg:'#F3F4F6',fg:'#374151'} };
  const setStatus = async (assignmentId, st) => {
    await db.from('lead_assignments').update({ status: st }).eq('id', assignmentId);
    setLeads((prev) => prev.map((l) => l.assignmentId === assignmentId ? { ...l, status: st } : l));
  };
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year:'numeric', month:'short', day:'numeric' }) : '—';
  const cardS = { background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' };
  if (loading) return <div style={{ padding: '40px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;
  if (!leads.length) return <VDPlaceholder icon="inbox" title={ar ? 'العملاء المحتملون' : 'Leads'} desc={ar ? 'لا يوجد عملاء محتملون مُسنَدون إليك بعد. يقوم فريق سرايا بإسناد الاستفسارات المطابقة لمتجرك.' : 'No leads assigned to you yet. Saraya staff assign inquiries that match your store.'} />;
  return (
    <div style={{ display: 'grid', gap: 10 }}>
      {leads.map((l) => { const m = STATUS[l.status] || STATUS.new; return (
        <div key={l.id} style={cardS}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{l.name || '—'}</div>
              <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 3, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                {l.phone && <a href={'tel:' + l.phone} style={{ color: 'var(--gold-deep)', textDecoration: 'none' }}>{l.phone}</a>}
                {l.email && <a href={'mailto:' + l.email} style={{ color: 'var(--gold-deep)', textDecoration: 'none' }}>{l.email}</a>}
                <span>{fmtDate(l.assigned_at || l.created_at)}</span>
              </div>
            </div>
            <select value={l.status || 'new'} onChange={(e) => setStatus(l.assignmentId, e.target.value)} style={{ fontSize: 12.5, padding: '4px 10px', borderRadius: 8, border: '1.5px solid var(--line-strong)', background: m.bg, color: m.fg, fontWeight: 600, cursor: 'pointer' }}>
              {Object.keys(STATUS).map((k) => <option key={k} value={k}>{ar ? STATUS[k].ar : STATUS[k].en}</option>)}
            </select>
          </div>
          {(l.service || l.budget || l.event_date) && (
            <div style={{ padding: '8px 18px', fontSize: 12.5, color: 'var(--fg-secondary)', display: 'flex', gap: 16, flexWrap: 'wrap', borderBottom: l.message ? '1px solid var(--line)' : 'none' }}>
              {l.service && <span>{ar ? 'الخدمة: ' : 'Service: '}{l.service}</span>}
              {l.budget && <span>{ar ? 'الميزانية: ' : 'Budget: '}{l.budget}</span>}
              {l.event_date && <span>{ar ? 'التاريخ: ' : 'Event: '}{fmtDate(l.event_date)}</span>}
            </div>
          )}
          {l.message && <div style={{ padding: '10px 18px', fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>{l.message}</div>}
        </div>
      ); })}
    </div>
  );
}

/* -------- Vendor Activation Checklist -------- */
function VendorActivationChecklist({ db, vendorId, ar, refreshKey, go, agreementSigned, hasListing }) {
  const [st, setSt] = useStateVD(null);
  useEffectVD(() => { (async () => {
    if (!db || !vendorId) return;
    const { data } = await db.rpc('vendor_activation_status', { vid: vendorId });
    setSt(data || null);
  })(); }, [db, vendorId, refreshKey]);
  if (!st) return null;
  const ITEMS = [
    { key: 'trade_license_number', en: 'Trade license number', ar: 'رقم الرخصة التجارية' },
    { key: 'trade_license_expiry', en: 'Trade license expiry',  ar: 'تاريخ انتهاء الرخصة' },
    { key: 'trade_license_doc',    en: 'Trade license document', ar: 'مستند الرخصة التجارية' },
    { key: 'id_doc',               en: 'Emirates ID document',   ar: 'مستند الهوية الإماراتية' },
    { key: 'bank_name',            en: 'Bank name',              ar: 'اسم البنك' },
    { key: 'bank_iban',            en: 'Bank IBAN',              ar: 'رقم الآيبان (IBAN)' },
    { key: 'bank_account_name',    en: 'Account holder name',    ar: 'اسم صاحب الحساب' },
    { key: 'iban_doc',             en: 'IBAN / bank-letter document', ar: 'مستند خطاب البنك / الآيبان' },
  ];
  // tab each KYC item routes to
  const TAB_FOR = {
    trade_license_number: 'profile', trade_license_expiry: 'profile',
    trade_license_doc: 'documents', id_doc: 'documents', iban_doc: 'documents',
    bank_name: 'documents', bank_iban: 'documents', bank_account_name: 'documents',
  };
  const steps = [
    ...ITEMS.map((i) => ({ ...i, done: !!st[i.key], tab: TAB_FOR[i.key] || 'profile' })),
    { key: '_agreement', en: 'Sign the vendor agreement', ar: 'توقيع اتفاقية المورّد', done: !!agreementSigned, tab: 'profile' },
    { key: '_listing',   en: 'Add your first listing',    ar: 'أضف أول منتج/خدمة',      done: !!hasListing,      tab: 'listings' },
  ];
  const total = steps.length;
  const done  = steps.filter((s) => s.done).length;
  const firstIncomplete = steps.find((s) => !s.done);
  const nav = (tab) => { if (typeof go === 'function') go(tab); };

  if (done === total) {
    return (
      <div style={{ marginBottom: 20, borderRadius: 14, padding: '14px 20px', background: '#F0FDF4', border: '1px solid #BBF7D0', display: 'flex', alignItems: 'center', gap: 10 }}>
        <Icon name="shield-check" size={20} style={{ color: '#16A34A', flexShrink: 0 }} />
        <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--fg-primary)' }}>{ar ? 'اكتمل التحقق — جاهز للتفعيل' : 'Verification complete — ready for activation'}</div>
      </div>
    );
  }
  return (
    <div style={{ marginBottom: 20, borderRadius: 14, padding: '16px 20px', background: '#FFFBEB', border: '1px solid #FDE68A' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Icon name="clipboard-check" size={20} style={{ color: '#D97706', flexShrink: 0 }} />
        <div style={{ fontWeight: 700, fontSize: 14 }}>{ar ? 'أكمل بيانات تفعيل متجرك' : 'Complete your store activation'}</div>
        <span style={{ marginInlineStart: 'auto', fontSize: 12.5, color: 'var(--fg-muted)', fontWeight: 700 }}>{done}/{total}{ar ? ' مكتمل' : ' complete'}</span>
      </div>
      <p style={{ fontSize: 12.5, color: 'var(--fg-secondary)', margin: '0 0 10px', lineHeight: 1.5 }}>{ar ? 'هذه البيانات مطلوبة لتفعيل متجرك. تُستخدم التفاصيل البنكية لتحويل مستحقاتك. اضغط على أي خطوة للانتقال إليها.' : 'These are required to activate your store. Your bank details are used to settle your payouts. Tap any step to jump to where you fix it.'}</p>
      {/* progress bar */}
      <div style={{ height: 6, borderRadius: 99, background: '#FDE68A', overflow: 'hidden', marginBottom: 12 }}>
        <div style={{ width: (done / total * 100) + '%', height: '100%', background: 'var(--gold)', borderRadius: 99, transition: 'width 220ms' }} />
      </div>
      <div style={{ display: 'grid', gap: 2 }}>
        {steps.map((step) => (
          <button key={step.key} type="button" onClick={() => nav(step.tab)} disabled={step.done}
            style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: ar ? 'right' : 'left',
              background: 'none', border: 'none', cursor: step.done ? 'default' : 'pointer', padding: '8px 4px',
              fontFamily: 'var(--font-body)', fontSize: 13, color: step.done ? 'var(--fg-muted)' : 'var(--fg-primary)' }}>
            <Icon name={step.done ? 'check-circle' : 'circle'} size={16}
              style={{ color: step.done ? '#16A34A' : 'var(--gold-deep)', flexShrink: 0 }} />
            <span style={{ textDecoration: step.done ? 'line-through' : 'none' }}>{ar ? step.ar : step.en}</span>
            {!step.done && <Icon name={ar ? 'chevron-left' : 'chevron-right'} size={14} style={{ marginInlineStart: 'auto', color: 'var(--fg-muted)' }} />}
          </button>
        ))}
      </div>
      {firstIncomplete && (
        <button type="button" onClick={() => nav(firstIncomplete.tab)}
          style={{ marginTop: 12, background: 'var(--gold)', color: 'var(--white)', border: 'none', borderRadius: 10,
            padding: '10px 18px', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>
          {ar ? 'الخطوة التالية: ' : 'Next step: '}{ar ? firstIncomplete.ar : firstIncomplete.en}
        </button>
      )}
    </div>
  );
}

/* -------- Vendor Bookings Tab -------- */
function VendorBookingsTab({ db, user, ar }) {
  const [items, setItems]   = useStateVD([]);
  const [loading, setLoading] = useStateVD(true);
  const [filter, setFilter] = useStateVD('upcoming');

  const fmtDate = (d) => d ? new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' }) : '—';
  const nm = (o) => o ? (ar ? (o.name_ar || o.name_en) : (o.name_en || o.name_ar)) : (ar ? 'عنصر' : 'Item');
  const custOf = (o) => o ? {
    name: o.guest_name || (o.profiles && o.profiles.display_name) || (ar ? 'عميل' : 'Customer'),
    phone: o.guest_phone || (o.profiles && o.profiles.phone) || '',
    email: o.guest_email || '',
    address: (o.delivery_address && (o.delivery_address.address || o.delivery_address.emirate)) ? [o.delivery_address.address, o.delivery_address.emirate].filter(Boolean).join(', ') : '',
  } : { name: ar ? 'عميل' : 'Customer', phone: '', email: '', address: '' };

  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const [rbRes, sbRes] = await Promise.all([
      db.from('rental_bookings').select('id, start_date, end_date, deposit_amount, deposit_paid, notes, rentals(name_en, name_ar), orders!inner(reference, status, guest_name, guest_email, guest_phone, delivery_address, created_at, vendor_id, profiles!customer_id(display_name, phone))').eq('orders.vendor_id', user.id),
      db.from('service_bookings').select('id, event_date, event_time, guest_count, venue, notes, services(name_en, name_ar), orders!inner(reference, status, guest_name, guest_email, guest_phone, delivery_address, created_at, vendor_id, profiles!customer_id(display_name, phone))').eq('orders.vendor_id', user.id),
    ]);
    const rentals  = (rbRes.data || []).map((r) => ({ id: 'r-' + r.id, kind: 'rental',  name: nm(r.rentals),  order: r.orders, cust: custOf(r.orders), start: r.start_date, end: r.end_date, sort: r.start_date, deposit: r.deposit_amount, depositPaid: r.deposit_paid, notes: r.notes }));
    const services = (sbRes.data || []).map((s) => ({ id: 's-' + s.id, kind: 'service', name: nm(s.services), order: s.orders, cust: custOf(s.orders), start: s.event_date, end: null,        sort: s.event_date, time: s.event_time, guests: s.guest_count, venue: s.venue, notes: s.notes }));
    setItems(rentals.concat(services).sort((a, b) => (a.sort || '').localeCompare(b.sort || '')));
    setLoading(false);
  }, [db, user]);

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

  const today = new Date().toISOString().slice(0, 10);
  const isUpcoming = (x) => (x.end || x.start || '') >= today;
  const filtered = filter === 'all' ? items : filter === 'upcoming' ? items.filter(isUpcoming) : items.filter((x) => !isUpcoming(x));

  const FILTER_TABS = [
    { id: 'upcoming', label: ar ? 'القادمة' : 'Upcoming' },
    { id: 'past',     label: ar ? 'السابقة' : 'Past' },
    { id: 'all',      label: ar ? 'الكل'    : 'All' },
  ];
  const STATUS = { processing:{en:'Processing',ar:'قيد المعالجة',bg:'#EFF6FF',fg:'#2563EB'}, pending:{en:'Pending',ar:'في الانتظار',bg:'#FEF9C3',fg:'#A16207'}, paid:{en:'Paid',ar:'مدفوع',bg:'#DCFCE7',fg:'#15803D'}, confirmed:{en:'Confirmed',ar:'مؤكد',bg:'#DCFCE7',fg:'#15803D'}, prep:{en:'Preparing',ar:'قيد التحضير',bg:'#EFF6FF',fg:'#2563EB'}, done:{en:'Completed',ar:'مكتمل',bg:'#DCFCE7',fg:'#15803D'}, cancelled:{en:'Cancelled',ar:'ملغى',bg:'#FEE2E2',fg:'#B91C1C'}, refunded:{en:'Refunded',ar:'مسترد',bg:'#FEE2E2',fg:'#B91C1C'} };
  const sBadge = (s) => { const m = STATUS[s] || { en: s || '—', ar: s || '—', bg: '#F3F4F6', fg: '#374151' }; return { label: ar ? m.ar : m.en, bg: m.bg, fg: m.fg }; };
  const cardS = { background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' };

  if (loading) return <div style={{ padding: '40px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 12 }}>
        {[
          { icon: 'calendar', label: ar ? 'إجمالي الحجوزات' : 'Total Bookings', value: items.length },
          { icon: 'clock',    label: ar ? 'القادمة'         : 'Upcoming',       value: items.filter(isUpcoming).length },
          { icon: 'package',  label: ar ? 'الإيجارات'        : 'Rentals',        value: items.filter((x) => x.kind === 'rental').length },
          { icon: 'sparkles', label: ar ? 'الخدمات'          : 'Services',       value: items.filter((x) => x.kind === 'service').length },
        ].map((kpi) => (
          <div key={kpi.icon} style={{ padding: '14px 16px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 8 }}>
              <Icon name={kpi.icon} size={14} style={{ color: 'var(--gold-deep)' }} />
              <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{kpi.label}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>{kpi.value}</div>
          </div>
        ))}
      </div>

      {/* Filter tabs */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {FILTER_TABS.map((t) => (
          <button key={t.id} onClick={() => setFilter(t.id)} style={{ padding: '6px 14px', borderRadius: 8, border: '1.5px solid ' + (filter === t.id ? 'var(--gold)' : 'var(--line)'), background: filter === t.id ? 'var(--gold-tint)' : 'var(--white)', color: filter === t.id ? 'var(--gold-deep)' : 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: filter === t.id ? 700 : 400, cursor: 'pointer' }}>
            {t.label}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div style={{ ...cardS, textAlign: 'center', padding: '48px 24px', color: 'var(--fg-muted)' }}>
          <Icon name="calendar" size={40} stroke={1} />
          <p style={{ marginTop: 12, fontSize: 14 }}>{ar ? 'لا توجد حجوزات' : 'No bookings'}</p>
        </div>
      ) : (
        <div style={{ display: 'grid', gap: 10 }}>
          {filtered.map((x) => {
            const b = sBadge(x.order && x.order.status);
            const dateStr = x.kind === 'rental' ? (fmtDate(x.start) + ' → ' + fmtDate(x.end)) : (fmtDate(x.start) + (x.time ? ' · ' + x.time : ''));
            return (
              <div key={x.id} style={cardS}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                      <span style={{ padding: '2px 8px', borderRadius: 6, fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', background: x.kind === 'rental' ? '#EEF2FF' : '#FDF2F8', color: x.kind === 'rental' ? '#4338CA' : '#BE185D' }}>{x.kind === 'rental' ? (ar ? 'إيجار' : 'Rental') : (ar ? 'خدمة' : 'Service')}</span>
                      <span style={{ fontWeight: 700, fontSize: 14 }}>{x.name}</span>
                    </div>
                    <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 4 }}>
                      {(x.order && x.order.reference) || '—'}
                    </div>
                  </div>
                  <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</span>
                </div>
                <div style={{ padding: '10px 18px', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <Icon name="calendar" size={14} style={{ color: 'var(--gold-deep)' }} />
                  <span style={{ fontSize: 13.5, fontWeight: 600 }}>{dateStr}</span>
                  {x.kind === 'service' && x.guests ? <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>· {x.guests} {ar ? 'ضيف' : 'guests'}</span> : null}
                  {x.kind === 'service' && x.venue ? <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>· {x.venue}</span> : null}
                  {x.kind === 'rental' && x.deposit ? <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>· {ar ? 'تأمين' : 'Deposit'} AED {Number(x.deposit).toFixed(2)}{x.depositPaid ? (ar ? ' (مدفوع)' : ' (paid)') : ''}</span> : null}
                </div>
                <div style={{ padding: '2px 18px 12px', display: 'grid', gap: 5, fontSize: 12.5, color: 'var(--fg-secondary)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="user" size={13} style={{ color: 'var(--fg-muted)' }} /><span style={{ fontWeight: 600 }}>{x.cust.name}</span></div>
                  {x.cust.phone ? <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="phone" size={13} style={{ color: 'var(--fg-muted)' }} /><a href={'tel:' + x.cust.phone} style={{ color: 'var(--gold-deep)', textDecoration: 'none' }}>{x.cust.phone}</a></div> : null}
                  {x.cust.email ? <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="mail" size={13} style={{ color: 'var(--fg-muted)' }} /><a href={'mailto:' + x.cust.email} style={{ color: 'var(--gold-deep)', textDecoration: 'none' }}>{x.cust.email}</a></div> : null}
                  {x.cust.address ? <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="map-pin" size={13} style={{ color: 'var(--fg-muted)' }} /><span>{x.cust.address}</span></div> : null}
                </div>
                {x.notes ? <div style={{ padding: '0 18px 12px', fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.5 }}>{x.notes}</div> : null}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* -------- Vendor Orders Tab -------- */
function VendorOrdersTab({ db, user, ar }) {
  const [orders,  setOrders]  = useStateVD([]);
  const [loading, setLoading] = useStateVD(true);
  const [sel,     setSel]     = useStateVD(null);
  const [updating, setUpdating] = useStateVD(null);
  const [filter,  setFilter]  = useStateVD('all');
  const [refundMsg, setRefundMsg] = useStateVD(null);
  const [delivering, setDelivering] = useStateVD(null);
  const [deliverMsg, setDeliverMsg] = useStateVD(null);

  const applyItemDelivery = (orderId, itemId, digital_delivery, delivered_at) => {
    const patch = (o) => (o && o.id === orderId)
      ? { ...o, order_items: (o.order_items || []).map((x) => x.id === itemId ? { ...x, digital_delivery, delivered_at } : x) }
      : o;
    setOrders((prev) => prev.map(patch));
    setSel((p) => patch(p));
  };

  const deliverDigital = async (order, item, file) => {
    if (!file) return;
    if (!window.SarayaService || !window.SarayaService.storage || !window.SarayaService.storage.uploadDigitalFile) { setDeliverMsg({ itemId: item.id, ok: false, text: ar ? 'خدمة التخزين غير متاحة.' : 'Storage service unavailable.' }); return; }
    if (file.size > 50 * 1024 * 1024) { setDeliverMsg({ itemId: item.id, ok: false, text: ar ? 'الحد الأقصى لحجم الملف 50 ميغابايت.' : 'Max file size is 50 MB.' }); return; }
    setDelivering(item.id); setDeliverMsg(null);
    try {
      const up = await window.SarayaService.storage.uploadDigitalFile(user.id, order.id, file);
      if (up.error) { setDeliverMsg({ itemId: item.id, ok: false, text: up.error }); setDelivering(null); return; }
      const { data: sess } = await db.auth.getSession();
      const token = sess && sess.session && sess.session.access_token;
      const resp = await fetch('https://mnnmxlavssernihgkpfv.supabase.co/functions/v1/digital-deliver', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
        body: JSON.stringify({ order_item_id: item.id, file: { path: up.path, name: up.name, type: up.type, size: up.size } }),
      });
      const j = await resp.json().catch(() => ({}));
      if (!resp.ok || !j.ok) { setDeliverMsg({ itemId: item.id, ok: false, text: j.error || (ar ? 'فشل التسليم.' : 'Delivery failed.') }); setDelivering(null); return; }
      applyItemDelivery(order.id, item.id, j.file, j.delivered_at);
      setDeliverMsg({ itemId: item.id, ok: true, text: ar ? 'تم تسليم الملف للعميل.' : 'File delivered to the customer.' });
    } catch (e) {
      setDeliverMsg({ itemId: item.id, ok: false, text: (ar ? 'خطأ: ' : 'Error: ') + (e.message || e) });
    }
    setDelivering(null);
  };

  const pickAndDeliver = (order, item) => {
    const input = document.createElement('input');
    input.type = 'file'; input.accept = '.pdf,.png,.jpg,.jpeg,.zip,.docx,.pptx,.xlsx,.ai,.psd,.svg';
    input.style.position = 'fixed'; input.style.left = '-9999px';
    input.onchange = () => { const f = input.files && input.files[0]; input.remove(); if (f) deliverDigital(order, item, f); };
    document.body.appendChild(input); input.click();
  };

  const VENDOR_STATUSES = ['processing','pending','confirmed','prep','out','done','cancelled'];
  const STATUS_LABELS = {
    processing: { en: 'Processing', ar: 'قيد المعالجة', bg: '#EFF6FF', fg: '#2563EB' },
    pending:    { en: 'Pending',    ar: 'في الانتظار',  bg: '#FEF9C3', fg: '#A16207' },
    paid:       { en: 'Paid',       ar: 'تم الدفع',     bg: '#DCFCE7', fg: '#15803D' },
    confirmed:  { en: 'Confirmed',  ar: 'مؤكد',         bg: '#DCFCE7', fg: '#15803D' },
    prep:       { en: 'Preparing',  ar: 'قيد التحضير',  bg: '#EFF6FF', fg: '#2563EB' },
    out:        { en: 'Out for Delivery', ar: 'خارج للتوصيل', bg: '#DBEAFE', fg: '#1D4ED8' },
    done:       { en: 'Delivered',  ar: 'مكتمل',        bg: '#DCFCE7', fg: '#15803D' },
    cancelled:  { en: 'Cancelled',  ar: 'ملغى',         bg: '#FEE2E2', fg: '#B91C1C' },
    refunded:   { en: 'Refunded',   ar: 'مسترد',        bg: '#FEE2E2', fg: '#B91C1C' },
  };
  const badge = (status) => {
    const m = STATUS_LABELS[status] || { en: status, ar: status, bg: '#F3F4F6', fg: '#374151' };
    return { label: ar ? m.ar : m.en, bg: m.bg, fg: m.fg };
  };
  // Payment state is derived from paid_at / refund — NEVER overwritten by fulfilment.
  const payBadge = (o) => (o && o.status === 'refunded')
    ? { label: ar ? 'مسترد' : 'Refunded', bg: '#FEE2E2', fg: '#B91C1C' }
    : (o && o.paid_at ? { label: ar ? 'مدفوع' : 'Paid', bg: '#DCFCE7', fg: '#15803D' } : { label: ar ? 'غير مدفوع' : 'Unpaid', bg: '#F3F4F6', fg: '#6B7280' });
  const fmtAED  = (n) => 'AED ' + Number(n || 0).toFixed(2);
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' }) : '—';
  const custName = (o) => (o && (o.guest_name || (o.profiles && o.profiles.display_name))) || '—';
  const custPhone = (o) => (o && (o.guest_phone || (o.profiles && o.profiles.phone))) || '';
  const custAddr = (o) => (o && o.delivery_address && (o.delivery_address.address || o.delivery_address.emirate)) ? [o.delivery_address.address, o.delivery_address.emirate].filter(Boolean).join(', ') : '';

  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const { data } = await db
      .from('orders')
      .select('id, reference, type, status, paid_at, total_amount, created_at, customer_confirmed_at, notes, delivery_address, guest_name, guest_email, guest_phone, profiles!customer_id(display_name, phone), order_items(id, product_id, name_en, name_ar, unit_price, quantity, line_total, digital_delivery, delivered_at, products!product_id(is_digital, meta))')
      .eq('vendor_id', user.id)
      .order('created_at', { ascending: false });
    const list = data || [];
    const ids = list.map((o) => o.id);
    if (ids.length) {
      const [rb, sb] = await Promise.all([
        db.from('rental_bookings').select('order_id, start_date, end_date').in('order_id', ids),
        db.from('service_bookings').select('order_id, event_date, event_time, guest_count, venue').in('order_id', ids),
      ]);
      const bmap = {};
      (rb.data || []).forEach((r) => { bmap[r.order_id] = { kind: 'rental', start: r.start_date, end: r.end_date }; });
      (sb.data || []).forEach((s) => { bmap[s.order_id] = { kind: 'service', start: s.event_date, time: s.event_time, guests: s.guest_count, venue: s.venue }; });
      list.forEach((o) => { o.booking = bmap[o.id] || null; });
    }
    setOrders(list);
    setLoading(false);
  }, [db, user]);

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

  const updateStatus = async (orderId, newStatus) => {
    setUpdating(orderId);
    await db.from('orders').update({ status: newStatus }).eq('id', orderId);
    setOrders((prev) => prev.map((o) => o.id === orderId ? { ...o, status: newStatus } : o));
    setSel((p) => p && p.id === orderId ? { ...p, status: newStatus } : p);
    setUpdating(null);
  };

  const doRefund = async (o) => {
    if (!window.refundOrder) return;
    if (!window.confirm(ar ? 'استرداد كامل المبلغ لهذا الطلب؟ لا يمكن التراجع.' : 'Refund the full amount for this order? This cannot be undone.')) return;
    setUpdating(o.id); setRefundMsg(null);
    try {
      const r = await window.refundOrder({ orderId: o.id });
      setOrders((prev) => prev.map((x) => x.id === o.id ? { ...x, status: r.full ? 'refunded' : x.status } : x));
      setSel((p) => p && p.id === o.id ? { ...p, status: r.full ? 'refunded' : p.status } : p);
      setRefundMsg({ ok: true, text: (ar ? 'تم الاسترداد: AED ' : 'Refunded AED ') + Number(r.amount).toFixed(2) });
    } catch (e) { setRefundMsg({ ok: false, text: (ar ? 'فشل الاسترداد: ' : 'Refund failed: ') + e.message }); }
    setUpdating(null);
  };

  const filtered = filter === 'all' ? orders : orders.filter((o) => o.status === filter);

  const FILTER_TABS = [
    { id: 'all',       label: ar ? 'الكل' : 'All' },
    { id: 'pending',   label: ar ? 'معلقة' : 'Pending' },
    { id: 'confirmed', label: ar ? 'مؤكدة' : 'Confirmed' },
    { id: 'prep',      label: ar ? 'قيد التحضير' : 'Preparing' },
    { id: 'out',       label: ar ? 'خارج للتوصيل' : 'Out' },
    { id: 'done',      label: ar ? 'مكتملة' : 'Done' },
  ];

  const NEXT_ACTIONS = {
    paid:       [{ status: 'confirmed', label: ar ? 'قبول الطلب' : 'Accept Order' }, { status: 'cancelled', label: ar ? 'رفض' : 'Reject' }],
    processing: [{ status: 'confirmed', label: ar ? 'قبول الطلب' : 'Accept Order' }],
    pending:    [{ status: 'confirmed', label: ar ? 'قبول الطلب' : 'Accept Order' }, { status: 'cancelled', label: ar ? 'رفض' : 'Reject' }],
    confirmed:  [{ status: 'prep',      label: ar ? 'بدء التحضير' : 'Start Prep' }],
    prep:       [{ status: 'out',       label: ar ? 'تم الإرسال'  : 'Mark Shipped' }],
    out:        [],
    done:       [],
    cancelled:  [],
  };

  if (loading) return <div style={{ padding: '40px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;

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

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 12 }}>
        {[
          { icon: 'inbox',        label: ar ? 'إجمالي الطلبات' : 'Total Orders', value: orders.length },
          { icon: 'clock',        label: ar ? 'معلقة'           : 'Pending',      value: orders.filter((o) => ['processing','pending','paid'].includes(o.status)).length },
          { icon: 'check-circle', label: ar ? 'مؤكدة'           : 'Confirmed',    value: orders.filter((o) => o.status === 'confirmed').length },
          { icon: 'truck',        label: ar ? 'مكتملة'          : 'Delivered',    value: orders.filter((o) => o.status === 'done').length },
        ].map((kpi) => (
          <div key={kpi.icon} style={{ padding: '14px 16px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 8 }}>
              <Icon name={kpi.icon} size={14} style={{ color: 'var(--gold-deep)' }} />
              <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{kpi.label}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500 }}>{kpi.value}</div>
          </div>
        ))}
      </div>

      {/* Filter tabs */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {FILTER_TABS.map((t) => (
          <button key={t.id} onClick={() => setFilter(t.id)} style={{ padding: '6px 14px', borderRadius: 8, border: '1.5px solid ' + (filter === t.id ? 'var(--gold)' : 'var(--line)'), background: filter === t.id ? 'var(--gold-tint)' : 'var(--white)', color: filter === t.id ? 'var(--gold-deep)' : 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: filter === t.id ? 700 : 400, cursor: 'pointer' }}>
            {t.label}
          </button>
        ))}
      </div>

      {!sel ? (
        filtered.length === 0 ? (
          <div style={{ ...cardS, textAlign: 'center', padding: '48px 24px', color: 'var(--fg-muted)' }}>
            <Icon name="shopping-bag" size={40} stroke={1} />
            <p style={{ marginTop: 12, fontSize: 14 }}>{ar ? 'لا توجد طلبات' : 'No orders yet'}</p>
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 10 }}>
            {filtered.map((o) => {
              const b = badge(o.status);
              const pb = payBadge(o);
              const cust = o.profiles;
              const items = o.order_items || [];
              const actions = NEXT_ACTIONS[o.status] || [];
              return (
                <div key={o.id} style={cardS}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{o.reference || '#' + o.id.slice(0,8).toUpperCase()}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 2 }}>
                        {fmtDate(o.created_at)} · {custName(o)}
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: pb.bg, color: pb.fg }}>{pb.label}</span>
                      <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</span>
                      <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--gold-deep)' }}>{fmtAED(o.total_amount)}</span>
                    </div>
                  </div>
                  <div style={{ padding: '10px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
                    <div style={{ fontSize: 13, color: 'var(--fg-secondary)' }}>
                      {items.slice(0, 2).map((it, i) => (
                        <span key={it.id}>{ar ? (it.name_ar || it.name_en) : it.name_en} × {it.quantity}{i < Math.min(items.length, 2) - 1 ? ', ' : ''}</span>
                      ))}
                      {items.length > 2 && <span style={{ color: 'var(--fg-muted)' }}> +{items.length - 2} {ar ? 'أخرى' : 'more'}</span>}
                    </div>
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                      {actions.map((a) => (
                        <button key={a.status} onClick={() => updateStatus(o.id, a.status)} disabled={updating === o.id}
                          style={{ padding: '6px 14px', borderRadius: 8, border: 'none', background: a.status === 'cancelled' ? '#FEE2E2' : 'var(--gold)', color: a.status === 'cancelled' ? '#B91C1C' : '#fff', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', opacity: updating === o.id ? 0.6 : 1 }}>
                          {updating === o.id ? '…' : a.label}
                        </button>
                      ))}
                      <button onClick={() => setSel(o)} style={{ padding: '6px 14px', borderRadius: 8, border: '1.5px solid var(--line-strong)', background: 'transparent', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 500, color: 'var(--fg-primary)' }}>
                        {ar ? 'عرض' : 'Details'}
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )
      ) : (
        <div>
          <button onClick={() => setSel(null)} style={backBtn}>
            <Icon name={ar ? 'arrow-right' : 'arrow-left'} size={14} />
            {ar ? 'الطلبات' : 'Orders'}
          </button>
          <div style={cardS}>
            <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
              <div>
                <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, margin: '0 0 4px' }}>{sel.reference || '#' + sel.id.slice(0,8).toUpperCase()}</h3>
                <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{fmtDate(sel.created_at)} · {custName(sel)}</div>
              </div>
              {(() => { const b = badge(sel.status), pb = payBadge(sel); return <span style={{ display: 'inline-flex', gap: 8, flexWrap: 'wrap' }}><span style={{ padding: '6px 16px', borderRadius: 20, fontSize: 13, fontWeight: 600, background: pb.bg, color: pb.fg }}>{pb.label}</span><span style={{ padding: '6px 16px', borderRadius: 20, fontSize: 13, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</span></span>; })()}
            </div>

            {/* Items */}
            <div style={{ padding: '0 22px' }}>
              <div style={{ padding: '14px 0 8px', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)' }}>{ar ? 'المنتجات' : 'Items'}</div>
              {(sel.order_items || []).map((it) => {
                const dig = !!(it.products && it.products.is_digital);
                const custom = !!(dig && it.digital_delivery && it.digital_delivery.path);
                const stdFile = !!(dig && it.products.meta && it.products.meta.digital_file && it.products.meta.digital_file.path);
                const dm = deliverMsg && deliverMsg.itemId === it.id ? deliverMsg : null;
                return (
                <div key={it.id} style={{ borderTop: '1px solid var(--line)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', gap: 12 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{ar ? (it.name_ar || it.name_en) : it.name_en}{dig && <span style={{ marginInlineStart: 8, fontSize: 10.5, fontWeight: 700, color: 'var(--gold-deep)', background: 'var(--gold-tint)', padding: '2px 8px', borderRadius: 999, verticalAlign: 'middle' }}>{ar ? 'رقمي' : 'DIGITAL'}</span>}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 2 }}>{ar ? 'الكمية' : 'Qty'}: {it.quantity} · {fmtAED(it.unit_price)} {ar ? 'للوحدة' : 'each'}</div>
                    </div>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>{fmtAED(it.line_total)}</div>
                  </div>
                  {dig && (
                    <div style={{ margin: '0 0 12px', padding: '10px 12px', background: '#FAF7EF', border: '1px solid var(--line)', borderRadius: 10 }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--fg-secondary)', flex: 1, minWidth: 200 }}>
                          <Icon name={custom ? 'check-circle' : (stdFile ? 'file' : 'clock')} size={15} style={{ color: custom ? '#15803D' : (stdFile ? 'var(--gold-deep)' : '#A16207'), flexShrink: 0 }} />
                          <span>{custom
                            ? (ar ? 'تم تسليم ملف مخصّص لهذا الطلب' : 'Custom file delivered for this order') + (it.delivered_at ? ' · ' + fmtDate(it.delivered_at) : '') + (it.digital_delivery.name ? ' · ' + it.digital_delivery.name : '')
                            : stdFile
                              ? (ar ? 'الملف القياسي للمنتج متاح للعميل تلقائياً. ارفع ملفاً مخصّصاً إذا كان الطلب يتطلب تخصيصاً.' : 'The standard product file is available to the customer automatically. Upload a custom file if this order needs personalisation.')
                              : (ar ? 'لا يوجد ملف بعد — ارفع ملف التسليم الرقمي للعميل.' : 'No file yet — upload the digital deliverable for the customer.')}</span>
                        </div>
                        <button onClick={() => pickAndDeliver(sel, it)} disabled={delivering === it.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 16px', borderRadius: 8, border: custom ? '1.5px solid var(--line-strong)' : 'none', background: custom ? 'transparent' : 'var(--gold)', color: custom ? 'var(--fg-primary)' : '#fff', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, cursor: delivering === it.id ? 'not-allowed' : 'pointer', opacity: delivering === it.id ? 0.6 : 1, flexShrink: 0 }}>
                          <Icon name="upload" size={14} />
                          {delivering === it.id ? (ar ? 'جارٍ الرفع…' : 'Uploading…') : custom ? (ar ? 'استبدال الملف' : 'Replace File') : (ar ? 'رفع وتسليم' : 'Upload & Deliver')}
                        </button>
                      </div>
                      {dm && <div style={{ marginTop: 6, fontSize: 12, color: dm.ok ? '#15803D' : '#B91C1C', display: 'flex', alignItems: 'center', gap: 6 }}><Icon name={dm.ok ? 'check-circle' : 'alert-circle'} size={13} />{dm.text}</div>}
                    </div>
                  )}
                </div>
                );
              })}
            </div>

            <div style={{ padding: '12px 22px 16px', borderTop: '1px solid var(--line)', background: 'var(--bg-tint)', display: 'flex', justifyContent: 'flex-end' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, color: 'var(--gold-deep)' }}>
                {ar ? 'المجموع: ' : 'Total: '}{fmtAED(sel.total_amount)}
              </div>
            </div>

            {/* Customer & delivery */}
            <div style={{ padding: '14px 22px', borderTop: '1px solid var(--line)' }}>
              <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)', marginBottom: 8 }}>{ar ? 'العميل والتوصيل' : 'Customer & Delivery'}</div>
              <div style={{ display: 'grid', gap: 6, fontSize: 13.5, color: 'var(--fg-secondary)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="user" size={14} style={{ color: 'var(--fg-muted)' }} /><span style={{ fontWeight: 600 }}>{custName(sel)}</span></div>
                {custPhone(sel) ? <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="phone" size={14} style={{ color: 'var(--fg-muted)' }} /><a href={'tel:' + custPhone(sel)} style={{ color: 'var(--gold-deep)', textDecoration: 'none' }}>{custPhone(sel)}</a></div> : null}
                {sel.guest_email ? <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="mail" size={14} style={{ color: 'var(--fg-muted)' }} /><a href={'mailto:' + sel.guest_email} style={{ color: 'var(--gold-deep)', textDecoration: 'none' }}>{sel.guest_email}</a></div> : null}
                {custAddr(sel) ? <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="map-pin" size={14} style={{ color: 'var(--fg-muted)' }} /><span>{custAddr(sel)}</span></div> : null}
              </div>
            </div>

            {/* Booking details */}
            {sel.booking && (
              <div style={{ padding: '14px 22px', borderTop: '1px solid var(--line)' }}>
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--fg-muted)', marginBottom: 8 }}>{ar ? 'تفاصيل الحجز' : 'Booking Details'}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13.5, color: 'var(--fg-secondary)' }}>
                  <Icon name="calendar" size={14} style={{ color: 'var(--gold-deep)' }} />
                  <span style={{ fontWeight: 600 }}>{sel.booking.kind === 'rental' ? (fmtDate(sel.booking.start) + ' → ' + fmtDate(sel.booking.end)) : (fmtDate(sel.booking.start) + (sel.booking.time ? ' · ' + sel.booking.time : ''))}</span>
                </div>
                {sel.booking.kind === 'service' && (sel.booking.guests || sel.booking.venue) ? <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 5 }}>{[sel.booking.guests ? sel.booking.guests + (ar ? ' ضيف' : ' guests') : '', sel.booking.venue].filter(Boolean).join(' · ')}</div> : null}
              </div>
            )}

            {/* Action bar */}
            {(NEXT_ACTIONS[sel.status] || []).length > 0 && (
              <div style={{ padding: '14px 22px', borderTop: '1px solid var(--line)', display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
                <span style={{ fontSize: 13, color: 'var(--fg-secondary)', flex: 1 }}>{ar ? 'تحديث الحالة:' : 'Update status:'}</span>
                {(NEXT_ACTIONS[sel.status] || []).map((a) => (
                  <button key={a.status} onClick={() => updateStatus(sel.id, a.status)} disabled={updating === sel.id}
                    style={{ padding: '8px 20px', borderRadius: 8, border: 'none', background: a.status === 'cancelled' ? '#FEE2E2' : 'var(--gold)', color: a.status === 'cancelled' ? '#B91C1C' : '#fff', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', opacity: updating === sel.id ? 0.6 : 1 }}>
                    {updating === sel.id ? '…' : a.label}
                  </button>
                ))}
              </div>
            )}

            {sel.status === 'refunded' ? (
              <div style={{ padding: '12px 22px', borderTop: '1px solid var(--line)', background: '#FEF2F2', display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, color: '#B91C1C' }}>
                <Icon name="rotate-ccw" size={16} />{ar ? 'تم استرداد هذا الطلب' : 'This order has been refunded'}
              </div>
            ) : sel.status !== 'cancelled' && (
              <div style={{ padding: '14px 22px', borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 13, color: 'var(--fg-secondary)', flex: 1 }}>{ar ? 'استرداد المبلغ للعميل عبر Stripe' : 'Refund the customer via Stripe'}</span>
                <button onClick={() => doRefund(sel)} disabled={updating === sel.id}
                  style={{ padding: '8px 20px', borderRadius: 8, border: '1.5px solid #B91C1C', background: 'transparent', color: '#B91C1C', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', opacity: updating === sel.id ? 0.6 : 1 }}>
                  {updating === sel.id ? '…' : (ar ? 'استرداد كامل' : 'Refund')}
                </button>
              </div>
            )}
            {refundMsg && (
              <div style={{ padding: '10px 22px', borderTop: '1px solid var(--line)', fontSize: 13, color: refundMsg.ok ? '#15803D' : '#B91C1C' }}>{refundMsg.text}</div>
            )}

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

            {sel.customer_confirmed_at && (
              <div style={{ padding: '12px 22px', borderTop: '1px solid var(--line)', background: '#F0FDF4', display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, color: '#15803D' }}>
                <Icon name="check-circle" size={16} />
                {ar ? 'أكّد العميل الاستلام بتاريخ ' + fmtDate(sel.customer_confirmed_at) : 'Customer confirmed delivery on ' + fmtDate(sel.customer_confirmed_at)}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

/* -------- Analytics Tab -------- */
function VendorAnalyticsTab({ db, user, ar, tier }) {
  const canExport = tier?.analytics_level === 'advanced';
  const exportCsv = function () {
    var rows = (stats && stats.orders) || [];
    var header = 'Order ID,Date,Status,Total (AED)\n';
    var body = rows.map(function (o) {
      return [o.id || '', o.created_at || '', o.status || '', Number(o.total || 0).toFixed(2)].join(',');
    }).join('\n');
    var blob = new Blob([header + body], { type: 'text/csv' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url; a.download = 'saraya-orders-export.csv'; a.click();
    URL.revokeObjectURL(url);
  };
  const [stats, setStats] = useStateVD(null);
  const [loading, setLoading] = useStateVD(true);
  const [period, setPeriod] = useStateVD(30);

  useEffectVD(() => {
    if (!db || !user) return;
    setLoading(true);
    const since = new Date(Date.now() - period * 86400000).toISOString();
    Promise.all([
      db.from('orders').select('total_amount, created_at, status').eq('vendor_id', user.id).gte('created_at', since),
      db.from('orders').select('id', { count: 'exact', head: true }).eq('vendor_id', user.id).gte('created_at', since),
      db.from('orders').select('id', { count: 'exact', head: true }).eq('vendor_id', user.id).eq('status', 'pending').gte('created_at', since),
    ]).then(([ordersRes, countRes, pendingRes]) => {
      const orders = ordersRes.data || [];
      const revenue = orders.filter((o) => o.status !== 'cancelled').reduce((s, o) => s + Number(o.total_amount || 0), 0);
      const avgOrder = orders.length ? revenue / orders.length : 0;
      setStats({
        revenue,
        orderCount: countRes.count || 0,
        pendingCount: pendingRes.count || 0,
        avgOrder,
        orders,
      });
      setLoading(false);
    });
  }, [db, user, period]);

  if (loading) return <div style={{ padding: '32px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      {/* Period selector */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {[7, 30, 90].map((d) => (
          <button key={d} onClick={() => setPeriod(d)} style={{ padding: '7px 16px', borderRadius: 8, border: '1.5px solid ' + (period === d ? 'var(--gold)' : 'var(--line)'), background: period === d ? 'var(--gold-tint)' : 'var(--white)', color: period === d ? 'var(--gold-deep)' : 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: period === d ? 700 : 400, cursor: 'pointer' }}>
            {ar ? `آخر ${d} يوم` : `Last ${d} days`}
          </button>
        ))}
        <button onClick={function () { if (canExport) exportCsv(); }} disabled={!canExport} title={canExport ? '' : (ar ? 'التصدير متاح لباقة بريميوم' : 'Export available on Premium package')} style={{ marginInlineStart: 'auto', display: 'flex', alignItems: 'center', gap: 6, padding: '7px 16px', borderRadius: 8, border: '1.5px solid var(--line)', background: canExport ? 'var(--white)' : 'var(--bg-tint)', color: canExport ? 'var(--fg-secondary)' : 'var(--fg-muted)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, cursor: canExport ? 'pointer' : 'not-allowed', opacity: canExport ? 1 : 0.6 }}>
          <Icon name={canExport ? 'download' : 'lock'} size={14} />
          {ar ? 'تصدير CSV' : 'Export CSV'}
        </button>
      </div>

      {/* KPI cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 14 }}>
        {[
          { icon: 'dollar-sign', label: ar ? 'الإيرادات' : 'Revenue',       value: `AED ${(stats?.revenue || 0).toFixed(0)}` },
          { icon: 'shopping-bag', label: ar ? 'الطلبات' : 'Orders',         value: stats?.orderCount || 0 },
          { icon: 'clock',       label: ar ? 'معلقة' : 'Pending',           value: stats?.pendingCount || 0 },
          { icon: 'trending-up', label: ar ? 'متوسط الطلب' : 'Avg. Order',  value: `AED ${(stats?.avgOrder || 0).toFixed(0)}` },
        ].map((kpi) => (
          <div key={kpi.icon} style={{ padding: '18px 20px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ display: 'inline-flex', width: 32, height: 32, borderRadius: 8, background: 'var(--gold-tint)', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={kpi.icon} size={15} style={{ color: 'var(--gold-deep)' }} />
              </span>
              <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{kpi.label}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 500, color: 'var(--fg-primary)' }}>{kpi.value}</div>
          </div>
        ))}
      </div>

      {/* Recent orders table */}
      <div style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--line)', fontWeight: 600, fontSize: 14 }}>
          {ar ? 'آخر الطلبات' : 'Recent Orders'}
        </div>
        {(stats?.orders || []).slice(0, 10).map((o, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 20px', borderBottom: '1px solid var(--line)' }}>
            <div style={{ flex: 1, fontSize: 13, color: 'var(--fg-secondary)' }}>{new Date(o.created_at).toLocaleDateString(ar ? 'ar-AE' : 'en-AE')}</div>
            <span style={{ padding: '3px 10px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: (o.status === 'delivered' ? '#3AB86C' : o.status === 'cancelled' ? '#E05454' : '#E8A838') + '22', color: o.status === 'delivered' ? '#3AB86C' : o.status === 'cancelled' ? '#E05454' : '#E8A838' }}>{o.status}</span>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--gold-deep)' }}>AED {Number(o.total || 0).toFixed(2)}</div>
          </div>
        ))}
        {!stats?.orders?.length && <div style={{ padding: '24px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>{ar ? 'لا توجد طلبات في هذه الفترة' : 'No orders in this period'}</div>}
      </div>
    </div>
  );
}

/* -------- Inventory Tab -------- */
function VendorSettingsTab({ db, user, profile, refreshProfile, ar, lang, setLang, tier }) { const [vp, setVp] = useStateVD(null); const [loadingVp, setLoadingVp] = useStateVD(true); const [fullName, setFullName] = useStateVD((profile && (profile.full_name || profile.display_name)) || ''); const [phone, setPhone] = useStateVD((profile && profile.phone) || ''); const [notifChannel, setNotifChannel] = useStateVD((profile && profile.notification_channel) || 'email'); const [langPref, setLangPref] = useStateVD((profile && profile.lang_pref) || lang || 'en'); const [tradeName, setTradeName] = useStateVD(''); const [tradeNameAr, setTradeNameAr] = useStateVD(''); const [whatsapp, setWhatsapp] = useStateVD(''); const [city, setCity] = useStateVD(''); const [website, setWebsite] = useStateVD(''); const [businessCategory, setBusinessCategory] = useStateVD([]); const [categories, setCategories] = useStateVD([]); const [licenseNumber, setLicenseNumber] = useStateVD(''); const [licenseExpiry, setLicenseExpiry] = useStateVD(''); const [bankName, setBankName] = useStateVD(''); const [bankIban, setBankIban] = useStateVD(''); const [bankAccountName, setBankAccountName] = useStateVD(''); const [logoUrl, setLogoUrl] = useStateVD(''); const [uploadingLogo, setUploadingLogo] = useStateVD(false); const [bannerUrl, setBannerUrl] = useStateVD(''); const [uploadingBanner, setUploadingBanner] = useStateVD(false); const [newPassword, setNewPassword] = useStateVD(''); const [confirmPassword, setConfirmPassword] = useStateVD(''); const [savingAccount, setSavingAccount] = useStateVD(false); const [savingBiz, setSavingBiz] = useStateVD(false); const [savingPassword, setSavingPassword] = useStateVD(false); const [msg, setMsg] = useStateVD(null); useEffectVD(() => { (async () => { if (!db || !user) { setLoadingVp(false); return; } const bizCats = [].concat((window.SERVICE_CATEGORIES || []).map((c) => ({ name_en: c.label.en, name_ar: c.label.ar })), (window.MARKETPLACE_CATEGORIES || []).map((c) => ({ name_en: c.label.en, name_ar: c.label.ar })), (window.RENTAL_CATEGORIES_CONFIG || []).map((c) => ({ name_en: c.label.en, name_ar: c.label.ar }))); setCategories(bizCats); const r = await db.from('vendor_profiles').select('*').eq('id', user.id).single(); if (r.data) { setVp(r.data); setTradeName(r.data.trade_name || ''); setTradeNameAr(r.data.trade_name_ar || ''); setWhatsapp(r.data.whatsapp || ''); setCity(r.data.city || ''); setWebsite(r.data.website || ''); setBusinessCategory(Array.isArray(r.data.business_category) ? r.data.business_category : (r.data.business_category ? [r.data.business_category] : [])); setLicenseNumber(r.data.trade_license_number || ''); setLicenseExpiry(r.data.trade_license_expiry || ''); const bk = (await db.from('vendor_banking').select('bank_name, bank_iban, bank_account_name').eq('vendor_id', user.id).maybeSingle()).data || {}; setBankName(bk.bank_name || ''); setBankIban(bk.bank_iban || ''); setBankAccountName(bk.bank_account_name || ''); setLogoUrl(r.data.logo_url || ''); setBannerUrl(r.data.banner_url || ''); } setLoadingVp(false); })(); }, [db, user]); const saveAccount = async () => { setSavingAccount(true); setMsg(null); const r = await db.from('profiles').update({ display_name: fullName, phone: phone, notification_channel: notifChannel, lang_pref: langPref }).eq('id', user.id); setSavingAccount(false); if (r.error) { setMsg({ type: 'err', text: r.error.message }); return; } if (refreshProfile) await refreshProfile(); if (setLang && langPref !== lang) setLang(langPref); setMsg({ type: 'ok', text: ar ? 'تم حفظ إعدادات الحساب' : 'Account settings saved' }); }; const saveBusiness = async () => { setSavingBiz(true); setMsg(null); const r = await db.from('vendor_profiles').update({ trade_name: tradeName, trade_name_ar: tradeNameAr, business_category: businessCategory, whatsapp: whatsapp, city: city, website: website, trade_license_number: licenseNumber, trade_license_expiry: licenseExpiry || null }).eq('id', user.id); if (!r.error) { const rb = await db.from('vendor_banking').upsert({ vendor_id: user.id, bank_name: bankName, bank_iban: bankIban, bank_account_name: bankAccountName, updated_at: new Date().toISOString() }, { onConflict: 'vendor_id' }); if (rb.error) r.error = rb.error; } setSavingBiz(false); if (r.error) { setMsg({ type: 'err', text: r.error.message }); return; } setMsg({ type: 'ok', text: ar ? 'تم حفظ الملف التجاري' : 'Business profile saved' }); }; const uploadLogo = async (file) => { if (!file || !user) return; setUploadingLogo(true); setMsg(null); const ext = (file.name.split('.').pop() || 'png'); const path = 'vendor-logos/' + user.id + '-' + Date.now() + '.' + ext; const up = await db.storage.from('listing-images').upload(path, file, { upsert: true }); if (up.error) { setUploadingLogo(false); setMsg({ type: 'err', text: up.error.message }); return; } const pub = db.storage.from('listing-images').getPublicUrl(path); const newUrl = pub && pub.data ? pub.data.publicUrl : ''; const r = await db.from('vendor_profiles').update({ logo_url: newUrl }).eq('id', user.id); setUploadingLogo(false); if (r.error) { setMsg({ type: 'err', text: r.error.message }); return; } setLogoUrl(newUrl); setMsg({ type: 'ok', text: ar ? 'تم تحديث الشعار' : 'Logo updated' }); };
    const uploadBanner = async (file) => {
      if (!file || !user) return;
      if (!(tier && tier.banner_eligibility)) { setMsg({ type: 'err', text: ar ? 'صورة البانر متاحة فقط لباقة Premium' : 'Banner image is available on the Premium package only' }); return; }
      setUploadingBanner(true); setMsg(null);
      const ext = (file.name.split('.').pop() || 'png');
      const path = 'vendor-banners/' + user.id + '-' + Date.now() + '.' + ext;
      const up = await db.storage.from('listing-images').upload(path, file, { upsert: true });
      if (up.error) { setUploadingBanner(false); setMsg({ type: 'err', text: up.error.message }); return; }
      const pub = db.storage.from('listing-images').getPublicUrl(path);
      const newUrl = pub && pub.data ? pub.data.publicUrl : '';
      const r2 = await db.from('vendor_profiles').update({ banner_url: newUrl }).eq('id', user.id);
      setUploadingBanner(false);
      if (r2.error) { setMsg({ type: 'err', text: r2.error.message }); return; }
      setBannerUrl(newUrl);
      setMsg({ type: 'ok', text: ar ? 'تم تحديث صورة البانر' : 'Banner image updated' });
    }; const savePassword = async () => { if (!newPassword || newPassword.length < 6) { setMsg({ type: 'err', text: ar ? 'يجب أن تكون كلمة المرور 6 أحرف على الأقل' : 'Password must be at least 6 characters' }); return; } if (newPassword !== confirmPassword) { setMsg({ type: 'err', text: ar ? 'كلمتا المرور غير متطابقتين' : 'Passwords do not match' }); return; } setSavingPassword(true); setMsg(null); const r2 = await db.auth.updateUser({ password: newPassword }); setSavingPassword(false); if (r2.error) { setMsg({ type: 'err', text: r2.error.message }); return; } setNewPassword(''); setConfirmPassword(''); setMsg({ type: 'ok', text: ar ? 'تم تحديث كلمة المرور' : 'Password updated' }); }; const fieldStyle = { width: '100%', padding: '10px 12px', borderRadius: 8, border: '1px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 14 }; const labelStyle = { fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }; const btnStyle = { padding: '10px 24px', borderRadius: 8, border: 'none', background: 'var(--gold-deep)', color: 'var(--white)', fontWeight: 600, fontSize: 14, cursor: 'pointer' }; if (loadingVp) return (<div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>); return (<div style={{ display: 'grid', gap: 20 }}>{msg && <div style={{ padding: '12px 16px', borderRadius: 8, background: msg.type === 'ok' ? '#F0FDF4' : '#FEF2F2', border: (msg.type === 'ok' ? '1px solid #86EFAC' : '1px solid #FCA5A5'), color: msg.type === 'ok' ? '#166534' : '#991B1B', fontSize: 13.5 }}>{msg.text}</div>}<Section title={ar ? 'إعدادات الحساب' : 'Account Settings'} desc={ar ? 'معلومات الحساب الشخصية' : 'Your personal account information'}><div style={{ display: 'grid', gap: 14 }}><div><label style={labelStyle}>{ar ? 'الاسم' : 'Name'}</label><input style={fieldStyle} value={fullName} onChange={(e) => setFullName(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'البريد الإلكتروني' : 'Email'}</label><div style={{ ...fieldStyle, background: 'var(--cream)', color: 'var(--fg-secondary)' }}>{(user && user.email) || '-'}</div></div><div><label style={labelStyle}>{ar ? 'رقم الهاتف' : 'Phone'}</label><input style={fieldStyle} value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+971 5X XXX XXXX" /></div><div><label style={labelStyle}>{ar ? 'لغة لوحة التحكم' : 'Dashboard Language'}</label><select style={fieldStyle} value={langPref} onChange={(e) => setLangPref(e.target.value)}><option value="en">English</option><option value="ar">العربية</option></select></div><div><label style={labelStyle}>{ar ? 'تفضيل الإشعارات' : 'Notification Preference'}</label><select style={fieldStyle} value={notifChannel} onChange={(e) => setNotifChannel(e.target.value)}><option value="email">{ar ? 'البريد الإلكتروني' : 'Email'}</option><option value="whatsapp">WhatsApp</option><option value="both">{ar ? 'كلاهما' : 'Both'}</option></select></div><button onClick={saveAccount} disabled={savingAccount} style={{ ...btnStyle, justifySelf: 'start', opacity: savingAccount ? 0.6 : 1 }}>{savingAccount ? (ar ? 'جارٍ الحفظ...' : 'Saving...') : (ar ? 'حفظ' : 'Save')}</button></div></Section><Section title={ar ? 'الملف التجاري' : 'Business Profile'} desc={ar ? 'معلومات نشاطك التجاري الظاهرة للعملاء' : 'Your business information shown to customers'}><div style={{ display: 'grid', gap: 14 }}><div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>{logoUrl ? <img src={logoUrl} style={{ width: 64, height: 64, borderRadius: 10, objectFit: 'cover', border: '1px solid var(--line)' }} /> : <div style={{ width: 64, height: 64, borderRadius: 10, background: 'var(--cream)', border: '1px solid var(--line)' }} />}<div><label style={labelStyle}>{ar ? 'شعار النشاط' : 'Business Logo'}</label><input type="file" accept="image/*" onChange={(e) => uploadLogo(e.target.files && e.target.files[0])} disabled={uploadingLogo} /></div></div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, opacity: (tier && tier.banner_eligibility) ? 1 : 0.6 }}>
                {bannerUrl ? <img src={bannerUrl} style={{ width: 96, height: 54, borderRadius: 10, objectFit: 'cover', border: '1px solid var(--line)' }} /> : <div style={{ width: 96, height: 54, borderRadius: 10, background: 'var(--cream)', border: '1px solid var(--line)' }} />}
                <div>
                  <label style={labelStyle}>
                    {ar ? 'صورة البانر' : 'Store Banner'}
                    {!(tier && tier.banner_eligibility) && (
                      <Icon name="lock" size={12} style={{ marginLeft: 6, verticalAlign: 'middle', color: 'var(--fg-muted)' }} />
                    )}
                  </label>
                  <input type="file" accept="image/*" onChange={(e) => uploadBanner(e.target.files && e.target.files[0])} disabled={uploadingBanner || !(tier && tier.banner_eligibility)} title={!(tier && tier.banner_eligibility) ? (ar ? 'متاح فقط لباقة Premium' : 'Available on Premium package only') : undefined} />
                  {!(tier && tier.banner_eligibility) && (
                    <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{ar ? 'متاح فقط لباقة Premium' : 'Available on Premium package only'}</div>
                  )}
                </div>
              </div><div><label style={labelStyle}>{ar ? 'الاسم التجاري (إنجليزي)' : 'Trade Name (English)'}</label><input style={fieldStyle} value={tradeName} onChange={(e) => setTradeName(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'الاسم التجاري (عربي)' : 'Trade Name (Arabic)'}</label><input style={fieldStyle} value={tradeNameAr} onChange={(e) => setTradeNameAr(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'الفئة التجارية' : 'Business Category'}</label><div style={{ ...fieldStyle, height: 'auto', maxHeight: 220, overflowY: 'auto', padding: 10 }}><label style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 600, paddingBottom: 6, marginBottom: 6, borderBottom: '1px solid rgba(0,0,0,0.1)' }}><input type="checkbox" checked={businessCategory.length === categories.length && categories.length > 0} onChange={(e) => setBusinessCategory(e.target.checked ? categories.map((c) => c.name_en) : [])} />{ar ? 'الكل' : 'All'}</label>{categories.map((c, i) => (<label key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '3px 0' }}><input type="checkbox" checked={businessCategory.includes(c.name_en)} onChange={(e) => setBusinessCategory(e.target.checked ? [...businessCategory, c.name_en] : businessCategory.filter((x) => x !== c.name_en))} />{ar ? c.name_ar : c.name_en}</label>))}</div></div><div><label style={labelStyle}>{ar ? 'واتساب' : 'WhatsApp'}</label><input style={fieldStyle} value={whatsapp} onChange={(e) => setWhatsapp(e.target.value)} placeholder="+971 5X XXX XXXX" /></div><div><label style={labelStyle}>{ar ? 'المدينة / منطقة الخدمة' : 'City / Service Area'}</label><input style={fieldStyle} value={city} onChange={(e) => setCity(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'الموقع الإلكتروني' : 'Website'}</label><input style={fieldStyle} value={website} onChange={(e) => setWebsite(e.target.value)} placeholder="https://" /></div><div><label style={labelStyle}>{ar ? 'رقم الرخصة التجارية' : 'Trade License Number'}</label><input style={fieldStyle} value={licenseNumber} onChange={(e) => setLicenseNumber(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'تاريخ انتهاء الرخصة' : 'Trade License Expiry'}</label><input type="date" style={fieldStyle} value={licenseExpiry || ''} onChange={(e) => setLicenseExpiry(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'اسم البنك' : 'Bank Name'}</label><input style={fieldStyle} value={bankName} onChange={(e) => setBankName(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'رقم الآيبان (IBAN)' : 'IBAN'}</label><input style={fieldStyle} value={bankIban} onChange={(e) => setBankIban(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'اسم صاحب الحساب' : 'Account Holder Name'}</label><input style={fieldStyle} value={bankAccountName} onChange={(e) => setBankAccountName(e.target.value)} /></div><button onClick={saveBusiness} disabled={savingBiz} style={{ ...btnStyle, justifySelf: 'start', opacity: savingBiz ? 0.6 : 1 }}>{savingBiz ? (ar ? 'جارٍ الحفظ...' : 'Saving...') : (ar ? 'حفظ الملف التجاري' : 'Save Business Profile')}</button></div></Section><Section title={ar ? 'تغيير كلمة المرور' : 'Change Password'} desc={ar ? 'اختر كلمة مرور جديدة لحسابك' : 'Choose a new password for your account'}><div style={{ display: 'grid', gap: 14 }}><div><label style={labelStyle}>{ar ? 'كلمة المرور الجديدة' : 'New Password'}</label><input type="password" style={fieldStyle} value={newPassword} onChange={(e) => setNewPassword(e.target.value)} /></div><div><label style={labelStyle}>{ar ? 'تأكيد كلمة المرور' : 'Confirm Password'}</label><input type="password" style={fieldStyle} value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} /></div><button onClick={savePassword} disabled={savingPassword} style={{ ...btnStyle, justifySelf: 'start', background: 'var(--white)', border: '1px solid var(--gold-deep)', color: 'var(--gold-deep)', opacity: savingPassword ? 0.6 : 1 }}>{savingPassword ? (ar ? 'جارٍ الحفظ...' : 'Saving...') : (ar ? 'تحديث كلمة المرور' : 'Update Password')}</button></div></Section></div>); } function NotificationsTab({ db, user, ar }) {
  const [items, setItemsNotif] = useStateVD([]);
  const [loadingNotif, setLoadingNotif] = useStateVD(true);
  const loadNotif = useCallbackVD(async () => {
    if (!user || !window.SarayaService) return;
    setLoadingNotif(true);
    const rows = await window.SarayaService.notifications.list(user.id, { limit: 50 });
    setItemsNotif(rows || []);
    setLoadingNotif(false);
  }, [user]);
  useEffectVD(() => { loadNotif(); }, [loadNotif]);
  const markRead = async (id) => {
    if (!window.SarayaService) return;
    await window.SarayaService.notifications.markRead(id);
    setItemsNotif((prev) => prev.map((n) => (n.id === id ? { ...n, is_read: true } : n)));
  };
  const markAll = async () => {
    if (!user || !window.SarayaService) return;
    await window.SarayaService.notifications.markAllRead(user.id);
    setItemsNotif((prev) => prev.map((n) => ({ ...n, is_read: true })));
  };
  if (loadingNotif) {
    return <div style={{ padding: 20, color: '#94a3b8', fontSize: 14 }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;
  }
  if (!items.length) {
    return (
      <VDPlaceholder icon="bell" title={ar ? 'الإشعارات' : 'Notifications'} desc={ar ? 'لا توجد إشعارات حتى الآن. ستظهر هنا تحديثات الطلبات والعروض وحالة الحساب.' : 'No notifications yet. Updates on orders, offers, and your account status will appear here.'} />
    );
  }
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h3 style={{ margin: 0, fontSize: 16 }}>{ar ? 'الإشعارات' : 'Notifications'}</h3>
        <button onClick={markAll} style={{ background: 'none', border: '1px solid #cbd5e1', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 13 }}>
          {ar ? 'وضع علامة مقروء على الكل' : 'Mark all read'}
        </button>
      </div>
      <div style={{ display: 'grid', gap: 10 }}>
        {items.map((n) => (
          <div key={n.id} onClick={() => !n.is_read && markRead(n.id)}
            style={{ padding: '14px 16px', borderRadius: 10, border: '1px solid ' + (n.is_read ? '#e2e8f0' : '#93c5fd'), background: n.is_read ? '#fff' : '#eff6ff', cursor: n.is_read ? 'default' : 'pointer' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
              <strong style={{ fontSize: 14 }}>{n.title || n.type}</strong>
              {!n.is_read && <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#3b82f6', flexShrink: 0, marginTop: 4 }} />}
            </div>
            <div style={{ fontSize: 13, color: '#475569', marginTop: 4 }}>{n.body}</div>
            <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 6 }}>{new Date(n.created_at).toLocaleString()}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function VendorInventoryTab({ db, user, ar }) {
  const [products, setProducts] = useStateVD([]);
  const [rentals, setRentals]   = useStateVD([]); const [services, setServices] = useStateVD([]);
  const [loading, setLoading]   = useStateVD(true);
  const [saving, setSaving]     = useStateVD(null);
  const [invType, setInvType]   = useStateVD('products');
  const [invOffered, setInvOffered] = useStateVD(['products', 'rentals', 'services']);
  useEffectVD(() => {
    if (!db || !user) return;
    db.from('vendor_profiles').select('offered_types').eq('id', user.id).maybeSingle()
      .then(({ data }) => { if (data && Array.isArray(data.offered_types) && data.offered_types.length) setInvOffered(data.offered_types); });
  }, [db, user]);

  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const [pRes, rRes, sRes] = await Promise.all([
      db.from('products').select('id, name_en, name_ar, stock_quantity, low_stock_threshold').eq('vendor_id', user.id).order('name_en'),
      db.from('rentals').select('id, name_en, name_ar, stock_quantity, low_stock_threshold').eq('vendor_id', user.id).order('name_en'), db.from('services').select('id, name_en, name_ar, stock_quantity, low_stock_threshold').eq('vendor_id', user.id).order('name_en'),
    ]);
    setProducts(pRes.data || []);
    setRentals(rRes.data || []); setServices(sRes.data || []);
    setLoading(false);
  }, [db, user]);

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

  const updateStock = async (table, id, field, value) => {
    setSaving(id + field);
    await db.from(table).update({ [field]: value === '' ? null : Number(value) }).eq('id', id);
    setSaving(null);
    if (table === 'products') {
      setProducts((prev) => prev.map((p) => p.id === id ? { ...p, [field]: value === '' ? null : Number(value) } : p));
    } else if (table === 'rentals') { setRentals((prev) => prev.map((r) => r.id === id ? { ...r, [field]: value === '' ? null : Number(value) } : r)); } else { setServices((prev) => prev.map((s) => s.id === id ? { ...s, [field]: value === '' ? null : Number(value) } : s)); }
  };

  if (loading) return <div style={{ padding: '32px', textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>;

  const renderTable = (items, table, title) => (
    <div style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden', marginBottom: 20 }}>
      <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--line)', fontWeight: 600, fontSize: 14, display: 'flex', alignItems: 'center', gap: 8 }}>
        <Icon name="boxes" size={16} style={{ color: 'var(--gold-deep)' }} />
        {title}
      </div>
      {items.length === 0 && <div style={{ padding: '24px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>{ar ? 'لا يوجد' : 'None yet'}</div>}
      {items.map((item) => {
        const low = item.stock_quantity !== null && item.low_stock_threshold !== null && item.stock_quantity <= item.low_stock_threshold;
        return (
          <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 20px', borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 140 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-primary)' }}>{ar ? (item.name_ar || item.name_en) : (item.name_en || item.name_ar)}</div>
              {low && <span style={{ fontSize: 11, color: '#E05454', fontWeight: 700 }}>⚠ {ar ? 'مخزون منخفض' : 'Low stock'}</span>}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <label style={{ fontSize: 12, color: 'var(--fg-muted)', whiteSpace: 'nowrap' }}>{ar ? 'المخزون' : 'Stock'}</label>
              <input
                type="number" min="0"
                defaultValue={item.stock_quantity ?? ''}
                onBlur={(e) => updateStock(table, item.id, 'stock_quantity', e.target.value)}
                style={{ width: 70, padding: '6px 8px', borderRadius: 6, border: '1.5px solid ' + (low ? '#EF4444' : 'var(--line)'), fontFamily: 'var(--font-body)', fontSize: 13, textAlign: 'center' }}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <label style={{ fontSize: 12, color: 'var(--fg-muted)', whiteSpace: 'nowrap' }}>{ar ? 'حد التنبيه' : 'Alert at'}</label>
              <input
                type="number" min="0"
                defaultValue={item.low_stock_threshold ?? 5}
                onBlur={(e) => updateStock(table, item.id, 'low_stock_threshold', e.target.value)}
                style={{ width: 70, padding: '6px 8px', borderRadius: 6, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 13, textAlign: 'center' }}
              />
            </div>
            {saving && saving.startsWith(item.id) && <Icon name="loader" size={14} style={{ color: 'var(--gold-deep)', animation: 'spin 1s linear infinite' }} />}
          </div>
        );
      })}
    </div>
  );

  return (
    <div>
      <div style={{ padding: '12px 16px', borderRadius: 10, background: 'var(--cream)', border: '1px solid var(--gold-light)', fontSize: 13, color: 'var(--fg-secondary)', marginBottom: 20, lineHeight: 1.6 }}>
        <Icon name="info" size={14} style={{ color: 'var(--gold-deep)', verticalAlign: 'middle', marginInlineEnd: 6 }} />
        {ar
          ? 'اضبط الكمية في المخزون وحد التنبيه لكل منتج. إذا وصل المخزون لحد التنبيه أو أقل، يظهر تحذير هنا.'
          : 'Set stock quantity and low-stock alert threshold per item. When stock reaches the threshold, a warning appears here.'}
      </div>
      {(() => {
        const allInvTabs = [
          { id: 'products', label: ar ? 'المنتجات' : 'Products', items: products, table: 'products' },
          { id: 'rentals',  label: ar ? 'الإيجارات' : 'Rentals',  items: rentals,  table: 'rentals' },
          { id: 'services', label: ar ? 'الخدمات' : 'Services',  items: services, table: 'services' },
        ];
        const filtered = allInvTabs.filter((t) => invOffered.includes(t.id));
        const invTabs = filtered.length ? filtered : allInvTabs;
        const active = invTabs.find((t) => t.id === invType) || invTabs[0];
        return (
          <>
            {/* Type focus — only the types this vendor offers */}
            {invTabs.length > 1 && (
            <div style={{ display: 'flex', gap: 0, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', background: 'var(--white)', marginBottom: 20 }}>
              {invTabs.map((t) => (
                <button key={t.id} onClick={() => setInvType(t.id)}
                  style={{ flex: 1, padding: '12px 8px', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, border: 'none', borderInlineEnd: t.id !== 'services' ? '1px solid var(--line)' : 'none', background: invType === t.id ? 'var(--espresso)' : 'transparent', color: invType === t.id ? 'var(--ivory)' : 'var(--fg-primary)', transition: 'background 150ms' }}>
                  {t.label} <span style={{ opacity: 0.7, fontWeight: 500 }}>({t.items.length})</span>
                </button>
              ))}
            </div>
            )}
            {renderTable(active.items, active.table, active.label)}
          </>
        );
      })()}
    </div>
  );
}

/* -------- Inline section helper -------- */
function Section({ title, desc, children }) {
  return (
    <div style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', padding: '24px' }}>
      {title && <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, marginBottom: 4 }}>{title}</h3>}
      {desc && <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', marginBottom: 20, lineHeight: 1.55 }}>{desc}</p>}
      {children}
    </div>
  );
}

/* -------- Vendor profile editor -------- */
function VendorProfileEditor({ vp, onSaved, ar }) {
  const db = window.SarayaDB;
  const { user } = useAuth();
  const [form, setForm] = useStateVD({
    trade_name:     vp?.trade_name     || '',
    trade_name_ar:  vp?.trade_name_ar  || '',
    description_en: vp?.description_en || '',
    description_ar: vp?.description_ar || '',
    whatsapp:       vp?.whatsapp       || '',
    website:        vp?.website        || '',
    instagram:      vp?.instagram      || '',
    city:           vp?.city           || '',
    short_description_en: vp?.short_description_en || '',
    short_description_ar: vp?.short_description_ar || '',
    service_areas_text: (vp?.service_areas && vp.service_areas.length ? vp.service_areas.join(', ') : ''),
  });
  const [busy, setBusy] = useStateVD(false);
  const [msg, setMsg]   = useStateVD('');

  const set = (k) => (e) => setForm((p) => ({ ...p, [k]: e.target.value }));

  const STATUSES_ORDER = ['registered', 'package_pending', 'payment_pending', 'pending_approval', 'approved'];

  const save = async (e) => {
    e.preventDefault();
    if (!db) return;
    setBusy(true); setMsg('');

    const { service_areas_text, ...formRest } = form;
    const updatePayload = { ...formRest, service_areas: String(service_areas_text || '').split(',').map((s) => s.trim()).filter(Boolean) };

    // If vendor is still at 'registered' and has filled in their trade name,
    // advance them to 'pending_approval' (free pilot launch — skips payment step).
    if (form.trade_name.trim()) {
      const { data: current } = await db.from('vendor_profiles').select('status').eq('id', user.id).maybeSingle();
      const currentIdx = STATUSES_ORDER.indexOf(current?.status);
      const targetIdx  = STATUSES_ORDER.indexOf('pending_approval');
      // currentIdx === -1 means there is no vendor_profiles row yet (onboarding was
      // never completed) — treat it as a fresh registration ready for review.
      if (currentIdx === -1 || currentIdx < targetIdx) {
        updatePayload.status = 'pending_approval';
      }
    }

    // Upsert (not update): if this vendor's vendor_profiles row was never created
    // — e.g. they closed the first-time onboarding pop-up — a plain update would
    // silently write to zero rows and report success. Upsert creates it instead.
    const { error } = await db.from('vendor_profiles').upsert({ id: user.id, ...updatePayload }, { onConflict: 'id' });
    setBusy(false);
    if (error) {
      setMsg(error.message);
    } else {
      setMsg(updatePayload.status === 'pending_approval'
        ? (ar ? 'تم الحفظ! حسابك قيد المراجعة من قِبل سرايا.' : 'Profile saved! Your account is now pending Saraya review.')
        : (ar ? 'تم الحفظ بنجاح' : 'Profile saved'));
      onSaved && onSaved();
    }
  };

  return (
    <Section title={ar ? 'ملف الشركة' : 'Business Profile'} desc={ar ? 'معلوماتك الظاهرة للعملاء في سرايا.' : 'This information is visible to customers on Saraya.'}>
      <form onSubmit={save} style={{ display: 'grid', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label={ar ? 'اسم الشركة (إنجليزي)' : 'Business Name (EN)'}>
            <TextInput value={form.trade_name} onChange={set('trade_name')} required />
          </Field>
          <Field label={ar ? 'اسم الشركة (عربي)' : 'Business Name (AR)'}>
            <TextInput value={form.trade_name_ar} onChange={set('trade_name_ar')} dir="rtl" />
          </Field>
        </div>

        <TranslateFieldControls enValue={form.trade_name} arValue={form.trade_name_ar} onSetEn={(v) => setForm((p) => ({ ...p, trade_name: v }))} onSetAr={(v) => setForm((p) => ({ ...p, trade_name_ar: v }))} ar={ar} />
        <Field label={ar ? 'نبذة (إنجليزي)' : 'Description (EN)'}>
          <textarea
            value={form.description_en}
            onChange={set('description_en')}
            rows={3}
            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={ar ? 'نبذة (عربي)' : 'Description (AR)'}>
          <textarea
            value={form.description_ar}
            onChange={set('description_ar')}
            dir="rtl"
            rows={3}
            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>

        <TranslateFieldControls enValue={form.description_en} arValue={form.description_ar} onSetEn={(v) => setForm((p) => ({ ...p, description_en: v }))} onSetAr={(v) => setForm((p) => ({ ...p, description_ar: v }))} ar={ar} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label={ar ? 'وصف مختصر (إنجليزي)' : 'Short tagline (EN)'}>
            <TextInput value={form.short_description_en} onChange={set('short_description_en')} maxLength={90} placeholder={ar ? 'جملة قصيرة تظهر على بطاقتك' : 'One short line shown on your card'} />
          </Field>
          <Field label={ar ? 'وصف مختصر (عربي)' : 'Short tagline (AR)'}>
            <TextInput value={form.short_description_ar} onChange={set('short_description_ar')} maxLength={90} dir="rtl" />
          </Field>
        </div>
        <Field label={ar ? 'مناطق الخدمة' : 'Service areas'}>
          <TextInput value={form.service_areas_text} onChange={set('service_areas_text')} placeholder={ar ? 'أبوظبي، دبي، الشارقة' : 'Abu Dhabi, Dubai, Sharjah'} />
          <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{ar ? 'افصل بين المناطق بفاصلة — تظهر على متجرك العام.' : 'Separate areas with commas — shown on your public store.'}</div>
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="WhatsApp"><TextInput type="tel" value={form.whatsapp} onChange={set('whatsapp')} placeholder="+971 5X XXX XXXX" /></Field>
          <Field label={ar ? 'المدينة' : 'City'}><TextInput value={form.city} onChange={set('city')} /></Field>
          <Field label={ar ? 'الموقع' : 'Website'}><TextInput type="text" value={form.website} onChange={set('website')} placeholder="https://" /></Field>
          <Field label="Instagram"><TextInput value={form.instagram} onChange={set('instagram')} placeholder="@yourhandle" /></Field>
        </div>
        {msg && <p style={{ fontSize: 13, color: msg.includes('error') || msg.includes('خطأ') ? '#B91C1C' : 'var(--success)', margin: 0 }}>{msg}</p>}
        <div style={{ display: 'flex', gap: 10 }}>
          <Button variant="primary" type="submit" loading={busy}>{ar ? 'حفظ التغييرات' : 'Save Changes'}</Button>
        </div>
      </form>
    </Section>
  );
}

function SubscriptionManageControls({ db, vendorId, ar, onRefresh, startStripeCheckout, checkingOut }) {
  const [mySub, setMySub] = useStateVD(null);
  const [tiers, setTiers] = useStateVD([]);
  const [busy, setBusy] = useStateVD(false);
  const [msg, setMsg] = useStateVD(null);

  const load = useCallbackVD(async () => {
    try { await db.rpc('apply_due_subscription_changes'); } catch (e) { /* best effort */ }
    try {
      const [subRes, tiersRes] = await Promise.all([
        db.from('subscriptions')
          .select('id, status, tier_id, pending_tier_id, current_period_end, subscription_tiers!subscriptions_tier_id_fkey(id, name, name_ar, package_level, price_monthly)')
          .eq('vendor_id', vendorId)
          .order('created_at', { ascending: false })
          .limit(1)
          .maybeSingle(),
        db.from('subscription_tiers')
          .select('id, name, name_ar, package_level, price_monthly')
          .eq('is_active', true)
          .order('package_level'),
      ]);
      setMySub(subRes.data || null);
      setTiers(tiersRes.data || []);
    } catch (e) { /* ignore */ }
  }, [db, vendorId]);

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

  if (!mySub) return null;

  const curLevel = mySub.subscription_tiers ? mySub.subscription_tiers.package_level : 0;
  const higher = tiers.filter((t) => t.package_level > curLevel);
  const lower = tiers.filter((t) => t.package_level < curLevel);
  const pendingTier = mySub.pending_tier_id ? tiers.find((t) => t.id === mySub.pending_tier_id) : null;
  const periodEndLabel = mySub.current_period_end
    ? new Date(mySub.current_period_end).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' })
    : (ar ? 'دورة الفوترة القادمة' : 'your next billing cycle');

  const runAction = async (action, newTierId) => {
    setBusy(true);
    setMsg(null);
    try {
      const { error } = await db.rpc('vendor_subscription_action', { p_action: action, p_new_tier_id: newTierId || null });
      if (error) throw error;
      setMsg({ ok: true, text: ar ? 'تم تنفيذ الطلب بنجاح.' : 'Request completed successfully.' });
      await load();
      if (onRefresh) onRefresh();
    } catch (e) {
      setMsg({ ok: false, text: (e && e.message) || (ar ? 'حدث خطأ، حاول مرة أخرى.' : 'Something went wrong, please try again.') });
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ padding: '16px 20px', borderRadius: 12, background: 'var(--cream)', fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.65 }}>
        <Icon name="info" size={14} style={{ color: 'var(--gold-deep)', marginInlineEnd: 6, verticalAlign: 'middle' }} />
        {ar
          ? 'الترقية تسري فوراً، والتخفيض يسري في دورة الفوترة القادمة.'
          : 'Upgrades take effect immediately; downgrades apply at your next billing cycle.'}
      </div>

      {msg && (
        <div style={{ padding: '10px 14px', borderRadius: 10, fontSize: 13, background: msg.ok ? 'var(--sage-light, #eaf5ec)' : 'var(--rose-light, #fbeaea)', color: msg.ok ? 'var(--sage-deep, #2f6b3a)' : 'var(--rose-deep, #9b2c2c)' }}>
          {msg.text}
        </div>
      )}

      {mySub.status === 'suspended' ? (
        <button
          type="button"
          disabled={busy}
          onClick={() => runAction('resume')}
          style={{ padding: '10px 16px', borderRadius: 10, border: '1px solid var(--gold-deep)', background: 'var(--gold-deep)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1 }}
        >
          {ar ? 'استئناف الباقة' : 'Resume Plan'}
        </button>
      ) : (
        <React.Fragment>
          {higher.length > 0 && (
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8, color: 'var(--fg-primary)' }}>
                {ar ? 'ترقية باقتك' : 'Upgrade your plan'}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {higher.map((t) => (
                  <button
                    key={t.id}
                    type="button"
                    disabled={checkingOut || busy}
                    onClick={() => startStripeCheckout(t.package_level)}
                    style={{ padding: '8px 14px', borderRadius: 10, border: '1px solid var(--gold-deep)', background: 'transparent', color: 'var(--gold-deep)', fontSize: 13, fontWeight: 600, cursor: (checkingOut || busy) ? 'default' : 'pointer', opacity: (checkingOut || busy) ? 0.6 : 1 }}
                  >
                    {ar ? ('الترقية إلى ' + (t.name_ar || t.name)) : ('Upgrade to ' + t.name)}
                  </button>
                ))}
              </div>
            </div>
          )}

          {pendingTier ? (
            <div style={{ padding: '10px 14px', borderRadius: 10, fontSize: 13, background: 'var(--cream)', color: 'var(--fg-secondary)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
              <span>
                {ar
                  ? ('سيتم التخفيض إلى ' + (pendingTier.name_ar || pendingTier.name) + ' في ' + periodEndLabel + '.')
                  : ('Scheduled downgrade to ' + pendingTier.name + ' on ' + periodEndLabel + '.')}
              </span>
              <button
                type="button"
                disabled={busy}
                onClick={() => runAction('cancel_downgrade')}
                style={{ padding: '6px 12px', borderRadius: 8, border: '1px solid var(--fg-secondary)', background: 'transparent', color: 'var(--fg-secondary)', fontSize: 12, fontWeight: 600, cursor: busy ? 'default' : 'pointer' }}
              >
                {ar ? 'إلغاء' : 'Cancel'}
              </button>
            </div>
          ) : lower.length > 0 && (
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8, color: 'var(--fg-primary)' }}>
                {ar ? 'تخفيض باقتك' : 'Downgrade your plan'}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {lower.map((t) => (
                  <button
                    key={t.id}
                    type="button"
                    disabled={busy}
                    onClick={() => { if (window.confirm(ar ? 'سيتم تطبيق التخفيض في دورة الفوترة القادمة. متابعة؟' : 'Downgrade will apply at your next billing cycle. Continue?')) runAction('request_downgrade', t.id); }}
                    style={{ padding: '8px 14px', borderRadius: 10, border: '1px solid var(--border)', background: 'transparent', color: 'var(--fg-secondary)', fontSize: 13, fontWeight: 600, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1 }}
                  >
                    {ar ? ('التخفيض إلى ' + (t.name_ar || t.name)) : ('Downgrade to ' + t.name)}
                  </button>
                ))}
              </div>
            </div>
          )}

          <button
            type="button"
            disabled={busy}
            onClick={() => { if (window.confirm(ar ? 'سيتم تعليق باقتك. هل تريد المتابعة؟' : 'This will suspend your plan. Continue?')) runAction('suspend'); }}
            style={{ padding: '8px 14px', borderRadius: 10, border: '1px solid var(--rose-deep, #9b2c2c)', background: 'transparent', color: 'var(--rose-deep, #9b2c2c)', fontSize: 13, fontWeight: 600, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1, alignSelf: 'flex-start' }}
          >
            {ar ? 'طلب تعليق الباقة' : 'Request Suspend'}
          </button>
        </React.Fragment>
      )}
    </div>
  );
}

/* -------- Vendor Subscription Tab -------- */
function VendorSubscriptionTab({ sub, tier, isTrial, trialDaysLeft, trialEnd, trialExpired, isRestricted, effectiveStatus, packageLevel, vendorId, db, ar, onRefresh }) {
  const [checkingOut, setCheckingOut] = useStateVD(false);
  const [checkoutErr, setCheckoutErr] = useStateVD(null);
  const [billing, setBilling] = useStateVD('monthly'); // 'monthly' | 'annual'
  const _cart = window.useCart ? window.useCart() : null;
  const { go: _go } = useNav();
  // Live pricing from the admin-managed subscription_tiers table (single source of truth).
  // The config file values are only a fallback used until this query resolves.
  const [tiersDb, setTiersDb] = useStateVD(null);
  useEffectVD(() => {
    let alive = true;
    (async () => {
      try {
        const { data } = await db.from('subscription_tiers')
          .select('package_level, price_monthly, price_annual, discount_percent, max_listings, rfq_access, rfq_responses_per_month, analytics_level, featured_placement, banner_eligibility, priority_support, promotion_access, can_create_discounts, commission_rate_override, visibility_priority')
          .eq('is_active', true);
        if (alive && data) {
          const m = {};
          data.forEach((t) => { if (t.package_level) m[t.package_level] = t; });
          setTiersDb(m);
        }
      } catch (e) { /* fall back to config */ }
    })();
    return () => { alive = false; };
  }, [db]);
  const priceFor = (level, id) => {
    const t = tiersDb && tiersDb[level];
    const cfg = window.VENDOR_PACKAGES_BY_ID[id];
    return {
      mo: (t && t.price_monthly != null) ? Number(t.price_monthly) : cfg.price,
      yr: (t && t.price_annual != null) ? Number(t.price_annual) : cfg.annualPrice,
    };
  };
  // A vendor already on a paid plan sees this panel as a "change plan / billing" switch.
  const isActivePaid = !!(sub && sub.status === 'active' && !isTrial);

  // Every feature row below is read from the admin-managed subscription_tiers
  // table so the vendor comparison ALWAYS matches what the admin configured.
  const _fv = (lvl) => (tiersDb && tiersDb[lvl]) || {};
  const _yesNo = (b) => b ? (ar ? 'نعم' : 'Yes') : (ar ? 'لا' : 'No');
  const _analytics = (a) => a === 'full' ? (ar ? 'كاملة + تصدير' : 'Full + export') : a === 'advanced' ? (ar ? 'متقدمة' : 'Advanced') : a === 'basic' ? (ar ? 'أساسية' : 'Basic') : (ar ? 'لا' : 'None');
  const _rfq = (t) => (!t || t.rfq_access === false) ? (ar ? 'لا' : 'No')
    : (t.rfq_responses_per_month == null ? (ar ? 'غير محدود' : 'Unlimited') : (t.rfq_responses_per_month + (ar ? ' /شهر' : ' / mo')));
  const _maxL = (lvl, id) => { const t = _fv(lvl); const cfg = window.VENDOR_PACKAGES_BY_ID[id]; return String((t.max_listings != null) ? t.max_listings : (cfg ? cfg.maxListings : '—')); };
  const _comm = (lvl) => { const c = _fv(lvl).commission_rate_override; return (c != null && c !== '') ? (Number(c) + '%') : '—'; };
  const PKG_FEATURES = [
    { label: ar ? 'الحد الأقصى للقوائم' : 'Max Listings',    p1: _maxL(1, 'starter'), p2: _maxL(2, 'growth'), p3: _maxL(3, 'premium') },
    { label: ar ? 'ردود طلبات الأسعار'  : 'RFQ responses',   p1: _rfq(_fv(1)), p2: _rfq(_fv(2)), p3: _rfq(_fv(3)) },
    { label: ar ? 'التحليلات'           : 'Analytics',       p1: _analytics(_fv(1).analytics_level), p2: _analytics(_fv(2).analytics_level), p3: _analytics(_fv(3).analytics_level) },
    { label: ar ? 'العرض المميز'        : 'Featured Placement', p1: _yesNo(_fv(1).featured_placement), p2: _yesNo(_fv(2).featured_placement), p3: _yesNo(_fv(3).featured_placement) },
    { label: ar ? 'الدعم بالأولوية'     : 'Priority Support',    p1: _yesNo(_fv(1).priority_support), p2: _yesNo(_fv(2).priority_support), p3: _yesNo(_fv(3).priority_support) },
    { label: ar ? 'أدوات الترويج'       : 'Promotion Tools',     p1: _yesNo(_fv(1).promotion_access), p2: _yesNo(_fv(2).promotion_access), p3: _yesNo(_fv(3).promotion_access) },
    { label: ar ? 'مكان كاروسيل الرئيسية' : 'Homepage featured carousel slot',    p1: _yesNo(_fv(1).banner_eligibility), p2: _yesNo(_fv(2).banner_eligibility), p3: _yesNo(_fv(3).banner_eligibility) },
    { label: ar ? 'إنشاء أكواد خصم'      : 'Create discount codes',    p1: _yesNo(_fv(1).can_create_discounts), p2: _yesNo(_fv(2).can_create_discounts), p3: _yesNo(_fv(3).can_create_discounts) },
    { label: ar ? 'العمولة'             : 'Commission',          p1: _comm(1), p2: _comm(2), p3: _comm(3) },
    { label: ar ? 'السعر الشهري' : 'Monthly Price',           p1: 'AED ' + priceFor(1, 'starter').mo, p2: 'AED ' + priceFor(2, 'growth').mo, p3: 'AED ' + priceFor(3, 'premium').mo },
    { label: ar ? 'السعر السنوي' : 'Annual Price',            p1: 'AED ' + priceFor(1, 'starter').yr.toLocaleString(), p2: 'AED ' + priceFor(2, 'growth').yr.toLocaleString(), p3: 'AED ' + priceFor(3, 'premium').yr.toLocaleString() },
  ];

  const pkgCols = [
    { key: 'p1', id: 'starter', level: 1, name: ar ? 'مورد مبتدئ' : 'Starter Vendor',  color: '#6B7280' },
    { key: 'p2', id: 'growth',  level: 2, name: ar ? 'مورد النمو' : 'Growth Vendor',   color: '#D97706' },
    { key: 'p3', id: 'premium', level: 3, name: ar ? 'مورد مميز'  : 'Premium Vendor',  color: '#7C3AED' },
  ];

  const startStripeCheckout = async (pkgLevel) => {
    setCheckingOut(true); setCheckoutErr(null);
    try {
      if (!window.stripeConfigured || !window.stripeConfigured()) {
        setCheckoutErr(ar ? 'لم يتم تفعيل الدفع بعد. تواصل مع سرايا.' : 'Stripe payment not yet configured. Contact Saraya Events.');
        setCheckingOut(false); return;
      }
      // Real recurring subscription via the create-subscription-checkout edge fn
      // (uses the vendor's JWT; applies the launch trial for first-timers).
      const result = await window.stripeSubscribe({
        packageLevel: pkgLevel,
        billingInterval: billing === 'annual' ? 'year' : 'month',
        successPath: 'vendor-dashboard',
        cancelPath: 'vendor-dashboard',
      });
      if (result && result.simulated) {
        setCheckoutErr(ar ? 'لم يتم تفعيل الدفع بعد. تواصل مع سرايا.' : 'Stripe payment not yet configured. Contact Saraya Events.');
      }
    } catch(e) {
      setCheckoutErr(e.message || 'Error');
    }
    setCheckingOut(false);
  };

  // Add the chosen package to the cart (with 5% VAT applied at checkout) and route
  // to the "Your Cart" checkout page, where Pay Now starts the recurring Stripe
  // subscription. Falls back to direct Stripe checkout if the cart is unavailable.
  const addPlanToCart = (pkgLevel) => {
    const idMap = { 1: 'starter', 2: 'growth', 3: 'premium' };
    const planId = idMap[pkgLevel] || 'starter';
    const p = priceFor(pkgLevel, planId);
    const interval = billing === 'annual' ? 'annual' : 'monthly';
    const amount = interval === 'annual' ? p.yr : p.mo;
    const t = tiersDb && tiersDb[pkgLevel];
    const nm = (t && t.name) || (window.VENDOR_PACKAGES_BY_ID[planId] ? window.VENDOR_PACKAGES_BY_ID[planId].en : ('Package ' + pkgLevel));
    const perEn = interval === 'annual' ? '/yr' : '/mo';
    if (!_cart || !_cart.add) { startStripeCheckout(pkgLevel); return; }
    _cart.add({
      id: 'vendor-plan-' + planId,
      isSubscription: true, digital: true, category: 'subscription', tone: 'champagne',
      price: amount,
      name: {
        en: 'Saraya Vendor Subscription — ' + nm + ' (AED ' + amount.toLocaleString() + perEn + ')',
        ar: 'اشتراك مورّد سرايا — ' + nm + ' (' + amount.toLocaleString() + ' درهم' + (interval === 'annual' ? '/سنة' : '/شهر') + ')',
      },
    }, 1, { interval: interval, packageLevel: pkgLevel, planId: planId, monthly: p.mo, annual: p.yr });
    _go('checkout');
  };

  const statusColor = isRestricted ? '#DC2626' : isTrial ? '#D97706' : '#16A34A';
  const statusBg    = isRestricted ? '#FEF2F2' : isTrial ? '#FFFBEB' : '#F0FDF4';

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      {/* Current status card */}
      <div style={{ background: 'var(--white)', borderRadius: 16, border: `1.5px solid ${statusColor}`, padding: '22px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <Badge tone="gold">{ar ? 'حالة الاشتراك' : 'Subscription Status'}</Badge>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500, marginTop: 8 }}>
              {tier?.name || (ar ? 'لا يوجد اشتراك' : 'No Subscription')}
            </h2>
            {tier && (
              <p style={{ color: 'var(--fg-secondary)', fontSize: 13.5, margin: '4px 0 0' }}>
                {isTrial
                  ? (ar ? 'وصول مجاني لمدة شهرين عند الإطلاق' : '2-month free access during platform launch')
                  : `AED ${tier.price_monthly}/mo`}
              </p>
            )}
          </div>
          <span style={{ padding: '6px 16px', borderRadius: 20, background: statusBg, color: statusColor, fontSize: 13, fontWeight: 700 }}>
            {effectiveStatus}
          </span>
        </div>

        {/* Trial details */}
        {sub && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(160px,1fr))', gap: 10, marginTop: 18 }}>
            {isTrial && [
              { icon: 'calendar',      label: ar ? 'بداية التجربة'   : 'Trial Start',    value: sub.trial_start_date ? new Date(sub.trial_start_date).toLocaleDateString('en-GB') : '—' },
              { icon: 'calendar-off',  label: ar ? 'نهاية التجربة'   : 'Trial Ends',     value: trialEnd ? trialEnd.toLocaleDateString('en-GB') : '—' },
              { icon: 'timer',         label: ar ? 'الأيام المتبقية' : 'Days Remaining', value: trialDaysLeft },
              { icon: 'package',       label: ar ? 'الحد الأقصى للقوائم' : 'Listing Limit', value: tier?.max_listings ?? 75 },
            ].map((item) => (
              <div key={item.label} style={{ padding: '12px 14px', borderRadius: 10, background: 'var(--bg-tint)', border: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 5 }}>
                  <Icon name={item.icon} size={13} style={{ color: 'var(--gold-deep)' }} />
                  <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{item.label}</span>
                </div>
                <p style={{ fontSize: 16, fontWeight: 700, margin: 0 }}>{item.value}</p>
              </div>
            ))}
            {!isTrial && sub.status === 'active' && [
              { icon: 'credit-card',   label: ar ? 'باقة' : 'Package',       value: tier?.name },
              { icon: 'package',       label: ar ? 'الحد الأقصى' : 'Listing Limit', value: tier?.max_listings },
              { icon: 'bar-chart-2',   label: ar ? 'التحليلات' : 'Analytics', value: tier?.analytics_level },
              { icon: 'star',          label: ar ? 'مميز' : 'Featured',       value: tier?.featured_placement ? (ar ? 'نعم' : 'Yes') : (ar ? 'لا' : 'No') },
              { icon: tier?.priority_support ? 'headset' : 'mail', label: ar ? 'الدعم' : 'Support', value: tier?.priority_support ? (ar ? 'أولوية (واتساب)' : 'Priority (WhatsApp)') : (ar ? 'بريد إلكتروني قياسي' : 'Standard Email') },
            ].map((item) => (
              <div key={item.label} style={{ padding: '12px 14px', borderRadius: 10, background: 'var(--bg-tint)', border: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 5 }}>
                  <Icon name={item.icon} size={13} style={{ color: 'var(--gold-deep)' }} />
                  <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{item.label}</span>
                </div>
                <p style={{ fontSize: 16, fontWeight: 700, margin: 0, textTransform: 'capitalize' }}>{item.value}</p>
              </div>
            ))}
          </div>
        )}

        {/* Trial message */}
        {isTrial && (
          <div style={{ marginTop: 16, padding: '12px 16px', borderRadius: 10, background: trialDaysLeft <= 7 ? '#FEF3C7' : 'var(--cream)', border: '1px solid var(--gold-light)', fontSize: 13.5, lineHeight: 1.65, color: 'var(--fg-secondary)' }}>
            <Icon name="info" size={14} style={{ color: 'var(--gold-deep)', marginInlineEnd: 6, verticalAlign: 'middle' }} />
            {ar
              ? 'وصولك المجاني للإطلاق نشط. بعد انتهاء التجربة، اختر باقة مدفوعة للاستمرار في استخدام سرايا للفعاليات.'
              : 'Your free launch access is active. After the trial ends, please select a paid subscription package to continue using Saraya Events Marketplace.'}
          </div>
        )}

        {/* Restricted message */}
        {isRestricted && (
          <div style={{ marginTop: 16, padding: '12px 16px', borderRadius: 10, background: '#FEF2F2', border: '1px solid #FECACA', fontSize: 13.5, color: '#B91C1C' }}>
            <Icon name="alert-triangle" size={14} style={{ marginInlineEnd: 6, verticalAlign: 'middle' }} />
            {ar
              ? 'انتهت فترة التجربة المجانية. اختر باقة مدفوعة لاستعادة الوصول الكامل ونشر قوائمك.'
              : 'Your free trial has ended. Choose a paid subscription package to restore full access and publish your listings.'}
          </div>
        )}
      </div>

      {/* Package comparison + selection (also shown to active vendors as a plan/billing switch) */}
      {true && (
        <div style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', overflow: 'hidden' }}>
          <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid var(--line)' }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, margin: 0 }}>
              {ar ? (isActivePaid ? 'تغيير الباقة أو الفوترة' : 'اختر باقتك') : (isActivePaid ? 'Change plan or billing' : 'Choose Your Package')}
            </h3>
            <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: '4px 0 0' }}>
              {ar
                ? (isActivePaid ? 'بدّل إلى الفوترة السنوية أو غيّر باقتك — تتم المعالجة عبر Stripe.' : 'انقر على "اختر" لبدء الدفع عبر Stripe.')
                : (isActivePaid ? 'Switch to annual billing or change your package — processed securely via Stripe.' : 'Click "Select" to proceed to Stripe payment.')}
            </p>
            {/* Monthly / Annual billing toggle */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, flexWrap: 'wrap' }}>
              <div style={{ display: 'inline-flex', background: 'var(--bg-tint)', border: '1px solid var(--line)', borderRadius: 999, padding: 4 }}>
                {[{ k: 'monthly', en: 'Monthly', ar: 'شهري' }, { k: 'annual', en: 'Annual', ar: 'سنوي' }].map((o) => (
                  <button key={o.k} onClick={() => setBilling(o.k)}
                    style={{ padding: '6px 18px', borderRadius: 999, border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 700, transition: 'all 160ms',
                      background: billing === o.k ? 'var(--gold)' : 'transparent',
                      color: billing === o.k ? 'var(--espresso)' : 'var(--fg-secondary)' }}>
                    {ar ? o.ar : o.en}
                  </button>
                ))}
              </div>
              <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--gold-deep)', background: '#FFFBEB', border: '1px solid var(--gold-light)', borderRadius: 999, padding: '4px 10px' }}>
                {ar ? 'وفّر حتى 25% سنوياً' : 'Save up to 25% yearly'}
              </span>
            </div>
          </div>

          {checkoutErr && (
            <div style={{ margin: '0 24px', padding: '10px 14px', borderRadius: 9, background: '#FEF2F2', color: '#DC2626', fontSize: 13, marginTop: 16 }}>
              {checkoutErr}
            </div>
          )}

          {/* Package cards */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 16, padding: '20px 24px' }}>
            {pkgCols.map((pkg) => (
              <div key={pkg.key} style={{ borderRadius: 14, border: `2px solid ${pkg.level === 2 ? pkg.color : 'var(--line)'}`,
                padding: '20px 18px', position: 'relative', background: pkg.level === 2 ? '#FFFBEB' : 'var(--white)' }}>
                {pkg.level === 2 && (
                  <div style={{ position: 'absolute', top: -12, left: '50%', transform: 'translateX(-50%)',
                    background: pkg.color, color: '#fff', fontSize: 11, fontWeight: 700, padding: '3px 12px',
                    borderRadius: 20, whiteSpace: 'nowrap' }}>
                    {ar ? 'الأكثر شيوعاً' : 'Most Popular'}
                  </div>
                )}
                <div style={{ fontWeight: 700, fontSize: 15, color: pkg.color, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  {pkg.name}
                  {isActivePaid && pkg.level === packageLevel && (
                    <span style={{ fontSize: 10, fontWeight: 700, color: '#16A34A', background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: 999, padding: '2px 8px' }}>
                      {ar ? 'الحالية' : 'Current'}
                    </span>
                  )}
                </div>
                {(() => {
                  const _p = priceFor(pkg.level, pkg.id);
                  const mo = _p.mo, yr = _p.yr;
                  if (billing === 'annual') {
                    const savePct = Math.round((1 - yr / (mo * 12)) * 100);
                    return (
                      <div style={{ marginBottom: 16 }}>
                        <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--fg-primary)' }}>
                          AED {yr.toLocaleString()}<span style={{ fontSize: 12, fontWeight: 400, color: 'var(--fg-muted)' }}>/yr</span>
                        </div>
                        <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--gold-deep)', marginTop: 3 }}>
                          {ar ? ('وفّر ' + savePct + '٪ مقابل الشهري') : ('Save ' + savePct + '% vs monthly')}
                        </div>
                      </div>
                    );
                  }
                  return (
                    <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--fg-primary)', marginBottom: 16 }}>
                      AED {mo}<span style={{ fontSize: 12, fontWeight: 400, color: 'var(--fg-muted)' }}>/mo</span>
                    </div>
                  );
                })()}
                {(() => {
                  const isCurrent = isActivePaid && pkg.level === packageLevel;
                  const isCurrentMonthly = isCurrent && billing === 'monthly';
                  let label;
                  if (checkingOut) label = ar ? 'جارٍ…' : 'Loading…';
                  else if (isCurrentMonthly) label = ar ? 'باقتك الحالية' : 'Current plan';
                  else if (isCurrent) label = ar ? 'التحويل إلى السنوي' : 'Switch to annual';
                  else if (isActivePaid) label = ar ? 'التبديل إلى هذه الباقة' : 'Switch to this plan';
                  else label = ar ? 'اختر هذه الباقة' : 'Select Package';
                  return (
                    <button
                      onClick={() => { if (!isCurrentMonthly) addPlanToCart(pkg.level); }}
                      disabled={checkingOut || isCurrentMonthly}
                      style={{ width: '100%', padding: '10px', borderRadius: 9, border: 'none', cursor: (checkingOut || isCurrentMonthly) ? 'default' : 'pointer',
                        background: isCurrentMonthly ? 'var(--line)' : (pkg.level === 2 ? pkg.color : pkg.level === 3 ? pkg.color : 'var(--espresso)'),
                        color: isCurrentMonthly ? 'var(--fg-secondary)' : '#fff', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700 }}>
                      {label}
                    </button>
                  );
                })()}
              </div>
            ))}
          </div>

          {/* Feature comparison table */}
          <div style={{ overflowX: 'auto', padding: '0 24px 24px' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
              <thead>
                <tr style={{ background: 'var(--bg-tint)', borderBottom: '1px solid var(--line)' }}>
                  <th style={{ padding: '10px 14px', textAlign: 'start', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em', width: '40%' }}>
                    {ar ? 'الميزة' : 'Feature'}
                  </th>
                  {pkgCols.map((pkg) => (
                    <th key={pkg.key} style={{ padding: '10px 14px', textAlign: 'center', fontWeight: 700, color: pkg.color, fontSize: 12.5 }}>
                      {pkg.level === 2 ? (ar ? 'النمو ★' : 'Growth ★') : pkg.level === 1 ? (ar ? 'مبتدئ' : 'Starter') : (ar ? 'بريميوم' : 'Premium')}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {PKG_FEATURES.map((row, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid var(--line)', background: i % 2 === 0 ? 'transparent' : 'var(--bg-tint)' }}>
                    <td style={{ padding: '10px 14px', fontWeight: 500, color: 'var(--fg-secondary)' }}>{row.label}</td>
                    {pkgCols.map((pkg) => {
                      const val = row[pkg.key];
                      const isNo  = val === 'No' || val === 'لا' || val === 'None' || val === 'لا يوجد';
                      const isYes = val === 'Yes' || val === 'نعم' || val === 'Priority' || val === 'أولوية';
                      return (
                        <td key={pkg.key} style={{ padding: '10px 14px', textAlign: 'center',
                          fontWeight: isYes ? 700 : 400,
                          color: isNo ? '#D1D5DB' : isYes ? '#16A34A' : 'var(--fg-primary)' }}>
                          {isNo ? '✗' : isYes ? '✓' : val}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Self-service plan management: upgrade/downgrade/suspend */}
      <SubscriptionManageControls db={db} vendorId={vendorId} ar={ar} onRefresh={onRefresh} startStripeCheckout={startStripeCheckout} checkingOut={checkingOut} />
    </div>
  );
}

