// vita-care.jsx — Proactive care: today's plan, reminders, therapy follow-up, post-cita check-in, controls

// ── Build today's care plan from the patient's state ────────────
function buildTodayPlan({ profile, asis, pic, seguimiento }) {
  const tasks = [];
  const meds = Array.isArray(profile.medicamentos) ? profile.medicamentos : (profile.medicamentos ? [profile.medicamentos] : []);
  // Medications — morning dose for each, plus a night dose for the first
  meds.forEach((m, i) => {
    tasks.push({ id: 'med-am-' + i, tipo: 'medicamento', titulo: m, sub: 'Con el desayuno', hora: '08:00', bloque: 'mañana', icon: 'pill' });
  });
  if (meds.length) tasks.push({ id: 'med-pm-0', tipo: 'medicamento', titulo: meds[0], sub: 'Con la cena', hora: '20:00', bloque: 'noche', icon: 'pill' });

  // Hydration (all day)
  tasks.push({ id: 'agua', tipo: 'habito', titulo: 'Tomar agua', sub: '8 vasos en el día', hora: 'Todo el día', bloque: 'mañana', icon: 'droplet' });

  // Activity — from PIC or ASIS priorities
  const wantsMove = (asis && asis.prioridades || []).some(p => /camin|ejerci|mover|activ/i.test(p)) || (pic && (pic.areas || []).some(a => /activ|ejerci/i.test(a.nombre || '')));
  tasks.push({ id: 'caminar', tipo: 'actividad', titulo: 'Caminar 15 minutos', sub: wantsMove ? 'Tu meta de hoy' : 'Mueve el cuerpo', hora: '17:00', bloque: 'tarde', icon: 'walk' });

  // Therapy / emotional check-in (if in psychology context — always offer a calm evening one)
  tasks.push({ id: 'animo', tipo: 'terapia', titulo: 'Registrar cómo te sientes', sub: 'Seguimiento emocional', hora: '21:00', bloque: 'noche', icon: 'brain' });

  // Appointment today?
  const citaHoy = (seguimiento || []).find(s => s.tipo === 'cita' && s.estado === 'agendado' && /hoy/i.test(s.detalle || ''));
  if (citaHoy) tasks.unshift({ id: 'cita-hoy', tipo: 'cita', titulo: citaHoy.titulo, sub: 'Tu cita de hoy', hora: '10:30', bloque: 'mañana', icon: 'video', fijo: true });

  return tasks;
}

const BLOQUES = [
  { k: 'mañana', label: 'Mañana', icon: 'sunrise' },
  { k: 'tarde', label: 'Tarde', icon: 'sundial' },
  { k: 'noche', label: 'Noche', icon: 'moon' },
];
const CARE_COLOR = (t, tipo) => ({ medicamento: t.accent, habito: '#5BC0EB', actividad: t.green, terapia: '#A98CD9', cita: t.accent }[tipo] || t.accent);

function todayKey() { const d = new Date(); return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate(); }

