// vita-track.jsx — Seguimiento (Vita manages pending items), living-ASIS add+changelog, PIC plan

const PIC_ICON = { heart: 'heart', sueno: 'moon', actividad: 'pulse', alimentacion: 'food', animo: 'animo' };
const picIcon = (k) => Icon[PIC_ICON[k] || k] || Icon.heart;
const SEG_ICON = { cita: 'calendar', examen: 'scan', laboratorio: 'lab', medicamento: 'pill' };
window.SEG_ICON = SEG_ICON;

const SEG_META = {
  cita: { label: 'Cita', icon: 'calendar', done: 'agendado', doneLabel: 'Agendada', action: 'Agéndame esta cita' },
  examen: { label: 'Examen', icon: 'scan', done: 'agendado', doneLabel: 'Programado', action: 'Prográmame el examen' },
  laboratorio: { label: 'Laboratorio', icon: 'lab', done: 'agendado', doneLabel: 'Programado', action: 'Prográmame el laboratorio' },
  medicamento: { label: 'Medicamento', icon: 'pill', done: 'activo', doneLabel: 'Recordatorio activo', action: 'Recuérdame tomarlo' },
};
const estadoMeta = (t, e) => ({
  pendiente: { label: 'Pendiente', color: '#E6A93C' },
  gestionando: { label: 'Vita gestionando…', color: t.accent },
  agendado: { label: 'Agendado', color: t.green },
  activo: { label: 'Recordatorio activo', color: t.green },
  completado: { label: 'Hecho', color: t.green },
}[e] || { label: e, color: t.muted });

// ── Seguimiento section on home ─────────────────────────────────
function SeguimientoSection({ t, persona, items, onOpen }) {
  if (!items || !items.length) return null;
  const pend = items.filter(i => i.estado === 'pendiente').length;
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '4px 4px 10px' }}>
        <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: t.muted }}>Vita está pendiente de</span>
        {pend > 0 && <span style={{ fontSize: 11.5, fontWeight: 700, color: '#E6A93C', background: hexA('#E6A93C', 0.16), padding: '3px 9px', borderRadius: 999 }}>{pend} por gestionar</span>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {items.map(it => {
          const meta = SEG_META[it.tipo] || SEG_META.cita;
          const em = estadoMeta(t, it.estado);
          return (
            <button key={it.id} onClick={() => onOpen(it)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: 13, borderRadius: 16, cursor: 'pointer', textAlign: 'left', width: '100%',
              border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', WebkitTapHighlightColor: 'transparent',
            }}>
              <span style={{ width: 42, height: 42, flexShrink: 0, borderRadius: 12, display: 'grid', placeItems: 'center', background: hexA(em.color, 0.14) }}>{Icon[meta.icon]({ s: 21, c: em.color })}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.titulo}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: em.color, animation: it.estado === 'gestionando' ? 'vitaPulse 1.2s infinite' : 'none' }} />
                  <span style={{ fontSize: 12, fontWeight: 600, color: em.color }}>{em.label}</span>
                  <span style={{ fontSize: 12, color: t.muted }}>· {meta.label}</span>
                </div>
              </div>
              {Icon.chevron({ s: 17, c: t.muted })}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ── Item action sheet — Vita takes charge ───────────────────────
function SegActionSheet({ t, persona, item, onClose, onAdvance }) {
  const meta = SEG_META[item.tipo] || SEG_META.cita;
  const em = estadoMeta(t, item.estado);
  const isDone = ['agendado', 'activo', 'completado'].includes(item.estado);
  const gestionando = item.estado === 'gestionando';
  return (
    <Sheet t={t} onClose={onClose}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <span style={{ width: 48, height: 48, borderRadius: 14, display: 'grid', placeItems: 'center', background: hexA(em.color, 0.15) }}>{Icon[meta.icon]({ s: 24, c: em.color })}</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: em.color }}>{meta.label}</div>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 23, color: t.text, lineHeight: 1.15 }}>{item.titulo}</div>
        </div>
      </div>
      {item.detalle && <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '0 0 16px', fontWeight: 450 }}>{item.detalle}</p>}

      {/* status timeline */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 14px', borderRadius: 14, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FBFCFE', border: `1px solid ${t.stroke}`, marginBottom: 18 }}>
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: em.color, animation: gestionando ? 'vitaPulse 1.2s infinite' : 'none' }} />
        <span style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{em.label}</span>
        {isDone && <span style={{ marginLeft: 'auto', color: t.green, display: 'flex' }}>{Icon.check({ s: 18, c: t.green, w: 3 })}</span>}
      </div>

      {isDone ? (
        <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: 14, borderRadius: 14, background: hexA(t.green, 0.1), border: `1px solid ${hexA(t.green, 0.3)}`, marginBottom: 4 }}>
          <VitaDot t={t} size={26} />
          <span style={{ fontSize: 13.5, color: t.textSoft, lineHeight: 1.45, fontWeight: 450 }}>
            {item.tipo === 'medicamento' ? 'Listo, te recuerdo tomarlo a tiempo y aviso cuando se acabe.' : 'Yo me encargo de coordinarlo con tu EPS y te aviso apenas tenga la fecha. Tú tranquilo.'}
          </span>
        </div>
      ) : (
        <button disabled={gestionando} onClick={() => onAdvance(item)} style={{
          width: '100%', padding: '15px', borderRadius: 15, border: 'none', cursor: gestionando ? 'default' : 'pointer',
          background: gestionando ? hexA(persona.accent, 0.3) : `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})`, color: t.onAccent,
          fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
        }}>
          {gestionando ? <><Spinner c={t.onAccent} /> Vita lo está gestionando…</> : <>{Icon.sparkle({ s: 17, c: t.onAccent })} {meta.action}</>}
        </button>
      )}
    </Sheet>
  );
}

