/* DOCTOR / PROFESSIONAL VIEW — consultation + notes + meds + follow-up
   Hydrated: recibe { user, onNavigate, onLogout } desde MainApp.
   Carga agenda real desde /api/doctor/agenda.
   Notas SOAP, receta y followup guardados en DB. */

const FOLLOWUP_OPTS = [
  {id:'1 semana',  label:'1 semana'},
  {id:'2 semanas', label:'2 semanas'},
  {id:'1 mes',     label:'1 mes'},
  {id:'3 meses',   label:'3 meses'},
  {id:'6 meses',   label:'6 meses'},
];

const VitalCell = ({ label, value, unit }) => (
  <div className="rounded-xl bg-paper ring-1 ring-line p-3">
    <div className="text-[10.5px] uppercase tracking-wider text-slate-400 font-medium">{label}</div>
    <div className="mt-1 flex items-baseline gap-1">
      <div className="text-[18px] font-semibold tnum tracking-tight text-midnight-900">{value}</div>
      <div className="text-[10.5px] text-slate-400">{unit}</div>
    </div>
  </div>
);

const SectionLabel = ({ children, optional }) => (
  <div className="flex items-center gap-2 mb-2">
    <div className="text-[11px] uppercase tracking-[0.12em] text-midnight-700 font-semibold">{children}</div>
    {optional && <span className="text-[10.5px] text-slate-400">opcional</span>}
  </div>
);

const AgendaRow = ({ a, active, onClick }) => {
  const startDate = new Date(a.start_at);
  const timeStr = startDate.toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit', hour12:false });
  const patientName = a.employee?.full_name || a.beneficiary?.name || 'Paciente';
  const specName = a.specialty?.name || '';
  const mode = a.mode === 'telemedicina' ? 'Telemed' : 'Presencial';
  const isDone = a.status === 'completed';
  const isCurrent = active;

  return (
    <div className={`relative pl-7 pr-3 py-3 cursor-pointer hover:bg-paper/60 ${isCurrent ? 'bg-paper' : ''}`} onClick={onClick}>
      <div className="absolute left-3 top-3.5">
        {isDone && <span className="h-2 w-2 rounded-full bg-slate-300 block"/>}
        {isCurrent && <span className="h-2.5 w-2.5 rounded-full bg-mint-500 block ring-4 ring-mint-100"/>}
        {!isDone && !isCurrent && <span className="h-2 w-2 rounded-full bg-slate-200 block ring-2 ring-white"/>}
      </div>
      <div className="flex items-center gap-2">
        <div className={`text-[11.5px] font-mono tnum ${isCurrent ? 'text-mint-700 font-semibold' : 'text-slate-500'}`}>{timeStr}</div>
        {isCurrent && <span className="text-[9.5px] uppercase tracking-wider font-semibold text-mint-700 bg-mint-100 px-1.5 py-0.5 rounded">En curso</span>}
        {isDone && <span className="text-[9.5px] uppercase tracking-wider font-semibold text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded">Atendido</span>}
      </div>
      <div className={`text-[12.5px] font-medium mt-1 ${isDone ? 'text-slate-400 line-through decoration-slate-200' : 'text-midnight-900'}`}>{patientName}</div>
      <div className="text-[11px] text-slate-400 mt-0.5">{specName} | {mode}</div>
    </div>
  );
};