// ── Home card: Tu cuidado de hoy ────────────────────────────────
function TodayCard({ t, persona, tasks, done, onToggle, onOpenCare }) {
  const total = tasks.length;
  const completed = tasks.filter(x => done[x.id]).length;
  const pct = total ? Math.round(completed / total * 100) : 0;
  const next = tasks.find(x => !done[x.id]);
  const accent = persona.accent;
  return (
    <div style={{ borderRadius: 24, padding: 18, marginBottom: 18, background: `linear-gradient(150deg, ${hexA(accent, t.dark ? 0.16 : 0.1)}, ${hexA(accent, 0.03)})`, border: `1px solid ${hexA(accent, 0.22)}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 13, marginBottom: 15 }}>
        <div style={{ position: 'relative', width: 52, height: 52, flexShrink: 0 }}>
          <ProgressRing value={pct} size={52} stroke={4} color={accent} track={t.dark ? 'rgba(255,255,255,0.1)' : 'rgba(10,26,51,0.08)'} />
          <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 800, color: t.text }}>{completed}/{total}</div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 21, color: t.text, lineHeight: 1.05 }}>Tu cuidado de hoy</div>
          <div style={{ fontSize: 13, color: t.textSoft, fontWeight: 450, marginTop: 2 }}>{pct === 100 ? '¡Lo lograste todo hoy! 💚' : next ? 'Sigue: ' + next.titulo : 'Vamos bien'}</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {tasks.slice(0, 3).map(task => (
          <CareRow key={task.id} t={t} persona={persona} task={task} done={!!done[task.id]} onToggle={() => onToggle(task.id)} compact />
        ))}
      </div>
      <button onClick={onOpenCare} style={{ width: '100%', marginTop: 12, padding: '11px', borderRadius: 12, cursor: 'pointer', border: `1px solid ${hexA(accent, 0.3)}`, background: 'transparent', color: accent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 13.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
        Ver todo mi cuidado {Icon.chevron({ s: 15, c: accent })}
      </button>
    </div>
  );
}

function CareRow({ t, persona, task, done, onToggle, compact }) {
  const color = CARE_COLOR(t, task.tipo);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: compact ? '10px 12px' : '13px 14px', borderRadius: 14, background: done ? (t.dark ? 'rgba(255,255,255,0.03)' : 'rgba(10,26,51,0.02)') : (t.dark ? 'rgba(255,255,255,0.05)' : '#FFFFFF'), border: `1px solid ${t.stroke}`, opacity: done ? 0.62 : 1, transition: 'opacity .25s' }}>
      <span style={{ width: 36, height: 36, flexShrink: 0, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(color, 0.14) }}>{Icon[task.icon]({ s: 19, c: color })}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, textDecoration: done ? 'line-through' : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{task.titulo}</div>
        <div style={{ fontSize: 12, color: t.muted, fontWeight: 500 }}>{task.hora} · {task.sub}</div>
      </div>
      {task.fijo ? (
        <span style={{ fontSize: 11, fontWeight: 700, color: persona.accent, background: hexA(persona.accent, 0.14), padding: '5px 10px', borderRadius: 999, flexShrink: 0 }}>Cita</span>
      ) : (
        <button onClick={onToggle} style={{ width: 28, height: 28, flexShrink: 0, borderRadius: '50%', cursor: 'pointer', border: `2px solid ${done ? color : t.strokeStrong}`, background: done ? color : 'transparent', display: 'grid', placeItems: 'center', WebkitTapHighlightColor: 'transparent' }}>
          {done && Icon.check({ s: 15, c: t.onAccent, w: 3 })}
        </button>
      )}
    </div>
  );
}

// ── Post-cita proactive check-in card (home) ────────────────────
function PostCitaCard({ t, persona, cita, onOpen, onDismiss }) {
  return (
    <div style={{ borderRadius: 20, padding: 16, marginBottom: 18, background: t.dark ? 'rgba(255,255,255,0.05)' : '#FFFFFF', border: `1px solid ${hexA(persona.accent, 0.3)}`, position: 'relative' }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <VitaDot t={t} size={36} active />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, lineHeight: 1.3 }}>¿Cómo te fue en tu cita?</div>
          <div style={{ fontSize: 13, color: t.textSoft, fontWeight: 450, lineHeight: 1.4, marginTop: 3 }}>{cita.titulo}. Cuéntame y me encargo de lo que sigue: controles, órdenes o fórmulas.</div>
          <button onClick={onOpen} style={{ marginTop: 12, padding: '10px 16px', borderRadius: 12, border: 'none', cursor: 'pointer', background: `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})`, color: t.onAccent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 13.5, fontWeight: 700 }}>Contarle a Vita</button>
        </div>
        <button onClick={onDismiss} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: t.muted, padding: 2, flexShrink: 0 }}>{Icon.x({ s: 16, c: t.muted })}</button>
      </div>
    </div>
  );
}

// ── Post-cita guided check-in sheet ─────────────────────────────
const ORDEN_OPCIONES = [
  { k: 'medicamento', label: 'Me formularon un medicamento', icon: 'pill' },
  { k: 'examen', label: 'Me ordenaron exámenes', icon: 'lab' },
  { k: 'control', label: 'Quedé con cita de control', icon: 'stethoscope' },
  { k: 'terapia', label: 'Me mandaron terapias', icon: 'walk' },
  { k: 'nada', label: 'Todo bien, sin órdenes nuevas', icon: 'check' },
];
function PostCitaSheet({ t, persona, cita, voice, tts, onClose, onResolve }) {
  const accent = persona.accent;
  const [step, setStep] = React.useState(0); // 0 asistió, 1 órdenes, 2 done
  const [asistio, setAsistio] = React.useState(null);
  const [ordenes, setOrdenes] = React.useState({});
  const spokenRef = React.useRef(-1);

  const prompts = ['¿Alcanzaste a ir a tu cita?', '¿El médico te dejó alguna orden? Marca lo que aplique.', ''];
  React.useEffect(() => {
    if (!tts || step >= 2 || step === spokenRef.current) return;
    spokenRef.current = step; voice && voice.speak(prompts[step], persona);
  }, [step]);

  const toggleOrden = (k) => setOrdenes(o => k === 'nada' ? { nada: !o.nada } : { ...o, [k]: !o[k], nada: false });

  const finish = () => {
    const nuevos = [];
    const eps = 'tu EPS';
    if (ordenes.medicamento) nuevos.push({ id: 'pc-med-' + Date.now(), tipo: 'medicamento', titulo: 'Nuevo medicamento formulado', detalle: 'Vita te recuerda tomarlo', estado: 'activo' });
    if (ordenes.examen) nuevos.push({ id: 'pc-exa-' + Date.now(), tipo: 'examen', titulo: 'Exámenes ordenados', detalle: 'Vita los agenda con ' + eps, estado: 'pendiente' });
    if (ordenes.control) nuevos.push({ id: 'pc-ctl-' + Date.now(), tipo: 'cita', titulo: 'Cita de control', detalle: 'En 2 meses · Vita te recuerda', estado: 'pendiente' });
    if (ordenes.terapia) nuevos.push({ id: 'pc-ter-' + Date.now(), tipo: 'examen', titulo: 'Plan de terapias', detalle: 'Vita coordina las sesiones', estado: 'pendiente' });
    onResolve(nuevos);
    setStep(2);
  };

  return (
    <Sheet t={t} onClose={onClose} tall>
      <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginBottom: 16 }}>
        {[0, 1, 2].map(i => <span key={i} style={{ width: i === step ? 22 : 7, height: 7, borderRadius: 999, background: i <= step ? accent : t.stroke, transition: 'all .3s' }} />)}
      </div>

      {step < 2 && (
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 18 }}>
          <VitaDot t={t} size={36} active />
          <div style={{ flex: 1, padding: '12px 15px', borderRadius: '4px 16px 16px 16px', background: t.dark ? 'rgba(255,255,255,0.06)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
            <div style={{ fontSize: 15.5, color: t.text, fontWeight: 500, lineHeight: 1.4 }}>{prompts[step]}</div>
          </div>
        </div>
      )}

      {step === 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button onClick={() => { setAsistio(true); setStep(1); }} style={btnPrimary(t, persona)}>{Icon.check({ s: 18, c: t.onAccent, w: 3 })} Sí, fui a la cita</button>
          <button onClick={() => { onResolve([{ id: 'pc-reag-' + Date.now(), tipo: 'cita', titulo: 'Reagendar ' + cita.titulo, detalle: 'Vita busca nuevo cupo', estado: 'pendiente' }]); setStep(2); }} style={btnGhost(t)}>No pude ir — reagéndala</button>
        </div>
      )}

      {step === 1 && (
        <div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {ORDEN_OPCIONES.map(o => {
              const on = ordenes[o.k];
              return (
                <button key={o.k} onClick={() => toggleOrden(o.k)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 13, borderRadius: 14, cursor: 'pointer', border: `1.5px solid ${on ? accent : t.stroke}`, background: on ? hexA(accent, 0.1) : (t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF'), textAlign: 'left', WebkitTapHighlightColor: 'transparent' }}>
                  <span style={{ width: 38, height: 38, flexShrink: 0, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(o.k === 'nada' ? t.green : accent, 0.14) }}>{Icon[o.icon]({ s: 19, c: o.k === 'nada' ? t.green : accent })}</span>
                  <span style={{ flex: 1, fontSize: 14, color: t.text, fontWeight: 600 }}>{o.label}</span>
                  <span style={{ width: 22, height: 22, flexShrink: 0, borderRadius: 7, border: `1.5px solid ${on ? accent : t.strokeStrong}`, background: on ? accent : 'transparent', display: 'grid', placeItems: 'center' }}>{on && Icon.check({ s: 13, c: t.onAccent, w: 3 })}</span>
                </button>
              );
            })}
          </div>
          <button disabled={!Object.values(ordenes).some(Boolean)} onClick={finish} style={{ ...btnPrimary(t, persona), marginTop: 16, opacity: Object.values(ordenes).some(Boolean) ? 1 : 0.4 }}>Listo, encárgate Vita</button>
        </div>
      )}

      {step === 2 && (
        <div style={{ textAlign: 'center', padding: '8px 0 4px' }}>
          <div style={{ width: 64, height: 64, borderRadius: '50%', background: t.green, display: 'grid', placeItems: 'center', margin: '0 auto 16px', boxShadow: `0 10px 26px ${hexA(t.green, 0.5)}` }}>{Icon.check({ s: 36, c: '#fff', w: 3 })}</div>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 24, color: t.text, marginBottom: 6 }}>Yo me encargo</div>
          <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '0 auto 18px', maxWidth: 280, fontWeight: 450 }}>Actualicé tu seguimiento y tu historia. Te voy recordando cada cosa a su tiempo. No tienes que estar pendiente. 💚</p>
          <button onClick={onClose} style={btnPrimary(t, persona)}>Entendido</button>
        </div>
      )}
    </Sheet>
  );
}

function btnPrimary(t, persona) { return { width: '100%', padding: '14px', borderRadius: 14, border: 'none', cursor: 'pointer', background: `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})`, color: t.onAccent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }; }
function btnGhost(t) { return { width: '100%', padding: '14px', borderRadius: 14, cursor: 'pointer', border: `1.5px solid ${t.strokeStrong}`, background: 'transparent', color: t.text, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15, fontWeight: 600 }; }

Object.assign(window, { buildTodayPlan, BLOQUES, CARE_COLOR, todayKey, TodayCard, CareRow, PostCitaCard, PostCitaSheet, btnPrimary, btnGhost });
