// Patient detail side panel + Add patient modal

function PatientPanel({ patient, data, onClose, onCall, onUpdate, onDelete }) {
  const [tab, setTab] = React.useState("overview");
  const [openInteraction, setOpenInteraction] = React.useState(null);
  const [editing, setEditing] = React.useState(false);
  const [form, setForm] = React.useState({});
  const [saving, setSaving] = React.useState(false);

  if (!patient) return null;

  const startEdit = () => {
    setForm({
      name: patient.name, phone: patient.phone, alternatePhone: patient.alternatePhone || "",
      alternateContact: patient.alternateContact || "", equipmentType: patient.equipmentType,
      equipmentDetails: patient.equipmentDetails || "", priority: patient.priority,
      region: patient.region, contactPreference: patient.contactPreference,
      contactFrequencyDays: patient.contactFrequencyDays, notes: patient.notes || "", status: patient.status,
    });
    setEditing(true);
    setTab("overview");
  };

  const saveEdit = async () => {
    setSaving(true);
    try {
      const r = await fetch(`${CLARA_API}/api/patients/${patient.id}`, {
        method: "PATCH", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, contactFrequencyDays: Number(form.contactFrequencyDays) }),
      });
      if (r.ok && onUpdate) onUpdate();
      setEditing(false);
    } catch {}
    setSaving(false);
  };

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const interactions = (data.interactions || [])
    .filter((i) => i.patientId === patient.id)
    .sort((a, b) => new Date(b.date) - new Date(a.date));
  const escalations = (data.escalations || [])
    .filter((e) => e.patientId === patient.id)
    .sort((a, b) => new Date(b.date) - new Date(a.date));

  const overdue = isOverdue(patient);
  const dsc = daysSinceContact(patient);
  const dw = daysWaiting(patient);
  const m = channelMeta(patient.contactPreference);
  const PrefIcon = I[m.icon];

  return (
    <div className="fixed inset-0 z-40 flex">
      <div className="flex-1 bg-black/40 backdrop-blur-sm fade-in" onClick={onClose}></div>
      <aside className="w-full max-w-[560px] bg-ink-900 border-l border-white/10 shadow-2xl slide-in flex flex-col">
        {/* Header */}
        <div className="px-6 py-5 border-b border-white/5 flex items-start justify-between gap-4">
          <div className="min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h2 className="text-lg font-semibold text-ink-100 truncate">{patient.name}</h2>
              <PriorityBadge priority={patient.priority} />
              {overdue && <Badge tone="rose" icon={<I.AlertTriangle size={11} />}>Vencido</Badge>}
            </div>
            <div className="text-[12px] font-mono text-ink-500 mt-1 flex items-center gap-2">
              <span>{patient.id}</span>
              <span className="text-ink-700">·</span>
              <span>{patient.phone}</span>
              <span className={`inline-flex items-center justify-center w-4 h-4 rounded ${m.bg} ${m.color}`} title={m.label}>
                <PrefIcon size={10} />
              </span>
            </div>
          </div>
          <button onClick={onClose} className="text-ink-500 hover:text-ink-200 p-1.5 rounded-md hover:bg-white/5">
            <I.X size={18} />
          </button>
        </div>

        {/* Action bar */}
        <div className="px-6 py-3 border-b border-white/5 flex items-center gap-2">
          <CallButton patient={patient} onCall={onCall} size="md" />
          {!editing ? (
            <Btn size="md" icon={<I.Edit2 size={14} />} onClick={startEdit}>Editar</Btn>
          ) : (
            <>
              <Btn size="md" tone="primary" icon={<I.Check size={14} />} onClick={saveEdit} disabled={saving}>
                {saving ? "Guardando…" : "Guardar"}
              </Btn>
              <Btn size="md" onClick={() => setEditing(false)}>Cancelar</Btn>
            </>
          )}
          <button
            onClick={() => { if (confirm("¿Eliminar a " + patient.name + "? No se puede deshacer.")) onDelete(); }}
            className="ml-auto inline-flex items-center gap-1.5 text-xs text-ink-500 hover:text-rose-300 px-2.5 py-1.5 rounded-md hover:bg-rose-500/10 transition-colors"
          >
            <I.Trash2 size={13} /> Eliminar
          </button>
        </div>

        {/* Tabs */}
        <div className="px-6 pt-4 border-b border-white/5">
          <nav className="flex gap-1">
            {[
              { id: "overview", label: editing ? "Editando" : "Resumen" },
              { id: "interactions", label: `Llamadas · ${interactions.length}` },
              { id: "escalations", label: `Escalaciones · ${escalations.length}` },
              { id: "notes", label: "Notas" },
            ].map((t) => (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                className={`px-3 py-2 text-xs font-medium border-b-2 -mb-px transition-colors ${
                  tab === t.id ? "border-sky-400 text-ink-100" : "border-transparent text-ink-400 hover:text-ink-200"
                }`}
              >
                {t.label}
              </button>
            ))}
          </nav>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5">
          {/* Overview — read mode */}
          {tab === "overview" && !editing && (
            <div className="flex flex-col gap-5">
              <div className="grid grid-cols-2 gap-3">
                <InfoStat label="Días en espera" value={`${dw} d`} />
                <InfoStat label="Último contacto" value={dsc != null ? `${dsc} d` : "—"} tone={overdue ? "rose" : "default"} />
                <InfoStat label="Frecuencia" value={`${patient.contactFrequencyDays} d`} />
                <InfoStat label="Estado" value={statusLabel(patient.status)} />
              </div>
              <PanelSection title="Equipo solicitado">
                <div className="flex items-start gap-3">
                  <span className="w-9 h-9 rounded-lg bg-sky-500/10 text-sky-300 inline-flex items-center justify-center shrink-0"><I.Box size={16} /></span>
                  <div>
                    <div className="text-sm text-ink-100 font-medium">{patient.equipmentType}</div>
                    <div className="text-xs text-ink-400 mt-1 leading-relaxed">{patient.equipmentDetails}</div>
                  </div>
                </div>
              </PanelSection>
              <PanelSection title="Contacto">
                <dl className="grid grid-cols-2 gap-y-2.5 gap-x-4 text-sm">
                  <KV k="Teléfono" v={<span className="font-mono text-ink-200">{patient.phone}</span>} />
                  <KV k="Alternativo" v={patient.alternatePhone ? <span className="font-mono text-ink-200">{patient.alternatePhone}</span> : <span className="text-ink-500">—</span>} />
                  <KV k="Contacto adicional" v={patient.alternateContact || <span className="text-ink-500">—</span>} />
                  <KV k="Preferencia" v={<span className="inline-flex items-center gap-1.5 text-ink-200"><PrefIcon size={12} className={m.color} /> {m.label}</span>} />
                  <KV k="Zona" v={<span className="inline-flex items-center gap-1 text-ink-200"><I.MapPin size={12} /> {patient.region}</span>} />
                  <KV k="Solicitud" v={<span className="text-ink-200">{fmtDate(patient.requestDate, { year: true })}</span>} />
                </dl>
              </PanelSection>
              <PanelSection title="Notas">
                <p className="text-sm text-ink-300 leading-relaxed">{patient.notes || <span className="text-ink-500">Sin notas</span>}</p>
              </PanelSection>
            </div>
          )}

          {/* Overview — edit mode */}
          {tab === "overview" && editing && (
            <div className="grid grid-cols-2 gap-3">
              <div className="col-span-2"><Field label="Nombre completo">
                <Input value={form.name} onChange={set("name")} />
              </Field></div>
              <Field label="Teléfono"><Input value={form.phone} onChange={set("phone")} /></Field>
              <Field label="Tel. alternativo"><Input value={form.alternatePhone} onChange={set("alternatePhone")} placeholder="—" /></Field>
              <div className="col-span-2"><Field label="Contacto adicional">
                <Input value={form.alternateContact} onChange={set("alternateContact")} placeholder="Familiar o cuidador" />
              </Field></div>
              <Field label="Equipo">
                <Select value={form.equipmentType} onChange={set("equipmentType")}>
                  {(data.equipmentTypes || []).map((t) => <option key={t.id} value={t.name}>{t.name}</option>)}
                </Select>
              </Field>
              <Field label="Prioridad">
                <Select value={form.priority} onChange={set("priority")}>
                  <option value="alta">Alta</option><option value="media">Media</option><option value="baja">Baja</option>
                </Select>
              </Field>
              <Field label="Zona">
                <Select value={form.region} onChange={set("region")}>
                  {["Madrid Centro","Madrid Norte","Madrid Sur","Madrid Este","Madrid Oeste"].map(r => <option key={r} value={r}>{r}</option>)}
                </Select>
              </Field>
              <Field label="Preferencia">
                <Select value={form.contactPreference} onChange={set("contactPreference")}>
                  <option value="voice">Voz</option><option value="whatsapp">WhatsApp</option>
                  <option value="sms">SMS</option><option value="email">Email</option>
                </Select>
              </Field>
              <Field label="Estado">
                <Select value={form.status} onChange={set("status")}>
                  <option value="waiting">En espera</option><option value="delivered">Entregado</option><option value="cancelled">Cancelado</option>
                </Select>
              </Field>
              <Field label="Frecuencia (días)">
                <Input type="number" min="1" max="120" value={form.contactFrequencyDays} onChange={set("contactFrequencyDays")} />
              </Field>
              <div className="col-span-2"><Field label="Detalles del equipo">
                <Textarea value={form.equipmentDetails} onChange={set("equipmentDetails")} />
              </Field></div>
              <div className="col-span-2"><Field label="Notas">
                <Textarea value={form.notes} onChange={set("notes")} />
              </Field></div>
            </div>
          )}

          {tab === "interactions" && (
            <div className="flex flex-col gap-2">
              {interactions.map((i) => {
                const cm = channelMeta(i.channel);
                const Icn = I[cm.icon];
                const open = openInteraction === i.id;
                const { header, turns } = parseTranscript(i.summary);
                return (
                  <div key={i.id} className="rounded-lg border border-white/5 bg-white/2 overflow-hidden">
                    <button onClick={() => setOpenInteraction(open ? null : i.id)} className="w-full text-left p-3 flex items-start gap-3 hover:bg-white/3">
                      <span className={`w-7 h-7 rounded-md ${cm.bg} ${cm.color} inline-flex items-center justify-center shrink-0`}><Icn size={13} /></span>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-xs text-ink-200 font-medium">{cm.label}</span>
                          <span className="text-ink-600">·</span>
                          <span className="text-xs text-ink-400">{i.direction === "outbound" ? "Saliente" : "Entrante"}</span>
                          <span className="text-ink-600">·</span>
                          <span className="text-xs text-ink-400">{outcomeLabel(i.outcome)}</span>
                        </div>
                        <div className="text-[11px] font-mono text-ink-500 mt-0.5">{fmtDateTime(i.date)}</div>
                        {!open && header && <div className="text-xs text-ink-400 mt-1.5 line-clamp-2">{header}</div>}
                      </div>
                      {turns.length > 0 && <I.ChevronDown size={14} className={`text-ink-500 transition-transform ${open ? "rotate-180" : ""}`} />}
                    </button>
                    {open && turns.length > 0 && (
                      <div className="border-t border-white/5 p-3 bg-ink-950/50 fade-in flex flex-col gap-2">
                        {turns.map((t, idx) => {
                          if (t.speaker === "tool_call") {
                            return (
                              <div key={idx} className="flex justify-center">
                                <div className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[11px] font-mono"
                                  style={{ background: "rgba(139, 92, 246, 0.08)", border: "1px solid rgba(139, 92, 246, 0.2)" }}>
                                  <I.Wrench size={10} className="text-violet-400 shrink-0" />
                                  <span className="text-violet-300 break-all">{t.text}</span>
                                </div>
                              </div>
                            );
                          }
                          if (t.speaker === "tool_result") {
                            return (
                              <div key={idx} className="flex justify-center">
                                <div className="inline-flex items-start gap-1.5 px-2.5 py-1.5 rounded-md text-[11px] font-mono"
                                  style={{ background: "rgba(52, 211, 153, 0.06)", border: "1px solid rgba(52, 211, 153, 0.2)" }}>
                                  <I.Check size={10} className="text-emerald-400 shrink-0 mt-px" />
                                  <span className="text-emerald-300/80 break-all">{t.text}</span>
                                </div>
                              </div>
                            );
                          }
                          return (
                          <div key={idx} className={`flex ${t.speaker === "bot" ? "justify-start" : "justify-end"}`}>
                            <div className={`bubble text-xs ${t.speaker === "bot" ? "bg-sky-500/10 text-ink-100 ring-1 ring-sky-500/20" : "bg-white/5 text-ink-100 ring-1 ring-white/10"}`}>{t.text}</div>
                          </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              })}
              {interactions.length === 0 && <Empty>Sin llamadas registradas</Empty>}
            </div>
          )}

          {tab === "escalations" && (
            <div className="flex flex-col gap-2">
              {escalations.map((e) => (
                <div key={e.id} className="rounded-lg border border-white/5 bg-white/2 p-4">
                  <div className="flex items-center justify-between gap-3 mb-2">
                    <UrgencyBadge urgency={e.urgency} />
                    <span className="text-[11px] font-mono text-ink-500">{fmtDateTime(e.date)}</span>
                  </div>
                  <p className="text-sm text-ink-300 leading-relaxed">{e.reason}</p>
                  <div className="flex items-center justify-between mt-3 pt-3 border-t border-white/5">
                    <span className="text-xs text-ink-400">Asignado a {e.assignedTo}</span>
                    {e.status === "resolved"
                      ? <Badge tone="emerald" icon={<I.Check size={11} />}>Resuelta</Badge>
                      : <Badge tone="amber">Pendiente</Badge>}
                  </div>
                </div>
              ))}
              {escalations.length === 0 && <Empty>Sin escalaciones</Empty>}
            </div>
          )}

          {tab === "notes" && (
            <div className="flex flex-col gap-3">
              <div className="rounded-lg border border-white/5 bg-white/2 p-4">
                <div className="text-[11px] uppercase tracking-wider text-ink-500 mb-2">Notas del expediente</div>
                <p className="text-sm text-ink-200 leading-relaxed whitespace-pre-line">{patient.notes || "Sin notas"}</p>
              </div>
              <Textarea placeholder="Añadir una nota interna…" />
              <Btn size="sm" tone="primary" className="self-end">Guardar nota</Btn>
            </div>
          )}
        </div>
      </aside>
    </div>
  );
}

const InfoStat = ({ label, value, tone = "default" }) => {
  const c = { default: "text-ink-100", rose: "text-rose-300", amber: "text-amber-300", emerald: "text-emerald-300" }[tone];
  return (
    <div className="rounded-lg border border-white/5 bg-white/2 px-3 py-2.5">
      <div className="text-[10px] uppercase tracking-wider text-ink-500">{label}</div>
      <div className={`text-lg font-semibold ${c} mt-0.5 tabular-nums`}>{value}</div>
    </div>
  );
};

const PanelSection = ({ title, children }) => (
  <section className="flex flex-col gap-3">
    <h3 className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold">{title}</h3>
    {children}
  </section>
);

const KV = ({ k, v }) => (
  <React.Fragment>
    <dt className="text-xs text-ink-500">{k}</dt>
    <dd className="text-xs text-right">{v}</dd>
  </React.Fragment>
);

// =========================
// ADD PATIENT MODAL
// =========================
function AddPatientModal({ data, onClose, onCreate }) {
  const [form, setForm] = React.useState({
    name: "",
    phone: "+34",
    alternatePhone: "",
    alternateContact: "",
    equipmentType: (data.equipmentTypes && data.equipmentTypes[0] && data.equipmentTypes[0].name) || "",
    equipmentDetails: "",
    priority: "media",
    region: "Madrid Centro",
    contactPreference: "voice",
    contactFrequencyDays: 14,
    notes: "",
  });
  const [showJson, setShowJson] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(null);

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const valid = form.name.trim().length > 1 && /^\+?\d[\d\s]{6,}$/.test(form.phone.replace(/\s/g, ""));

  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    const nextId = "P" + String((data.patients || []).length + 1).padStart(3, "0");
    const payload = {
      id: nextId,
      ...form,
      contactFrequencyDays: Number(form.contactFrequencyDays),
      requestDate: new Date().toISOString().slice(0, 10),
      lastContactDate: null,
      status: "waiting",
      alternatePhone: form.alternatePhone || null,
      alternateContact: form.alternateContact || null,
    };
    setSubmitted(payload);
    setShowJson(true);
    onCreate(payload);
  };

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm fade-in" onClick={onClose}></div>
      <div className="relative w-full max-w-2xl bg-ink-900 border border-white/10 rounded-2xl shadow-2xl fade-in flex flex-col max-h-[90vh]">
        <div className="px-6 py-4 border-b border-white/5 flex items-center justify-between">
          <div>
            <h2 className="text-base font-semibold text-ink-100">Nuevo paciente</h2>
            <p className="text-xs text-ink-400 mt-0.5">Alta de expediente en cartera</p>
          </div>
          <button onClick={onClose} className="text-ink-500 hover:text-ink-200 p-1.5 rounded-md hover:bg-white/5">
            <I.X size={18} />
          </button>
        </div>

        <form onSubmit={submit} className="flex-1 overflow-y-auto px-6 py-5 grid grid-cols-2 gap-4">
          <div className="col-span-2"><Field label="Nombre completo" required>
            <Input value={form.name} onChange={set("name")} placeholder="Ej. Pedro Álvarez Castro" />
          </Field></div>

          <Field label="Teléfono" required hint="Incluye el prefijo del país (+34)">
            <Input value={form.phone} onChange={set("phone")} placeholder="+34607827824" />
          </Field>
          <Field label="Teléfono alternativo">
            <Input value={form.alternatePhone} onChange={set("alternatePhone")} placeholder="—" />
          </Field>

          <div className="col-span-2"><Field label="Contacto adicional" hint="Familiar o cuidador (nombre + relación)">
            <Input value={form.alternateContact} onChange={set("alternateContact")} placeholder="Hija — Carmen Ruiz" />
          </Field></div>

          <Field label="Equipo solicitado" required>
            <Select value={form.equipmentType} onChange={set("equipmentType")}>
              {(data.equipmentTypes || []).map((t) => (
                <option key={t.id} value={t.name}>{t.name}</option>
              ))}
            </Select>
          </Field>
          <Field label="Prioridad" required>
            <Select value={form.priority} onChange={set("priority")}>
              <option value="alta">Alta</option>
              <option value="media">Media</option>
              <option value="baja">Baja</option>
            </Select>
          </Field>

          <div className="col-span-2"><Field label="Detalles clínicos del equipo">
            <Textarea value={form.equipmentDetails} onChange={set("equipmentDetails")} placeholder="Diagnóstico, configuración, particularidades…" />
          </Field></div>

          <Field label="Zona" required>
            <Select value={form.region} onChange={set("region")}>
              {["Madrid Centro", "Madrid Norte", "Madrid Sur", "Madrid Este", "Madrid Oeste"].map((r) => <option key={r} value={r}>{r}</option>)}
            </Select>
          </Field>
          <Field label="Preferencia de contacto" required>
            <Select value={form.contactPreference} onChange={set("contactPreference")}>
              <option value="voice">Voz</option>
              <option value="whatsapp">WhatsApp</option>
              <option value="sms">SMS</option>
              <option value="email">Email</option>
            </Select>
          </Field>

          <div className="col-span-2"><Field label="Frecuencia de contacto" hint="Días entre seguimientos automáticos">
            <Input type="number" min="1" max="120" value={form.contactFrequencyDays} onChange={set("contactFrequencyDays")} />
          </Field></div>

          <div className="col-span-2"><Field label="Notas internas">
            <Textarea value={form.notes} onChange={set("notes")} placeholder="Edad, observaciones, horarios preferidos…" />
          </Field></div>

          {showJson && submitted && (
            <div className="col-span-2 rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-4">
              <div className="flex items-center gap-2 text-emerald-300 text-sm font-medium">
                <I.Check size={14} /> Paciente creado: {submitted.id} — {submitted.name}
              </div>
              <details className="mt-2">
                <summary className="text-xs text-emerald-200/70 cursor-pointer hover:text-emerald-200">Ver payload JSON</summary>
                <pre className="text-[11px] font-mono text-ink-300 mt-2 overflow-x-auto whitespace-pre">{JSON.stringify(submitted, null, 2)}</pre>
              </details>
            </div>
          )}
        </form>

        <div className="px-6 py-4 border-t border-white/5 flex items-center justify-end gap-2">
          <Btn onClick={onClose}>Cancelar</Btn>
          <Btn tone="primary" onClick={submit} disabled={!valid}>
            <I.Plus size={14} /> Crear paciente
          </Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PatientPanel, AddPatientModal });
