// ============================================================
// 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: 'الرخصة التجارية' } },
    { key: 'emirates_id',      label: { en: 'Emirates ID',       ar: 'الهوية الإماراتية' } },
    { key: 'vat_certificate',  label: { en: 'VAT Certificate',   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; }
    const { data: urlData } = db.storage.from('vendor-documents').getPublicUrl(path);
    await db.from('vendor_documents').upsert({
      vendor_id: vendorId, doc_type: docType,
      file_url: urlData.publicUrl, file_name: file.name,
    }, { onConflict: 'vendor_id,doc_type' });
    // 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();
  };

  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}</span>
            </div>
            <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>
        );
      })}
      {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, onSign, ar }) {
  const db = window.SarayaDB;
  const [agreed, setAgreed] = useStateVD(false);
  const [busy, setBusy] = useStateVD(false);

  const AGREEMENT_VERSION = '1.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);
    // Store agreement acceptance timestamp; no IP capture (GDPR compliance)
    await db.from('vendor_profiles').update({
      agreement_version: AGREEMENT_VERSION,
      agreement_signed_at: new Date().toISOString(),
      status: 'agreement_accepted',
    }).eq('id', vendorId);
    setBusy(false);
    onSign && onSign();
  };

  if (alreadySigned) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderRadius: 10, background: 'var(--cream)', border: '1.5px solid var(--gold)' }}>
        <Icon name="badge-check" size={20} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
        <span style={{ fontSize: 13.5, color: 'var(--fg-primary)' }}>
          {ar ? 'وقّعت على اتفاقية البائع.' : 'You have signed the Vendor Agreement.'}
        </span>
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gap: 14 }}>
      <div style={{
        maxHeight: 200, overflowY: 'auto', padding: '14px 16px',
        borderRadius: 10, border: '1px solid var(--line)',
        background: 'var(--bg-tint)', fontSize: 12.5, lineHeight: 1.7,
        color: 'var(--fg-secondary)', fontFamily: 'monospace', whiteSpace: 'pre-wrap',
      }}>
        {AGREEMENT_TEXT_EN}
      </div>
      <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 }) {
  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_rental_days: '', 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(isEdit
    ? { ...blank, ...initial, meta: { ...(blank.meta || {}), ...(initial.meta || {}) } }
    : blank);
  const [saving,       setSaving]       = useStateVD(false);
  const [err,          setErr]          = useStateVD(null);
  const [uploadingImg, setUploadingImg] = useStateVD(false);

  /* ── 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 });

  /* ── 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 } }));

  /* ── 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);

  /* ── 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 (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_rental_days = payload.min_rental_days ? Number(payload.min_rental_days) : null;
      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) { setErr(typeof result.error === 'string' ? result.error : (result.error.message || 'Save failed')); return; }
    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');

  /* ── 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>

          {categories.length > 0 && (
            <VDField label={ar ? 'الفئة *' : 'Category *'}>
              <VDSelect value={form.category_id} onChange={(e) => set('category_id', e.target.value)}
                options={categories.map((c) => ({ value: c.id, label: (ar ? c.name_ar || c.name_en : c.name_en) || c.slug }))} />
            </VDField>
          )}

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

          {type === 'products' && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: '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'}>
                  <VDInput type="number" min="0" step="0.01" value={form.sale_price || ''} onChange={(e) => set('sale_price', e.target.value)} placeholder="—" />
                </VDField>
                <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>
              <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>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 18 }}>
                {[['is_popular', ar ? 'مميّز' : 'Popular'], ['is_new', ar ? 'جديد' : 'New Arrival'], ['is_digital', ar ? 'رقمي' : 'Digital Product'], ['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 ? 'الحد الأدنى للأيام' : 'Min rental days'}>
                  <VDInput type="number" min="1" step="1" value={form.min_rental_days || ''} onChange={(e) => set('min_rental_days', e.target.value)} placeholder="1" />
                </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>
              </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>
          )}

          {/* ── 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>

          {/* ── 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>
              )}
            </>
          )}

          {/* ── 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', 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: 'cover', 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>
              </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>
        </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, onCountsChange, initialType, ar }) {
  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 svc = window.SarayaService;

  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]);
  

  const openAdd = () => {
    if (items.length >= maxListings) {
      alert(ar ? `لقد وصلت إلى الحد الأقصى من القوائم (${maxListings}).` : `You've reached the listing limit (${maxListings}) for your plan.`);
      return;
    }
    setEditItem(null);
    setShowModal(true);
  };

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

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

  const handleSaved = () => { closeModal(); loadItems(); onCountsChange && onCountsChange(); };

  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 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 }}>
      {/* Sub-tabs */}
      <div style={{ display: 'flex', gap: 0, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', background: 'var(--white)' }}>
        {LISTING_TYPES.map((t) => (
          <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: t !== 'services' ? '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>

      {/* 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>
      ) : (
        <div style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
            <thead>
              <tr style={{ background: 'var(--bg-tint)', borderBottom: '1px solid var(--line)' }}>
                <th style={{ padding: '11px 16px', textAlign: 'start', fontWeight: 600, color: 'var(--fg-secondary)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em' }}>{ar ? 'اسم القائمة' : 'Name'}</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' }}>
                      <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>
                    <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>
      )}

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

      {/* 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 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).single(),
        db.from('vendor_documents').select('*').eq('vendor_id', user.id),
        db.from('subscriptions').select('*, subscription_tiers(*)').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',     icon: 'layout-dashboard', label: { en: 'Overview',     ar: 'نظرة عامة' } },
    { key: 'profile',      icon: 'user',             label: { en: 'Store Profile', ar: 'ملف المتجر' } },
    { key: 'documents',    icon: 'file-text',        label: { en: 'Documents',    ar: 'الوثائق' } },
    { key: 'subscription', icon: 'credit-card',      label: { en: 'Subscription', ar: 'الاشتراك' } },
    { key: 'listings',     icon: 'package',          label: { en: 'Listings',     ar: 'القوائم' } },
    { key: 'orders',       icon: 'shopping-bag',     label: { en: 'Orders',       ar: 'الطلبات' } },
    { key: 'bookings',     icon: 'calendar',         label: { en: 'Bookings',     ar: 'الحجوزات' } },
    { key: 'rfqs',         icon: 'file-question',    label: { en: 'RFQs',         ar: 'عروض الأسعار' } },
    { key: 'leads',        icon: 'inbox',            label: { en: 'Leads',        ar: 'العملاء المحتملون' } },
    { key: 'complaints',   icon: 'alert-circle',     label: { en: 'Complaints',   ar: 'الشكاوى' } },
    { key: 'payouts',      icon: 'banknote',         label: { en: 'Payments',     ar: 'المدفوعات' } },
    { key: 'analytics',    icon: 'bar-chart-2',      label: { en: 'Analytics',    ar: 'الإحصائيات' } },
    { key: 'inventory',    icon: 'boxes',            label: { en: 'Inventory',    ar: 'المخزون' } },
    { key: 'notifications', icon: 'bell',            label: { en: 'Notifications', ar: 'الإشعارات' } },
    { key: 'settings',     icon: 'settings',         label: { en: 'Settings',     ar: 'الإعدادات' } },
  ];

  // Which tabs are accessible at the vendor's current package/subscription level
  const ALWAYS_OPEN = ['overview', 'profile', 'documents', 'subscription', 'settings', 'notifications'];
  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;
  };

  return (
    <main style={{ paddingTop: 100, minHeight: '100vh', background: 'var(--bg-canvas)' }}>
      <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>
          {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)' }}>
              {[
                { id: 'starter', en: 'Starter', ar: 'مبتدئ', price: 99 },
                { id: 'growth', en: 'Growth', ar: 'النمو', price: 199, badge: { en: 'Recommended', ar: 'موصى به' } },
                { id: 'premium', en: 'Premium', ar: 'مميز', price: 399 },
              ].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>

        {/* 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 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--fg-muted)', padding: '6px 12px 10px' }}>
              {ar ? 'لوحة البائع' : 'Vendor Panel'}
            </div>
            {TABS.map((t) => {
              const locked = !tabAllowed(t.key);
              return (
                <button key={t.key}
                  onClick={() => { if (!locked) setActiveTab(t.key); else setActiveTab('subscription'); }}
                  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 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>

          {/* 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 }}>
                <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} 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} onCountsChange={load} initialType={pendingListingType} ar={ar} />
            )}

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

            {/* BOOKINGS */}
            {activeTab === 'bookings' && (
              <VDPlaceholder icon="calendar" title={ar ? 'الحجوزات' : 'Bookings'} desc={ar ? 'تقويم حجوزات الخدمات والإيجارات قيد التطوير — سيتوفر قريبًا.' : 'A dedicated calendar for rental and service bookings is in development and will be available soon.'} />
            )}

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

            {/* LEADS */}
            {activeTab === 'leads' && (
              <VDPlaceholder icon="inbox" title={ar ? 'العملاء المحتملون' : 'Leads'} desc={ar ? 'صندوق العملاء المحتملين المخصص لبائعك قيد التطوير — سيتوفر قريبًا.' : 'A dedicated leads inbox matched to your business is in development and will be available soon.'} />
            )}

            {/* COMPLAINTS */}
            {activeTab === 'complaints' && (
              <VDPlaceholder icon="alert-circle" title={ar ? 'الشكاوى' : 'Complaints'} desc={ar ? 'نظام الشكاوى والنزاعات قيد التطوير — سيتوفر قريبًا.' : 'The complaints and disputes system is in development and will be available soon.'} />
            )}

            {/* PAYOUTS */}
            {activeTab === 'payouts' && (
              <VDPlaceholder icon="banknote" title={ar ? 'المدفوعات' : 'Payments'} desc={ar ? 'سجل مدفوعات تفصيلي قيد التطوير. راجع الملخص في تبويب نظرة عامة.' : 'A detailed payout ledger is in development. See the summary on the Overview tab.'} />
            )}

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

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

            {/* NOTIFICATIONS */}
            {activeTab === 'notifications' && (
              <VDPlaceholder icon="bell" title={ar ? 'الإشعارات' : 'Notifications'} desc={ar ? 'مركز إشعارات داخل لوحة التحكم قيد التطوير — سيتوفر قريبًا.' : 'An in-dashboard notification center is in development and will be available soon.'} />
            )}

            {/* SETTINGS */}
            {activeTab === 'settings' && (
              <div style={{ display: 'grid', gap: 28 }}>
                <VendorSettingsTab db={db} user={user} profile={profile} refreshProfile={refreshProfile} ar={ar} lang={lang} setLang={setLang} />
                <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>
            )}
          </>
        )}
          </div>{/* end main content */}
        </div>{/* end sidebar+content flex */}
      </Container>
    </main>
  );
}
window.VendorDashboardPage = VendorDashboardPage;

/* -------- 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 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 };
  };
  const fmtAED  = (n) => 'AED ' + Number(n || 0).toFixed(2);
  const fmtDate = (d) => new Date(d).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' });

  const load = useCallbackVD(async () => {
    if (!db || !user) return;
    setLoading(true);
    const { data } = await db
      .from('orders')
      .select('id, reference, type, status, total_amount, created_at, customer_confirmed_at, notes, delivery_address, profiles!customer_id(display_name, phone), order_items(id, name_en, name_ar, unit_price, quantity, line_total)')
      .eq('vendor_id', user.id)
      .order('created_at', { ascending: false });
    setOrders(data || []);
    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 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 = {
    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'].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 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)}{cust && <span> · {cust.display_name || '—'}</span>}
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</span>
                      <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--gold-deep)' }}>{fmtAED(o.total_amount)}</span>
                    </div>
                  </div>
                  <div style={{ padding: '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)} · {sel.profiles?.display_name || '—'}</div>
              </div>
              {(() => { const b = badge(sel.status); return <span style={{ padding: '6px 16px', borderRadius: 20, fontSize: 13, fontWeight: 600, background: b.bg, color: b.fg }}>{b.label}</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) => (
                <div key={it.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderTop: '1px solid var(--line)', gap: 12 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 500 }}>{ar ? (it.name_ar || it.name_en) : it.name_en}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 2 }}>{ar ? 'الكمية' : 'Qty'}: {it.quantity} · {fmtAED(it.unit_price)} {ar ? 'للوحدة' : 'each'}</div>
                  </div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{fmtAED(it.line_total)}</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>

            {/* 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.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 }) {
  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>
        ))}
      </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 }) { 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 [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 catRes = await db.from('categories').select('name_en, name_ar, type').eq('is_active', true).order('type'); setCategories((catRes && catRes.data) || []); 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(r.data.business_category || ''); setLicenseNumber(r.data.trade_license_number || ''); setLicenseExpiry(r.data.trade_license_expiry || ''); setBankName(r.data.bank_name || ''); setBankIban(r.data.bank_iban || ''); setBankAccountName(r.data.bank_account_name || ''); setLogoUrl(r.data.logo_url || ''); } setLoadingVp(false); })(); }, [db, user]); const saveAccount = async () => { setSavingAccount(true); setMsg(null); const r = await db.from('profiles').update({ full_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, bank_name: bankName, bank_iban: bankIban, bank_account_name: bankAccountName }).eq('id', user.id); 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 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><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><select style={fieldStyle} value={businessCategory} onChange={(e) => setBusinessCategory(e.target.value)}><option value="">{ar ? 'اختر فئة' : 'Select a category'}</option>{categories.map((c, i) => (<option key={i} value={c.name_en}>{ar ? c.name_ar : c.name_en}</option>))}</select></div><div><label style={labelStyle}>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}>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 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 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>
      {renderTable(products, 'products', ar ? 'المنتجات' : 'Products')}
      {renderTable(rentals, 'rentals', ar ? 'الإيجارات' : 'Rentals')}{renderTable(services, 'services', ar ? 'الخدمات' : 'Services')}
    </div>
  );
}

/* -------- Inline section helper -------- */
function Section({ title, desc, children }) {
  return (
    <div style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', padding: '24px' }}>
      <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           || '',
  });
  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 updatePayload = { ...form };

    // 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).single();
      const currentIdx = STATUSES_ORDER.indexOf(current?.status);
      const targetIdx  = STATUSES_ORDER.indexOf('pending_approval');
      if (currentIdx !== -1 && currentIdx < targetIdx) {
        updatePayload.status = 'pending_approval';
      }
    }

    const { error } = await db.from('vendor_profiles').update(updatePayload).eq('id', user.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>
        <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>
        <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>
  );
}

