// Deal drawer — slide-in detail with People, Package, Activity, Playbook tabs.

function DealDrawer({ deal, contacts, playbooks, onClose, onUpdate, onMoveStage, onDelete, onSelectContact }) {
  const [tab, setTab] = useState('overview');
  const [newNote, setNewNote] = useState('');
  const [ConfirmEl, confirm] = useConfirm();

  if (!deal) return null;
  const stage = STAGE_BY_ID[deal.stage];
  const owner = OWNERS.find(o => o.id === deal.owner);
  const student = getContact(contacts, deal.studentId);
  const payer = getContact(contacts, deal.payerId);
  const differentPayer = student && payer && student.id !== payer.id;
  const activeStages = STAGES.filter(s => s.id !== 'LostDisqualified' && !s.archived);
  const curIdx = STAGE_INDEX[deal.stage];
  const nextStage = STAGES[curIdx + 1];
  const prevStage = curIdx > 0 ? STAGES[curIdx - 1] : null;

  // Lead-like object for playbook placeholder rendering
  const placeholderLead = {
    name: student ? contactFullName(student) : deal.title,
    studentName: student ? contactFullName(student) : null,
    gradeOrYear: deal.gradeOrYear, subjects: deal.subjects,
    selectedPackage: deal.selectedPackage, customPackagePrice: deal.customPackagePrice,
    clarityCallDate: deal.clarityCallDate, clarityCallTime: deal.clarityCallTime,
    invoiceNumber: deal.invoiceNumber, invoiceAmount: deal.invoiceAmount,
  };

  const addNote = () => {
    if (!newNote.trim()) return;
    onUpdate({ ...deal, notes: [{ id: 'n' + Date.now(), timestamp: new Date().toISOString(), text: newNote.trim(), author: owner ? owner.name : 'You' }, ...deal.notes] });
    setNewNote('');
  };

  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-[560px] 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 mb-3">
            <div className="min-w-0">
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-semibold mb-1">Deal</div>
              <div className="text-base font-semibold text-slate-900">{deal.title}</div>
            </div>
            <div className="flex items-center gap-1">
              <IconButton icon={<Icon.X size={16}/>} onClick={onClose} title="Close"/>
            </div>
          </div>

          {/* Stage stepper */}
          <div className="bg-slate-50 border border-slate-200 rounded-lg p-3">
            <div className="flex items-center justify-between mb-2.5">
              <div className="flex items-center gap-2">
                <span className="text-[11px] text-slate-500 font-medium uppercase tracking-wider">Stage</span>
                <StageChip stageId={deal.stage} size="lg"/>
              </div>
              <div className="flex items-center gap-1">
                {prevStage && (
                  <button onClick={() => onMoveStage(deal.id, prevStage.id)}
                    className="h-7 px-2 text-[11px] font-medium text-slate-600 hover:bg-white border border-transparent hover:border-slate-200 rounded inline-flex items-center gap-1">
                    <Icon.ChevronLeft size={12}/> {prevStage.short}
                  </button>
                )}
                {nextStage && (
                  <button onClick={() => onMoveStage(deal.id, nextStage.id)}
                    className="h-7 px-2.5 text-[11px] font-semibold text-white bg-slate-900 hover:bg-slate-800 rounded inline-flex items-center gap-1">
                    {nextStage.short} <Icon.ChevronRight size={12}/>
                  </button>
                )}
              </div>
            </div>
            <p className="text-[12px] text-slate-600">{stage.hint}</p>
            <div className="flex gap-1 mt-3">
              {activeStages.map((s, i) => {
                const isLost = deal.stage === 'LostDisqualified';
                return (
                  <button key={s.id} onClick={() => onMoveStage(deal.id, s.id)} title={s.label}
                    className="flex-1 h-1.5 rounded-full transition-all"
                    style={{ background: isLost ? '#FECDD3' : i === curIdx ? STAGE_TOKENS[s.color].dot : i < curIdx ? '#94A3B8' : '#E2E8F0' }}/>
                );
              })}
            </div>
          </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>

        {/* Tabs */}
        <div className="px-6 border-b border-slate-200">
          <div className="flex gap-4 -mb-px">
            {[
              { id: 'overview', label: 'Overview' },
              { id: 'package',  label: 'Package & Deal' },
              { id: 'activity', label: `Activity (${deal.notes.length})` },
              { id: 'playbook', label: 'Playbook' },
            ].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)}
                className={`py-2.5 text-[13px] font-medium border-b-2 transition-colors ${tab === t.id ? 'border-slate-900 text-slate-900' : 'border-transparent text-slate-500 hover:text-slate-700'}`}>
                {t.label}
              </button>
            ))}
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 space-y-5">
          {tab === 'overview' && (
            <>
              {/* People */}
              <div>
                <div className="text-[11px] uppercase tracking-wider text-slate-500 font-semibold mb-2">People on this deal</div>
                <div className="space-y-2">
                  {student && (
                    <button onClick={() => onSelectContact(student)} className="w-full flex items-center gap-3 p-3 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 text-left">
                      <Avatar name={contactFullName(student)} size={36}/>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-semibold text-slate-900">{contactFullName(student)}</span>
                          <span className="text-[10px] px-1.5 py-0.5 bg-sky-100 text-sky-700 rounded font-semibold uppercase tracking-wider">Student</span>
                        </div>
                        <div className="text-[11px] text-slate-500">{student.segment} · {student.gradeOrYear}</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-3 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 text-left">
                      <Avatar name={contactFullName(payer)} size={36}/>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-semibold text-slate-900">{contactFullName(payer)}</span>
                          <span className="text-[10px] px-1.5 py-0.5 bg-violet-100 text-violet-700 rounded font-semibold uppercase tracking-wider">Payer</span>
                        </div>
                        <div className="text-[11px] text-slate-500">{payer.type} · {payer.phone}</div>
                      </div>
                      <Icon.ChevronRight size={14} className="text-slate-400"/>
                    </button>
                  ) : (
                    <div className="text-[12px] text-slate-500 italic px-1">Student pays for their own lessons (self-payer).</div>
                  )}
                </div>
              </div>

              {/* Why */}
              <div>
                <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1.5">Why they reached out</div>
                <p className="text-[13.5px] text-slate-800 leading-relaxed bg-slate-50 border border-slate-200 rounded-lg p-3.5">"{deal.struggleSubjectDetail}"</p>
              </div>

              {/* Facts */}
              <div className="grid grid-cols-2 gap-4">
                <Fact label="Subjects" value={(deal.subjects||[]).join(', ')}/>
                <Fact label="Level" value={`${deal.segment === 'University' ? 'University' : 'High School'} · ${deal.gradeOrYear}`}/>
                <Fact label="Assigned to" value={owner ? <div className="flex items-center gap-2"><Avatar name={owner.name} color={owner.color} size={22}/><span>{owner.name}</span></div> : '—'}/>
                <Fact label="Source" value={deal.utmSource || 'Direct'}/>
                {deal.utmCampaign && <Fact label="Campaign" value={deal.utmCampaign}/>}
                <Fact label="Follow-ups" value={deal.followUpCount}/>
                <Fact label="Deal created" value={fmtDateTime(deal.addedTime)}/>
                {deal.wonAt && <Fact label="Won on" value={fmtDateLong(deal.wonAt)}/>}
              </div>

              {deal.stage === 'LostDisqualified' && (
                <div className="bg-rose-50 border border-rose-200 rounded-lg p-3.5">
                  <div className="text-[11px] font-medium text-rose-700 uppercase tracking-wider mb-1">Lost: {deal.disqualifiedReason || 'Closed'}</div>
                  {deal.disqualifiedCustomFeedback && <p className="text-[13px] text-rose-900">{deal.disqualifiedCustomFeedback}</p>}
                </div>
              )}
            </>
          )}

          {tab === 'package' && <DealPackageTab deal={deal} onUpdate={onUpdate}/>}

          {tab === 'activity' && (
            <>
              <div className="bg-white border border-slate-200 rounded-lg p-3 focus-within:border-slate-300">
                <textarea rows={2} value={newNote} onChange={(e) => setNewNote(e.target.value)}
                  placeholder="Add a note, call summary or next step…"
                  className="w-full text-[13px] text-slate-800 placeholder:text-slate-400 outline-none resize-none"/>
                <div className="flex items-center justify-end mt-1.5">
                  <Button size="sm" variant="brand" onClick={addNote} disabled={!newNote.trim()}>Save note</Button>
                </div>
              </div>
              <div className="space-y-3">
                {deal.notes.map(n => (
                  <div key={n.id} className="flex gap-3">
                    <Avatar name={n.author} size={28}/>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-baseline gap-2">
                        <span className="text-[13px] font-medium text-slate-900">{n.author}</span>
                        <span className="text-[11px] text-slate-400">{fmtTimeAgo(n.timestamp)}</span>
                      </div>
                      <p className="text-[13px] text-slate-700 mt-0.5 whitespace-pre-wrap">{n.text}</p>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {tab === 'playbook' && <DealPlaybookTab deal={deal} playbooks={playbooks} placeholderLead={placeholderLead}/>}
        </div>

        {/* Footer */}
        <div className="border-t border-slate-200 px-6 py-3 flex items-center justify-between bg-slate-50">
          <div className="text-[11px] text-slate-500">Created {fmtDateLong(deal.addedTime)}</div>
          <div className="flex items-center gap-2">
            {deal.stage !== 'LostDisqualified' && (
              <Button size="sm" variant="danger" icon={<Icon.X size={12}/>}
                onClick={() => confirm({ title: 'Mark deal as lost?', body: <span>Mark <strong>{deal.title}</strong> as Lost? You can move it back later.</span>, confirmLabel: 'Yes, mark lost', tone: 'warning', onConfirm: () => onMoveStage(deal.id, 'LostDisqualified') })}>
                Mark lost
              </Button>
            )}
            <Button size="sm" variant="ghost" icon={<Icon.Trash size={12}/>}
              onClick={() => confirm({ title: 'Delete deal?', body: <span>Permanently delete <strong>{deal.title}</strong>? The linked contacts are kept; only this opportunity is removed.</span>, confirmLabel: 'Delete deal', tone: 'danger', onConfirm: () => onDelete(deal.id) })}>
              Delete
            </Button>
          </div>
        </div>
      </aside>
    </div>
  );
}
window.DealDrawer = DealDrawer;

function Fact({ label, value }) {
  return (
    <div>
      <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-1">{label}</div>
      <div className="text-[13px] text-slate-800">{value || <span className="text-slate-400">—</span>}</div>
    </div>
  );
}

function DealPackageTab({ deal, onUpdate }) {
  const [fmt, setFmt] = useState(deal.packageFormat || 'Private');
  const groupKey = deal.segment === 'University' ? 'University' : 'High School';
  const gradeOptions = (window.GRADE_OPTIONS && window.GRADE_OPTIONS[groupKey]) || [];
  const studentGrade = normalizeGrade(deal.gradeOrYear, deal.segment);
  const [grade, setGrade] = useState(deal.packageGrade || studentGrade || (gradeOptions[0] || ''));

  const all = PRICING[deal.segment] || PRICING.HighSchool;
  // Packages in this format that have a price for the chosen grade.
  const packages = all.filter(p => (p.format || 'Private') === fmt && packagePriceForGrade(p, grade) != null);

  const selectPackage = (pkg) => {
    const price = packagePriceForGrade(pkg, grade);
    onUpdate({
      ...deal, selectedPackage: pkg.name, customPackagePrice: price, packageFormat: pkg.format || 'Private', packageGrade: grade,
      notes: [{ id: 'n' + Date.now(), timestamp: new Date().toISOString(), text: `Selected ${pkg.name} ${pkg.format || 'Private'} package (${grade}) — ${fmtZAR(price)}/month.`, author: 'You' }, ...deal.notes],
    });
  };

  return (
    <>
      <div className="flex flex-wrap items-center gap-2">
        <div className="inline-flex items-center p-0.5 bg-slate-100 rounded-lg">
          {['Private','Semi-Private'].map(f => (
            <button key={f} onClick={() => setFmt(f)}
              className={`h-7 px-3 text-[11.5px] font-semibold rounded-md transition-all ${fmt === f ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}>
              {f === 'Private' ? 'Private (1-on-1)' : 'Semi-Private (max 3)'}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-1.5 ml-auto">
          <span className="text-[11px] text-slate-500">Pricing for</span>
          <select value={grade} onChange={e => setGrade(e.target.value)}
            className="h-7 px-2 text-[12px] font-medium bg-white border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-100 text-slate-800">
            {gradeOptions.map(g => <option key={g} value={g}>{g}</option>)}
          </select>
        </div>
      </div>
      {studentGrade && grade === studentGrade && (
        <div className="text-[11px] text-slate-500 inline-flex items-center gap-1"><Icon.School size={12} className="text-slate-400"/> Showing prices for the student's grade ({studentGrade}).</div>
      )}

      <div className="grid grid-cols-2 gap-3">
        {packages.map((pkg, idx) => {
          const price = packagePriceForGrade(pkg, grade);
          const active = deal.selectedPackage === pkg.name && (deal.packageFormat || 'Private') === (pkg.format || 'Private') && (deal.packageGrade || '') === grade;
          return (
            <button key={pkg.name + pkg.format + idx} onClick={() => selectPackage(pkg)}
              className={`text-left rounded-lg border p-3.5 transition-all ${active ? 'border-indigo-500 bg-indigo-50/40 ring-2 ring-indigo-100' : 'border-slate-200 hover:border-slate-300 bg-white'}`}>
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm font-semibold text-slate-900">{pkg.name}</span>
                {active && <Icon.Check size={14} className="text-indigo-600"/>}
              </div>
              <div className="text-xl font-semibold text-slate-900 tabular-nums">{fmtZAR(price)}<span className="text-[11px] font-normal text-slate-500">/mo</span></div>
              <div className="text-[11px] text-slate-500 mt-0.5">{pkg.hours} · {grade}</div>
              <div className="text-[12px] text-slate-600 mt-2">{pkg.desc}</div>
            </button>
          );
        })}
        {packages.length === 0 && (
          <div className="col-span-2 text-[12px] text-slate-400 italic py-3">No {fmt} packages priced for {grade}. Add one in Services → Investment Packages.</div>
        )}
      </div>
      <div className="bg-slate-50 border border-slate-200 rounded-lg p-4 space-y-3">
        <div className="text-[11px] font-medium text-slate-500 uppercase tracking-wider">Deal status</div>
        <div className="grid grid-cols-2 gap-3 text-[13px]">
          <div className="flex items-center justify-between">
            <span className="text-slate-500">Registration form</span>
            {deal.registrationFormSubmitted ? <span className="text-emerald-700 inline-flex items-center gap-1"><Icon.Check size={12}/> Received</span> : <span className="text-slate-400">Pending</span>}
          </div>
          <div className="flex items-center justify-between"><span className="text-slate-500">Invoice</span><span className="text-slate-700 tabular-nums">{deal.invoiceNumber || <span className="text-slate-400">—</span>}</span></div>
          <div className="flex items-center justify-between"><span className="text-slate-500">Invoice amount</span><span className="text-slate-700 tabular-nums">{deal.invoiceAmount ? fmtZAR(deal.invoiceAmount) : <span className="text-slate-400">—</span>}</span></div>
          <div className="flex items-center justify-between">
            <span className="text-slate-500">Payment</span>
            {deal.invoicePaid ? <span className="text-emerald-700 inline-flex items-center gap-1"><Icon.Check size={12}/> Paid</span> : <span className="text-slate-400">Awaiting EFT</span>}
          </div>
        </div>
      </div>
    </>
  );
}

function DealPlaybookTab({ deal, playbooks, placeholderLead }) {
  const playbook = (playbooks || []).find(p => p.stageId === deal.stage);
  if (!playbook) {
    return (
      <div className="bg-slate-50 border border-slate-200 rounded-lg p-5 text-center">
        <Icon.Book size={20} className="mx-auto text-slate-400 mb-2"/>
        <div className="text-sm font-medium text-slate-700">No playbook linked</div>
        <div className="text-[12px] text-slate-500 mt-1">Open the Playbooks view to create one for this stage.</div>
      </div>
    );
  }
  return (
    <>
      <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-3.5">
        <div className="text-[11px] font-medium text-indigo-700 uppercase tracking-wider mb-1">Playbook for this stage</div>
        <div className="text-sm font-semibold text-indigo-900">{playbook.title}</div>
        <p className="text-[13px] text-indigo-900/90 mt-1.5 whitespace-pre-wrap">{playbook.instructions}</p>
      </div>
      <div>
        <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-2">Next actions</div>
        <ul className="space-y-1.5">
          {playbook.actions.map((a, i) => (
            <li key={i} className="flex items-start gap-2 text-[13px] text-slate-700">
              <span className="mt-1 w-1.5 h-1.5 rounded-full bg-slate-400 shrink-0"/>
              <span>{renderPlaybookText(a, placeholderLead)}</span>
            </li>
          ))}
        </ul>
      </div>
      <div>
        <div className="text-[11px] text-slate-500 font-medium uppercase tracking-wider mb-2">WhatsApp template</div>
        <div className="bg-emerald-50/40 border border-emerald-200 rounded-lg p-3.5 text-[13px] text-slate-800 whitespace-pre-wrap leading-relaxed">{renderPlaybookText(playbook.template, placeholderLead)}</div>
      </div>
    </>
  );
}