function DoctorView({ user, onNavigate, onLogout }) {
  const u = user || { full_name:'Dra. Helena Restrepo', initials:'HR', sub_specialty:'Cardiologia clinica', room:'Consultorio 2, Piso 4' };
  const initials = u.initials || u.full_name.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();

  /* State */
  const [activeTab, setActiveTab]         = React.useState('dashboard'); /* 'dashboard' | 'agenda' | 'patients' */
  const [dashData, setDashData]           = React.useState(null);
  const [loadingDash, setLoadingDash]     = React.useState(true);
  const [agendaDate, setAgendaDate]       = React.useState(new Date().toISOString().slice(0,10));
  const [agenda, setAgenda]               = React.useState([]);
  const [selectedAppt, setSelectedAppt]   = React.useState(null);
  const [patientData, setPatientData]     = React.useState(null);
  const [loadingAgenda, setLoadingAgenda] = React.useState(true);
  const [loadingPatient, setLoadingPatient] = React.useState(false);

  /* Patients tab */
  const [patients, setPatients]           = React.useState([]);
  const [loadingPatients, setLoadingPatients] = React.useState(false);
  const [selectedPatientHistory, setSelectedPatientHistory] = React.useState(null);
  const [expandedRecord, setExpandedRecord] = React.useState(null); /* { apptId, data, loading } */

  function loadRecord(apptId) {
    if (expandedRecord?.apptId === apptId && !expandedRecord.loading) {
      setExpandedRecord(null); return; /* toggle off */
    }
    setExpandedRecord({ apptId, data: null, loading: true });
    window.apiFetch(`/api/doctor/record/${apptId}`)
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data) setExpandedRecord({ apptId, data, loading: false });
        else setExpandedRecord(null);
      })
      .catch(() => setExpandedRecord(null));
  }

  /* SOAP notes */
  const [soapReason, setSoapReason]       = React.useState('');
  const [soapExploration, setSoapExploration] = React.useState('');
  const [soapDiagnosis, setSoapDiagnosis] = React.useState('');
  const [soapPlan, setSoapPlan]           = React.useState('');

  /* Meds */
  const [meds, setMeds]                   = React.useState([]);
  const [newMed, setNewMed]               = React.useState({ drug:'', dose:'', frequency:'', duration:'', route:'Oral', instructions:'' });

  /* Followup */
  const [followupPeriod, setFollowupPeriod] = React.useState('1 mes');
  const [followupNote, setFollowupNote]   = React.useState('');
  const [needsFollowup, setNeedsFollowup] = React.useState(true);

  /* Save state */
  const [saving, setSaving]               = React.useState(false);
  const [saveMsg, setSaveMsg]             = React.useState('');

  /* Summary overlay after closing consultation */
  const [showSummary, setShowSummary]     = React.useState(false);
  const [summaryData, setSummaryData]     = React.useState(null);

  /* Cargar dashboard + agenda al montar */
  function loadDashboard() {
    setLoadingDash(true);
    window.apiFetch('/api/doctor/dashboard')
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d) setDashData(d); })
      .catch(() => {})
      .finally(() => setLoadingDash(false));
  }

  function loadAgenda(date) {
    setLoadingAgenda(true);
    setSelectedAppt(null);
    setPatientData(null);
    window.apiFetch(`/api/doctor/agenda?date=${date}`)
      .then(r => r.ok ? r.json() : { agenda:[] })
      .then(data => {
        setAgenda(data.agenda || []);
        const today = new Date().toISOString().slice(0,10);
        if (date === today) {
          const first = (data.agenda || []).find(a => a.status !== 'completed');
          if (first) selectAppointment(first.id);
        }
      })
      .catch(() => {})
      .finally(() => setLoadingAgenda(false));
  }

  function shiftAgendaDate(days) {
    const d = new Date(agendaDate + 'T12:00:00');
    d.setDate(d.getDate() + days);
    const newDate = d.toISOString().slice(0,10);
    setAgendaDate(newDate);
    loadAgenda(newDate);
  }

  function goToToday() {
    const today = new Date().toISOString().slice(0,10);
    setAgendaDate(today);
    loadAgenda(today);
  }

  React.useEffect(() => {
    loadDashboard();
    loadAgenda(agendaDate);
  }, []);

  const [patientError, setPatientError] = React.useState(null);

  /* Cargar datos del paciente para una cita */
  function selectAppointment(apptId) {
    setSelectedAppt(apptId);
    setLoadingPatient(true);
    setPatientData(null);
    setPatientError(null);
    setSaveMsg('');

    window.apiFetch(`/api/doctor/patient/${apptId}`)
      .then(async r => {
        if (!r.ok) {
          const err = await r.json().catch(() => ({}));
          throw new Error(err.error || `Error ${r.status}`);
        }
        return r.json();
      })
      .then(data => {
        setPatientData(data);
        /* Rellenar formularios con datos existentes */
        if (data.notes) {
          setSoapReason(data.notes.reason || '');
          setSoapExploration(data.notes.exploration || '');
          setSoapDiagnosis(data.notes.diagnosis || '');
          setSoapPlan(data.notes.plan || '');
        } else {
          setSoapReason(''); setSoapExploration(''); setSoapDiagnosis(''); setSoapPlan('');
        }
        setMeds(data.prescriptions || []);
        if (data.followup) {
          setFollowupPeriod(data.followup.period || '1 mes');
          setFollowupNote(data.followup.note || '');
          setNeedsFollowup(true);
        } else {
          setFollowupPeriod('1 mes');
          setFollowupNote('');
        }
      })
      .catch(err => {
        console.error('[DoctorView] Error cargando paciente:', err);
        setPatientError(err.message);
      })
      .finally(() => setLoadingPatient(false));
  }

  /* Guardar notas SOAP */
  async function handleSaveNotes() {
    if (!selectedAppt) return;
    setSaving(true);
    try {
      const res = await window.apiFetch('/api/doctor/notes', {
        method: 'POST',
        body: JSON.stringify({
          appointment_id: selectedAppt,
          reason: soapReason, exploration: soapExploration,
          diagnosis: soapDiagnosis, plan: soapPlan,
        }),
      });
      if (res.ok) setSaveMsg('Notas guardadas');
    } catch {}
    finally { setSaving(false); setTimeout(() => setSaveMsg(''), 3000); }
  }

  /* Agregar medicamento */
  function addMed() {
    if (!newMed.drug || !newMed.dose) return;
    setMeds(prev => [...prev, { ...newMed, id: Date.now() }]);
    setNewMed({ drug:'', dose:'', frequency:'', duration:'', route:'Oral', instructions:'' });
  }

  function removeMed(idx) { setMeds(prev => prev.filter((_, i) => i !== idx)); }

  /* Guardar prescripciones */
  async function handleSavePrescriptions() {
    if (!selectedAppt || meds.length === 0) return;
    setSaving(true);
    try {
      await window.apiFetch('/api/doctor/prescriptions', {
        method: 'POST',
        body: JSON.stringify({
          appointment_id: selectedAppt,
          medications: meds.map(m => ({
            drug: m.drug, dose: m.dose, frequency: m.frequency || 'Segun indicacion',
            duration: m.duration || 'Segun indicacion', route: m.route, instructions: m.instructions,
          })),
        }),
      });
      setSaveMsg('Receta guardada');
    } catch {}
    finally { setSaving(false); setTimeout(() => setSaveMsg(''), 3000); }
  }

  /* Firmar y cerrar consulta */
  async function handleComplete() {
    if (!selectedAppt) return;
    if (!confirm('Vas a firmar y cerrar esta consulta. Continuar?')) return;

    setSaving(true);
    try {
      /* Guardar todo primero */
      await handleSaveNotes();
      if (meds.length > 0) await handleSavePrescriptions();
      if (needsFollowup) {
        await window.apiFetch('/api/doctor/followups', {
          method: 'POST',
          body: JSON.stringify({
            appointment_id: selectedAppt,
            period: followupPeriod, note: followupNote,
          }),
        });
      }
      /* Completar */
      const res = await window.apiFetch(`/api/doctor/complete/${selectedAppt}`, { method: 'PATCH' });
      if (res.ok) {
        /* Guardar datos del resumen antes de limpiar estado */
        const closedAppt = agenda.find(a => a.id === selectedAppt);
        const closedTime = closedAppt ? new Date(closedAppt.start_at).toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit', hour12:false }) : '';
        setSummaryData({
          patientName,
          patientInitials,
          reason: currentAppt?.reason || patientData?.appointment?.reason || 'Consulta',
          time: closedTime,
          soap: { reason: soapReason, exploration: soapExploration, diagnosis: soapDiagnosis, plan: soapPlan },
          medications: [...meds],
          followup: needsFollowup ? { period: followupPeriod, note: followupNote } : null,
        });
        setShowSummary(true);
      }
    } catch {}
    finally { setSaving(false); }
  }

  /* Cerrar resumen y avanzar a siguiente cita */
  async function handleDismissSummary() {
    setShowSummary(false);
    setSummaryData(null);
    setSaveMsg('Consulta cerrada y firmada');
    /* Refrescar agenda */
    try {
      const r2 = await window.apiFetch('/api/doctor/agenda');
      if (r2.ok) {
        const d = await r2.json();
        setAgenda(d.agenda || []);
        const next = (d.agenda || []).find(a => a.status !== 'completed');
        if (next) selectAppointment(next.id);
        else { setSelectedAppt(null); setPatientData(null); }
      }
    } catch {}
    setTimeout(() => setSaveMsg(''), 4000);
  }

  const currentAppt = agenda.find(a => a.id === selectedAppt);
  const patient = patientData?.appointment?.employee || patientData?.appointment?.beneficiary;
  const patientName = patient?.full_name || patient?.name || 'Paciente';
  const patientInitials = patientName.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
  const doneCount = agenda.filter(a => a.status === 'completed').length;
  const pendingCount = agenda.filter(a => a.status !== 'completed').length;

  return (
    <div className="flex bg-paper min-h-screen font-sans text-ink">

      {/* SIDEBAR */}
      <aside className="w-[232px] shrink-0 bg-midnight-950 text-white px-4 py-6 flex flex-col sticky top-0 h-screen overflow-y-auto">
        <div className="px-2 mb-8"><Logo tone="light"/></div>

        <div className="px-2 mb-2 text-[10.5px] uppercase tracking-[0.16em] text-white/30 font-medium">Profesional</div>
        <div className="rounded-xl bg-white/5 ring-1 ring-white/5 p-3 mb-5">
          <div className="flex items-start gap-3">
            <div className="h-10 w-10 rounded-full bg-gradient-to-br from-mint-300 to-mint-500 grid place-items-center text-white text-[12px] font-semibold">{initials}</div>
            <div className="min-w-0">
              <div className="text-[12.5px] font-semibold leading-tight">{u.full_name}</div>
              <div className="text-[11px] text-white/50 mt-0.5">{u.sub_specialty || u.specialty?.name || ''}</div>
            </div>
          </div>
          <div className="mt-3 pt-3 border-t border-white/10 text-[11px] text-white/60">{u.room || ''}</div>
        </div>

        <nav className="space-y-1">
          <NavItem icon={<svg viewBox="0 0 24 24" className="h-4 w-4" fill="none"><rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.5"/></svg>}
            label="Dashboard" active={activeTab === 'dashboard'}
            onClick={() => { setActiveTab('dashboard'); loadDashboard(); }}/>
          <NavItem icon={<I.cal/>}   label="Mi agenda" active={activeTab === 'agenda'} badge={String(agenda.length)}
            onClick={() => setActiveTab('agenda')}/>
          <NavItem icon={<I.users/>} label="Pacientes" active={activeTab === 'patients'}
            onClick={() => {
              setActiveTab('patients');
              if (patients.length === 0) {
                setLoadingPatients(true);
                window.apiFetch('/api/doctor/patients')
                  .then(r => r.ok ? r.json() : { patients:[] })
                  .then(d => setPatients(d.patients || []))
                  .catch(() => {})
                  .finally(() => setLoadingPatients(false));
              }
            }}/>
        </nav>

        <div className="px-2 mt-7 mb-2 text-[10.5px] uppercase tracking-[0.16em] text-white/30 font-medium">Hoy</div>
        <div className="grid grid-cols-2 gap-2 px-1">
          <div className="rounded-lg bg-white/5 p-3">
            <div className="text-[10.5px] text-white/40 uppercase tracking-wider">Atendidos</div>
            <div className="text-[18px] font-semibold tnum mt-1">{doneCount}</div>
          </div>
          <div className="rounded-lg bg-white/5 p-3">
            <div className="text-[10.5px] text-white/40 uppercase tracking-wider">Pendientes</div>
            <div className="text-[18px] font-semibold tnum mt-1 text-mint-300">{pendingCount}</div>
          </div>
        </div>

        <div className="mt-auto pt-4 border-t border-white/10">
          <button onClick={onLogout} className="w-full h-9 rounded-lg text-white/60 text-[12.5px] hover:bg-white/5 hover:text-white/80">
            Cerrar sesion
          </button>
        </div>
      </aside>

      {/* MAIN */}
      <main className="flex-1 min-w-0 flex flex-col">
        {/* topbar */}
        <div className="h-16 border-b border-line bg-white/70 backdrop-blur px-7 flex items-center gap-4">
          <div>
            <div className="text-[11px] text-slate-500">{new Date().toLocaleDateString('es-CO', { weekday:'long', day:'numeric', month:'long', year:'numeric' })}</div>
            <div className="text-[14px] font-semibold text-midnight-900 leading-tight">
              {activeTab === 'dashboard' ? 'Dashboard' : activeTab === 'agenda' ? `Mi agenda${selectedAppt ? ' | consulta en curso' : ''}` : 'Mis pacientes'}
            </div>
          </div>
          <div className="ml-auto flex items-center gap-2">
            {saveMsg && <span className="text-[12px] text-mint-700 font-medium inline-flex items-center gap-1"><I.check className="h-3.5 w-3.5"/>{saveMsg}</span>}
          </div>
        </div>

        <div className="flex-1 flex min-h-0">

          {/* ═══════ DASHBOARD TAB ═══════ */}
          {activeTab === 'dashboard' && (
            <div className="flex-1 overflow-y-auto">
              <div className="max-w-[1040px] px-8 py-7">
                {loadingDash && <div className="py-16 text-[13px] text-slate-400 text-center">Cargando dashboard...</div>}
                {!loadingDash && dashData && (() => {
                  const t = dashData.today;
                  const m = dashData.month;
                  const w = dashData.week;
                  const dist = dashData.dayDistribution;
                  const maxBar = Math.max(...(dist?.values || [1]), 1);

                  /* Saludo segun hora */
                  const hour = new Date().getHours();
                  const greeting = hour < 12 ? 'Buenos dias' : hour < 18 ? 'Buenas tardes' : 'Buenas noches';

                  return (
                    <div className="space-y-6">

                      {/* Saludo */}
                      <div>
                        <div className="text-[22px] font-semibold tracking-tight text-midnight-900">{greeting}, {u.full_name.split(' ').slice(0,2).join(' ')}</div>
                        <div className="text-[13px] text-slate-500 mt-1">
                          {t.pending > 0
                            ? `Tienes ${t.pending} cita${t.pending > 1 ? 's' : ''} pendiente${t.pending > 1 ? 's' : ''} hoy`
                            : t.completed > 0 ? 'Todas las citas de hoy completadas' : 'Sin citas programadas para hoy'}
                        </div>
                      </div>

                      {/* KPI Cards - Row 1 */}
                      <div className="grid grid-cols-4 gap-4">
                        {/* Progreso del dia */}
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card col-span-1">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium">Progreso hoy</div>
                          <div className="mt-3 flex items-center gap-4">
                            <div className="relative h-16 w-16">
                              <svg viewBox="0 0 36 36" className="h-16 w-16 -rotate-90">
                                <path d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                                  fill="none" stroke="#e2e8f0" strokeWidth="3"/>
                                <path d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                                  fill="none" stroke="#34d399" strokeWidth="3"
                                  strokeDasharray={`${t.progressPercent}, 100`}
                                  strokeLinecap="round"/>
                              </svg>
                              <div className="absolute inset-0 flex items-center justify-center">
                                <span className="text-[14px] font-bold tnum text-midnight-900">{t.progressPercent}%</span>
                              </div>
                            </div>
                            <div>
                              <div className="text-[24px] font-bold tnum text-midnight-900">{t.completed}<span className="text-[14px] text-slate-400 font-normal">/{t.total}</span></div>
                              <div className="text-[11px] text-slate-400">completadas</div>
                            </div>
                          </div>
                        </div>

                        {/* Proxima cita */}
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium">Proxima cita</div>
                          {t.nextPending ? (
                            <div className="mt-3">
                              <div className="text-[28px] font-bold tnum tracking-tight text-midnight-900">{t.nextPending.timeStr}</div>
                              <div className="text-[11px] text-slate-400 mt-1">pendiente</div>
                              <button onClick={() => setActiveTab('agenda')}
                                className="mt-2 text-[11px] text-mint-700 font-medium hover:text-mint-800">Ver agenda</button>
                            </div>
                          ) : (
                            <div className="mt-3">
                              <div className="text-[16px] font-semibold text-mint-600 mt-2">Dia libre</div>
                              <div className="text-[11px] text-slate-400 mt-1">Sin citas pendientes</div>
                            </div>
                          )}
                        </div>

                        {/* Racha */}
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium">Racha activa</div>
                          <div className="mt-3">
                            <div className="text-[28px] font-bold tnum tracking-tight text-midnight-900">{dashData.streak}<span className="text-[14px] text-slate-400 font-normal ml-1">dias</span></div>
                            <div className="text-[11px] text-slate-400 mt-1">consecutivos atendiendo</div>
                          </div>
                          <div className="flex items-center gap-1 mt-2">
                            {[...Array(Math.min(dashData.streak, 7))].map((_, i) => (
                              <div key={i} className="h-2 w-2 rounded-full bg-mint-400"/>
                            ))}
                            {dashData.streak > 7 && <span className="text-[10px] text-slate-400 ml-1">+{dashData.streak - 7}</span>}
                          </div>
                        </div>

                        {/* Promedio diario */}
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium">Promedio diario</div>
                          <div className="mt-3">
                            <div className="text-[28px] font-bold tnum tracking-tight text-midnight-900">{dashData.avgPerDay}</div>
                            <div className="text-[11px] text-slate-400 mt-1">citas/dia (ult. 4 semanas)</div>
                          </div>
                        </div>
                      </div>

                      {/* Row 2: Mes + Distribucion */}
                      <div className="grid grid-cols-3 gap-4">

                        {/* Resumen del mes */}
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card col-span-1">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium mb-4">
                            Este mes ({new Date().toLocaleDateString('es-CO', { month: 'long' })})
                          </div>
                          <div className="space-y-3">
                            <div className="flex items-center justify-between">
                              <span className="text-[12.5px] text-slate-600">Total de citas</span>
                              <span className="text-[14px] font-bold tnum text-midnight-900">{m.total}</span>
                            </div>
                            <div className="h-px bg-line"/>
                            <div className="flex items-center justify-between">
                              <span className="text-[12.5px] text-slate-600">Completadas</span>
                              <span className="text-[14px] font-bold tnum text-mint-600">{m.completed}</span>
                            </div>
                            <div className="h-px bg-line"/>
                            <div className="flex items-center justify-between">
                              <span className="text-[12.5px] text-slate-600">Pacientes unicos</span>
                              <span className="text-[14px] font-bold tnum text-midnight-900">{m.uniquePatients}</span>
                            </div>
                            <div className="h-px bg-line"/>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <div className="h-2.5 w-2.5 rounded-full bg-midnight-400"/>
                                <span className="text-[12.5px] text-slate-600">Presencial</span>
                              </div>
                              <span className="text-[13px] font-semibold tnum text-midnight-900">{m.presencial}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <div className="h-2.5 w-2.5 rounded-full bg-mint-400"/>
                                <span className="text-[12.5px] text-slate-600">Telemedicina</span>
                              </div>
                              <span className="text-[13px] font-semibold tnum text-midnight-900">{m.telemedicina}</span>
                            </div>
                          </div>
                        </div>

                        {/* Distribucion semanal - bar chart */}
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card col-span-2">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium mb-4">
                            Distribucion semanal (ultimas 4 semanas)
                          </div>
                          <div className="flex items-end gap-3 h-[140px] px-2">
                            {(dist?.labels || []).map((label, i) => {
                              const val = dist?.values?.[i] || 0;
                              const pct = maxBar > 0 ? (val / maxBar) * 100 : 0;
                              return (
                                <div key={label} className="flex-1 flex flex-col items-center gap-1.5">
                                  <div className="text-[11px] font-bold tnum text-midnight-900">{val}</div>
                                  <div className="w-full rounded-t-lg transition-all"
                                    style={{ height: `${Math.max(pct, 4)}%`, background: `linear-gradient(180deg, #34d399 0%, #0f766e 100%)` }}/>
                                  <div className="text-[10.5px] text-slate-400 font-medium">{label}</div>
                                </div>
                              );
                            })}
                          </div>
                        </div>
                      </div>

                      {/* Row 3: Citas de hoy */}
                      <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                        <div className="flex items-center justify-between mb-4">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium">Citas de hoy</div>
                          <button onClick={() => setActiveTab('agenda')} className="text-[11px] text-mint-700 font-medium hover:text-mint-800">
                            Ver agenda completa
                          </button>
                        </div>
                        {agenda.length === 0 && <div className="text-[12.5px] text-slate-400 py-4 text-center">Sin citas programadas</div>}
                        {agenda.length > 0 && (
                          <div className="grid grid-cols-1 gap-2">
                            {agenda.map(a => {
                              const time = new Date(a.start_at).toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit', hour12:false });
                              const pName = a.employee?.full_name || a.beneficiary?.name || 'Paciente';
                              const done = a.status === 'completed';
                              return (
                                <div key={a.id} className={`flex items-center gap-4 p-3 rounded-xl ring-1 transition cursor-pointer hover:bg-paper/80
                                  ${done ? 'ring-line bg-paper/40' : 'ring-mint-200 bg-mint-50/30'}`}
                                  onClick={() => { setActiveTab('agenda'); selectAppointment(a.id); }}>
                                  <div className={`h-2.5 w-2.5 rounded-full shrink-0 ${done ? 'bg-slate-300' : 'bg-mint-500'}`}/>
                                  <div className="text-[12px] font-mono tnum text-slate-500 w-12">{time}</div>
                                  <div className="flex-1 min-w-0">
                                    <div className={`text-[12.5px] font-medium ${done ? 'text-slate-400 line-through' : 'text-midnight-900'}`}>{pName}</div>
                                  </div>
                                  <div className="text-[11px] text-slate-400">{a.specialty?.name || ''}</div>
                                  <div className="text-[10px] text-slate-400 capitalize">{a.mode === 'telemedicina' ? 'Telemed' : 'Presencial'}</div>
                                  <span className={`text-[9px] uppercase tracking-wider font-semibold px-1.5 py-0.5 rounded
                                    ${done ? 'text-slate-500 bg-slate-100' : 'text-mint-700 bg-mint-100'}`}>
                                    {done ? 'Atendido' : 'Pendiente'}
                                  </span>
                                </div>
                              );
                            })}
                          </div>
                        )}
                      </div>

                      {/* Row 4: Semana + accesos rapidos */}
                      <div className="grid grid-cols-2 gap-4">
                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium mb-3">Esta semana</div>
                          <div className="flex items-baseline gap-2">
                            <div className="text-[28px] font-bold tnum text-midnight-900">{w.total}</div>
                            <div className="text-[12px] text-slate-400">citas totales</div>
                          </div>
                          <div className="flex items-center gap-2 mt-2">
                            <div className="flex-1 h-2 rounded-full bg-slate-100 overflow-hidden">
                              <div className="h-full rounded-full bg-mint-400 transition-all" style={{ width: `${w.total > 0 ? (w.completed / w.total) * 100 : 0}%` }}/>
                            </div>
                            <span className="text-[11px] tnum text-slate-500">{w.completed}/{w.total}</span>
                          </div>
                        </div>

                        <div className="bg-white rounded-2xl ring-1 ring-line p-5 shadow-card">
                          <div className="text-[10.5px] uppercase tracking-[0.12em] text-slate-400 font-medium mb-3">Acceso rapido</div>
                          <div className="grid grid-cols-2 gap-2">
                            <button onClick={() => setActiveTab('agenda')}
                              className="h-12 rounded-xl ring-1 ring-line bg-paper hover:bg-slate-50 text-[12px] text-midnight-800 font-medium flex items-center justify-center gap-2 transition">
                              <I.cal className="h-4 w-4 text-mint-600"/> Agenda
                            </button>
                            <button onClick={() => { setActiveTab('patients'); if (patients.length === 0) { setLoadingPatients(true); window.apiFetch('/api/doctor/patients').then(r => r.ok ? r.json() : { patients:[] }).then(d => setPatients(d.patients || [])).catch(() => {}).finally(() => setLoadingPatients(false)); } }}
                              className="h-12 rounded-xl ring-1 ring-line bg-paper hover:bg-slate-50 text-[12px] text-midnight-800 font-medium flex items-center justify-center gap-2 transition">
                              <I.users className="h-4 w-4 text-mint-600"/> Pacientes
                            </button>
                          </div>
                        </div>
                      </div>

                    </div>
                  );
                })()}
              </div>
            </div>
          )}

          {activeTab === 'patients' && (
            <div className="flex-1 overflow-y-auto">
              <div className="max-w-[960px] px-8 py-7">
                <div className="text-[11.5px] uppercase tracking-[0.12em] font-semibold text-midnight-700 mb-4">
                  Pacientes atendidos ({patients.length})
                </div>
                {loadingPatients && <div className="py-8 text-[13px] text-slate-400 text-center">Cargando pacientes...</div>}
                {!loadingPatients && patients.length === 0 && <div className="py-8 text-[13px] text-slate-400 text-center">Sin pacientes registrados</div>}
                {!loadingPatients && patients.length > 0 && (
                  <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
                    <table className="w-full text-left">
                      <thead>
                        <tr className="text-[11px] uppercase tracking-wider text-slate-500 bg-paper/50">
                          <th className="font-medium px-5 py-3">Paciente</th>
                          <th className="font-medium px-3 py-3">Codigo</th>
                          <th className="font-medium px-3 py-3">EPS</th>
                          <th className="font-medium px-3 py-3">Consultas</th>
                          <th className="font-medium px-3 py-3">Ultima visita</th>
                          <th className="font-medium px-3 py-3 w-20">Detalle</th>
                        </tr>
                      </thead>
                      <tbody>
                        {patients.map((p, i) => {
                          const ini = p.name.split(' ').map(n => n[0]).slice(0,2).join('').toUpperCase();
                          const lastVisit = p.appointments[0]?.start_at
                            ? new Date(p.appointments[0].start_at).toLocaleDateString('es-CO', { day:'2-digit', month:'short', year:'numeric' })
                            : '-';
                          return (
                            <tr key={p.id} className={`text-[12.5px] ${i !== patients.length-1 ? 'border-b border-line' : ''} hover:bg-paper/50 transition`}>
                              <td className="px-5 py-3">
                                <div className="flex items-center gap-3">
                                  <div className="h-8 w-8 rounded-full bg-midnight-50 text-midnight-700 grid place-items-center text-[11px] font-semibold">{ini}</div>
                                  <div>
                                    <div className="text-midnight-900 font-medium">{p.name}</div>
                                    {p.is_beneficiary && <div className="text-[10.5px] text-slate-400">Beneficiario ({p.relation})</div>}
                                  </div>
                                </div>
                              </td>
                              <td className="px-3 py-3 tnum text-midnight-800 font-medium">{p.code || '-'}</td>
                              <td className="px-3 py-3 text-slate-600">{p.eps || '-'}</td>
                              <td className="px-3 py-3 tnum text-midnight-800">{p.appointments.length}</td>
                              <td className="px-3 py-3 text-slate-600">{lastVisit}</td>
                              <td className="px-3 py-3">
                                <button onClick={() => setSelectedPatientHistory(selectedPatientHistory === p.id ? null : p.id)}
                                  className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-midnight-700" title="Ver historial">
                                  <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                                </button>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                )}

                {/* Historial expandido de un paciente */}
                {selectedPatientHistory && (() => {
                  const p = patients.find(x => x.id === selectedPatientHistory);
                  if (!p) return null;
                  const rec = expandedRecord;
                  return (
                    <div className="mt-4 bg-white rounded-2xl ring-1 ring-line shadow-card p-6">
                      <div className="flex items-center justify-between mb-4">
                        <div className="text-[14px] font-semibold text-midnight-900">Expediente de {p.name}</div>
                        <button onClick={() => { setSelectedPatientHistory(null); setExpandedRecord(null); }} className="text-[12px] text-slate-400 hover:text-slate-600">Cerrar</button>
                      </div>
                      <div className="flex items-center gap-4 mb-4 text-[12px] text-slate-500">
                        {p.code && <span>Codigo: <span className="font-medium text-midnight-800">{p.code}</span></span>}
                        {p.eps && <span>EPS: <span className="font-medium text-midnight-800">{p.eps}</span></span>}
                        {p.blood_type && <span>Sangre: <span className="font-medium text-midnight-800">{p.blood_type}</span></span>}
                        <span>{p.appointments.length} consulta{p.appointments.length !== 1 ? 's' : ''}</span>
                      </div>
                      <div className="space-y-2">
                        {p.appointments.map(appt => {
                          const isExpanded = rec?.apptId === appt.id && !rec.loading && rec.data;
                          const isLoading = rec?.apptId === appt.id && rec.loading;
                          return (
                            <div key={appt.id} className="rounded-xl ring-1 ring-line overflow-hidden">
                              <div className={`flex items-start gap-3 p-3 cursor-pointer hover:bg-paper/80 transition ${isExpanded ? 'bg-paper' : 'bg-white'}`}
                                onClick={() => loadRecord(appt.id)}>
                                <div className="shrink-0 mt-0.5">
                                  {appt.status === 'completed'
                                    ? <span className="h-2 w-2 rounded-full bg-mint-500 block"/>
                                    : <span className="h-2 w-2 rounded-full bg-amber-400 block"/>}
                                </div>
                                <div className="flex-1 min-w-0">
                                  <div className="flex items-center gap-2">
                                    <div className="text-[12.5px] font-medium text-midnight-900">
                                      {new Date(appt.start_at).toLocaleDateString('es-CO', { day:'2-digit', month:'short', year:'numeric' })}
                                    </div>
                                    <div className="text-[11px] text-slate-400">
                                      {new Date(appt.start_at).toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit', hour12:false })}
                                    </div>
                                    <span className={`text-[9.5px] uppercase tracking-wider font-semibold px-1.5 py-0.5 rounded
                                      ${appt.status === 'completed' ? 'text-mint-700 bg-mint-100' : 'text-amber-700 bg-amber-100'}`}>
                                      {appt.status === 'completed' ? 'Atendido' : appt.status}
                                    </span>
                                  </div>
                                  <div className="text-[11px] text-slate-500 mt-0.5">
                                    {appt.specialty || ''}{appt.professional_name ? ` - ${appt.professional_name}` : ''} | {appt.mode === 'telemedicina' ? 'Telemed' : 'Presencial'}
                                  </div>
                                  {appt.diagnosis && <div className="text-[11.5px] text-midnight-700 mt-1">Dx: {appt.diagnosis}</div>}
                                </div>
                                <div className="shrink-0 mt-1">
                                  <svg viewBox="0 0 24 24" className={`h-4 w-4 text-slate-400 transition ${isExpanded ? 'rotate-90' : ''}`} fill="none">
                                    <path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                                  </svg>
                                </div>
                              </div>

                              {isLoading && <div className="px-6 py-4 text-[12px] text-slate-400 text-center border-t border-line">Cargando expediente...</div>}

                              {isExpanded && (() => {
                                const d = rec.data;
                                return (
                                  <div className="border-t border-line bg-paper/40 p-5 space-y-4">

                                    {/* SOAP */}
                                    {d.notes && (
                                      <div>
                                        <div className="text-[10.5px] uppercase tracking-[0.12em] text-midnight-700 font-semibold mb-2">Notas SOAP</div>
                                        <div className="grid grid-cols-2 gap-3">
                                          {[
                                            {label:'Motivo de consulta', val: d.notes.reason},
                                            {label:'Exploracion', val: d.notes.exploration},
                                            {label:'Diagnostico', val: d.notes.diagnosis},
                                            {label:'Plan', val: d.notes.plan},
                                          ].map(f => (
                                            <div key={f.label} className="rounded-lg bg-white ring-1 ring-line p-3">
                                              <div className="text-[10px] uppercase tracking-wider text-slate-400 font-medium mb-1">{f.label}</div>
                                              <div className="text-[12.5px] text-midnight-900 whitespace-pre-wrap">{f.val || <span className="text-slate-300 italic">Sin registro</span>}</div>
                                            </div>
                                          ))}
                                        </div>
                                        {d.notes.signed_at && (
                                          <div className="mt-2 text-[10.5px] text-slate-400">
                                            Firmado: {new Date(d.notes.signed_at).toLocaleString('es-CO', { day:'2-digit', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' })}
                                          </div>
                                        )}
                                      </div>
                                    )}
                                    {!d.notes && <div className="text-[12px] text-slate-400 italic">Sin notas SOAP registradas</div>}

                                    {/* Recetas */}
                                    {d.prescriptions && d.prescriptions.length > 0 && (
                                      <div>
                                        <div className="text-[10.5px] uppercase tracking-[0.12em] text-midnight-700 font-semibold mb-2">Receta ({d.prescriptions.length})</div>
                                        <div className="space-y-1.5">
                                          {d.prescriptions.map((m, mi) => (
                                            <div key={mi} className="rounded-lg bg-white ring-1 ring-line p-3 flex items-start gap-3">
                                              <div className="h-6 w-6 rounded-md bg-mint-50 text-mint-700 grid place-items-center text-[10px] font-bold shrink-0">{mi+1}</div>
                                              <div className="flex-1 min-w-0">
                                                <div className="text-[12.5px] font-medium text-midnight-900">{m.drug}</div>
                                                <div className="text-[11px] text-slate-500 mt-0.5">
                                                  {m.dose} | {m.frequency} | {m.duration}{m.route ? ` | ${m.route}` : ''}
                                                </div>
                                                {m.instructions && <div className="text-[11px] text-slate-400 mt-0.5">{m.instructions}</div>}
                                              </div>
                                            </div>
                                          ))}
                                        </div>
                                      </div>
                                    )}

                                    {/* Seguimiento */}
                                    {d.followup && (
                                      <div>
                                        <div className="text-[10.5px] uppercase tracking-[0.12em] text-midnight-700 font-semibold mb-2">Seguimiento</div>
                                        <div className="rounded-lg bg-white ring-1 ring-line p-3">
                                          <div className="flex items-center gap-3 text-[12.5px]">
                                            <span className="text-midnight-900 font-medium">Cita de control en {d.followup.period}</span>
                                            {d.followup.mode && <span className="text-[10.5px] text-slate-400">({d.followup.mode})</span>}
                                            {d.followup.priority && d.followup.priority !== 'normal' && (
                                              <span className="text-[9.5px] uppercase tracking-wider font-semibold text-rose-600 bg-rose-50 px-1.5 py-0.5 rounded">{d.followup.priority}</span>
                                            )}
                                          </div>
                                          {d.followup.note && <div className="text-[11px] text-slate-500 mt-1">{d.followup.note}</div>}
                                        </div>
                                      </div>
                                    )}

                                    {!d.notes && (!d.prescriptions || d.prescriptions.length === 0) && !d.followup && (
                                      <div className="text-[12px] text-slate-400 italic text-center py-2">Esta consulta no tiene expediente registrado</div>
                                    )}
                                  </div>
                                );
                              })()}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })()}
              </div>
            </div>
          )}

          {activeTab === 'agenda' && <>
          {/* AGENDA RAIL */}
          <div className="w-[260px] shrink-0 border-r border-line bg-white/60 overflow-y-auto">
            <div className="px-3 pt-4 pb-3">
              <div className="flex items-center justify-between mb-1">
                <button onClick={() => shiftAgendaDate(-1)}
                  className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-midnight-700 transition">
                  <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M15 19l-7-7 7-7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
                <div className="text-center">
                  <div className="text-[11.5px] uppercase tracking-[0.12em] font-semibold text-midnight-700">
                    {agendaDate === new Date().toISOString().slice(0,10) ? 'Hoy' :
                      new Date(agendaDate + 'T12:00:00').toLocaleDateString('es-CO', { weekday:'short' }).replace(/^\w/, c => c.toUpperCase())}
                  </div>
                  <div className="text-[10.5px] text-slate-400 tnum">
                    {new Date(agendaDate + 'T12:00:00').toLocaleDateString('es-CO', { day:'numeric', month:'short' })}
                  </div>
                </div>
                <button onClick={() => shiftAgendaDate(1)}
                  className="h-7 w-7 rounded-lg hover:bg-slate-100 grid place-items-center text-slate-400 hover:text-midnight-700 transition">
                  <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none"><path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              </div>
              {agendaDate !== new Date().toISOString().slice(0,10) && (
                <button onClick={goToToday} className="w-full text-[10.5px] text-mint-700 font-medium hover:text-mint-800 text-center mt-1">
                  Volver a hoy
                </button>
              )}
            </div>
            {loadingAgenda && <div className="px-4 py-8 text-[12px] text-slate-400 text-center">Cargando agenda...</div>}
            {!loadingAgenda && agenda.length === 0 && (
              <div className="px-4 py-8 text-[12px] text-slate-400 text-center">
                Sin citas{agendaDate === new Date().toISOString().slice(0,10) ? ' hoy' : ''}
              </div>
            )}
            <div className="relative">
              <div className="absolute left-[15px] top-3 bottom-3 w-px bg-line"/>
              {agenda.map(a => (
                <AgendaRow key={a.id} a={a} active={a.id === selectedAppt} onClick={() => selectAppointment(a.id)}/>
              ))}
            </div>
          </div>

          {/* CONSULTATION PANEL */}
          <div className="flex-1 min-w-0 overflow-y-auto">
            {!selectedAppt && (
              <div className="flex items-center justify-center h-full text-[14px] text-slate-400">
                Selecciona una cita de la agenda para iniciar la consulta
              </div>
            )}

            {loadingPatient && (
              <div className="flex items-center justify-center h-full text-[14px] text-slate-400">
                Cargando datos del paciente...
              </div>
            )}

            {selectedAppt && !loadingPatient && patientError && (
              <div className="flex flex-col items-center justify-center h-full gap-3">
                <div className="text-[14px] text-rose-600 font-medium">Error al cargar datos del paciente</div>
                <div className="text-[12.5px] text-slate-500">{patientError}</div>
                <button onClick={() => selectAppointment(selectedAppt)}
                  className="h-9 px-4 rounded-lg bg-midnight-900 text-white text-[12.5px] font-medium hover:bg-midnight-800 transition">
                  Reintentar
                </button>
              </div>
            )}

            {selectedAppt && !loadingPatient && patientData && (
              <div className="max-w-[920px] px-8 py-7 space-y-6">

                {/* PATIENT HEADER */}
                <div className="bg-white rounded-2xl ring-1 ring-line p-6 shadow-card">
                  <div className="flex items-start gap-5">
                    <div className="h-16 w-16 rounded-2xl bg-gradient-to-br from-mint-300 to-mint-500 grid place-items-center text-white text-[20px] font-semibold shrink-0">{patientInitials}</div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <h1 className="text-[22px] font-semibold tracking-tight text-midnight-900 leading-tight">{patientName}</h1>
                        {patient?.code && <Badge tone="midnight">{patient.code}</Badge>}
                        {patient?.area && <Badge tone="mint">{"Emplead@ | " + patient.area}</Badge>}
                        {patient?.relation && <Badge tone="amber">{"Beneficiari@ | " + patient.relation}</Badge>}
                      </div>
                      <div className="text-[12.5px] text-slate-500 mt-1 tnum">
                        {patient?.eps && `EPS: ${patient.eps}`}
                        {patient?.blood_type && ` | RH: ${patient.blood_type}`}
                      </div>
                    </div>
                    <div className="text-right shrink-0">
                      <div className="text-[10.5px] uppercase tracking-wider text-slate-400">Motivo</div>
                      <div className="text-[13px] font-medium text-midnight-900 mt-1">{currentAppt?.reason || patientData.appointment?.reason || 'Consulta'}</div>
                      <div className="mt-3 inline-flex items-center gap-1.5 rounded-full bg-mint-50 ring-1 ring-inset ring-mint-200 px-2 py-0.5 text-[10.5px] font-medium text-mint-700">
                        <span className="h-1.5 w-1.5 rounded-full bg-mint-500 animate-pulse"/>
                        {currentAppt?.status === 'completed' ? 'Completada' : 'En consulta'}
                      </div>
                    </div>
                  </div>
                </div>

                {/* PRIOR VISITS (historial del paciente) */}
                {patientData.history && patientData.history.length > 0 && (
                  <div className="bg-white rounded-2xl ring-1 ring-line p-6 shadow-card">
                    <div className="flex items-center justify-between mb-4">
                      <div className="text-[15px] font-semibold text-midnight-900">Historial del paciente</div>
                      <div className="text-[11px] text-slate-400">{patientData.history.length} consulta{patientData.history.length !== 1 ? 's' : ''} previas</div>
                    </div>
                    <div className="space-y-2 max-h-[340px] overflow-y-auto pr-1">
                      {patientData.history.map(h => {
                        const isExp = expandedRecord?.apptId === h.id && !expandedRecord.loading && expandedRecord.data;
                        const isLoad = expandedRecord?.apptId === h.id && expandedRecord.loading;
                        return (
                          <div key={h.id} className="rounded-xl ring-1 ring-line overflow-hidden">
                            <div className={`p-3 text-[12px] cursor-pointer hover:bg-paper/80 transition flex items-start gap-2 ${isExp ? 'bg-paper' : ''}`}
                              onClick={() => loadRecord(h.id)}>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center justify-between">
                                  <div className="font-medium text-midnight-900">{h.specialty?.name || 'Consulta'}</div>
                                  <div className="text-[10.5px] text-slate-400 tnum">{new Date(h.start_at).toLocaleDateString('es-CO', { day:'2-digit', month:'short', year:'numeric' })}</div>
                                </div>
                                <div className="text-slate-500 mt-0.5">{h.professional?.full_name}</div>
                                {h.clinical_notes?.[0]?.diagnosis && (
                                  <div className="text-slate-600 mt-1 leading-snug">Dx: {h.clinical_notes[0].diagnosis}</div>
                                )}
                              </div>
                              <svg viewBox="0 0 24 24" className={`h-3.5 w-3.5 text-slate-400 shrink-0 mt-1 transition ${isExp ? 'rotate-90' : ''}`} fill="none">
                                <path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                              </svg>
                            </div>
                            {isLoad && <div className="px-4 py-3 text-[11px] text-slate-400 text-center border-t border-line">Cargando...</div>}
                            {isExp && (() => {
                              const d = expandedRecord.data;
                              return (
                                <div className="border-t border-line bg-paper/40 p-4 space-y-3">
                                  {d.notes && (
                                    <div className="grid grid-cols-2 gap-2">
                                      {[
                                        {label:'Motivo', val: d.notes.reason},
                                        {label:'Exploracion', val: d.notes.exploration},
                                        {label:'Diagnostico', val: d.notes.diagnosis},
                                        {label:'Plan', val: d.notes.plan},
                                      ].map(f => (
                                        <div key={f.label} className="rounded-lg bg-white ring-1 ring-line p-2.5">
                                          <div className="text-[9.5px] uppercase tracking-wider text-slate-400 font-medium">{f.label}</div>
                                          <div className="text-[11.5px] text-midnight-900 mt-0.5 whitespace-pre-wrap">{f.val || <span className="text-slate-300 italic">-</span>}</div>
                                        </div>
                                      ))}
                                    </div>
                                  )}
                                  {!d.notes && <div className="text-[11px] text-slate-400 italic">Sin notas SOAP</div>}
                                  {d.prescriptions && d.prescriptions.length > 0 && (
                                    <div>
                                      <div className="text-[9.5px] uppercase tracking-wider text-slate-400 font-medium mb-1">Receta</div>
                                      {d.prescriptions.map((m, mi) => (
                                        <div key={mi} className="text-[11.5px] text-midnight-900">
                                          {mi+1}. {m.drug} - {m.dose} | {m.frequency} | {m.duration}
                                        </div>
                                      ))}
                                    </div>
                                  )}
                                  {d.followup && (
                                    <div className="text-[11.5px] text-slate-500">
                                      Seguimiento: {d.followup.period}{d.followup.note ? ` - ${d.followup.note}` : ''}
                                    </div>
                                  )}
                                </div>
                              );
                            })()}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* SOAP NOTES */}
                <div className="bg-white rounded-2xl ring-1 ring-line p-6 shadow-card">
                  <div className="flex items-center justify-between mb-5">
                    <div>
                      <div className="text-[15px] font-semibold text-midnight-900">Notas SOAP</div>
                      <div className="text-[12px] text-slate-500 mt-0.5">Notas de la consulta. Visibles para futuros profesionales tratantes.</div>
                    </div>
                    <button onClick={handleSaveNotes} disabled={saving}
                      className="h-8 px-3 rounded-lg bg-midnight-50 text-midnight-700 text-[12px] font-medium hover:bg-midnight-100 disabled:opacity-50">
                      {saving ? 'Guardando...' : 'Guardar notas'}
                    </button>
                  </div>

                  <div className="grid grid-cols-2 gap-5">
                    <div>
                      <SectionLabel>S - Motivo de consulta</SectionLabel>
                      <textarea rows={3} value={soapReason} onChange={e => setSoapReason(e.target.value)}
                        placeholder="Que refiere el paciente..."
                        className="w-full rounded-xl bg-white ring-1 ring-line p-3.5 text-[13px] text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-300 leading-relaxed resize-none"/>
                    </div>
                    <div>
                      <SectionLabel>O - Exploracion fisica</SectionLabel>
                      <textarea rows={3} value={soapExploration} onChange={e => setSoapExploration(e.target.value)}
                        placeholder="Hallazgos del examen fisico..."
                        className="w-full rounded-xl bg-white ring-1 ring-line p-3.5 text-[13px] text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-300 leading-relaxed resize-none"/>
                    </div>
                    <div>
                      <SectionLabel>A - Diagnostico / Impresion</SectionLabel>
                      <textarea rows={3} value={soapDiagnosis} onChange={e => setSoapDiagnosis(e.target.value)}
                        placeholder="Diagnostico o impresion clinica..."
                        className="w-full rounded-xl bg-white ring-1 ring-line p-3.5 text-[13px] text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-300 leading-relaxed resize-none"/>
                    </div>
                    <div>
                      <SectionLabel>P - Plan de manejo</SectionLabel>
                      <textarea rows={3} value={soapPlan} onChange={e => setSoapPlan(e.target.value)}
                        placeholder="Plan terapeutico, examenes, indicaciones..."
                        className="w-full rounded-xl bg-white ring-1 ring-line p-3.5 text-[13px] text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-300 leading-relaxed resize-none"/>
                    </div>
                  </div>
                </div>

                {/* MEDICATIONS */}
                <div className="bg-white rounded-2xl ring-1 ring-line shadow-card overflow-hidden">
                  <div className="px-6 py-5 border-b border-line flex items-center justify-between">
                    <div>
                      <div className="text-[15px] font-semibold text-midnight-900">Medicamentos prescritos</div>
                      <div className="text-[12px] text-slate-500 mt-0.5">Verifica alergias antes de prescribir.</div>
                    </div>
                    <button onClick={handleSavePrescriptions} disabled={saving || meds.length === 0}
                      className="h-8 px-3 rounded-lg bg-midnight-50 text-midnight-700 text-[12px] font-medium hover:bg-midnight-100 disabled:opacity-50">
                      Guardar receta
                    </button>
                  </div>

                  {/* Existing meds */}
                  {meds.length > 0 && (
                    <>
                      <div className="grid grid-cols-12 gap-3 px-4 py-2.5 bg-paper/60 border-b border-line text-[10.5px] uppercase tracking-wider text-slate-500 font-medium">
                        <div className="col-span-3">Medicamento</div>
                        <div className="col-span-2">Dosis</div>
                        <div className="col-span-2">Frecuencia</div>
                        <div className="col-span-2">Duracion</div>
                        <div className="col-span-3">Indicaciones</div>
                      </div>
                      {meds.map((m, i) => (
                        <div key={m.id || i} className={`grid grid-cols-12 gap-3 items-start px-4 py-3 ${i < meds.length-1 ? 'border-b border-line' : ''}`}>
                          <div className="col-span-3">
                            <div className="text-[13px] font-semibold text-midnight-900">{m.drug}</div>
                            <div className="text-[11.5px] text-slate-500 mt-0.5">{m.route || 'Oral'}</div>
                          </div>
                          <div className="col-span-2 text-[12.5px] text-midnight-800 tnum pt-0.5">{m.dose}</div>
                          <div className="col-span-2 text-[12.5px] text-midnight-800 pt-0.5">{m.frequency}</div>
                          <div className="col-span-2 text-[12.5px] text-midnight-800 tnum pt-0.5">{m.duration}</div>
                          <div className="col-span-3 flex items-start justify-between gap-2">
                            <div className="text-[11.5px] text-slate-500 leading-snug">{m.instructions || ''}</div>
                            <button onClick={() => removeMed(i)} className="text-slate-400 hover:text-rose-600 mt-0.5 shrink-0">
                              <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none"><path d="M4 7h16M9 7V4h6v3M7 7l1 13h8l1-13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                            </button>
                          </div>
                        </div>
                      ))}
                    </>
                  )}

                  {/* Add new med */}
                  <div className="px-4 py-4 bg-paper/40 border-t border-line">
                    <div className="grid grid-cols-12 gap-2 items-end">
                      <div className="col-span-3">
                        <label className="text-[10.5px] text-slate-500">Medicamento</label>
                        <input value={newMed.drug} onChange={e => setNewMed(p => ({...p, drug:e.target.value}))}
                          className="w-full h-9 rounded-lg ring-1 ring-line px-2.5 text-[12.5px] text-midnight-900 focus:outline-none focus:ring-midnight-300" placeholder="Nombre"/>
                      </div>
                      <div className="col-span-2">
                        <label className="text-[10.5px] text-slate-500">Dosis</label>
                        <input value={newMed.dose} onChange={e => setNewMed(p => ({...p, dose:e.target.value}))}
                          className="w-full h-9 rounded-lg ring-1 ring-line px-2.5 text-[12.5px] text-midnight-900 focus:outline-none focus:ring-midnight-300" placeholder="50 mg"/>
                      </div>
                      <div className="col-span-2">
                        <label className="text-[10.5px] text-slate-500">Frecuencia</label>
                        <input value={newMed.frequency} onChange={e => setNewMed(p => ({...p, frequency:e.target.value}))}
                          className="w-full h-9 rounded-lg ring-1 ring-line px-2.5 text-[12.5px] text-midnight-900 focus:outline-none focus:ring-midnight-300" placeholder="c/8h"/>
                      </div>
                      <div className="col-span-2">
                        <label className="text-[10.5px] text-slate-500">Duracion</label>
                        <input value={newMed.duration} onChange={e => setNewMed(p => ({...p, duration:e.target.value}))}
                          className="w-full h-9 rounded-lg ring-1 ring-line px-2.5 text-[12.5px] text-midnight-900 focus:outline-none focus:ring-midnight-300" placeholder="7 dias"/>
                      </div>
                      <div className="col-span-3 flex gap-2">
                        <input value={newMed.instructions} onChange={e => setNewMed(p => ({...p, instructions:e.target.value}))}
                          className="flex-1 h-9 rounded-lg ring-1 ring-line px-2.5 text-[12.5px] text-midnight-900 focus:outline-none focus:ring-midnight-300" placeholder="Indicaciones"/>
                        <button onClick={addMed} className="h-9 w-9 rounded-lg bg-midnight-900 text-white grid place-items-center hover:bg-midnight-800 shrink-0">
                          <I.plus className="h-4 w-4"/>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

                {/* FOLLOW-UP */}
                <div className="bg-white rounded-2xl ring-1 ring-line p-6 shadow-card">
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="text-[15px] font-semibold text-midnight-900">Seguimiento sugerido</div>
                      <div className="text-[12px] text-slate-500 mt-0.5">Define cuando deberia volver el paciente.</div>
                    </div>
                    <label className="inline-flex items-center gap-2 cursor-pointer">
                      <span className="text-[12.5px] text-slate-600">Requiere seguimiento</span>
                      <button onClick={() => setNeedsFollowup(v => !v)} className={`h-5 w-9 rounded-full relative transition ${needsFollowup ? 'bg-mint-500' : 'bg-slate-200'}`}>
                        <span className={`absolute top-0.5 h-4 w-4 rounded-full bg-white shadow transition ${needsFollowup ? 'left-[18px]' : 'left-0.5'}`}/>
                      </button>
                    </label>
                  </div>

                  {needsFollowup && (
                    <>
                      <div className="mt-5 grid grid-cols-5 gap-2">
                        {FOLLOWUP_OPTS.map(o => (
                          <button key={o.id} onClick={() => setFollowupPeriod(o.id)}
                            className={`h-11 rounded-xl text-[12.5px] font-medium ring-1 transition
                              ${followupPeriod === o.id
                                ? 'bg-midnight-900 text-white ring-midnight-900'
                                : 'bg-white text-midnight-800 ring-line hover:ring-midnight-300 hover:bg-paper'}`}>
                            {o.label}
                          </button>
                        ))}
                      </div>
                      <div className="mt-4">
                        <SectionLabel optional>Nota para el proximo profesional</SectionLabel>
                        <textarea rows={2} value={followupNote} onChange={e => setFollowupNote(e.target.value)}
                          placeholder="Indicaciones para la proxima consulta..."
                          className="w-full rounded-xl bg-white ring-1 ring-line p-3.5 text-[13px] text-midnight-900 placeholder:text-slate-300 focus:outline-none focus:ring-midnight-300 leading-relaxed resize-none"/>
                      </div>
                    </>
                  )}
                </div>

                {/* ACTIONS BAR */}
                <div className="sticky bottom-0 -mx-8 px-8 py-4 bg-paper/95 backdrop-blur border-t border-line flex items-center gap-2">
                  <button onClick={handleSaveNotes} disabled={saving}
                    className="h-11 px-4 rounded-xl text-[13px] text-midnight-800 font-medium ring-1 ring-line bg-white hover:bg-paper disabled:opacity-50">
                    Guardar borrador
                  </button>
                  <div className="ml-auto">
                    <button onClick={handleComplete} disabled={saving || currentAppt?.status === 'completed'}
                      className="h-11 px-5 rounded-xl text-[13px] font-semibold text-white bg-midnight-900 hover:bg-midnight-800 inline-flex items-center gap-2 disabled:opacity-50">
                      {saving ? 'Procesando...' : 'Firmar y cerrar consulta'}
                      <I.check className="h-4 w-4 text-mint-300"/>
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
          </>}
        </div>
      </main>

      {/* SUMMARY OVERLAY */}
      {showSummary && summaryData && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-midnight-950/60 backdrop-blur-sm">
          <div className="bg-white rounded-2xl shadow-pop w-[640px] max-h-[90vh] overflow-y-auto ring-1 ring-line">

            {/* Header */}
            <div className="px-7 pt-7 pb-5 border-b border-line">
              <div className="flex items-center gap-4">
                <div className="h-12 w-12 rounded-xl bg-mint-100 grid place-items-center">
                  <I.check className="h-6 w-6 text-mint-600"/>
                </div>
                <div>
                  <div className="text-[10.5px] uppercase tracking-[0.14em] text-mint-600 font-medium">Consulta finalizada</div>
                  <div className="text-[20px] font-semibold tracking-tight text-midnight-900 leading-tight mt-1">{summaryData.patientName}</div>
                  <div className="text-[12px] text-slate-500 mt-0.5">{summaryData.reason} | {summaryData.time}</div>
                </div>
              </div>
            </div>

            <div className="px-7 py-5 space-y-5">

              {/* SOAP summary */}
              <div>
                <div className="text-[11px] uppercase tracking-[0.12em] text-midnight-700 font-semibold mb-3">Notas SOAP</div>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    {key:'reason',      label:'S - Motivo'},
                    {key:'exploration', label:'O - Exploracion'},
                    {key:'diagnosis',   label:'A - Diagnostico'},
                    {key:'plan',        label:'P - Plan'},
                  ].map(f => (
                    <div key={f.key} className="rounded-xl bg-paper ring-1 ring-line p-3">
                      <div className="text-[10.5px] uppercase tracking-wider text-slate-400 font-medium mb-1">{f.label}</div>
                      <div className="text-[12.5px] text-midnight-900 leading-snug whitespace-pre-wrap">
                        {summaryData.soap[f.key] || <span className="text-slate-300 italic">Sin registro</span>}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Medications summary */}
              {summaryData.medications.length > 0 && (
                <div>
                  <div className="text-[11px] uppercase tracking-[0.12em] text-midnight-700 font-semibold mb-3">Receta ({summaryData.medications.length})</div>
                  <div className="rounded-xl ring-1 ring-line overflow-hidden">
                    {summaryData.medications.map((m, i) => (
                      <div key={i} className={`px-4 py-2.5 flex items-center gap-4 ${i > 0 ? 'border-t border-line' : ''}`}>
                        <div className="h-8 w-8 rounded-lg bg-midnight-50 grid place-items-center shrink-0">
                          <svg viewBox="0 0 24 24" className="h-4 w-4 text-midnight-600" fill="none">
                            <rect x="5" y="2" width="14" height="20" rx="2" stroke="currentColor" strokeWidth="1.5"/>
                            <path d="M9 6h6M9 10h6M9 14h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                          </svg>
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="text-[13px] font-semibold text-midnight-900">{m.drug}</div>
                          <div className="text-[11.5px] text-slate-500">{m.dose} | {m.frequency || 'Segun indicacion'} | {m.duration || 'Segun indicacion'}</div>
                        </div>
                        <div className="text-[11px] text-slate-400 shrink-0">{m.route || 'Oral'}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {summaryData.medications.length === 0 && (
                <div className="rounded-xl bg-paper ring-1 ring-line p-4 text-center text-[12.5px] text-slate-400">
                  Sin medicamentos prescritos en esta consulta
                </div>
              )}

              {/* Follow-up summary */}
              <div>
                <div className="text-[11px] uppercase tracking-[0.12em] text-midnight-700 font-semibold mb-3">Seguimiento</div>
                {summaryData.followup ? (
                  <div className="rounded-xl bg-paper ring-1 ring-line p-4 flex items-center gap-3">
                    <div className="h-10 w-10 rounded-xl bg-mint-100 grid place-items-center shrink-0">
                      <I.cal className="h-5 w-5 text-mint-600"/>
                    </div>
                    <div>
                      <div className="text-[13px] font-semibold text-midnight-900">Proxima cita en {summaryData.followup.period}</div>
                      {summaryData.followup.note && <div className="text-[12px] text-slate-500 mt-0.5">{summaryData.followup.note}</div>}
                    </div>
                  </div>
                ) : (
                  <div className="rounded-xl bg-paper ring-1 ring-line p-4 text-center text-[12.5px] text-slate-400">
                    No requiere seguimiento
                  </div>
                )}
              </div>
            </div>

            {/* Footer */}
            <div className="px-7 py-5 border-t border-line flex items-center justify-between">
              <div className="text-[11.5px] text-slate-400">
                Firmada por {u.full_name} | {new Date().toLocaleTimeString('es-CO', { hour:'2-digit', minute:'2-digit' })}
              </div>
              <button onClick={handleDismissSummary}
                className="h-11 px-6 rounded-xl bg-midnight-900 text-white text-[13px] font-semibold hover:bg-midnight-800 inline-flex items-center gap-2">
                Volver a mi agenda
                <I.chevR className="h-4 w-4"/>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.DoctorView = DoctorView;
