/* ============================================================
   Saraya Events — Vendor Management (redesigned panel)
   Self-contained. Rendered by AdminDashboard for the "vendors" tab.
   Props (all supplied by AdminDashboard, same scope/handlers):
     vendors, tiers, stats, db, busyId,
     setVendorStatus(id, status, reason?), giveFreeAccess(id, tierId),
     notifyVendor(id, tradeName), openVendorDetailsWindow(vendor),
     setConfirm({ msg, dangerous?, onOk })
   No external component deps — own palette so it renders identically
   regardless of which CSS custom properties the host page defines.
   ============================================================ */
function VendorManagementPanel(props) {
  var R = React;
  var vendors = props.vendors || [];
  var tiers = props.tiers || [];
  var stats = props.stats || {};
  var db = props.db;
  var busyId = props.busyId;
  var setVendorStatus = props.setVendorStatus || function () {};
  var giveFreeAccess = props.giveFreeAccess || function () {};
  var notifyVendor = props.notifyVendor || function () {};
  var openVendorDetailsWindow = props.openVendorDetailsWindow || function () {};
  var setConfirm = props.setConfirm || function () {};

  var _f = R.useState('all'); var filter = _f[0], setFilter = _f[1];
  var _q = R.useState(''); var query = _q[0], setQuery = _q[1];
  var _m = R.useState(null); var menuId = _m[0], setMenuId = _m[1];
  var _d = R.useState(null); var drawer = _d[0], setDrawer = _d[1];
  var _p = R.useState(null); var profile = _p[0], setProfile = _p[1];
  var _s = R.useState({}); var subs = _s[0], setSubs = _s[1];
  var _vd = R.useState([]); var drawerDocs = _vd[0], setDrawerDocs = _vd[1];

  // ---- palette (mockup tokens, as literals — no CSS-var dependency) ----
  var T = {
    gold: '#C9A961', goldDeep: '#A8884A', goldLight: '#E2CE9A', goldTint: '#F5EDD8',
    white: '#FFFFFF', ivory: '#FAF6F0', cream: '#F3EDE3', sand: '#E8DFCF',
    stone: '#A89E94', slate: '#6B5D52', espresso: '#2A1F1A',
    line: 'rgba(42,31,26,0.08)', lineStrong: 'rgba(42,31,26,0.16)', scrim: 'rgba(42,31,26,0.40)',
    success: '#5C8A6E', successBg: '#E8EFE9', warning: '#C9954D', warningBg: '#F8EDD9',
    error: '#B05050', errorBg: '#F5E3E3', info: '#6B7E96', infoBg: '#E5E9EE',
    serif: "'Cormorant Garamond',Georgia,serif",
    body: "'Outfit','Inter',system-ui,sans-serif"
  };

  // ---- load subscriptions for the subscription column ----
  R.useEffect(function () {
    var alive = true;
    if (!db) return function () {};
    (async function () {
      try {
        var res = await db.from('subscriptions').select('*, subscription_tiers(name, price_monthly)');
        if (!alive) return;
        var map = {};
        (res.data || []).forEach(function (s) { map[s.vendor_id] = s; });
        setSubs(map);
      } catch (e) { /* non-fatal: column just shows as no plan */ }
    })();
    return function () { alive = false; };
  }, [db, vendors.length]);

  // ---- load KYC documents for the open drawer vendor ----
  R.useEffect(function () {
    var alive = true;
    if (!db || !drawer || !drawer.id) { setDrawerDocs([]); return function () {}; }
    (async function () {
      try {
        var res = await db.from('vendor_documents').select('doc_type, file_name, file_url').eq('vendor_id', drawer.id);
        if (alive) setDrawerDocs(res.data || []);
      } catch (e) { if (alive) setDrawerDocs([]); }
    })();
    return function () { alive = false; };
  }, [db, drawer]);

  function viewVendorDoc(fileUrl) {
    if (!fileUrl || !db) return;
    var path = fileUrl.indexOf('/vendor-documents/') >= 0 ? fileUrl.split('/vendor-documents/')[1] : fileUrl;
    db.storage.from('vendor-documents').createSignedUrl(path, 300).then(function (r) {
      if (r && r.data && r.data.signedUrl) window.open(r.data.signedUrl, '_blank', 'noopener');
      else if (r && r.error) window.alert(r.error.message);
    });
  }

  // ---- helpers ----
  function bucketOf(st) {
    if (st === 'approved' || st === 'active') return 'approved';
    if (st === 'suspended') return 'suspended';
    return 'pending';
  }
  function statusLabel(st) {
    var map = {
      approved: 'Approved', active: 'Active', suspended: 'Suspended',
      pending_approval: 'Pending', agreement_accepted: 'Pending',
      under_review: 'Under review', documents_submitted: 'Docs submitted',
      registered: 'Registered'
    };
    return map[st] || (st ? st.charAt(0).toUpperCase() + st.slice(1) : '—');
  }
  function subEndOf(s) {
    if (!s) return null;
    var d = s.current_period_end || s.subscription_end_date || s.trial_end_date;
    return d ? new Date(d) : null;
  }
  function daysLeftOf(s) {
    var end = subEndOf(s);
    if (!end) return null;
    return Math.ceil((end.getTime() - Date.now()) / 86400000);
  }
  function planKind(s) {
    if (!s) return 'none';
    var dl = daysLeftOf(s);
    if (dl !== null && dl < 0) return 'expired';
    if (['expired', 'canceled', 'cancelled', 'past_due'].indexOf(s.status) !== -1) return 'expired';
    if (s.is_free_access) return 'free';
    if (s.is_trial_active || s.status === 'trialing') return 'trial';
    if (Number(s.amount_paid) > 0) return 'paid';
    return 'free';
  }
  function isExpired(vId) {
    var s = subs[vId];
    return planKind(s) === 'expired';
  }
  function fmtDate(d) {
    if (!d) return '—';
    try { return new Date(d).toLocaleDateString(); } catch (e) { return '—'; }
  }
  function contactOf(v) { return (v.profiles && v.profiles.display_name) || '—'; }
  function phoneOf(v) { return (v.profiles && v.profiles.phone) || v.whatsapp || '—'; }
  function categoryOf(v) {
    var c = v.business_category;
    if (Array.isArray(c)) return c.join(', ') || '—';
    return c || '—';
  }

  // ---- derived counts ----
  var counts = {
    all: vendors.length,
    pending: vendors.filter(function (v) { return bucketOf(v.status) === 'pending'; }).length,
    approved: vendors.filter(function (v) { return bucketOf(v.status) === 'approved'; }).length,
    suspended: vendors.filter(function (v) { return bucketOf(v.status) === 'suspended'; }).length,
    expired: vendors.filter(function (v) { return isExpired(v.id); }).length
  };
  var kpiPending = (stats.pendingApproval != null) ? stats.pendingApproval : counts.pending;
  var kpiActive = (stats.activeVendors != null) ? stats.activeVendors : counts.approved;
  var kpiSusp = counts.suspended;
  var kpiExpiring = vendors.filter(function (v) {
    var s = subs[v.id]; var dl = daysLeftOf(s);
    return isExpired(v.id) || (dl !== null && dl >= 0 && dl <= 7);
  }).length;

  // ---- filtering ----
  function matchFilter(v) {
    if (filter === 'all') return true;
    if (filter === 'expired') return isExpired(v.id);
    return bucketOf(v.status) === filter;
  }
  var rows = vendors.filter(function (v) {
    if (!matchFilter(v)) return false;
    var name = (v.trade_name || '').toLowerCase();
    return name.indexOf((query || '').toLowerCase()) !== -1;
  });

  // ---- status actions from the pill menu ----
  function doSuspend(v) {
    setMenuId(null);
    setConfirm({ msg: 'Suspend "' + (v.trade_name || 'this vendor') + '"? It will be hidden from the marketplace.', dangerous: true,
      onOk: function () { setConfirm(null); setVendorStatus(v.id, 'suspended'); } });
  }
  function doApprove(v) {
    setMenuId(null);
    setConfirm({ msg: 'Approve "' + (v.trade_name || 'this vendor') + '"?',
      onOk: function () { setConfirm(null); setVendorStatus(v.id, 'approved'); } });
  }
  function doReinstate(v) { setMenuId(null); setVendorStatus(v.id, 'approved'); }
  function doReject(v) {
    setMenuId(null);
    var reason = window.prompt('Rejection reason:');
    if (reason) setVendorStatus(v.id, 'registered', reason);
  }
  function doNotify(v) { setMenuId(null); notifyVendor(v.id, v.trade_name); }
  function doFreeSub(v) {
    setMenuId(null);
    if (tiers.length > 0) giveFreeAccess(v.id, tiers[0].id);
    else window.alert('No subscription tier is configured yet.');
  }

  // ---- tiny style helpers ----
  function pillStyle(kind) {
    var m = {
      approved: { bg: T.successBg, fg: T.success },
      pending: { bg: T.warningBg, fg: T.warning },
      suspended: { bg: T.errorBg, fg: T.error }
    }[kind] || { bg: T.cream, fg: T.slate };
    return {
      display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600,
      padding: '5px 11px', borderRadius: 999, cursor: 'pointer', border: '1px solid transparent',
      userSelect: 'none', background: m.bg, color: m.fg, fontFamily: T.body
    };
  }
  function tagStyle(kind) {
    var m = {
      trial: { bg: T.infoBg, fg: T.info }, paid: { bg: T.successBg, fg: T.success },
      free: { bg: T.goldTint, fg: T.goldDeep }, expired: { bg: T.errorBg, fg: T.error },
      none: { bg: T.cream, fg: T.stone }
    }[kind] || { bg: T.cream, fg: T.stone };
    return {
      fontSize: 10.5, fontWeight: 600, letterSpacing: '.03em', padding: '2px 8px',
      borderRadius: 999, textTransform: 'uppercase', background: m.bg, color: m.fg
    };
  }
  var planLabel = { trial: 'Trial', paid: 'Paid', free: 'Free', expired: 'Expired', none: 'No plan' };

  // ---- KPI card ----
  function Kpi(o) {
    return R.createElement('div', { style: {
      background: T.white, border: '1px solid ' + T.line, borderRadius: 16, padding: '16px 18px',
      boxShadow: '0 1px 2px rgba(42,31,26,0.04),0 4px 16px rgba(42,31,26,0.04)', position: 'relative', overflow: 'hidden'
    } },
      R.createElement('div', { style: { position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: o.accent } }),
      R.createElement('div', { style: { fontFamily: T.serif, fontSize: 32, fontWeight: 600, lineHeight: 1, color: T.espresso } }, o.num),
      R.createElement('div', { style: { fontSize: 12, color: T.slate, marginTop: 6 } }, o.label),
      R.createElement('div', { style: { fontSize: 11, color: T.stone, marginTop: 2 } }, o.hint)
    );
  }

  var CARD = { background: T.white, border: '1px solid ' + T.line, borderRadius: 16,
    boxShadow: '0 1px 2px rgba(42,31,26,0.04),0 4px 16px rgba(42,31,26,0.04)' };

  // subscription cell content
  function SubCell(v) {
    var s = subs[v.id];
    var kind = planKind(s);
    var dl = daysLeftOf(s);
    var pkg = (s && s.subscription_tiers && s.subscription_tiers.name) || (s ? 'Subscription' : 'No subscription');
    var daysNode = null;
    if (s) {
      if (kind === 'expired') daysNode = R.createElement('span', { style: { fontSize: 12, color: T.error, fontWeight: 600 } }, 'Expired');
      else if (dl !== null) daysNode = R.createElement('span', { style: { fontSize: 12, color: dl <= 7 ? T.error : T.slate, fontWeight: dl <= 7 ? 600 : 400 } }, dl + 'd left');
    }
    return R.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
      R.createElement('span', { style: { fontSize: 12, fontWeight: 600, color: T.espresso } }, pkg),
      R.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
        R.createElement('span', { style: tagStyle(kind) }, planLabel[kind]),
        daysNode
      )
    );
  }

  // caret icon
  function caret() {
    return R.createElement('svg', { viewBox: '0 0 24 24', width: 11, height: 11, style: { stroke: 'currentColor', fill: 'none', strokeWidth: 2.4 } },
      R.createElement('path', { d: 'm6 9 6 6 6-6' }));
  }

  // ---- status pill + dropdown menu ----
  function StatusControl(v) {
    var b = bucketOf(v.status);
    var open = menuId === v.id;
    var items = [];
    if (b === 'approved') items.push({ label: 'Suspend vendor', danger: true, on: function () { doSuspend(v); } });
    if (b === 'suspended') items.push({ label: 'Reinstate vendor', go: true, on: function () { doReinstate(v); } });
    if (b === 'pending') {
      items.push({ label: 'Approve vendor', go: true, on: function () { doApprove(v); } });
      items.push({ label: 'Reject', danger: true, on: function () { doReject(v); } });
    }
    items.push({ sep: true });
    items.push({ label: 'View details', on: function () { setMenuId(null); setDrawer(v); } });
    items.push({ label: 'Notify vendor', on: function () { doNotify(v); } });
    items.push({ label: 'Grant free sub', on: function () { doFreeSub(v); } });

    return R.createElement('div', { style: { position: 'relative', display: 'inline-block' }, onClick: function (e) { e.stopPropagation(); } },
      R.createElement('span', { style: pillStyle(b), onClick: function () { setMenuId(open ? null : v.id); } },
        R.createElement('span', { style: { width: 7, height: 7, borderRadius: '50%', background: 'currentColor' } }),
        statusLabel(v.status), caret()
      ),
      open ? R.createElement('div', { style: {
        position: 'absolute', top: 'calc(100% + 6px)', left: 0, background: T.white,
        border: '1px solid ' + T.lineStrong, borderRadius: 8,
        boxShadow: '0 2px 4px rgba(42,31,26,0.06),0 12px 32px rgba(42,31,26,0.08)', minWidth: 180, zIndex: 30, padding: 5
      } },
        items.map(function (it, i) {
          if (it.sep) return R.createElement('div', { key: i, style: { height: 1, background: T.line, margin: '4px 2px' } });
          return R.createElement('button', { key: i, onClick: it.on, style: {
            display: 'flex', width: '100%', alignItems: 'center', gap: 9, background: 'transparent', border: 0,
            textAlign: 'left', fontFamily: T.body, fontSize: 13, padding: '8px 10px', borderRadius: 6, cursor: 'pointer',
            color: it.danger ? T.error : it.go ? T.success : T.espresso
          } }, it.label);
        })
      ) : null
    );
  }

  // ---- one table row ----
  function Row(v) {
    return R.createElement('tr', { key: v.id, onClick: function () { setDrawer(v); }, style: { cursor: 'pointer', borderBottom: '1px solid ' + T.line } },
      R.createElement('td', { style: { padding: '16px 18px', verticalAlign: 'middle' } },
        R.createElement('div', { style: { fontWeight: 600, fontSize: 14.5, color: T.espresso } }, v.trade_name || '—'),
        R.createElement('div', { style: { fontSize: 11, color: T.stone, marginTop: 2, fontFamily: 'monospace' } }, String(v.id).slice(0, 8))
      ),
      R.createElement('td', { style: { padding: '16px 18px' } }, StatusControl(v)),
      R.createElement('td', { style: { padding: '16px 18px' }, onClick: function (e) { e.stopPropagation(); } }, SubCell(v)),
      R.createElement('td', { style: { padding: '16px 18px', fontSize: 14, color: v.city ? T.espresso : T.stone } }, v.city || '—'),
      R.createElement('td', { style: { padding: '16px 18px', fontSize: 14, color: T.espresso } }, fmtDate(v.created_at)),
      R.createElement('td', { style: { padding: '16px 18px', textAlign: 'right' }, onClick: function (e) { e.stopPropagation(); } },
        R.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' } },
          R.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: T.goldDeep, cursor: 'pointer' }, onClick: function () { setDrawer(v); } }, 'Details'),
          R.createElement('div', { style: { width: 32, height: 32, borderRadius: 8, border: '1px solid ' + T.lineStrong, background: T.white, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: T.slate, fontWeight: 700 }, onClick: function () { setMenuId(menuId === v.id ? null : v.id); } }, '⋯')
        )
      )
    );
  }

  // ---- drawer ----
  function drawerRow(k, val) {
    return R.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center', padding: '7px 0', fontSize: 13.5, borderTop: '1px solid ' + T.line } },
      R.createElement('span', { style: { color: T.slate } }, k),
      R.createElement('span', { style: { fontWeight: 600, color: T.espresso, textAlign: 'right' } }, val)
    );
  }
  function Drawer() {
    if (!drawer) return null;
    var v = drawer;
    var s = subs[v.id];
    var kind = planKind(s);
    var dl = daysLeftOf(s);
    var block = { background: T.white, border: '1px solid ' + T.line, borderRadius: 16, padding: '16px 18px', marginBottom: 14 };
    var h4 = { fontFamily: T.body, fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: T.stone, margin: '0 0 12px', fontWeight: 600 };
    var actBtn = function (label, kind2, on) {
      var st = { width: '100%', textAlign: 'center', padding: 11, fontFamily: T.body, fontSize: 13, fontWeight: 600, borderRadius: 8, cursor: 'pointer', border: '1px solid ' + T.lineStrong, background: T.white, color: T.espresso, marginBottom: 0 };
      if (kind2 === 'danger') { st.background = T.errorBg; st.color = T.error; st.border = '1px solid transparent'; }
      if (kind2 === 'good') { st.background = T.successBg; st.color = T.success; st.border = '1px solid transparent'; }
      if (kind2 === 'primary') { st.background = T.espresso; st.color = T.ivory; st.border = '1px solid ' + T.espresso; }
      return R.createElement('button', { onClick: on, style: st }, label);
    };
    var b = bucketOf(v.status);
    var controls = [];
    if (b === 'approved') controls.push(actBtn('Suspend vendor', 'danger', function () { doSuspend(v); }));
    if (b === 'suspended') controls.push(actBtn('Reinstate vendor', 'good', function () { doReinstate(v); }));
    if (b === 'pending') { controls.push(actBtn('Approve vendor', 'good', function () { doApprove(v); })); controls.push(actBtn('Reject application', 'danger', function () { doReject(v); })); }
    controls.push(actBtn('Notify vendor', '', function () { doNotify(v); }));
    controls.push(actBtn('Grant free subscription', '', function () { doFreeSub(v); }));

    return R.createElement(R.Fragment, null,
      R.createElement('div', { onClick: function () { setDrawer(null); }, style: { position: 'fixed', inset: 0, background: T.scrim, zIndex: 50 } }),
      R.createElement('aside', { style: { position: 'fixed', top: 0, right: 0, bottom: 0, width: 420, maxWidth: '92vw', background: T.ivory, boxShadow: '0 4px 8px rgba(42,31,26,0.06),0 24px 56px rgba(42,31,26,0.12)', zIndex: 60, overflowY: 'auto', fontFamily: T.body } },
        R.createElement('div', { style: { padding: '22px 24px', borderBottom: '1px solid ' + T.line, background: T.white, position: 'sticky', top: 0, zIndex: 2 } },
          R.createElement('span', { onClick: function () { setDrawer(null); }, style: { position: 'absolute', top: 20, right: 20, cursor: 'pointer', color: T.stone, fontSize: 22, lineHeight: 1 } }, '✕'),
          R.createElement('div', { style: { display: 'flex', gap: 14, alignItems: 'center' } },
            R.createElement('div', { style: { width: 44, height: 44, borderRadius: 999, background: T.goldTint, color: T.goldDeep, fontFamily: T.serif, fontWeight: 600, fontSize: 20, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, (v.trade_name || '?').charAt(0)),
            R.createElement('div', null,
              R.createElement('div', { style: { fontFamily: T.serif, fontSize: 22, fontWeight: 600, color: T.espresso } }, v.trade_name || '—'),
              R.createElement('div', { style: { fontSize: 11, color: T.stone, marginTop: 3, fontFamily: 'monospace' } }, String(v.id).slice(0, 8))
            )
          )
        ),
        R.createElement('div', { style: { padding: '22px 24px' } },
          R.createElement('button', { onClick: function () { openVendorDetailsWindow(v); }, style: { width: '100%', marginBottom: 14, padding: 12, background: T.espresso, color: T.ivory, border: '1px solid ' + T.espresso, borderRadius: 8, fontFamily: T.body, fontSize: 13, fontWeight: 600, cursor: 'pointer' } }, 'View full business profile →'),
          R.createElement('div', { style: block },
            R.createElement('h4', { style: h4 }, 'Account'),
            drawerRow('Status', statusLabel(v.status)),
            drawerRow('Registered', fmtDate(v.created_at)),
            drawerRow('Trade licence #', v.trade_license_number || '—')
          ),
          R.createElement('div', { style: block },
            R.createElement('h4', { style: h4 }, 'KYC Documents'),
            ['trade_license', 'emirates_id', 'bank_letter', 'vat_certificate'].map(function (dtk) {
              var labels = { trade_license: 'Trade License', emirates_id: 'Emirates ID', bank_letter: 'Bank Letter / IBAN', vat_certificate: 'VAT Certificate' };
              var doc = drawerDocs.filter(function (d) { return d.doc_type === dtk; })[0];
              return R.createElement('div', { key: dtk, style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid ' + T.line, gap: 10 } },
                R.createElement('span', { style: { fontSize: 13, color: doc ? T.espresso : T.stone } }, labels[dtk] + (doc ? '' : ' — not uploaded')),
                doc ? R.createElement('button', { onClick: function () { viewVendorDoc(doc.file_url); }, style: { padding: '5px 12px', borderRadius: 7, border: '1.5px solid ' + T.goldDeep, background: 'transparent', color: T.goldDeep, fontFamily: T.body, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', flexShrink: 0 } }, 'View') : null
              );
            })
          ),
          R.createElement('div', { style: block },
            R.createElement('h4', { style: h4 }, 'Details as entered'),
            drawerRow('Business name', v.trade_name || '—'),
            drawerRow('Contact person', contactOf(v)),
            drawerRow('Phone', phoneOf(v)),
            drawerRow('WhatsApp', v.whatsapp || '—'),
            drawerRow('Category', categoryOf(v)),
            drawerRow('City', v.city || '—'),
            drawerRow('Website', v.website || '—'),
            drawerRow('Instagram', v.instagram || '—')
          ),
          R.createElement('div', { style: Object.assign({}, block, { borderColor: T.goldLight, background: 'linear-gradient(180deg,' + T.goldTint + ',' + T.white + ')' }) },
            R.createElement('h4', { style: h4 }, 'Subscription · linked'),
            drawerRow('Package', (s && s.subscription_tiers && s.subscription_tiers.name) || '—'),
            drawerRow('Plan', planLabel[kind]),
            drawerRow('Expiry', s ? ((kind === 'expired' ? 'Expired · ' : '') + fmtDate(subEndOf(s)) + (dl !== null && dl >= 0 ? ' (' + dl + 'd left)' : '')) : '—')
          ),
          R.createElement('div', { style: block },
            R.createElement('h4', { style: h4 }, 'Control'),
            R.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 9 } }, controls)
          )
        )
      )
    );
  }

  // ---- root render ----
  var thStyle = { textAlign: 'left', fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: T.stone, fontWeight: 600, padding: '14px 18px', background: T.ivory, borderBottom: '1px solid ' + T.line };
  var tabDefs = [
    { k: 'all', label: 'All', c: counts.all },
    { k: 'pending', label: 'Pending', c: counts.pending },
    { k: 'approved', label: 'Approved', c: counts.approved },
    { k: 'suspended', label: 'Suspended', c: counts.suspended },
    { k: 'expired', label: 'Sub expired', c: counts.expired }
  ];

  return R.createElement('div', { style: { fontFamily: T.body } },
    // KPI strip
    R.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 22 } },
      Kpi({ num: kpiPending, label: 'Pending approvals', hint: 'Needs your review', accent: T.warning }),
      Kpi({ num: kpiActive, label: 'Active vendors', hint: 'Approved & live', accent: T.success }),
      Kpi({ num: kpiSusp, label: 'Suspended', hint: 'Hidden from site', accent: T.error }),
      Kpi({ num: kpiExpiring, label: 'Subs expiring ≤7d', hint: 'Follow up soon', accent: T.gold })
    ),
    // toolbar
    R.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 14, flexWrap: 'wrap' } },
      R.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, background: T.white, border: '1px solid ' + T.lineStrong, borderRadius: 8, padding: '9px 14px', minWidth: 230 } },
        R.createElement('svg', { viewBox: '0 0 24 24', width: 15, height: 15, style: { stroke: T.stone, fill: 'none', strokeWidth: 2 } },
          R.createElement('circle', { cx: 11, cy: 11, r: 8 }), R.createElement('path', { d: 'm21 21-4.3-4.3' })),
        R.createElement('input', { value: query, onChange: function (e) { setQuery(e.target.value); }, placeholder: 'Search vendors…', style: { border: 0, outline: 0, background: 'transparent', fontFamily: T.body, fontSize: 14, width: '100%', color: T.espresso } })
      ),
      R.createElement('div', { style: { fontSize: 12, color: T.stone } }, rows.length + ' of ' + vendors.length + ' vendors')
    ),
    // tabs
    R.createElement('div', { style: { display: 'flex', gap: 4, borderBottom: '1px solid ' + T.line, marginBottom: 2, flexWrap: 'wrap' } },
      tabDefs.map(function (t) {
        var active = filter === t.k;
        return R.createElement('div', { key: t.k, onClick: function () { setFilter(t.k); }, style: {
          padding: '11px 16px', fontSize: 14, fontWeight: active ? 600 : 500, color: active ? T.espresso : T.slate,
          cursor: 'pointer', borderBottom: '2px solid ' + (active ? T.gold : 'transparent'), marginBottom: -1,
          display: 'flex', alignItems: 'center', gap: 8
        } },
          t.label,
          R.createElement('span', { style: { background: active ? T.goldTint : T.cream, color: active ? T.goldDeep : T.slate, fontSize: 11, fontWeight: 600, padding: '1px 8px', borderRadius: 999 } }, t.c)
        );
      })
    ),
    // table
    R.createElement('div', { style: Object.assign({}, CARD, { overflow: 'hidden', marginTop: 16 }) },
      R.createElement('div', { style: { overflowX: 'auto' } },
        R.createElement('table', { style: { width: '100%', borderCollapse: 'collapse' } },
          R.createElement('thead', null,
            R.createElement('tr', null,
              R.createElement('th', { style: Object.assign({}, thStyle, { width: '24%' }) }, 'Business'),
              R.createElement('th', { style: Object.assign({}, thStyle, { width: '16%' }) }, 'Account status'),
              R.createElement('th', { style: Object.assign({}, thStyle, { width: '22%' }) }, 'Subscription'),
              R.createElement('th', { style: Object.assign({}, thStyle, { width: '12%' }) }, 'City'),
              R.createElement('th', { style: Object.assign({}, thStyle, { width: '12%' }) }, 'Registered'),
              R.createElement('th', { style: Object.assign({}, thStyle, { width: '14%', textAlign: 'right' }) }, 'Actions')
            )
          ),
          R.createElement('tbody', null,
            rows.length ? rows.map(function (v) { return Row(v); })
              : R.createElement('tr', null, R.createElement('td', { colSpan: 6, style: { textAlign: 'center', color: T.stone, padding: 40, fontSize: 14 } }, 'No vendors in this view.'))
          )
        )
      )
    ),
    Drawer()
  );
}

window.VendorManagementPanel = VendorManagementPanel;