// ── Add information (living ASIS) ───────────────────────────────
const ADD_OPTIONS = [
  { key: 'Resultado de laboratorio', icon: 'lab' },
  { key: 'Examen o imagen médica', icon: 'scan' },
  { key: 'Resumen de visita al médico', icon: 'doc' },
  { key: 'Nuevo medicamento', icon: 'pill' },
  { key: 'Cómo me he sentido', icon: 'animo' },
];

function AddInfoSheet({ t, persona, onClose, onAdd }) {
  const [pick, setPick] = React.useState(null);
  const accent = persona.accent;
  return (
    <Sheet t={t} onClose={onClose}>
      <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 26, color: t.text, marginBottom: 4 }}>Alimenta tu historia</div>
      <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '0 0 16px', fontWeight: 450 }}>Súbeme algo nuevo y actualizo tu análisis al instante. Entre más me das, mejor te cuido.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {ADD_OPTIONS.map(o => (
          <button key={o.key} onClick={() => setPick(o.key)} style={{
            display: 'flex', alignItems: 'center', gap: 13, padding: 14, borderRadius: 15, cursor: 'pointer', textAlign: 'left', width: '100%',
            border: `1.5px solid ${pick === o.key ? accent : t.stroke}`, background: pick === o.key ? hexA(accent, 0.1) : (t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF'), WebkitTapHighlightColor: 'transparent', transition: 'all .15s',
          }}>
            <span style={{ width: 40, height: 40, flexShrink: 0, borderRadius: 12, display: 'grid', placeItems: 'center', background: hexA(accent, 0.13) }}>{Icon[o.icon]({ s: 21, c: accent })}</span>
            <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: t.text }}>{o.key}</span>
            <span style={{ width: 22, height: 22, borderRadius: '50%', border: `2px solid ${pick === o.key ? accent : t.strokeStrong}`, background: pick === o.key ? accent : 'transparent', display: 'grid', placeItems: 'center' }}>{pick === o.key && Icon.check({ s: 13, c: t.onAccent, w: 3 })}</span>
          </button>
        ))}
      </div>
      <button disabled={!pick} onClick={() => onAdd(pick)} style={{
        width: '100%', marginTop: 18, padding: '15px', borderRadius: 15, border: 'none', cursor: pick ? 'pointer' : 'default', opacity: pick ? 1 : 0.45,
        background: `linear-gradient(135deg, ${accent}, ${persona.accentDeep})`, color: t.onAccent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15.5, fontWeight: 700,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
      }}>{Icon.upload({ s: 18, c: t.onAccent })} Subir y actualizar mi ASIS</button>
    </Sheet>
  );
}

