const { useState: useStateV, useEffect: useEffectV, useCallback: useCallbackV } = React;

// ── Helpers ────────────────────────────────────────────────────────────────────

function fmtDateV(ts) {
  if (!ts) return '—';
  return new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

function fmtRelativeV(ts) {
  if (!ts) return '—';
  const diff = Date.now() - new Date(ts).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

function initialsV(name) {
  if (!name) return '?';
  return name.split(' ').map(s => s[0]).join('').slice(0, 2).toUpperCase();
}

const DOC_TYPE_LABEL = { citizenship: 'Citizenship', passport: 'Passport', license: "Driver's License" };
const VEHICLE_LABEL  = { bicycle: 'Bicycle', motorcycle: 'Motorcycle', scooter: 'Scooter', car: 'Car', on_foot: 'On Foot' };
const VEHICLE_ICON   = { bicycle: '🚲', motorcycle: '🏍️', scooter: '🛵', car: '🚗', on_foot: '🚶' };

const KYC_STATUS_CHIP    = { pending: 'warn', approved: 'pos', rejected: 'neg' };
const DRIVER_STATUS_CHIP = { pending_approval: 'warn', approved: 'pos', rejected: 'neg', suspended: 'neg' };
const STORE_STATUS_CHIP  = { unverified: 'warn', pending: 'warn', verified: 'pos', rejected: 'neg' };

// ── Push notification helper ──────────────────────────────────────────────────

const SUPPORT_USER_ID_V = 'ce477efa-bd17-432c-9a45-8bee5e985719';

async function sendPushV(sb, userId, title, body) {
  const now = new Date().toISOString();
  const rows = [
    { user_id: userId, type: 'promotional', title, body, data: { source: 'admin_action' }, read: false, created_at: now },
  ];
  if (userId !== SUPPORT_USER_ID_V) {
    rows.push({ user_id: SUPPORT_USER_ID_V, type: 'promotional', title: `[Preview] ${title}`, body, data: { source: 'admin_action', preview: true }, read: false, created_at: now });
  }
  await sb.from('user_notifications').insert(rows);
}

// ── DB fetch ───────────────────────────────────────────────────────────────────

async function fetchKycList(sb, filter) {
  let q = sb.from('kyc_submissions').select('*').order('created_at', { ascending: false }).limit(100);
  if (filter !== 'all') q = q.eq('status', filter);
  const { data } = await q;
  if (!data?.length) return [];
  const userIds = [...new Set(data.map(r => r.user_id))];
  const { data: profiles } = await sb.from('user_profiles')
    .select('id, username, display_name, email, avatar_url, verification_level').in('id', userIds);
  const pm = {};
  (profiles || []).forEach(p => { pm[p.id] = p; });
  return data.map(r => ({ ...r, profile: pm[r.user_id] || null }));
}

async function fetchKycPendingCount(sb) {
  const { count } = await sb.from('kyc_submissions')
    .select('*', { count: 'exact', head: true }).eq('status', 'pending');
  return count ?? 0;
}

async function fetchDriverList(sb, filter) {
  let q = sb.from('delivery_partners').select('*').order('created_at', { ascending: false }).limit(100);
  if (filter !== 'all') q = q.eq('status', filter);
  const { data: partners } = await q;
  if (!partners?.length) return [];
  const userIds = partners.map(p => p.user_id);
  const { data: profiles } = await sb.from('user_profiles')
    .select('id, username, display_name, email, phone, avatar_url').in('id', userIds);
  const pm = {};
  (profiles || []).forEach(p => { pm[p.id] = p; });
  return partners.map(p => ({
    id: p.id, user_id: p.user_id, vehicle_type: p.vehicle_type,
    coverage_city: p.coverage_city, coverage_area: p.coverage_area,
    status: p.status, is_active: p.is_active ?? false,
    total_deliveries: p.total_deliveries ?? 0,
    completed_deliveries: p.completed_deliveries ?? 0,
    rating: p.rating ?? 5.0,
    verification_documents: p.verification_documents || {},
    created_at: p.created_at, profile: pm[p.user_id] || null,
  }));
}

async function fetchDriverPendingCount(sb) {
  const { count } = await sb.from('delivery_partners')
    .select('*', { count: 'exact', head: true }).eq('status', 'pending_approval');
  return count ?? 0;
}

async function fetchStoreList(sb, filter) {
  let q = sb.from('stores')
    .select('id, seller_id, name, verification_status, business_name, tax_id, business_documents, created_at')
    .order('created_at', { ascending: false }).limit(100);
  if (filter !== 'all') q = q.eq('verification_status', filter);
  const { data } = await q;
  if (!data?.length) return [];
  const sellerIds = [...new Set(data.map(s => s.seller_id))];
  const { data: profiles } = await sb.from('user_profiles')
    .select('id, username, display_name, email, avatar_url').in('id', sellerIds);
  const pm = {};
  (profiles || []).forEach(p => { pm[p.id] = p; });
  return data.map(s => ({
    id: s.id, seller_id: s.seller_id, name: s.name,
    verification_status: s.verification_status || 'unverified',
    business_name: s.business_name, tax_id: s.tax_id,
    business_documents: s.business_documents || [],
    created_at: s.created_at, profile: pm[s.seller_id] || null,
  }));
}

// ── Small shared components ────────────────────────────────────────────────────

const AvatarV = ({ name, size = 36 }) => (
  <div style={{
    width: size, height: size, borderRadius: 8,
    background: 'var(--surface-2)', border: '1px solid var(--hairline)',
    display: 'grid', placeItems: 'center', flexShrink: 0,
    fontFamily: 'var(--font-mono)', fontSize: size * 0.33, fontWeight: 600,
    color: 'var(--ink-2)',
  }}>
    {initialsV(name)}
  </div>
);

const KvRow = ({ label, value }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '8px 16px', borderBottom: '1px solid var(--hairline)' }}>
    <span className="muted" style={{ fontSize: 12 }}>{label}</span>
    <span style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--ink)' }}>{value}</span>
  </div>
);

