// Raw Leads inbox + Qualify flow — entry point of the three-entity model.

function LeadsInboxView({ rawLeads, contacts, onQualify, onDisqualify, onView, embedded }) {
  return (
    <div className={embedded ? '' : 'px-7 py-6 max-w-[1100px] mx-auto'}>
      <div className="flex items-end justify-between mb-4">
        <div>
          <p className="text-xs text-slate-500">Raw enquiries waiting to be qualified into a Contact + Deal — or disqualified. Qualifying moves them out of the inbox; a record stays in the engaged tabs.</p>
        </div>
        <div className="text-xs text-slate-500 shrink-0 ml-4">{rawLeads.length} awaiting triage</div>
      </div>

      {rawLeads.length === 0 ? (
        <div className="bg-white border border-dashed border-slate-200 rounded-xl p-12 text-center">
          <Icon.Inbox size={22} className="mx-auto text-slate-300 mb-2"/>
          <div className="text-sm font-medium text-slate-700">Inbox zero</div>
          <div className="text-xs text-slate-500 mt-1">All leads have been qualified or disqualified.</div>
        </div>
      ) : (
        <ul className="space-y-3">
          {rawLeads.map(l => {
            const matched = l.matchedContactId ? getContact(contacts, l.matchedContactId) : null;
            return (
              <li key={l.id} className="bg-white border border-slate-200 rounded-xl overflow-hidden hover:border-slate-300 transition-colors">
                <div className="p-5 cursor-pointer" onClick={() => onView && onView(l)}>
                  <div className="flex items-start gap-3.5">
                    <Avatar name={l.name} size={40}/>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-sm font-semibold text-slate-900">{l.name}</span>
                        <span className="text-xs text-slate-500">{l.email}</span>
                        <span className="text-slate-300">·</span>
                        <span className="text-xs text-slate-500 tabular-nums">{l.phone}</span>
                      </div>
                      <div className="flex items-center gap-2 flex-wrap mt-1.5">
                        <SegmentPill segment={l.formAnswers.segment}/>
                        <span className="text-[11px] text-slate-500">{l.formAnswers.gradeOrYear}</span>
                        <span className="text-slate-300">·</span>
                        {l.formAnswers.subjects.map(s => <SubjectChip key={s} subject={s}/>)}
                        <span className="text-slate-300">·</span>
                        <span className="text-[11px] text-slate-500">Source: {l.source}</span>
                      </div>
                      <p className="text-[13px] text-slate-700 italic mt-2.5 leading-relaxed">"{l.formAnswers.struggle}"</p>

                      {matched && (
                        <div className="mt-3 bg-violet-50 border border-violet-200 rounded-md p-2.5 flex items-center gap-2.5">
                          <span className="text-violet-600 shrink-0"><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 phone: <strong>{contactFullName(matched)}</strong></div>
                            <div className="text-[11.5px] text-violet-700 mt-0.5">Qualifying will add a new deal to this existing contact instead of creating a duplicate.</div>
                          </div>
                        </div>
                      )}
                    </div>
                    <div className="flex flex-col items-end gap-1 shrink-0">
                      <span className="text-[11px] text-slate-400">{fmtDateTime(l.submittedAt)}</span>
                      <span className="text-[11px] text-indigo-600 font-medium inline-flex items-center gap-0.5">View <Icon.ChevronRight size={11}/></span>
                    </div>
                  </div>
                </div>
                <div className="px-5 py-3 bg-slate-50 border-t border-slate-100 flex items-center justify-end gap-2">
                  <Button size="sm" variant="ghost" onClick={() => onDisqualify(l)}>Disqualify</Button>
                  <Button size="sm" variant="brand" icon={<Icon.Check size={13}/>} onClick={() => onQualify(l)}>Qualify lead</Button>
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
window.LeadsInboxView = LeadsInboxView;

// ============================================================
// RAW LEAD DRAWER — read-only detail of an inbound enquiry, with Qualify/Disqualify.
// ============================================================
function RawLeadDrawer({ lead, contacts, onClose, onQualify, onDisqualify, onSelectContact }) {
  if (!lead) return null;
  const fa = lead.formAnswers || {};
  const emailMatch = (contacts || []).find(c => lead.email && lead.email !== '—' && (c.email || '').toLowerCase() === lead.email.toLowerCase());
  const phoneMatch = !emailMatch ? (contacts || []).find(c => lead.phone && (c.phone || '').replace(/\s/g,'') === (lead.phone || '').replace(/\s/g,'')) : null;
  const match = emailMatch || phoneMatch;
  const isParentEnquiry = fa.whoNeedsTutoring && fa.whoNeedsTutoring !== 'Myself';

  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>
  );

  return (
    <div className="fixed inset-0 z-40">
      <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">
        <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="flex items-center gap-2">
                  <div className="text-base font-semibold text-slate-900 truncate">{lead.name}</div>
                  <span className="text-[10px] px-1.5 py-0.5 bg-emerald-50 text-emerald-700 rounded font-semibold uppercase tracking-wider">Inbox</span>
                </div>
                <div className="text-xs text-slate-500 truncate">
                  {isParentEnquiry && fa.studentName ? `Enquiry for ${fa.studentName}` : 'Student enquiry'} · {fa.segment === 'University' ? 'University' : 'High School'} · {fa.gradeOrYear}
                </div>
              </div>
            </div>
            <IconButton icon={<Icon.X size={16}/>} onClick={onClose} title="Close"/>
          </div>
          <div className="flex flex-wrap items-center gap-2 mt-3">
            <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>

        <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">"{fa.struggle}"</p>
          </div>

          {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 {emailMatch ? '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>
                {onSelectContact && <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={fa.segment === 'University' ? 'University' : 'High School'}/>
            <Field label="Grade / Year" value={fa.gradeOrYear}/>
            <Field label="Subjects" value={(fa.subjects || []).join(', ')}/>
            <Field label="Who needs tutoring" value={fa.whoNeedsTutoring}/>
            {fa.studentName && <Field label="Student name" value={fa.studentName}/>}
            <Field label="Budget" value={fa.budgetWilling}/>
            <Field label="Wants to start" value={fa.whenToStart}/>
            <Field label="Email" value={lead.email}/>
            <Field label="Phone" value={lead.phone} mono/>
            <Field label="Submitted" value={fmtDateTime(lead.submittedAt)}/>
          </div>
        </div>

        <div className="border-t border-slate-200 px-6 py-3 flex items-center justify-between bg-slate-50">
          <span className="text-[11px] text-emerald-700 inline-flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-emerald-500"/> Awaiting qualification</span>
          <div className="flex items-center gap-2">
            <Button size="sm" variant="danger" icon={<Icon.X size={12}/>} onClick={() => { onDisqualify(lead); onClose(); }}>Disqualify</Button>
            <Button size="sm" variant="brand" icon={<Icon.Check size={13}/>} onClick={() => { onQualify(lead); onClose(); }}>Qualify lead</Button>
          </div>
        </div>
      </aside>
    </div>
  );
}
window.RawLeadDrawer = RawLeadDrawer;

function QualifyModal({ lead, contacts, onClose, onConfirm }) {
  const matched = lead && lead.matchedContactId ? getContact(contacts, lead.matchedContactId) : null;
  const [decision, setDecision] = useState(matched ? 'link' : 'create');
  const [owner, setOwner] = useState((OWNERS.find(o => o.id !== 'system') || {}).id || '');
  useEffect(() => { setDecision(matched ? 'link' : 'create'); setOwner((OWNERS.find(o => o.id !== 'system') || {}).id || ''); }, [lead?.id]);
  if (!lead) return null;

  return (
    <Modal open={!!lead} onClose={onClose} width="max-w-lg">
      <div className="px-5 py-4 border-b border-slate-200">
        <div className="text-base font-semibold text-slate-900">Qualify lead</div>
        <div className="text-xs text-slate-500 mt-0.5">This will create a new Deal and link it to a Contact.</div>
      </div>
      <div className="p-5 space-y-4 overflow-y-auto">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500 mb-2">Step 1 · The person</div>
          {matched ? (
            <div className="space-y-2">
              <label className={`flex items-start gap-2.5 p-3 border rounded-lg cursor-pointer ${decision === 'link' ? 'border-indigo-300 bg-indigo-50/40 ring-2 ring-indigo-100' : 'border-slate-200'}`}>
                <input type="radio" checked={decision === 'link'} onChange={() => setDecision('link')} className="mt-1"/>
                <div className="flex-1">
                  <div className="text-sm font-semibold text-slate-900">Link to existing contact</div>
                  <div className="flex items-center gap-2 mt-1.5">
                    <Avatar name={contactFullName(matched)} size={26}/>
                    <div>
                      <div className="text-[13px] font-medium text-slate-800">{contactFullName(matched)}</div>
                      <div className="text-[11px] text-slate-500">{matched.phone} — added {fmtTimeAgo(matched.addedAt)}</div>
                    </div>
                  </div>
                </div>
              </label>
              <label className={`flex items-start gap-2.5 p-3 border rounded-lg cursor-pointer ${decision === 'create' ? 'border-indigo-300 bg-indigo-50/40 ring-2 ring-indigo-100' : 'border-slate-200'}`}>
                <input type="radio" checked={decision === 'create'} onChange={() => setDecision('create')} className="mt-1"/>
                <div className="flex-1">
                  <div className="text-sm font-semibold text-slate-900">Create new contact</div>
                  <div className="text-[11px] text-slate-500 mt-1">Use only if this is genuinely a different person.</div>
                </div>
              </label>
            </div>
          ) : (
            <div className="bg-slate-50 border border-slate-200 rounded-lg p-3">
              <div className="text-sm font-semibold text-slate-900">Create new contact</div>
              <div className="text-[12px] text-slate-600 mt-1">No existing contact matches {lead.phone}. A new Contact will be created for <strong>{lead.name}</strong>.</div>
              {lead.formAnswers.whoNeedsTutoring !== 'Myself' && lead.formAnswers.studentName && (
                <div className="text-[12px] text-slate-600 mt-2 pt-2 border-t border-slate-200">A second Student contact for <strong>{lead.formAnswers.studentName}</strong> will also be created and linked as <em>child of</em> {lead.name}.</div>
              )}
            </div>
          )}
        </div>

        <div>
          <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-500 mb-2">Step 2 · The deal</div>
          <div className="bg-slate-50 border border-slate-200 rounded-lg p-3 space-y-1.5 text-[12.5px] text-slate-700">
            <div className="flex justify-between"><span className="text-slate-500">Title</span> <span>{(lead.formAnswers.studentName || lead.name)} — {lead.formAnswers.subjects.join(' + ')}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Subjects</span> <span>{lead.formAnswers.subjects.join(', ')}</span></div>
            <div className="flex justify-between"><span className="text-slate-500">Level</span> <span>{lead.formAnswers.segment} · {lead.formAnswers.gradeOrYear}</span></div>
            <div className="flex justify-between items-center"><span className="text-slate-500">Starting stage</span> <StageChip stageId="CallPending"/></div>
            <div className="flex justify-between"><span className="text-slate-500">Source</span> <span>{lead.source}</span></div>
          </div>
          {/* Assign to team member */}
          <div className="mt-3">
            <label className="text-[11px] font-medium text-slate-500 mb-1 block">Assign to</label>
            <div className="flex items-center gap-2">
              {owner && (() => { const o = OWNERS.find(x => x.id === owner); return o ? <Avatar name={o.name} color={o.color} size={28}/> : null; })()}
              <select value={owner} onChange={e => setOwner(e.target.value)}
                className="flex-1 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">
                <option value="">Unassigned</option>
                {OWNERS.filter(o => o.id !== 'system').map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
              </select>
            </div>
          </div>
        </div>
      </div>
      <div className="px-5 py-3.5 bg-slate-50 border-t border-slate-200 flex items-center justify-end gap-2">
        <Button variant="secondary" onClick={onClose}>Cancel</Button>
        <Button variant="brand" icon={<Icon.Check size={13}/>} onClick={() => onConfirm({ leadId: lead.id, decision, matchedContactId: matched?.id, owner })}>Qualify and create deal</Button>
      </div>
    </Modal>
  );
}
window.QualifyModal = QualifyModal;