// reanalysis overlay
function ReanalyzeOverlay({ t, persona, waveStyle, nuevo }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 90, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 36, textAlign: 'center',
      background: t.dark ? 'rgba(6,18,43,0.94)' : 'rgba(244,247,251,0.96)', backdropFilter: 'blur(6px)', animation: 'vitaFade .25s both' }}>
      <Waveform state="thinking" variant={waveStyle} accent={persona.accent} accentDeep={persona.accentDeep} size={140} />
      <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 26, color: t.text, marginTop: 14 }}>Actualizando tu ASIS</div>
      <p style={{ fontSize: 14.5, color: t.textSoft, marginTop: 6, maxWidth: 260, lineHeight: 1.5, fontWeight: 450 }}>Estoy leyendo <b style={{ color: t.text }}>{nuevo}</b> y conectándolo con tu historia…</p>
    </div>
  );
}

// changelog banner shown on home after an update
function ChangelogBanner({ t, persona, cambios, version, onClose }) {
  if (!cambios || !cambios.length) return null;
  return (
    <div style={{ borderRadius: 20, padding: 16, marginBottom: 16, border: `1.5px solid ${hexA(persona.accent, 0.4)}`, background: `linear-gradient(135deg, ${hexA(persona.accent, 0.16)}, ${hexA(persona.accent, 0.04)})`, animation: 'vitaIn .4s both' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
        <span style={{ width: 30, height: 30, borderRadius: 9, display: 'grid', placeItems: 'center', background: persona.accent }}>{Icon.refresh({ s: 17, c: t.onAccent })}</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 800, color: t.text }}>Vita actualizó tu análisis</div>
          <div style={{ fontSize: 11.5, color: t.muted, fontWeight: 500 }}>Versión {version} · ahora mismo</div>
        </div>
        <button onClick={onClose} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: t.muted, display: 'grid', placeItems: 'center' }}>{Icon.x({ s: 18, c: t.muted })}</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {cambios.map((c, i) => (
          <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
            <span style={{ marginTop: 2, color: persona.accent, display: 'flex', flexShrink: 0 }}>{Icon.check({ s: 16, c: persona.accent, w: 3 })}</span>
            <span style={{ fontSize: 13.5, color: t.text, lineHeight: 1.4, fontWeight: 500 }}>{c}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── PIC — Programa de Intervención / Plan Preventivo ────────────
function PicActivateCard({ t, persona, ready, onActivate, generating }) {
  return (
    <div style={{ borderRadius: 22, padding: 18, marginBottom: 18, position: 'relative', overflow: 'hidden',
      background: `linear-gradient(135deg, ${hexA(persona.accent, 0.18)}, ${hexA(persona.accentDeep, 0.06)})`, border: `1.5px solid ${hexA(persona.accent, 0.4)}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        {Icon.shield({ s: 18, c: persona.accent })}
        <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: persona.accent }}>Plan preventivo · PIC</span>
      </div>
      <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 23, color: t.text, lineHeight: 1.15, marginBottom: 6 }}>Ya tengo lo mínimo para armar tu plan</div>
      <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '0 0 14px', fontWeight: 450 }}>
        Tu ASIS ya me dice por dónde empezar. Déjame construir tu <b style={{ color: t.text }}>Programa de Intervención</b> para cuidarte y sumar años de vida.
      </p>
      <button disabled={generating} onClick={onActivate} style={{
        width: '100%', padding: '14px', borderRadius: 15, border: 'none', cursor: generating ? 'default' : 'pointer',
        background: `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})`, color: t.onAccent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15.5, fontWeight: 700,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, boxShadow: `0 10px 24px ${hexA(persona.accent, 0.4)}`,
      }}>{generating ? <><Spinner c={t.onAccent} /> Armando tu plan…</> : <>{Icon.sparkle({ s: 17, c: t.onAccent })} Empezar mi plan preventivo</>}</button>
    </div>
  );
}

function PicSection({ t, persona, pic, onOpen }) {
  if (!pic) return null;
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '4px 4px 10px' }}>
        <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: t.muted }}>Tu plan preventivo · PIC</span>
        <button onClick={onOpen} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: persona.accent, fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 3, fontFamily: 'Hanken Grotesk, sans-serif' }}>Ver todo {Icon.chevron({ s: 14, c: persona.accent })}</button>
      </div>
      <div style={{ borderRadius: 20, padding: 16, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}`, marginBottom: 10 }}>
        <p style={{ fontSize: 14.5, color: t.textSoft, lineHeight: 1.5, margin: 0, fontWeight: 450 }}>{pic.enfoque}</p>
      </div>
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4 }}>
        {(pic.areas || []).map((a, i) => (
          <button key={i} onClick={onOpen} style={{ flexShrink: 0, width: 150, textAlign: 'left', cursor: 'pointer', borderRadius: 18, padding: 14, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', WebkitTapHighlightColor: 'transparent' }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(persona.accent, 0.14) }}>{picIcon(a.icono)({ s: 20, c: persona.accent })}</span>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, marginTop: 10 }}>{a.nombre}</div>
            <div style={{ fontSize: 12.5, color: t.muted, marginTop: 2, fontWeight: 500 }}>{a.meta}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

function PicSheet({ t, persona, pic, onClose }) {
  if (!pic) return null;
  return (
    <Sheet t={t} onClose={onClose} tall>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        {Icon.shield({ s: 18, c: persona.accent })}
        <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: persona.accent }}>Plan preventivo · PIC</span>
      </div>
      <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 27, color: t.text, lineHeight: 1.1, marginBottom: 8 }}>{pic.titulo}</div>
      <p style={{ fontSize: 14.5, color: t.textSoft, lineHeight: 1.5, margin: '0 0 18px', fontWeight: 450 }}>{pic.enfoque}</p>

      <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.5, textTransform: 'uppercase', color: t.muted, marginBottom: 10 }}>Áreas de intervención</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 20 }}>
        {(pic.areas || []).map((a, i) => (
          <div key={i} style={{ borderRadius: 16, padding: 15, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FBFCFE' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(persona.accent, 0.14) }}>{picIcon(a.icono)({ s: 20, c: persona.accent })}</span>
              <div><div style={{ fontSize: 15.5, fontWeight: 700, color: t.text }}>{a.nombre}</div><div style={{ fontSize: 12.5, color: persona.accent, fontWeight: 600 }}>{a.meta}</div></div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              {(a.acciones || []).map((ac, j) => (
                <div key={j} style={{ display: 'flex', gap: 9, alignItems: 'center' }}>
                  <span style={{ width: 18, height: 18, borderRadius: 6, flexShrink: 0, border: `1.5px solid ${t.strokeStrong}` }} />
                  <span style={{ fontSize: 13.5, color: t.text, fontWeight: 500 }}>{ac}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.5, textTransform: 'uppercase', color: t.muted, marginBottom: 10 }}>Metas que vamos a lograr</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {(pic.metas || []).map((m, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 13, borderRadius: 14, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF' }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(t.green, 0.14) }}>{picIcon(m.icono)({ s: 20, c: t.green })}</span>
            <span style={{ flex: 1, fontSize: 14.5, fontWeight: 600, color: t.text, lineHeight: 1.3 }}>{m.titulo}</span>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: persona.accent, background: hexA(persona.accent, 0.12), padding: '5px 10px', borderRadius: 999, whiteSpace: 'nowrap' }}>{m.plazo}</span>
          </div>
        ))}
      </div>
    </Sheet>
  );
}

// shared bottom sheet shell
function Sheet({ t, onClose, children, tall }) {
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 80, background: 'rgba(3,10,24,0.55)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-end', animation: 'vitaFade .2s ease both' }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxHeight: tall ? '88%' : '78%', overflow: 'auto', borderRadius: '26px 26px 0 0',
        background: t.dark ? t.bg1 : '#FFFFFF', border: `1px solid ${t.stroke}`, borderBottom: 'none',
        padding: '14px 22px 38px', animation: 'vitaSheet .32s cubic-bezier(.2,.8,.2,1) both',
      }}>
        <div style={{ width: 40, height: 5, borderRadius: 999, background: t.strokeStrong, margin: '0 auto 16px' }} />
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { SeguimientoSection, SegActionSheet, AddInfoSheet, ReanalyzeOverlay, ChangelogBanner, PicActivateCard, PicSection, PicSheet, Sheet });
