// Contacts — list + detail drawer. Part of the three-entity model.

// ============================================================
// CONTACTS LIST
// ============================================================
function ContactsView({ contacts, deals, onSelectContact, search }) {
  const [typeFilter, setTypeFilter] = useState('All');
  const [localSearch, setLocalSearch] = useState('');
  const q = (search || localSearch).toLowerCase();

  const enriched = useMemo(() => contacts.map(c => {
    const my = dealsForContact(deals, c.id);
    const won = my.filter(d => d.stage === 'FulfillmentReady');
    const active = my.filter(d => isActiveStage(d.stage));
    const ltv = won.reduce((s, d) => s + (d.customPackagePrice || 0), 0);
    const lastActivity = my.length ? my.map(d => d.wonAt || d.addedTime).sort().reverse()[0] : c.addedAt;
    return { ...c, _deals: my, _won: won, _active: active, _ltv: ltv, _last: lastActivity };
  }), [contacts, deals]);

  const filtered = enriched.filter(c => {
    if (typeFilter !== 'All' && c.type !== typeFilter) return false;
    if (q) {
      const full = contactFullName(c).toLowerCase();
      if (!full.includes(q) && !(c.email || '').toLowerCase().includes(q) && !(c.phone || '').includes(q)
        && !(c.subjects || []).some(s => s.toLowerCase().includes(q))) return false;
    }
    return true;
  }).sort((a,b) => b._ltv - a._ltv);

  return (
    <div className="px-7 py-5 max-w-[1300px] mx-auto">
      <div className="flex flex-wrap items-center gap-2 mb-4">
        <div className="inline-flex items-center p-0.5 bg-slate-100 rounded-lg">
          {['All','Parent','Student'].map(t => (
            <button key={t} onClick={() => setTypeFilter(t)}
              className={`h-7 px-3 text-[12px] font-semibold rounded-md transition-all ${
                typeFilter === t ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'
              }`}>{t}</button>
          ))}
        </div>
        {!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 name, email, phone…"
              className="h-8 w-64 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} of {contacts.length} contacts</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-[26%]">Contact</th>
                <th className="px-4 py-2.5">Type</th>
                <th className="px-4 py-2.5">Relationships</th>
                <th className="px-4 py-2.5 text-center">Deals</th>
                <th className="px-4 py-2.5 text-right">Lifetime value</th>
                <th className="px-4 py-2.5">Last activity</th>
                <th className="px-2 py-2.5"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.map(c => (
                <tr key={c.id} onClick={() => onSelectContact(c)} className="hover:bg-slate-50 cursor-pointer">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2.5">
                      <Avatar name={contactFullName(c)} size={30}/>
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-slate-900 truncate">{contactFullName(c)}</div>
                        <div className="text-[11px] text-slate-500 truncate">{c.email !== '—' ? c.email : c.phone}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3"><TypeBadge type={c.type}/></td>
                  <td className="px-4 py-3 text-[12px] text-slate-600">
                    {(c.relationships || []).length === 0
                      ? <span className="text-slate-400">—</span>
                      : `${c.relationships.length} relationship${c.relationships.length > 1 ? 's' : ''}`}
                  </td>
                  <td className="px-4 py-3 text-center text-[12.5px] tabular-nums">
                    <span className="text-emerald-700 font-semibold">{c._won.length}</span>
                    <span className="text-slate-300"> / </span>
                    <span className="text-amber-700">{c._active.length}</span>
                  </td>
                  <td className="px-4 py-3 text-right text-[13px] font-semibold text-slate-900 tabular-nums">
                    {c._ltv ? <>{fmtZAR(c._ltv)}<span className="text-[10px] text-slate-400 font-normal">/mo</span></> : <span className="text-slate-400 font-normal">—</span>}
                  </td>
                  <td className="px-4 py-3 text-[11.5px] text-slate-500">{fmtTimeAgo(c._last)}</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={7}>
                  <Empty title="No contacts match" hint="Try clearing filters or adjusting your search." icon={<Icon.Users size={18}/>}/>
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="px-4 py-2 bg-slate-50 border-t border-slate-100 text-[11px] text-slate-500 flex items-center gap-4">
          <span className="inline-flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-emerald-500"/> Won deals</span>
          <span className="inline-flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-amber-500"/> Active deals</span>
          <span className="text-slate-400">Sorted by lifetime value</span>
        </div>
      </div>
    </div>
  );
}
window.ContactsView = ContactsView;

// ============================================================
// CONTACT DRAWER
// ============================================================
function ContactDrawer({ contact, contacts, deals, onClose, onSelectContact, onSelectDeal, onUpdate, onDelete }) {
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState(contact);
  const [ConfirmEl, confirm] = useConfirm();

  useEffect(() => { setForm(contact); setEditing(false); }, [contact?.id]);
  if (!contact) return null;

  const my = dealsForContact(deals, contact.id);
  const won = my.filter(d => d.stage === 'FulfillmentReady');
  const ltv = won.reduce((s, d) => s + (d.customPackagePrice || 0), 0);
  const referrals = referralsFor(contacts, contact.id);

  const inputCls = "w-full h-8 px-2.5 text-sm bg-white border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-100 text-slate-900";

  const save = () => { onUpdate(form); setEditing(false); };

  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-[640px] bg-white shadow-2xl border-l border-slate-200 flex flex-col">
        {/* Header */}
        <div className="px-6 pt-5 pb-5 border-b border-slate-200">
          <div className="flex items-start justify-between gap-3 mb-4">
            <div className="flex items-center gap-3.5 min-w-0">
              <Avatar name={contactFullName(contact)} size={56}/>
              <div className="min-w-0">
                <div className="text-lg font-semibold text-slate-900">{contactFullName(contact)}</div>
                <div className="flex items-center gap-2 mt-1">
                  <TypeBadge type={contact.type}/>
                  {contact.segment && <span className="text-[11px] text-slate-500">{contact.segment} · {contact.gradeOrYear}</span>}
                </div>
                <div className="text-[11px] text-slate-500 mt-1.5">Member {fmtTimeAgo(contact.addedAt)} · Joined {fmtDateLong(contact.addedAt)}</div>
              </div>
            </div>
            <div className="flex items-center gap-1">
              {!editing && <IconButton icon={<Icon.Settings size={15}/>} title="Edit contact" onClick={() => setEditing(true)}/>}
              <IconButton icon={<Icon.X size={16}/>} onClick={onClose} title="Close"/>
            </div>
          </div>

          {/* KPI strip */}
          <div className="grid grid-cols-3 gap-3">
            <div className="bg-emerald-50 border border-emerald-100 rounded-lg p-3">
              <div className="text-[10px] uppercase tracking-wider text-emerald-700 font-semibold">Lifetime value</div>
              <div className="text-xl font-bold text-emerald-900 tabular-nums mt-0.5">{fmtZARShort(ltv)}<span className="text-[11px] font-normal text-emerald-700">/mo</span></div>
            </div>
            <div className="bg-slate-50 border border-slate-200 rounded-lg p-3">
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-semibold">Total deals</div>
              <div className="text-xl font-bold text-slate-900 tabular-nums mt-0.5">{my.length}<span className="text-[11px] font-normal text-slate-500"> ({won.length} won)</span></div>
            </div>
            <div className="bg-slate-50 border border-slate-200 rounded-lg p-3">
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-semibold">Referrals</div>
              <div className="text-xl font-bold text-slate-900 tabular-nums mt-0.5">{referrals.length}</div>
            </div>
          </div>

          {!editing && (
            <div className="flex items-center gap-2 mt-4">
              <Button size="sm" variant="brand" icon={<Icon.Chat size={12}/>}>WhatsApp</Button>
              <Button size="sm" variant="secondary" icon={<Icon.Phone size={12}/>}>Call</Button>
              <Button size="sm" variant="secondary" icon={<Icon.Mail size={12}/>}>Email</Button>
            </div>
          )}
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 space-y-5">
          {/* Contact details (editable) */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <div className="text-[11px] uppercase tracking-wider text-slate-500 font-semibold">Contact details</div>
            </div>
            {editing ? (
              <div className="space-y-3 bg-slate-50 border border-slate-200 rounded-lg p-3.5">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block mb-1">First name</label>
                    <input className={inputCls} value={form.firstName} onChange={e => setForm({...form, firstName: e.target.value})}/>
                  </div>
                  <div>
                    <label className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block mb-1">Last name</label>
                    <input className={inputCls} value={form.lastName} onChange={e => setForm({...form, lastName: e.target.value})}/>
                  </div>
                </div>
                <div>
                  <label className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block mb-1">Type</label>
                  <select className={inputCls} value={form.type} onChange={e => setForm({...form, type: e.target.value})}>
                    <option>Parent</option><option>Student</option><option>Other</option>
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block mb-1">Phone</label>
                    <input className={inputCls} value={form.phone} onChange={e => setForm({...form, phone: e.target.value})}/>
                  </div>
                  <div>
                    <label className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block mb-1">Email</label>
                    <input className={inputCls} value={form.email} onChange={e => setForm({...form, email: e.target.value})}/>
                  </div>
                </div>
                <div>
                  <label className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block mb-1">Notes</label>
                  <textarea rows={3} className={inputCls + ' h-auto py-2 resize-y'} value={form.notes || ''} onChange={e => setForm({...form, notes: e.target.value})}/>
                </div>
                <div className="flex items-center justify-end gap-1.5 pt-1">
                  <Button size="sm" variant="ghost" onClick={() => { setForm(contact); setEditing(false); }}>Cancel</Button>
                  <Button size="sm" variant="brand" icon={<Icon.Check size={12}/>} onClick={save}>Save changes</Button>
                </div>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-2 gap-3 text-[13px]">
                  <div><div className="text-[11px] text-slate-500">Phone</div><div className="text-slate-800 tabular-nums">{contact.phone}</div></div>
                  <div><div className="text-[11px] text-slate-500">Email</div><div className="text-slate-800 break-all">{contact.email}</div></div>
                </div>
                {(contact.tags || []).length > 0 && (
                  <div className="flex flex-wrap gap-1.5 mt-3">
                    {contact.tags.map(t => <span key={t} className="px-2 py-0.5 bg-slate-100 text-slate-700 text-[11px] rounded font-medium">#{t}</span>)}
                  </div>
                )}
              </>
            )}
          </div>

          {/* Relationships */}
          {(contact.relationships || []).length > 0 && (
            <div>
              <div className="text-[11px] uppercase tracking-wider text-slate-500 font-semibold mb-2">Relationships</div>
              <div className="space-y-1.5">
                {contact.relationships.map((r, i) => {
                  const other = getContact(contacts, r.contactId); if (!other) return null;
                  return (
                    <button key={i} onClick={() => onSelectContact(other)}
                      className="w-full flex items-center gap-3 p-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 text-left">
                      <span className="text-[11px] text-slate-500 font-medium w-24 shrink-0">{RELATIONSHIP_LABELS[r.kind] || r.kind}</span>
                      <Avatar name={contactFullName(other)} size={26}/>
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium text-slate-900 truncate">{contactFullName(other)}</div>
                        <div className="text-[11px] text-slate-500 truncate">{other.type}{other.gradeOrYear ? ` · ${other.gradeOrYear}` : ''}</div>
                      </div>
                      <Icon.ChevronRight size={14} className="text-slate-400"/>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Referrals brought */}
          {referrals.length > 0 && (
            <div>
              <div className="text-[11px] uppercase tracking-wider text-slate-500 font-semibold mb-2">Referrals brought in</div>
              <div className="space-y-1.5">
                {referrals.map(r => (
                  <button key={r.id} onClick={() => onSelectContact(r)}
                    className="w-full flex items-center gap-3 p-2 bg-emerald-50/40 border border-emerald-200 rounded-lg hover:bg-emerald-50 text-left">
                    <span className="text-emerald-600 shrink-0"><Icon.Sparkles size={13}/></span>
                    <Avatar name={contactFullName(r)} size={26}/>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-slate-900 truncate">{contactFullName(r)}</div>
                      <div className="text-[11px] text-slate-500 truncate">{r.type}{r.gradeOrYear ? ` · ${r.gradeOrYear}` : ''}</div>
                    </div>
                    <Icon.ChevronRight size={14} className="text-slate-400"/>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Deals timeline */}
          <div>
            <div className="text-[11px] uppercase tracking-wider text-slate-500 font-semibold mb-2">Deals timeline ({my.length})</div>
            {my.length === 0 ? (
              <div className="bg-slate-50 border border-dashed border-slate-200 rounded-lg p-5 text-center text-[12px] text-slate-500">No deals linked yet.</div>
            ) : (
              <ul className="space-y-2">
                {my.slice().sort((a,b) => new Date(b.addedTime) - new Date(a.addedTime)).map(d => {
                  const student = getContact(contacts, d.studentId);
                  const payer = getContact(contacts, d.payerId);
                  return (
                    <li key={d.id}>
                      <button onClick={() => onSelectDeal(d)}
                        className="w-full text-left bg-white border border-slate-200 rounded-lg p-3 hover:border-slate-300 hover:shadow-sm transition">
                        <div className="flex items-start justify-between gap-2 mb-1">
                          <span className="text-[13px] font-semibold text-slate-900">{d.title}</span>
                          <StageChip stageId={d.stage}/>
                        </div>
                        <div className="text-[11.5px] text-slate-500 mb-1.5">
                          {d.studentId !== d.payerId && payer && student
                            ? <>Student: <strong className="text-slate-700">{student.firstName}</strong> · Payer: <strong className="text-slate-700">{payer.firstName}</strong></>
                            : <>{student ? contactFullName(student) : '—'} (self-payer)</>}
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-[11px] text-slate-500">{d.selectedPackage || 'No package yet'} · {(d.subjects||[]).join(', ')}</span>
                          {d.customPackagePrice && <span className="text-[12.5px] font-semibold text-slate-900 tabular-nums">{fmtZAR(d.customPackagePrice)}<span className="text-[10px] text-slate-400 font-normal">/mo</span></span>}
                        </div>
                        <div className="text-[10px] text-slate-400 mt-1.5">{d.stage === 'FulfillmentReady' ? `Won ${fmtTimeAgo(d.wonAt)}` : `Created ${fmtTimeAgo(d.addedTime)}`}</div>
                      </button>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>

          {/* Notes */}
          {!editing && contact.notes && (
            <div>
              <div className="text-[11px] uppercase tracking-wider text-slate-500 font-semibold mb-2">Notes</div>
              <div className="bg-slate-50 border border-slate-200 rounded-lg p-3 text-[13px] text-slate-700 leading-relaxed">{contact.notes}</div>
            </div>
          )}
        </div>

        {/* Delete footer */}
        {!editing && onDelete && (
          <div className="border-t border-slate-200 px-6 py-3 flex items-center justify-between bg-slate-50">
            <span className="text-[11px] text-slate-400">{deals.filter(d => d.studentId === contact.id || d.payerId === contact.id).length} linked deal(s) will be kept.</span>
            <Button size="sm" variant="ghost" icon={<Icon.Trash size={12}/>}
              className="text-rose-600 hover:bg-rose-50"
              onClick={() => confirm({
                title: 'Delete contact?',
                body: <span>Are you sure you want to permanently delete <strong>{contactFullName(contact)}</strong>? Their relationships to other contacts will be removed. Deals stay in the pipeline. This cannot be undone.</span>,
                confirmLabel: 'Delete contact',
                tone: 'danger',
                onConfirm: () => onDelete(contact.id),
              })}>
              Delete contact
            </Button>
          </div>
        )}
      </aside>
    </div>
  );
}
window.ContactDrawer = ContactDrawer;
