// ─── CRM Contacts Page ───────────────────────────────────────────────────────

function CRMPage() {
  const [contacts, setContacts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(null);
  const { toasts, addToast } = C.useToast();

  const handleCall = async (phoneNumber, contactName) => {
    addToast(`Dispatching call to ${phoneNumber}…`, 'info');
    try {
      const res = await fetch('/api/call/single', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: phoneNumber, caller_name: contactName || '' }),
      });
      const data = await res.json();
      if (res.ok && data.status !== 'error') addToast(`Call dispatched to ${phoneNumber}`, 'success');
      else addToast(data.message || data.detail || 'Call dispatch failed', 'error');
    } catch (e) {
      addToast('Call dispatch error: ' + e.message, 'error');
    }
  };

  React.useEffect(() => {
    fetch('/api/contacts')
      .then(r => r.json())
      .then(data => { setContacts(Array.isArray(data) ? data : []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  const filtered = contacts.filter(c => {
    const hot = c.is_booked;
    const warm = !c.is_booked && (c.total_calls || 0) > 1;
    const cold = !c.is_booked && (c.total_calls || 0) <= 1;
    const status = hot ? 'hot' : warm ? 'warm' : 'cold';
    if (statusFilter !== 'all' && status !== statusFilter) return false;
    if (search) {
      const q = search.toLowerCase();
      return (c.phone_number || '').includes(q) || (c.caller_name || '').toLowerCase().includes(q);
    }
    return true;
  });

  const contact = contacts.find(c => c.phone_number === selected);

  const getStatus = c => c.is_booked ? 'hot' : (c.total_calls || 0) > 1 ? 'warm' : 'cold';
  const STATUS_C = { hot: 'red', warm: 'amber', cold: 'blue' };

  return (
    <div>
      <C.ToastContainer toasts={toasts} />
      <C.PageHeader title="CRM Contacts" sub="Prospects from inbound calls and LeadRat sync"
        action={<C.Btn variant="primary">+ Add Contact</C.Btn>} />

      {loading ? <C.Spinner /> : (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20 }}>
          <div>
            <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'center' }}>
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search name or phone…"
                style={{ flex: 1, background: '#13161e', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 8, color: '#e8eaef', fontSize: 13, padding: '8px 12px', outline: 'none' }} />
              <C.Tabs tabs={['all','hot','warm','cold']} active={statusFilter} onChange={setStatusFilter} />
            </div>
            <C.Card>
              <C.Table cols={['Name / Phone','Calls','Status','Last Seen','Actions']}
                empty="No contacts found."
                rows={filtered.map(c => {
                  const st = getStatus(c);
                  return [
                    <div style={{ cursor: 'pointer' }} onClick={() => setSelected(c.phone_number)}>
                      <div style={{ fontWeight: 700, color: '#e8eaef' }}>{c.caller_name || 'Unknown'}</div>
                      <div style={{ fontSize: 11, color: '#7b849a', fontVariantNumeric: 'tabular-nums' }}>{c.phone_number}</div>
                    </div>,
                    <span style={{ fontSize: 13, color: '#c8cdd8' }}>{c.total_calls ?? 0}</span>,
                    <C.Badge color={STATUS_C[st]}>{st.charAt(0).toUpperCase() + st.slice(1)}</C.Badge>,
                    <span style={{ fontSize: 12, color: '#7b849a' }}>{c.last_seen ? new Date(c.last_seen).toLocaleDateString('en-IN', { month: 'short', day: 'numeric' }) : '—'}</span>,
                    <div style={{ display: 'flex', gap: 6 }}>
                      <C.Btn variant="ghost" size="sm" onClick={() => setSelected(c.phone_number)}>View</C.Btn>
                      <C.Btn variant="ghost" size="sm" onClick={() => handleCall(c.phone_number, c.caller_name)}>Call</C.Btn>
                    </div>,
                  ];
                })} />
            </C.Card>
          </div>

          <div>
            {contact ? (
              <C.Card title={contact.caller_name || contact.phone_number} action={<C.Btn variant="ghost" size="sm" onClick={() => setSelected(null)}>✕</C.Btn>}>
                <div style={{ padding: '16px 20px', display: 'grid', gap: 12 }}>
                  {(() => { const st = getStatus(contact); return <C.Badge color={STATUS_C[st]}>{st.charAt(0).toUpperCase() + st.slice(1)} Lead</C.Badge>; })()}
                  {[
                    { label: 'Phone', value: contact.phone_number },
                    { label: 'Name', value: contact.caller_name || '—' },
                    { label: 'Total Calls', value: contact.total_calls ?? 0 },
                    { label: 'Booking Status', value: contact.is_booked ? 'Booked' : 'Not booked' },
                    { label: 'Last Seen', value: contact.last_seen ? new Date(contact.last_seen).toLocaleString('en-IN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true }) : '—' },
                    { label: 'WhatsApp Unread', value: contact.whatsapp_unread_count ?? '—' },
                  ].map(r => (
                    <div key={r.label}>
                      <div style={{ fontSize: 11, color: '#7b849a', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{r.label}</div>
                      <div style={{ fontSize: 13, color: '#e8eaef', marginTop: 2, fontWeight: 500 }}>{String(r.value)}</div>
                    </div>
                  ))}
                  <div style={{ display: 'grid', gap: 6, marginTop: 4 }}>
                    <C.Btn variant="primary" size="sm" onClick={() => handleCall(contact.phone_number, contact.caller_name)}>Trigger Call</C.Btn>
                    <C.Btn variant="ghost" size="sm">Send WhatsApp</C.Btn>
                    <C.Btn variant="ghost" size="sm">Book Appointment</C.Btn>
                  </div>
                </div>
              </C.Card>
            ) : (
              <C.Card style={{ padding: '40px 24px', textAlign: 'center' }}>
                <div style={{ fontSize: 13, color: '#5a6375' }}>Select a contact to view details</div>
              </C.Card>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CRMPage });