const SectionHeader = ({ icon, title, right }) => {
  const I = window.Icons;
  return (
    <div className="panel-h" style={{ gap: 8 }}>
      <span style={{ color: 'var(--ink-3)', display: 'flex' }}>{icon}</span>
      <span>{title}</span>
      {right && <div className="right">{right}</div>}
    </div>
  );
};

// ── List row components ────────────────────────────────────────────────────────

const KycRow = ({ item, selected, onClick }) => {
  const I = window.Icons;
  const name = item.profile?.display_name || item.profile?.username || item.full_name;
  const chip = KYC_STATUS_CHIP[item.status] || 'warn';
  return (
    <div onClick={onClick} style={{
      padding: '11px 14px', borderBottom: '1px solid var(--hairline)',
      cursor: 'pointer', background: selected ? 'var(--surface-2)' : 'transparent',
      position: 'relative',
    }}>
      {selected && <div style={{ position: 'absolute', left: 0, top: 6, bottom: 6, width: 2, background: 'var(--accent)' }} />}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <AvatarV name={name} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontSize: 13, fontWeight: 550, color: selected ? 'var(--accent-ink)' : 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
            <span className="muted" style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', flexShrink: 0 }}>{fmtRelativeV(item.created_at)}</span>
          </div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 3 }}>
            <span className="muted" style={{ fontSize: 11.5 }}>{DOC_TYPE_LABEL[item.document_type] || item.document_type}</span>
            <span className={`chip dot ${chip}`} style={{ fontSize: 10 }}>{item.status}</span>
          </div>
        </div>
        <I.arrowR size={13} style={{ color: 'var(--ink-3)', flexShrink: 0 }} />
      </div>
    </div>
  );
};

const DriverRow = ({ item, selected, onClick }) => {
  const I = window.Icons;
  const name = item.profile?.display_name || item.profile?.username || 'Unknown';
  const chip = DRIVER_STATUS_CHIP[item.status] || 'warn';
  const statusLabel = item.status === 'pending_approval' ? 'pending' : item.status;
  return (
    <div onClick={onClick} style={{
      padding: '11px 14px', borderBottom: '1px solid var(--hairline)',
      cursor: 'pointer', background: selected ? 'var(--surface-2)' : 'transparent',
      position: 'relative',
    }}>
      {selected && <div style={{ position: 'absolute', left: 0, top: 6, bottom: 6, width: 2, background: 'var(--accent)' }} />}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <AvatarV name={name} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontSize: 13, fontWeight: 550, color: selected ? 'var(--accent-ink)' : 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
            <span className="muted" style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', flexShrink: 0 }}>{fmtRelativeV(item.created_at)}</span>
          </div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 3 }}>
            <span className="muted" style={{ fontSize: 11.5 }}>{VEHICLE_ICON[item.vehicle_type]} {VEHICLE_LABEL[item.vehicle_type] || item.vehicle_type}</span>
            <span className="muted" style={{ fontSize: 11 }}>·</span>
            <span className="muted" style={{ fontSize: 11.5 }}>{item.coverage_city}</span>
            <span className={`chip dot ${chip}`} style={{ fontSize: 10 }}>{statusLabel}</span>
          </div>
        </div>
        <I.arrowR size={13} style={{ color: 'var(--ink-3)', flexShrink: 0 }} />
      </div>
    </div>
  );
};

const StoreRow = ({ item, selected, onClick }) => {
  const I = window.Icons;
  const owner = item.profile?.display_name || item.profile?.username || 'Unknown';
  const chip = STORE_STATUS_CHIP[item.verification_status] || 'warn';
  return (
    <div onClick={onClick} style={{
      padding: '11px 14px', borderBottom: '1px solid var(--hairline)',
      cursor: 'pointer', background: selected ? 'var(--surface-2)' : 'transparent',
      position: 'relative',
    }}>
      {selected && <div style={{ position: 'absolute', left: 0, top: 6, bottom: 6, width: 2, background: 'var(--accent)' }} />}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8, flexShrink: 0,
          background: '#fef3c7', border: '1px solid #fde68a',
          display: 'grid', placeItems: 'center', fontSize: 16,
        }}>🏪</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontSize: 13, fontWeight: 550, color: selected ? 'var(--accent-ink)' : 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.name}</span>
            <span className={`chip dot ${chip}`} style={{ fontSize: 10, flexShrink: 0 }}>{item.verification_status}</span>
          </div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 3 }}>
            <span className="muted" style={{ fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{owner}</span>
            {item.business_documents.length > 0 && (
              <>
                <span className="muted" style={{ fontSize: 11 }}>·</span>
                <span className="muted" style={{ fontSize: 11 }}>{item.business_documents.length} doc{item.business_documents.length !== 1 ? 's' : ''}</span>
              </>
            )}
          </div>
        </div>
        <I.arrowR size={13} style={{ color: 'var(--ink-3)', flexShrink: 0 }} />
      </div>
    </div>
  );
};