/* -------- 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 PKG_FEATURES = [
        { label: ar ? 'الحد الأقصى للقوائم' : 'Max Listings',          p1: String(window.VENDOR_PACKAGES_BY_ID.starter.maxListings), p2: String(window.VENDOR_PACKAGES_BY_ID.growth.maxListings), p3: String(window.VENDOR_PACKAGES_BY_ID.premium.maxListings) },
    { label: ar ? 'الوصول إلى RFQ'     : 'RFQ Access',             p1: ar ? 'لا' : 'No', p2: ar ? 'نعم' : 'Yes', p3: ar ? 'أولوية' : 'Priority' },
    { label: ar ? 'التحليلات'          : 'Analytics',               p1: ar ? 'لا' : 'None', p2: ar ? 'أساسية' : 'Basic', p3: ar ? 'متقدمة' : 'Advanced' },
    { label: ar ? 'العرض المميز'       : 'Featured Listing',        p1: ar ? 'لا' : 'No', p2: ar ? 'لا' : 'No', p3: ar ? 'نعم' : 'Yes' },
    { label: ar ? 'أدوات الترويج'      : 'Promotion Tools',         p1: ar ? 'لا' : 'No', p2: ar ? 'أساسية' : 'Basic', p3: ar ? 'كاملة' : 'Full' },
    { label: ar ? 'الإدارة الأولوية'   : 'Priority Support',        p1: ar ? 'لا' : 'No', p2: ar ? 'لا' : 'No', p3: ar ? 'نعم' : 'Yes' },
    { label: ar ? 'العملاء المحتملون'  : 'Leads & Inquiries',       p1: ar ? 'لا' : 'No', p2: ar ? 'نعم' : 'Yes', p3: ar ? 'نعم + أولوية' : 'Yes + Priority' },
    { label: ar ? 'إدارة الحجوزات'    : 'Bookings & Complaints',   p1: ar ? 'لا' : 'No', p2: ar ? 'نعم' : 'Yes', p3: ar ? 'نعم' : 'Yes' },
    { label: ar ? 'السعر الشهري' : 'Monthly Price',           p1: 'AED ' + window.VENDOR_PACKAGES_BY_ID.starter.price, p2: 'AED ' + window.VENDOR_PACKAGES_BY_ID.growth.price, p3: 'AED ' + window.VENDOR_PACKAGES_BY_ID.premium.price },
    { label: ar ? 'السعر السنوي' : 'Annual Price',            p1: 'AED ' + window.VENDOR_PACKAGES_BY_ID.starter.annualPrice.toLocaleString(), p2: 'AED ' + window.VENDOR_PACKAGES_BY_ID.growth.annualPrice.toLocaleString(), p3: 'AED ' + window.VENDOR_PACKAGES_BY_ID.premium.annualPrice.toLocaleString() },
  ];

  const pkgCols = [
    { key: 'p1', level: 1, name: ar ? 'المبتدئ'  : 'Package 1 — Starter',  color: '#6B7280' },
    { key: 'p2', level: 2, name: ar ? 'النمو'     : 'Package 2 — Growth',   color: '#D97706' },
    { key: 'p3', level: 3, name: ar ? 'بريميوم'   : 'Package 3 — Premium',  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;
      }
      const TIER_INFO = { 1: { name: 'Starter Vendor', price: 99 }, 2: { name: 'Growth Vendor', price: 199 }, 3: { name: 'Premium Vendor', price: 399 } };
      const info = TIER_INFO[pkgLevel];
      const lineItems = window.buildStripeLineItems([{ name: info.name, price: info.price, qty: 1, isSubscription: true }]);
      const result = await window.stripeCheckout({
        mode: 'subscription',
        lineItems,
        customer: { id: vendorId },
        metadata: { vendor_id: vendorId, subscription_type: info.name },
        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);
  };

  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') },
            ].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 */}
      {(isRestricted || trialExpired || !sub || sub.status !== 'active') && (
        <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 ? 'اختر باقتك' : 'Choose Your Package'}
            </h3>
            <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: '4px 0 0' }}>
              {ar ? 'انقر على "اختر" لبدء الدفع عبر Stripe.' : 'Click "Select" to proceed to Stripe payment.'}
            </p>
          </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 }}>{pkg.name}</div>
                <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--fg-primary)', marginBottom: 16 }}>
                  {pkg.key === 'p1' ? 'AED 99' : pkg.key === 'p2' ? 'AED 199' : 'AED 399'}
                  <span style={{ fontSize: 12, fontWeight: 400, color: 'var(--fg-muted)' }}>/mo</span>
                </div>
                <button
                  onClick={() => startStripeCheckout(pkg.level)}
                  disabled={checkingOut}
                  style={{ width: '100%', padding: '10px', borderRadius: 9, border: 'none', cursor: checkingOut ? 'wait' : 'pointer',
                    background: pkg.level === 2 ? pkg.color : pkg.level === 3 ? pkg.color : 'var(--espresso)',
                    color: '#fff', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700 }}>
                  {checkingOut ? (ar ? 'جارٍ…' : 'Loading…') : (ar ? 'اختر هذه الباقة' : 'Select Package')}
                </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>
      )}

      {/* Current plan detail (when active paid) */}
      {!isRestricted && sub?.status === 'active' && (
        <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
            ? 'لتغيير أو ترقية باقتك، تواصل مع فريق سرايا أو انتظر دورة الفوترة القادمة.'
            : 'To change or upgrade your package, contact the Saraya team or wait for your next billing cycle.'}
        </div>
      )}
    </div>
  );
}

