// Leads table — name, contact details, level, added.
// Reads synthesized lead-like rows (built from deals + contacts in app.jsx).
// Clicking a row opens the lead's full detail (source, level, struggle — the New Lead form info).

// Date-range popover filter (filters by enquiry/added date).
function DateRangeFilter({ from, to, onFrom, onTo }) {
  const [open, setOpen] = useState(false);
  const active = from || to;
  const inputCls = "h-8 px-2 text-xs bg-white border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-100 text-slate-800";
  const fmt = (d) => d ? new Date(d + 'T00:00:00').toLocaleDateString('en-ZA', { day: 'numeric', month: 'short' }) : null;
  const label = active ? `${fmt(from) || '…'} – ${fmt(to) || '…'}` : 'Any time';
  return (
    <div className="relative">
      <button onClick={() => setOpen(o => !o)}
        className={`h-8 px-2.5 inline-flex items-center gap-1.5 text-xs font-medium border rounded-md hover:bg-slate-50 ${active ? 'text-indigo-700 bg-indigo-50 border-indigo-200' : 'text-slate-700 bg-white border-slate-200'}`}>
        <Icon.Calendar size={13}/>
        <span className="text-slate-500">Date:</span>
        <span>{label}</span>
        <Icon.ChevronDown size={12}/>
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-20" onClick={() => setOpen(false)}/>
          <div className="absolute top-9 left-0 w-64 bg-white border border-slate-200 rounded-lg shadow-lg p-3 z-30">
            <div className="text-[10px] uppercase tracking-wider text-slate-400 font-semibold mb-2">Enquiry date range</div>
            <div className="space-y-2">
              <label className="block">
                <span className="text-[11px] text-slate-500">From</span>
                <input type="date" value={from} max={to || undefined} onChange={e => onFrom(e.target.value)} className={inputCls + ' w-full mt-0.5'}/>
              </label>
              <label className="block">
                <span className="text-[11px] text-slate-500">To</span>
                <input type="date" value={to} min={from || undefined} onChange={e => onTo(e.target.value)} className={inputCls + ' w-full mt-0.5'}/>
              </label>
            </div>
            <div className="flex items-center justify-between mt-3 pt-2 border-t border-slate-100">
              <button onClick={() => { onFrom(''); onTo(''); }} className="text-[11px] font-medium text-slate-500 hover:text-slate-800">Clear</button>
              <button onClick={() => setOpen(false)} className="text-[11px] font-semibold text-indigo-600 hover:text-indigo-700">Done</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function LeadsTable({ leads, onSelectLead, search, rawLeads = [], contacts = [], onQualifyRaw, onDisqualifyRaw, onViewRaw }) {
  const [statusFilter, setStatusFilter] = useState('Inbox');
  const [segmentFilter, setSegmentFilter] = useState('All');
  const [sortBy, setSortBy] = useState('updated');
  const [localSearch, setLocalSearch] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const q = (search || localSearch || '').toLowerCase();

  // Qualified = moved into the active pipeline (past New, not Lost).
  // Unqualified = still New (awaiting qualification) or Lost/Disqualified.
  const isQualified = (l) => l.stage !== 'New' && l.stage !== 'LostDisqualified';

  const filtered = useMemo(() => {
    let list = [...leads];
    if (statusFilter === 'Qualified')   list = list.filter(isQualified);
    if (statusFilter === 'Unqualified') list = list.filter(l => !isQualified(l));
    if (segmentFilter !== 'All') list = list.filter(l => l.segment === segmentFilter);
    if (dateFrom) { const from = new Date(dateFrom + 'T00:00:00'); list = list.filter(l => new Date(l.addedTime) >= from); }
    if (dateTo) { const to = new Date(dateTo + 'T23:59:59'); list = list.filter(l => new Date(l.addedTime) <= to); }
    if (q) {
      list = list.filter(l =>
        l.name.toLowerCase().includes(q) ||
        (l.email || '').toLowerCase().includes(q) ||
        (l.phone || '').includes(q) ||
        (l.subjects || []).some(s => s.toLowerCase().includes(q)) ||
        (l.gradeOrYear || '').toLowerCase().includes(q)
      );
    }
    if (sortBy === 'updated') list.sort((a,b) => new Date(b.addedTime) - new Date(a.addedTime));
    if (sortBy === 'name')    list.sort((a,b) => a.name.localeCompare(b.name));
    if (sortBy === 'stage')   list.sort((a,b) => STAGE_INDEX[a.stage] - STAGE_INDEX[b.stage]);
    return list;
  }, [leads, statusFilter, segmentFilter, q, sortBy, dateFrom, dateTo]);

  return (
    <div className="px-7 pt-4 pb-5 max-w-[1400px] mx-auto">
      {/* Sub-menu tabs */}
      <div className="flex items-center gap-1 border-b border-slate-200 mb-4 -mx-7 px-7">
        {[
          { id: 'Inbox', label: 'Lead Inbox' },
          { id: 'Qualified', label: 'Qualified Leads' },
          { id: 'Unqualified', label: 'Unqualified Leads' },
          { id: 'All', label: 'All Engaged Leads' },
        ].map(t => {
          const count = t.id === 'Inbox' ? rawLeads.length
            : t.id === 'All' ? leads.length
            : t.id === 'Qualified' ? leads.filter(isQualified).length
            : leads.filter(l => !isQualified(l)).length;
          const on = statusFilter === t.id;
          const isInbox = t.id === 'Inbox';
          return (
            <button key={t.id} onClick={() => setStatusFilter(t.id)}
              className={`relative inline-flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium -mb-px border-b-2 transition-colors ${
                on ? 'border-indigo-600 text-slate-900' : 'border-transparent text-slate-500 hover:text-slate-800'
              }`}>
              {isInbox && <Icon.Inbox size={14} className={on ? 'text-indigo-600' : 'text-slate-400'}/>}
              {t.label}
              <span className={`text-[11px] tabular-nums px-1.5 h-[18px] inline-flex items-center rounded-full font-semibold ${
                on ? (isInbox ? 'bg-emerald-50 text-emerald-700' : 'bg-indigo-50 text-indigo-700') : 'bg-slate-100 text-slate-500'
              }`}>{count}</span>
            </button>
          );
        })}
      </div>

      {statusFilter === 'Inbox' ? (
        <LeadsInboxView rawLeads={rawLeads} contacts={contacts} onQualify={onQualifyRaw} onDisqualify={onDisqualifyRaw} onView={onViewRaw} embedded/>
      ) : (
      <>
      {/* Filter bar */}
      <div className="flex flex-wrap items-center gap-2 mb-4">
        <FilterPill label="Level" value={segmentFilter} options={['All','HighSchool','University']}
          render={(v) => v === 'HighSchool' ? 'High School' : v}
          onChange={setSegmentFilter} />
        <FilterPill label="Sort" value={sortBy} options={['updated','name','stage']}
          render={(v) => ({ updated: 'Recently added', name: 'Name (A–Z)', stage: 'Pipeline stage' })[v]}
          onChange={setSortBy} />
        <DateRangeFilter from={dateFrom} to={dateTo} onFrom={setDateFrom} onTo={setDateTo} />
        {!search && (
          <div className="relative">
            <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"><Icon.Search size={13}/></span>
            <input value={localSearch} onChange={e => setLocalSearch(e.target.value)}
              placeholder="Search leads…"
              className="h-8 w-56 pl-8 pr-3 text-sm bg-white border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-100"/>
          </div>
        )}
        <div className="flex-1"/>
        <div className="text-xs text-slate-500">{filtered.length} leads</div>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr className="text-left text-[11px] uppercase tracking-wider text-slate-500 font-semibold">
                <th className="px-4 py-2.5 w-[30%]">Lead</th>
                <th className="px-4 py-2.5">Contact details</th>
                <th className="px-4 py-2.5">Level</th>
                <th className="px-4 py-2.5">Added</th>
                <th className="px-2 py-2.5"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.map(l => (
                <tr key={l.id} onClick={() => onSelectLead(l)}
                  className="hover:bg-slate-50 cursor-pointer transition-colors">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2.5">
                      <Avatar name={l.name} size={30}/>
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-slate-900 truncate">{l.name}</div>
                        {l.studentName && l.studentName !== l.name && <div className="text-[11px] text-slate-500 truncate">for {l.studentName}</div>}
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-[12.5px] text-slate-700 truncate max-w-[240px]">{l.email && l.email !== '—' ? l.email : <span className="text-slate-400">No email</span>}</div>
                    <div className="text-[11.5px] text-slate-500 tabular-nums whitespace-nowrap">{l.phone && l.phone !== '—' ? l.phone : '—'}</div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5">
                      <SegmentPill segment={l.segment}/>
                      <span className="text-[11px] text-slate-500">{l.gradeOrYear}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-[12px] text-slate-500">
                    <div className="text-slate-700 tabular-nums whitespace-nowrap">{fmtDateTime(l.addedTime)}</div>
                    <div className="text-[11px] text-slate-400">{fmtTimeAgo(l.addedTime)}</div>
                  </td>
                  <td className="px-2 py-3 text-right">
                    <Icon.ChevronRight size={14} className="text-slate-400"/>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={5}>
                  <Empty title="No leads match" hint="Try clearing filters or adjusting your search." icon={<Icon.Users size={18}/>}/>
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
      </>
      )}
    </div>
  );
}
window.LeadsTable = LeadsTable;

// ============================================================
// LEAD DETAIL DRAWER — view + edit the New Lead form info.
// ============================================================
function LeadDetailDrawer({ lead, contacts, leadSources, onClose, onSelectContact, onSave, onQualify, onDisqualify, onDelete, onAssign }) {
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState(lead);
  const [ConfirmEl, confirm] = useConfirm();
  const [assignOpen, setAssignOpen] = useState(false);
  useEffect(() => { setForm(lead); setEditing(false); setAssignOpen(false); }, [lead?.id]);
  if (!lead) return null;

  const student = getContact(contacts, lead.studentId);
  const payer = getContact(contacts, lead.payerId);
  const differentPayer = student && payer && student.id !== payer.id;
  const owner = OWNERS.find(o => o.id === lead.owner);
  const sourceNames = (leadSources || []).filter(s => !s.archived).map(s => s.name);

  // Existing-contact match — prefer email, fall back to phone.
  const emailMatch = (contacts || []).find(c => lead.email && lead.email !== '—' && (c.email || '').toLowerCase() === lead.email.toLowerCase());
  const phoneMatch = !emailMatch ? (contacts || []).find(c => lead.phone && lead.phone !== '—' && (c.phone || '').replace(/\s/g,'') === (lead.phone || '').replace(/\s/g,'')) : null;
  const match = emailMatch || phoneMatch;
  const matchedByEmail = !!emailMatch;
  const isLost = lead.stage === 'LostDisqualified';
  const isQualified = lead.stage !== 'New' && lead.stage !== 'LostDisqualified';

  const setField = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleSubject = (s) => setField('subjects', (form.subjects || []).includes(s)
    ? form.subjects.filter(x => x !== s) : [...(form.subjects || []), s]);
  const save = () => { onSave({ ...form, name: form.name.trim() }); setEditing(false); };

  const Field = ({ label, value, mono }) => (
    <div>
      <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1">{label}</div>
      <div className={`text-[13px] text-slate-800 ${mono ? 'tabular-nums' : ''}`}>{value || <span className="text-slate-400">—</span>}</div>
    </div>
  );
  const inputCls = "w-full h-9 px-3 text-sm bg-white border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-100 focus:border-slate-300 text-slate-900";

  return (
    <div className="fixed inset-0 z-40">
      {ConfirmEl}
      <div onClick={onClose} className="absolute inset-0 bg-slate-900/30 backdrop-blur-sm"/>
      <aside className="absolute top-0 right-0 h-full w-full max-w-[520px] bg-white shadow-2xl border-l border-slate-200 flex flex-col">
        {/* Header */}
        <div className="px-6 pt-5 pb-4 border-b border-slate-200">
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-center gap-3.5 min-w-0">
              <Avatar name={lead.name} size={48}/>
              <div className="min-w-0">
                <div className="text-base font-semibold text-slate-900 truncate">{lead.name}</div>
                <div className="text-xs text-slate-500 truncate">
                  {lead.studentName && lead.studentName !== lead.name ? `Enquiry for ${lead.studentName}` : 'Student enquiry'} · {lead.segment === 'University' ? 'University' : 'High School'} · {lead.gradeOrYear}
                </div>
              </div>
            </div>
            <div className="flex items-center gap-1">
              {!editing && <IconButton icon={<Icon.Settings size={15}/>} title="Edit lead" onClick={() => setEditing(true)}/>}
              <IconButton icon={<Icon.X size={16}/>} onClick={onClose} title="Close"/>
            </div>
          </div>
          {!editing && (
            <div className="flex flex-wrap items-center gap-2 mt-3">
              {/* Inline assign control */}
              {onAssign && (
                <div className="relative">
                  <button onClick={() => setAssignOpen(o => !o)} onBlur={() => setTimeout(() => setAssignOpen(false), 150)}
                    className="h-8 pl-1 pr-2 inline-flex items-center gap-1.5 bg-white border border-slate-200 rounded-md hover:bg-slate-50 text-[12px] font-medium text-slate-700">
                    {owner ? <Avatar name={owner.name} color={owner.color} size={22}/> : <span className="h-[22px] w-[22px] rounded-full bg-slate-100 text-slate-400 inline-flex items-center justify-center"><Icon.Users size={12}/></span>}
                    <span>{owner ? owner.name : 'Assign'}</span>
                    <Icon.ChevronDown size={12} className="text-slate-400"/>
                  </button>
                  {assignOpen && (
                    <div className="absolute top-9 left-0 w-52 bg-white border border-slate-200 rounded-lg shadow-lg p-1 z-50">
                      <div className="text-[10px] uppercase tracking-wider text-slate-400 px-2 py-1.5">Assign to</div>
                      {OWNERS.filter(o => o.id !== 'system').map(o => (
                        <button key={o.id} onMouseDown={(e) => { e.preventDefault(); onAssign(lead, o.id); setAssignOpen(false); }}
                          className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-slate-50 text-left ${lead.owner === o.id ? 'bg-slate-50' : ''}`}>
                          <Avatar name={o.name} color={o.color} size={22}/>
                          <span className="text-[13px] text-slate-800 flex-1">{o.name}</span>
                          {lead.owner === o.id && <Icon.Check size={13} className="text-indigo-600"/>}
                        </button>
                      ))}
                      {lead.owner && (
                        <button onMouseDown={(e) => { e.preventDefault(); onAssign(lead, null); setAssignOpen(false); }}
                          className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-slate-50 text-left text-[12px] text-slate-500 border-t border-slate-100 mt-1">
                          <span className="h-[22px] w-[22px] inline-flex items-center justify-center"><Icon.X size={12}/></span> Unassign
                        </button>
                      )}
                    </div>
                  )}
                </div>
              )}
              <Button size="sm" variant="brand" icon={<Icon.Chat size={13}/>}>WhatsApp</Button>
              <Button size="sm" variant="secondary" icon={<Icon.Phone size={13}/>}>Call</Button>
              <Button size="sm" variant="secondary" icon={<Icon.Mail size={13}/>}>Email</Button>
            </div>
          )}
        </div>

        {/* Body */}
        {editing ? (
          <div className="flex-1 overflow-y-auto p-6 space-y-4">
            <div>
              <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Lead name</label>
              <input className={inputCls} value={form.name} onChange={e => setField('name', e.target.value)}/>
            </div>
            <div>
              <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">What they're struggling with</label>
              <textarea rows={3} className={inputCls + ' h-auto py-2 resize-y'} value={form.struggle || ''} onChange={e => setField('struggle', e.target.value)}/>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Where they come from</label>
                <select className={inputCls} value={form.source || ''} onChange={e => setField('source', e.target.value)}>
                  {!sourceNames.includes(form.source) && form.source && <option>{form.source}</option>}
                  {sourceNames.map(s => <option key={s}>{s}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Campaign</label>
                <input className={inputCls} value={form.campaign || ''} onChange={e => setField('campaign', e.target.value)} placeholder="—"/>
              </div>
              <div>
                <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Level</label>
                <select className={inputCls} value={form.segment} onChange={e => setField('segment', e.target.value)}>
                  <option value="HighSchool">High School</option>
                  <option value="University">University</option>
                </select>
              </div>
              <div>
                <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Grade / Year</label>
                <input className={inputCls} value={form.gradeOrYear || ''} onChange={e => setField('gradeOrYear', e.target.value)}/>
              </div>
            </div>
            <div>
              <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Subjects</label>
              <div className="flex gap-1.5">
                {['Mathematics','Accounting','Statistics'].map(s => {
                  const on = (form.subjects || []).includes(s);
                  return (
                    <button key={s} type="button" onClick={() => toggleSubject(s)}
                      className={`flex-1 h-8 px-2 text-xs rounded-md border transition-colors ${on ? 'bg-indigo-50 text-indigo-700 border-indigo-200' : 'bg-white text-slate-700 border-slate-200 hover:bg-slate-50'}`}>{s}</button>
                  );
                })}
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Email</label>
                <input className={inputCls} value={form.email === '—' ? '' : form.email} onChange={e => setField('email', e.target.value)} placeholder="name@email.com"/>
              </div>
              <div>
                <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Phone</label>
                <input className={inputCls} value={form.phone === '—' ? '' : form.phone} onChange={e => setField('phone', e.target.value)} placeholder="+27 …"/>
              </div>
            </div>
            <div>
              <label className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1 block">Assigned to</label>
              <select className={inputCls} value={form.owner} onChange={e => setField('owner', e.target.value)}>
                {OWNERS.filter(o => o.id !== 'system').map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
              </select>
            </div>

            <div className="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
              <Button size="md" variant="secondary" onClick={() => { setForm(lead); setEditing(false); }}>Cancel</Button>
              <Button size="md" variant="brand" icon={<Icon.Check size={14}/>} onClick={save} disabled={!form.name.trim()}>Save changes</Button>
            </div>
          </div>
        ) : (
          <div className="flex-1 overflow-y-auto p-6 space-y-5">
            <div>
              <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1.5">What they're struggling with</div>
              <p className="text-[13.5px] text-slate-800 leading-relaxed bg-slate-50 border border-slate-200 rounded-lg p-3.5">"{lead.struggle}"</p>
            </div>

            {/* Existing contact match */}
            {match ? (
              <div className="bg-violet-50 border border-violet-200 rounded-lg p-3 flex items-start gap-2.5">
                <span className="text-violet-600 mt-0.5"><Icon.Alert size={14}/></span>
                <div className="flex-1 min-w-0">
                  <div className="text-[12.5px] font-medium text-violet-900">Existing contact match by {matchedByEmail ? 'email' : 'phone'}: <strong>{contactFullName(match)}</strong></div>
                  <div className="text-[11.5px] text-violet-700 mt-0.5">Qualifying links this lead to the existing contact instead of creating a duplicate.</div>
                  <button onClick={() => onSelectContact(match)} className="text-[11.5px] font-semibold text-violet-800 hover:underline mt-1">View contact →</button>
                </div>
              </div>
            ) : (
              <div className="bg-slate-50 border border-slate-200 rounded-lg p-3 flex items-start gap-2.5">
                <span className="text-slate-400 mt-0.5"><Icon.Users size={14}/></span>
                <div className="text-[12px] text-slate-600">No existing contact matches this email or phone — qualifying will create a new contact.</div>
              </div>
            )}

            <div className="grid grid-cols-2 gap-4">
              <Field label="Where they come from" value={lead.source}/>
              <Field label="Campaign" value={lead.campaign}/>
              <Field label="Level" value={lead.segment === 'University' ? 'University' : 'High School'}/>
              <Field label="Grade / Year" value={lead.gradeOrYear}/>
              <Field label="Subjects" value={(lead.subjects || []).join(', ')}/>
              <Field label="Who needs tutoring" value={lead.whoNeedsTutoring}/>
              <Field label="Email" value={lead.email}/>
              <Field label="Phone" value={lead.phone} mono/>
              <Field label="Assigned to" value={owner ? owner.name : '—'}/>
              <Field label="Enquiry date" value={fmtDateTime(lead.addedTime)}/>
            </div>

            {(student || payer) && (
              <div>
                <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-2">Linked contacts</div>
                <div className="space-y-2">
                  {student && (
                    <button onClick={() => onSelectContact(student)} className="w-full flex items-center gap-3 p-2.5 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 text-left">
                      <Avatar name={contactFullName(student)} size={28}/>
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium text-slate-900 truncate">{contactFullName(student)}</div>
                        <div className="text-[11px] text-slate-500">Student</div>
                      </div>
                      <Icon.ChevronRight size={14} className="text-slate-400"/>
                    </button>
                  )}
                  {differentPayer && (
                    <button onClick={() => onSelectContact(payer)} className="w-full flex items-center gap-3 p-2.5 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 text-left">
                      <Avatar name={contactFullName(payer)} size={28}/>
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium text-slate-900 truncate">{contactFullName(payer)}</div>
                        <div className="text-[11px] text-slate-500">Payer</div>
                      </div>
                      <Icon.ChevronRight size={14} className="text-slate-400"/>
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Qualify / Disqualify footer */}
        {!editing && (
          <div className="border-t border-slate-200 px-6 py-3 flex items-center justify-between bg-slate-50">
            <div className="text-[11px] font-medium">
              {isLost
                ? <span className="text-rose-600 inline-flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-rose-500"/> Disqualified</span>
                : isQualified
                  ? <span className="text-emerald-700 inline-flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-emerald-500"/> Qualified</span>
                  : <span className="text-slate-500 inline-flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-slate-400"/> Awaiting qualification</span>}
            </div>
            <div className="flex items-center gap-2">
              {!isLost && <Button size="sm" variant="danger" icon={<Icon.X size={12}/>} onClick={() => onDisqualify(lead)}>Disqualify</Button>}
              <Button size="sm" variant="brand" icon={<Icon.Check size={13}/>} onClick={() => onQualify(lead, match)}
                disabled={isQualified}>
                {isLost ? 'Re-qualify lead' : isQualified ? 'Qualified' : 'Qualify lead'}
              </Button>
            </div>
          </div>
        )}

        {/* Delete row */}
        {!editing && onDelete && (
          <div className="border-t border-slate-200 px-6 py-2.5 flex items-center justify-between bg-white">
            <span className="text-[11px] text-slate-400">Permanently remove this lead and its deal record.</span>
            <Button size="sm" variant="ghost" icon={<Icon.Trash size={12}/>}
              className="text-rose-600 hover:bg-rose-50"
              onClick={() => confirm({
                title: 'Delete lead?',
                body: <span>Are you sure you want to permanently delete <strong>{lead.name}</strong>? This removes the lead and its deal record. Linked contacts are kept. This cannot be undone.</span>,
                confirmLabel: 'Delete lead',
                tone: 'danger',
                onConfirm: () => onDelete(lead),
              })}>
              Delete lead
            </Button>
          </div>
        )}
      </aside>
    </div>
  );
}
window.LeadDetailDrawer = LeadDetailDrawer;