// ── Detail panels ──────────────────────────────────────────────────────────────

const KycDetail = ({ item, actionLoading, onApprove, onReject, onBack }) => {
  const I = window.Icons;
  const sb = window.supabaseClient;
  const [frontUrl, setFrontUrl] = useStateV(null);
  const [backUrl, setBackUrl]   = useStateV(null);
  const [urlLoading, setUrlLoading] = useStateV(false);
  const isPending = item.status === 'pending';
  const name = item.profile?.display_name || item.profile?.username || item.full_name;
  const chip = KYC_STATUS_CHIP[item.status] || 'warn';

  useEffectV(() => {
    setFrontUrl(null); setBackUrl(null);
    if (!item.document_front_path || !sb) return;
    setUrlLoading(true);
    Promise.all([
      sb.storage.from('kyc-documents').createSignedUrl(item.document_front_path, 3600),
      item.document_back_path
        ? sb.storage.from('kyc-documents').createSignedUrl(item.document_back_path, 3600)
        : Promise.resolve({ data: null }),
    ]).then(([f, b]) => {
      setFrontUrl(f.data?.signedUrl || null);
      setBackUrl(b.data?.signedUrl || null);
      setUrlLoading(false);
    }).catch(() => setUrlLoading(false));
  }, [item.id]);

  return (
    <div style={{ flex: 1, overflow: 'auto' }}>
      {/* Back button (mobile) */}
      <div style={{ padding: '10px 16px 0', display: 'none' }} className="detail-back">
        <button className="btn ghost" style={{ height: 26, fontSize: 12 }} onClick={onBack}>
          <I.arrowR size={12} style={{ transform: 'rotate(180deg)' }} />Back
        </button>
      </div>

      <div style={{ padding: 20, maxWidth: 640, margin: '0 auto' }}>
        {/* Header card */}
        <div className="panel" style={{ padding: 18, marginBottom: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <AvatarV name={name} size={44} />
              <div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{name}</span>
                  <span className={`chip dot ${chip}`}>{item.status}</span>
                </div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                  {item.profile?.email && <span style={{ marginRight: 10 }}>{item.profile.email}</span>}
                  {item.profile?.username && <span style={{ marginRight: 10 }}>@{item.profile.username}</span>}
                  <span>Submitted {fmtDateV(item.created_at)}</span>
                </div>
              </div>
            </div>
            {isPending && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
                <button className="btn primary" style={{ height: 28, fontSize: 12 }} disabled={actionLoading} onClick={onApprove}>
                  <I.check size={11} />Approve
                </button>
                <button className="btn" style={{ height: 28, fontSize: 12, color: 'var(--neg)', borderColor: 'var(--neg)' }} disabled={actionLoading} onClick={onReject}>
                  <I.x size={11} />Reject
                </button>
              </div>
            )}
          </div>
          {item.rejection_reason && (
            <div style={{ marginTop: 12, padding: '10px 12px', background: 'var(--neg-bg, #fef2f2)', border: '1px solid var(--neg-border, #fecaca)', borderRadius: 6 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--neg)', marginBottom: 3 }}>Rejection reason</div>
              <div style={{ fontSize: 12.5, color: 'var(--neg)' }}>{item.rejection_reason}</div>
            </div>
          )}
        </div>

        {/* Identity details */}
        <div className="panel" style={{ marginBottom: 14, overflow: 'hidden' }}>
          <SectionHeader icon={<I.users size={13} />} title="Identity Details" />
          {[
            { label: 'Full name', value: item.full_name },
            { label: 'Phone', value: item.phone_number },
            { label: 'Document type', value: DOC_TYPE_LABEL[item.document_type] || item.document_type },
            ...(item.document_number ? [{ label: 'Document number', value: item.document_number }] : []),
          ].map(({ label, value }) => <KvRow key={label} label={label} value={value} />)}
        </div>

        {/* Documents */}
        <div className="panel" style={{ marginBottom: 14, overflow: 'hidden' }}>
          <SectionHeader icon={<I.receipt size={13} />} title="Identity Documents" />
          <div style={{ padding: 16 }}>
            {urlLoading ? (
              <div className="muted" style={{ fontSize: 12, padding: '12px 0' }}>Loading document URLs…</div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: item.document_back_path ? '1fr 1fr' : '1fr', gap: 14 }}>
                <DocImageV label="Front" url={frontUrl} path={item.document_front_path} />
                {item.document_back_path && <DocImageV label="Back" url={backUrl} path={item.document_back_path} />}
              </div>
            )}
          </div>
        </div>

        {/* Reviewed */}
        {item.reviewed_at && (
          <div className="panel" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8, flexShrink: 0, display: 'grid', placeItems: 'center',
              background: item.status === 'approved' ? 'var(--pos-bg, #f0fdf4)' : 'var(--neg-bg, #fef2f2)',
            }}>
              {item.status === 'approved' ? <I.check size={16} style={{ color: 'var(--pos)' }} /> : <I.x size={16} style={{ color: 'var(--neg)' }} />}
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 550, color: 'var(--ink)', textTransform: 'capitalize' }}>{item.status}</div>
              <div className="muted" style={{ fontSize: 11.5 }}>{fmtDateV(item.reviewed_at)}</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

const DocImageV = ({ label, url, path }) => {
  const I = window.Icons;
  if (!url) {
    return (
      <div style={{ borderRadius: 6, border: '1px solid var(--hairline)', background: 'var(--surface-2)', padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, minHeight: 120 }}>
        <I.receipt size={18} style={{ color: 'var(--ink-3)' }} />
        <span className="muted" style={{ fontSize: 11, textAlign: 'center' }}>{label} — No preview</span>
        {path && <span className="muted" style={{ fontSize: 10, fontFamily: 'var(--font-mono)', wordBreak: 'break-all', textAlign: 'center' }}>{path}</span>}
      </div>
    );
  }
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</span>
        <a href={url} target="_blank" rel="noopener noreferrer" style={{ fontSize: 11, color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', gap: 3 }}>
          <I.externalArrow size={11} />Full size
        </a>
      </div>
      <img src={url} alt={`Document ${label}`}
        style={{ width: '100%', borderRadius: 6, border: '1px solid var(--hairline)', objectFit: 'contain', background: 'var(--surface-2)' }}
        onError={e => { e.target.style.display = 'none'; }} />
    </div>
  );
};

const DriverDetail = ({ item, actionLoading, onApprove, onReject, onSuspend, onBack }) => {
  const I = window.Icons;
  const isPending   = item.status === 'pending_approval';
  const isApproved  = item.status === 'approved';
  const isSuspended = item.status === 'suspended';
  const name = item.profile?.display_name || item.profile?.username || 'Unknown Driver';
  const chip = DRIVER_STATUS_CHIP[item.status] || 'warn';
  const statusLabel = item.status === 'pending_approval' ? 'pending' : item.status;
  const docEntries = Object.entries(item.verification_documents || {}).filter(([, v]) => !!v);

  return (
    <div style={{ flex: 1, overflow: 'auto' }}>
      <div style={{ padding: 20, maxWidth: 640, margin: '0 auto' }}>
        {/* Header */}
        <div className="panel" style={{ padding: 18, marginBottom: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <AvatarV name={name} size={44} />
              <div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{name}</span>
                  <span className={`chip dot ${chip}`}>{statusLabel}</span>
                </div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                  {item.profile?.email && <span style={{ marginRight: 10 }}>{item.profile.email}</span>}
                  {item.profile?.phone && <span style={{ marginRight: 10 }}>{item.profile.phone}</span>}
                  <span>Applied {fmtDateV(item.created_at)}</span>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
              {isPending && (
                <>
                  <button className="btn primary" style={{ height: 28, fontSize: 12 }} disabled={actionLoading} onClick={onApprove}>
                    <I.check size={11} />Approve
                  </button>
                  <button className="btn" style={{ height: 28, fontSize: 12, color: 'var(--neg)', borderColor: 'var(--neg)' }} disabled={actionLoading} onClick={onReject}>
                    <I.x size={11} />Reject
                  </button>
                </>
              )}
              {isApproved && (
                <button className="btn" style={{ height: 28, fontSize: 12, color: 'var(--neg)', borderColor: 'var(--neg)' }} disabled={actionLoading} onClick={onSuspend}>
                  Suspend
                </button>
              )}
              {isSuspended && (
                <button className="btn primary" style={{ height: 28, fontSize: 12 }} disabled={actionLoading} onClick={onSuspend}>
                  Reactivate
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Stats (approved) */}
        {isApproved && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 14 }}>
            {[
              { label: 'Total deliveries', value: item.total_deliveries, color: 'var(--ink)' },
              { label: 'Completed',        value: item.completed_deliveries, color: 'var(--pos)' },
              { label: 'Rating',           value: Number(item.rating).toFixed(1), color: '#d97706' },
            ].map(({ label, value, color }) => (
              <div key={label} className="panel" style={{ padding: '12px 14px', textAlign: 'center' }}>
                <div className="num" style={{ fontSize: 22, fontWeight: 700, color }}>{value}</div>
                <div className="muted" style={{ fontSize: 10.5, marginTop: 2 }}>{label}</div>
              </div>
            ))}
          </div>
        )}

        {/* Application details */}
        <div className="panel" style={{ marginBottom: 14, overflow: 'hidden' }}>
          <SectionHeader icon={<I.truck size={13} />} title="Application Details" />
          {[
            { label: 'Vehicle type', value: `${VEHICLE_ICON[item.vehicle_type] || ''} ${VEHICLE_LABEL[item.vehicle_type] || item.vehicle_type}` },
            { label: 'Coverage city', value: item.coverage_city },
            ...(item.coverage_area ? [{ label: 'Coverage area', value: item.coverage_area }] : []),
          ].map(({ label, value }) => <KvRow key={label} label={label} value={value} />)}
        </div>

        {/* Documents */}
        <div className="panel" style={{ overflow: 'hidden' }}>
          <SectionHeader icon={<I.receipt size={13} />} title="Verification Documents" />
          <div style={{ padding: 14 }}>
            {docEntries.length === 0 ? (
              <div className="muted" style={{ fontSize: 12 }}>No documents uploaded</div>
            ) : docEntries.map(([key, url]) => (
              <a key={key} href={url} target="_blank" rel="noopener noreferrer"
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 6, border: '1px solid var(--hairline)', marginBottom: 8, textDecoration: 'none', color: 'var(--ink)', background: 'var(--surface-2)' }}>
                <I.receipt size={15} style={{ color: 'var(--ink-3)', flexShrink: 0 }} />
                <span style={{ flex: 1, fontSize: 13, fontWeight: 500, textTransform: 'capitalize' }}>{key.replace(/_/g, ' ')}</span>
                <I.externalArrow size={13} style={{ color: 'var(--accent-ink)' }} />
              </a>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const StoreDetail = ({ item, actionLoading, onVerify, onUnverify, onBack }) => {
  const I = window.Icons;
  const isVerified = item.verification_status === 'verified';
  const owner = item.profile?.display_name || item.profile?.username || 'Unknown';
  const chip = STORE_STATUS_CHIP[item.verification_status] || 'warn';

  return (
    <div style={{ flex: 1, overflow: 'auto' }}>
      <div style={{ padding: 20, maxWidth: 640, margin: '0 auto' }}>
        {/* Header */}
        <div className="panel" style={{ padding: 18, marginBottom: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <div style={{ width: 44, height: 44, borderRadius: 10, background: '#fef3c7', border: '1px solid #fde68a', display: 'grid', placeItems: 'center', fontSize: 22, flexShrink: 0 }}>🏪</div>
              <div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{item.name}</span>
                  <span className={`chip dot ${chip}`}>{item.verification_status}</span>
                </div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
                  <span style={{ marginRight: 10 }}>Owner: {owner}</span>
                  {item.profile?.email && <span style={{ marginRight: 10 }}>{item.profile.email}</span>}
                  <span>Created {fmtDateV(item.created_at)}</span>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
              {!isVerified ? (
                <button className="btn primary" style={{ height: 28, fontSize: 12 }} disabled={actionLoading} onClick={onVerify}>
                  <I.check size={11} />Verify Store
                </button>
              ) : (
                <button className="btn" style={{ height: 28, fontSize: 12, color: 'var(--neg)', borderColor: 'var(--neg)' }} disabled={actionLoading} onClick={onUnverify}>
                  Revoke
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Business info */}
        {(item.business_name || item.tax_id) && (
          <div className="panel" style={{ marginBottom: 14, overflow: 'hidden' }}>
            <SectionHeader icon={<I.store size={13} />} title="Business Information" />
            {item.business_name && <KvRow label="Business name" value={item.business_name} />}
            {item.tax_id && <KvRow label="Tax ID / PAN" value={item.tax_id} />}
          </div>
        )}

        {/* Business documents */}
        <div className="panel" style={{ overflow: 'hidden' }}>
          <SectionHeader icon={<I.receipt size={13} />} title="Business Documents"
            right={<span className="muted" style={{ fontSize: 11 }}>{item.business_documents.length} uploaded</span>}
          />
          <div style={{ padding: 14 }}>
            {item.business_documents.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '20px 0' }}>
                <div className="muted" style={{ fontSize: 12, marginBottom: 4 }}>No documents uploaded yet</div>
                <div className="muted" style={{ fontSize: 11.5 }}>You can still verify the store manually.</div>
              </div>
            ) : item.business_documents.map((doc, i) => (
              <a key={i} href={doc.url} target="_blank" rel="noopener noreferrer"
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 6, border: '1px solid var(--hairline)', marginBottom: 8, textDecoration: 'none', color: 'var(--ink)', background: 'var(--surface-2)' }}>
                <I.receipt size={15} style={{ color: 'var(--ink-3)', flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{doc.name || `Document ${i + 1}`}</div>
                  {doc.uploaded_at && <div className="muted" style={{ fontSize: 11 }}>{fmtDateV(doc.uploaded_at)}</div>}
                </div>
                <I.externalArrow size={13} style={{ color: 'var(--accent-ink)', flexShrink: 0 }} />
              </a>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Main page ──────────────────────────────────────────────────────────────────

const VerificationsPage = () => {
  const I = window.Icons;
  const sb = window.supabaseClient;

  const [tab, setTab] = useStateV('kyc');
  const [search, setSearch] = useStateV('');

  // KYC
  const [kycList, setKycList]             = useStateV([]);
  const [kycFilter, setKycFilter]         = useStateV('pending');
  const [kycLoading, setKycLoading]       = useStateV(false);
  const [kycPending, setKycPending]       = useStateV(0);
  const [selectedKyc, setSelectedKyc]     = useStateV(null);

  // Drivers
  const [drivers, setDrivers]               = useStateV([]);
  const [driverFilter, setDriverFilter]     = useStateV('pending_approval');
  const [driversLoading, setDriversLoading] = useStateV(false);
  const [driverPending, setDriverPending]   = useStateV(0);
  const [selectedDriver, setSelectedDriver] = useStateV(null);

  // Stores
  const [stores, setStores]               = useStateV([]);
  const [storeFilter, setStoreFilter]     = useStateV('unverified');
  const [storesLoading, setStoresLoading] = useStateV(false);
  const [selectedStore, setSelectedStore] = useStateV(null);

  const [actionLoading, setActionLoading] = useStateV(false);

  // ── Fetches ──────────────────────────────────────────────────────────────────

  const doFetchKyc = useCallbackV(async () => {
    if (!sb) return;
    setKycLoading(true);
    const [list, count] = await Promise.all([fetchKycList(sb, kycFilter), fetchKycPendingCount(sb)]);
    setKycList(list);
    setKycPending(count);
    setKycLoading(false);
  }, [kycFilter]);

  const doFetchDrivers = useCallbackV(async () => {
    if (!sb) return;
    setDriversLoading(true);
    const [list, count] = await Promise.all([fetchDriverList(sb, driverFilter), fetchDriverPendingCount(sb)]);
    setDrivers(list);
    setDriverPending(count);
    setDriversLoading(false);
  }, [driverFilter]);

  const doFetchStores = useCallbackV(async () => {
    if (!sb) return;
    setStoresLoading(true);
    const list = await fetchStoreList(sb, storeFilter);
    setStores(list);
    setStoresLoading(false);
  }, [storeFilter]);

  useEffectV(() => { doFetchKyc(); }, [doFetchKyc]);
  useEffectV(() => { doFetchDrivers(); }, [doFetchDrivers]);
  useEffectV(() => { doFetchStores(); }, [doFetchStores]);

  // ── KYC Actions ──────────────────────────────────────────────────────────────

  const handleApproveKyc = async () => {
    if (!selectedKyc) return;
    if (!confirm(`Approve KYC for ${selectedKyc.full_name}? This grants full P2P payment access.`)) return;
    setActionLoading(true);
    try {
      const { error } = await sb.rpc('approve_kyc', { p_submission_id: selectedKyc.id });
      if (error) throw error;
      await sendPushV(sb, selectedKyc.user_id,
        'Identity Verified!',
        'Congratulations! Your identity has been verified. You can now send, receive, and request money directly in chat. Welcome to the full Pipal experience!',
      );
      setSelectedKyc(null);
      doFetchKyc();
    } catch (e) { alert(`Failed: ${e.message}`); }
    finally { setActionLoading(false); }
  };

  const handleRejectKyc = async () => {
    if (!selectedKyc) return;
    const reason = prompt('Rejection reason (shown to user):');
    if (!reason?.trim()) return;
    setActionLoading(true);
    try {
      const { error } = await sb.rpc('reject_kyc', { p_submission_id: selectedKyc.id, p_rejection_reason: reason.trim() });
      if (error) throw error;
      await sendPushV(sb, selectedKyc.user_id,
        'Identity Verification Update',
        `We weren't able to verify your identity this time. Reason: ${reason.trim()}. Please re-submit with a clearer document and we'll review it again.`,
      );
      setSelectedKyc(null);
      doFetchKyc();
    } catch (e) { alert(`Failed: ${e.message}`); }
    finally { setActionLoading(false); }
  };

  // ── Driver Actions ────────────────────────────────────────────────────────────

  const handleApproveDriver = async () => {
    if (!selectedDriver) return;
    if (!confirm(`Approve ${selectedDriver.profile?.display_name || 'this driver'} as a delivery partner?`)) return;
    setActionLoading(true);
    try {
      await Promise.all([
        sb.from('delivery_partners').update({ status: 'approved', is_active: true }).eq('user_id', selectedDriver.user_id),
        sb.from('user_profiles').update({ can_deliver: true, account_status: 'active' }).eq('id', selectedDriver.user_id),
      ]);
      sb.from('admin_action_log').insert({ action_type: 'driver_approved', resource_id: selectedDriver.user_id, resource_type: 'delivery_partner', action_details: { vehicle_type: selectedDriver.vehicle_type } });
      await sendPushV(sb, selectedDriver.user_id,
        "You're a Pipal Delivery Partner!",
        "Welcome to the team! Your delivery partner application has been approved. You can now start accepting deliveries and earning. Head to the app to get started.",
      );
      setSelectedDriver(null);
      doFetchDrivers();
    } finally { setActionLoading(false); }
  };

  const handleRejectDriver = async () => {
    if (!selectedDriver) return;
    const reason = prompt('Rejection reason (shown to driver):');
    if (!reason?.trim()) return;
    setActionLoading(true);
    try {
      await Promise.all([
        sb.from('delivery_partners').update({ status: 'rejected', is_active: false }).eq('user_id', selectedDriver.user_id),
        sb.from('user_profiles').update({ can_deliver: false }).eq('id', selectedDriver.user_id),
      ]);
      sb.from('admin_action_log').insert({ action_type: 'driver_rejected', resource_id: selectedDriver.user_id, resource_type: 'delivery_partner', action_details: {} });
      await sendPushV(sb, selectedDriver.user_id,
        'Delivery Application Update',
        `Thank you for applying to be a Pipal delivery partner. Unfortunately we couldn't approve your application at this time. Reason: ${reason.trim()}. You're welcome to apply again once you've addressed this.`,
      );
      setSelectedDriver(null);
      doFetchDrivers();
    } finally { setActionLoading(false); }
  };

  const handleSuspendDriver = async () => {
    if (!selectedDriver) return;
    const isSusp = selectedDriver.status === 'suspended';
    if (!confirm(`${isSusp ? 'Reactivate' : 'Suspend'} ${selectedDriver.profile?.display_name || 'this driver'}?`)) return;
    setActionLoading(true);
    try {
      const newStatus = isSusp ? 'approved' : 'suspended';
      await Promise.all([
        sb.from('delivery_partners').update({ status: newStatus, is_active: !isSusp }).eq('user_id', selectedDriver.user_id),
        sb.from('user_profiles').update({ can_deliver: !isSusp }).eq('id', selectedDriver.user_id),
      ]);
      await sendPushV(sb, selectedDriver.user_id,
        isSusp ? 'Account Reactivated' : 'Account Suspended',
        isSusp
          ? 'Good news — your delivery partner account has been reactivated. You can start accepting deliveries again.'
          : 'Your delivery partner account has been temporarily suspended. Please contact support if you think this is a mistake.',
      );
      doFetchDrivers();
    } finally { setActionLoading(false); }
  };

  // ── Store Actions ─────────────────────────────────────────────────────────────

  const handleVerifyStore = async () => {
    if (!selectedStore) return;
    if (!confirm(`Verify "${selectedStore.name}"? This marks the store as trusted.`)) return;
    setActionLoading(true);
    try {
      await sb.from('stores').update({ verification_status: 'verified' }).eq('id', selectedStore.id);
      sb.from('admin_action_log').insert({ action_type: 'store_verified', resource_id: selectedStore.id, resource_type: 'store', action_details: { store_name: selectedStore.name } });
      await sendPushV(sb, selectedStore.seller_id,
        `${selectedStore.name} is now Verified!`,
        "Great news! Your store has been verified by the Pipal team. The verified badge is now visible to buyers, helping you build trust and get more orders. Keep it up!",
      );
      setSelectedStore(s => s?.id === selectedStore.id ? { ...s, verification_status: 'verified' } : s);
      doFetchStores();
    } finally { setActionLoading(false); }
  };

  const handleUnverifyStore = async () => {
    if (!selectedStore) return;
    const reasonInput = prompt(`Reason for revoking "${selectedStore.name}" verification (optional, shown to seller):`);
    if (reasonInput === null) return;
    const reason = reasonInput.trim();
    setActionLoading(true);
    try {
      await sb.from('stores').update({ verification_status: 'unverified' }).eq('id', selectedStore.id);
      await sendPushV(sb, selectedStore.seller_id,
        'Store Verification Revoked',
        reason
          ? `Your store "${selectedStore.name}" verification has been revoked. Reason: ${reason}. Please contact support or re-submit your documents to get verified again.`
          : `Your store "${selectedStore.name}" verification has been revoked by our team. Please contact support for more details.`,
      );
      setSelectedStore(s => s?.id === selectedStore.id ? { ...s, verification_status: 'unverified' } : s);
      doFetchStores();
    } finally { setActionLoading(false); }
  };

  // ── Filtered lists ────────────────────────────────────────────────────────────

  const q = search.toLowerCase();
  const filteredKyc = q
    ? kycList.filter(k => k.full_name?.toLowerCase().includes(q) || k.profile?.email?.toLowerCase().includes(q) || k.profile?.username?.toLowerCase().includes(q))
    : kycList;
  const filteredDrivers = q
    ? drivers.filter(d => d.profile?.display_name?.toLowerCase().includes(q) || d.profile?.email?.toLowerCase().includes(q) || d.coverage_city?.toLowerCase().includes(q))
    : drivers;
  const filteredStores = q
    ? stores.filter(s => s.name?.toLowerCase().includes(q) || s.profile?.display_name?.toLowerCase().includes(q) || s.profile?.email?.toLowerCase().includes(q))
    : stores;

  const hasDetail = tab === 'kyc' ? !!selectedKyc : tab === 'drivers' ? !!selectedDriver : !!selectedStore;
  const clearDetail = () => { setSelectedKyc(null); setSelectedDriver(null); setSelectedStore(null); };

  const switchTab = t => { setTab(t); setSearch(''); clearDetail(); };

  const TABS = [
    { id: 'kyc',     label: 'KYC / Identity',       icon: <I.shield size={13} />, badge: kycPending },
    { id: 'drivers', label: 'Driver Applications',   icon: <I.bike size={13} />,  badge: driverPending },
    { id: 'stores',  label: 'Store Verification',    icon: <I.store size={13} />, badge: 0 },
  ];

  // ── Render ────────────────────────────────────────────────────────────────────

  return (
    <div className="page" data-screen-label="Verifications" style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, padding: 0, overflow: 'hidden' }}>

      {/* Page header */}
      <div className="page-h" style={{ padding: '14px 20px', flexShrink: 0, borderBottom: '1px solid var(--hairline)' }}>
        <div>
          <div className="ts">
            {kycPending + driverPending > 0 && <><span className="live">ACTION</span><span style={{ margin: '0 8px' }}>·</span></>}
            {kycPending + driverPending} pending review
          </div>
          <h1>Verifications</h1>
        </div>
        <div className="acts">
          <button className="btn" onClick={() => { doFetchKyc(); doFetchDrivers(); doFetchStores(); }}>
            <I.refresh size={12} />Refresh
          </button>
        </div>
      </div>

      {/* Body: two-column split */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {/* LEFT: list panel */}
        <div style={{
          width: 340, flexShrink: 0, borderRight: '1px solid var(--hairline)',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
        }}>

          {/* Tab selector */}
          <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--hairline)', display: 'flex', flexDirection: 'column', gap: 4 }}>
            {TABS.map(t => (
              <div key={t.id} onClick={() => switchTab(t.id)} style={{
                display: 'flex', alignItems: 'center', gap: 8,
                padding: '7px 10px', borderRadius: 6, cursor: 'pointer',
                background: tab === t.id ? 'var(--surface-2)' : 'transparent',
                border: tab === t.id ? '1px solid var(--hairline)' : '1px solid transparent',
              }}>
                <span style={{ color: tab === t.id ? 'var(--accent-ink)' : 'var(--ink-3)', display: 'flex' }}>{t.icon}</span>
                <span style={{ flex: 1, fontSize: 13, fontWeight: tab === t.id ? 550 : 400, color: tab === t.id ? 'var(--ink)' : 'var(--ink-2)' }}>{t.label}</span>
                {t.badge > 0 && (
                  <span style={{ background: 'var(--warn)', color: '#fff', borderRadius: 20, padding: '1px 6px', fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)' }}>{t.badge}</span>
                )}
              </div>
            ))}
          </div>

          {/* Search */}
          <div style={{ padding: '8px 12px', borderBottom: '1px solid var(--hairline)', position: 'relative' }}>
            <I.search size={13} style={{ position: 'absolute', left: 22, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }} />
            <input
              type="text" value={search} placeholder="Search…"
              onChange={e => setSearch(e.target.value)}
              style={{ width: '100%', paddingLeft: 28, paddingRight: 10, height: 30, fontSize: 12.5, background: 'var(--surface-2)', border: '1px solid var(--hairline)', borderRadius: 6, color: 'var(--ink)', boxSizing: 'border-box' }}
            />
          </div>

          {/* Status filter chips */}
          <div style={{ padding: '6px 12px', borderBottom: '1px solid var(--hairline)', display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {tab === 'kyc' && ['pending','approved','rejected','all'].map(s => (
              <div key={s} onClick={() => setKycFilter(s)} style={{ padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 500, cursor: 'pointer', background: kycFilter === s ? 'var(--ink)' : 'var(--surface-2)', color: kycFilter === s ? 'var(--paper)' : 'var(--ink-2)', textTransform: 'capitalize' }}>{s}</div>
            ))}
            {tab === 'drivers' && ['pending_approval','approved','rejected','suspended','all'].map(s => (
              <div key={s} onClick={() => setDriverFilter(s)} style={{ padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 500, cursor: 'pointer', background: driverFilter === s ? 'var(--ink)' : 'var(--surface-2)', color: driverFilter === s ? 'var(--paper)' : 'var(--ink-2)', textTransform: 'capitalize' }}>{s === 'pending_approval' ? 'pending' : s}</div>
            ))}
            {tab === 'stores' && ['unverified','pending','verified','all'].map(s => (
              <div key={s} onClick={() => setStoreFilter(s)} style={{ padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 500, cursor: 'pointer', background: storeFilter === s ? 'var(--ink)' : 'var(--surface-2)', color: storeFilter === s ? 'var(--paper)' : 'var(--ink-2)', textTransform: 'capitalize' }}>{s}</div>
            ))}
          </div>

          {/* List */}
          <div style={{ flex: 1, overflow: 'auto' }}>
            {tab === 'kyc' && (
              kycLoading ? <div className="muted" style={{ padding: 20, fontSize: 12 }}>Loading…</div>
              : filteredKyc.length === 0 ? <div className="muted" style={{ padding: 20, fontSize: 12 }}>No KYC submissions</div>
              : filteredKyc.map(k => <KycRow key={k.id} item={k} selected={selectedKyc?.id === k.id} onClick={() => setSelectedKyc(k)} />)
            )}
            {tab === 'drivers' && (
              driversLoading ? <div className="muted" style={{ padding: 20, fontSize: 12 }}>Loading…</div>
              : filteredDrivers.length === 0 ? <div className="muted" style={{ padding: 20, fontSize: 12 }}>No driver applications</div>
              : filteredDrivers.map(d => <DriverRow key={d.id} item={d} selected={selectedDriver?.user_id === d.user_id} onClick={() => setSelectedDriver(d)} />)
            )}
            {tab === 'stores' && (
              storesLoading ? <div className="muted" style={{ padding: 20, fontSize: 12 }}>Loading…</div>
              : filteredStores.length === 0 ? <div className="muted" style={{ padding: 20, fontSize: 12 }}>No stores found</div>
              : filteredStores.map(s => <StoreRow key={s.id} item={s} selected={selectedStore?.id === s.id} onClick={() => setSelectedStore(s)} />)
            )}
          </div>
        </div>

        {/* RIGHT: detail panel */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {hasDetail ? (
            <>
              {tab === 'kyc' && selectedKyc && (
                <KycDetail item={selectedKyc} actionLoading={actionLoading}
                  onApprove={handleApproveKyc} onReject={handleRejectKyc} onBack={clearDetail} />
              )}
              {tab === 'drivers' && selectedDriver && (
                <DriverDetail item={selectedDriver} actionLoading={actionLoading}
                  onApprove={handleApproveDriver} onReject={handleRejectDriver}
                  onSuspend={handleSuspendDriver} onBack={clearDetail} />
              )}
              {tab === 'stores' && selectedStore && (
                <StoreDetail item={selectedStore} actionLoading={actionLoading}
                  onVerify={handleVerifyStore} onUnverify={handleUnverifyStore} onBack={clearDetail} />
              )}
            </>
          ) : (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, color: 'var(--ink-3)' }}>
              <I.shield size={32} style={{ opacity: 0.35 }} />
              <span style={{ fontSize: 13 }}>Select an item to review</span>
            </div>
          )}
        </div>

      </div>
    </div>
  );
};

window.VerificationsPage = VerificationsPage;
