// vita-home.jsx — ASIS generation reveal + friendly patient home/dashboard

const DIM_ICON = { heart: 'heart', sueno: 'moon', actividad: 'pulse', alimentacion: 'food', animo: 'animo' };
const AMBER = '#E6A93C';
const estadoColor = (t, e) => e === 'bien' ? t.green : e === 'atencion' ? t.coral : AMBER;
const estadoLabel = (e) => e === 'bien' ? 'Bien' : e === 'atencion' ? 'Atención' : 'Cuidar';
const semColor = (t, e) => e === 'verde' ? t.green : e === 'rojo' ? t.coral : AMBER;

// ── ASIS generating / reveal ────────────────────────────────────
function AsisGenerating({ t, persona, waveStyle }) {
  const [step, setStep] = React.useState(0);
  const steps = ['Organizando lo que me contaste…', 'Revisando tus documentos…', 'Preparando tu análisis de salud…'];
  React.useEffect(() => {
    const iv = setInterval(() => setStep(s => Math.min(steps.length - 1, s + 1)), 1100);
    return () => clearInterval(iv);
  }, []);
  return (
    <Stage t={t}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 36px', textAlign: 'center' }}>
        <Waveform state="thinking" variant={waveStyle} accent={persona.accent} accentDeep={persona.accentDeep} size={150} />
        <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 30, color: t.text, margin: '18px 0 6px' }}>Tu ASIS</div>
        <div style={{ fontSize: 14, color: t.muted, marginBottom: 22, fontWeight: 500 }}>Análisis de Situación de Salud</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%', maxWidth: 280 }}>
          {steps.map((s, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, opacity: i <= step ? 1 : 0.35, transition: 'opacity .4s' }}>
              <span style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center',
                background: i < step ? t.green : i === step ? hexA(persona.accent, 0.18) : 'transparent', border: i >= step ? `2px solid ${t.stroke}` : 'none' }}>
                {i < step ? Icon.check({ s: 13, c: '#fff', w: 3 }) : i === step ? <span style={{ width: 8, height: 8, borderRadius: '50%', background: persona.accent, animation: 'vitaPulse 1.1s infinite' }} /> : null}
              </span>
              <span style={{ fontSize: 14, color: t.textSoft, fontWeight: 500, textAlign: 'left' }}>{s}</span>
            </div>
          ))}
        </div>
      </div>
    </Stage>
  );
}

// ── Home / dashboard ────────────────────────────────────────────
function HomeScreen({ t, persona, profile, asis, docs, seguimiento, pic, picReady, picGenerating, changelog, careTasks, careDone, onToggleCare, onOpenCare, postCita, onOpenPostCita, onDismissPostCita, notifCount, onOpenNotifs, onTalk, onAddInfo, onOpenSeg, onActivatePic, onOpenPic, onDismissChangelog, onShowHistory, onOpenHistory, onOpenProfile, onOpenServices, onShowSecurity, onToggleTheme }) {
  const name = (profile.nombre || 'persona').split(' ')[0];
  const sem = semColor(t, asis.estadoGeneral);
  const fechaRaw = new Date().toLocaleDateString('es-CO', { weekday: 'long', day: 'numeric', month: 'long' });
  const fecha = fechaRaw.charAt(0).toUpperCase() + fechaRaw.slice(1);
  const plan = profile.prepagada && profile.prepagada !== 'Ninguna' ? profile.prepagada : profile.eps;
  const scrollRef = React.useRef(null);
  // when Vita updates the ASIS, bring the changelog into view
  React.useEffect(() => {
    if (changelog && scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [changelog && changelog.version]);

  return (
    <Stage t={t}>
      <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '58px 18px 96px' }}>
        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 12.5, color: t.muted, fontWeight: 600 }}>{fecha}</div>
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 30, color: t.text, lineHeight: 1.1, marginTop: 2 }}>Hola, {name}</div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <button onClick={onOpenNotifs} title="Notificaciones" style={{ position: 'relative', width: 38, height: 38, borderRadius: 12, cursor: 'pointer', display: 'grid', placeItems: 'center', border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)', color: t.textSoft, WebkitTapHighlightColor: 'transparent' }}>
              {Icon.bell({ s: 18, c: t.textSoft })}
              {notifCount > 0 && <span style={{ position: 'absolute', top: -4, right: -4, minWidth: 18, height: 18, padding: '0 5px', borderRadius: 999, background: t.coral, color: '#fff', fontSize: 11, fontWeight: 800, display: 'grid', placeItems: 'center', border: `2px solid ${t.dark ? '#0a1a33' : '#fff'}` }}>{notifCount}</span>}
            </button>
            <IconBtn t={t} onClick={onToggleTheme} title="Tema">{t.dark ? Icon.sun({ s: 17 }) : Icon.moon({ s: 17 })}</IconBtn>
            <VitaDot t={t} size={38} />
          </div>
        </div>

        {/* changelog after a live update */}
        <ChangelogBanner t={t} persona={persona} cambios={changelog && changelog.cambios} version={changelog && changelog.version} onClose={onDismissChangelog} />

        {/* health status hero (semáforo) */}
        <button onClick={onTalk} style={{ width: '100%', textAlign: 'left', cursor: 'pointer', border: 'none', borderRadius: 24, padding: 20, marginBottom: 14,
          background: `linear-gradient(135deg, ${hexA(sem, 0.22)}, ${hexA(sem, 0.06)})`, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, borderRadius: 24, border: `1.5px solid ${hexA(sem, 0.35)}` }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(sem, 0.2), boxShadow: `0 0 0 6px ${hexA(sem, 0.1)}` }}>
              {Icon.heart({ s: 32, c: sem, fill: sem })}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: 0.8, textTransform: 'uppercase', color: sem }}>Tu salud hoy</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: t.text, lineHeight: 1.25, marginTop: 3 }}>{asis.estadoTexto}</div>
            </div>
          </div>
        </button>

        {/* ASIS summary */}
        <div style={{ borderRadius: 22, padding: 18, marginBottom: 16, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}`, boxShadow: t.shadow }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {Icon.sparkle({ s: 16, c: persona.accent })}
              <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: t.text }}>Tu análisis de salud</span>
            </div>
            {changelog && changelog.version > 1 && <span style={{ fontSize: 11, fontWeight: 700, color: t.muted }}>v{changelog.version}</span>}
          </div>
          <p style={{ fontSize: 15.5, lineHeight: 1.55, color: t.textSoft, margin: 0, fontWeight: 450 }}>{asis.resumen}</p>
          <button onClick={onAddInfo} style={{ marginTop: 14, width: '100%', padding: '12px', borderRadius: 13, cursor: 'pointer', border: `1.5px solid ${hexA(persona.accent, 0.4)}`, background: hexA(persona.accent, t.dark ? 0.1 : 0.06), color: persona.accent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 14, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, WebkitTapHighlightColor: 'transparent' }}>
            {Icon.plus({ s: 18, c: persona.accent })} Alimentar mi historia
          </button>
        </div>

        {/* post-cita proactive check-in */}
        {postCita && <PostCitaCard t={t} persona={persona} cita={postCita} onOpen={onOpenPostCita} onDismiss={onDismissPostCita} />}

        {/* Tu cuidado de hoy — proactive daily care */}
        {careTasks && careTasks.length > 0 && <TodayCard t={t} persona={persona} tasks={careTasks} done={careDone} onToggle={onToggleCare} onOpenCare={onOpenCare} />}

        {/* PIC: activate gate OR plan section */}
        {pic
          ? <PicSection t={t} persona={persona} pic={pic} onOpen={onOpenPic} />
          : picReady && <PicActivateCard t={t} persona={persona} ready onActivate={onActivatePic} generating={picGenerating} />}

        {/* Seguimiento — Vita manages pending items */}
        <SeguimientoSection t={t} persona={persona} items={seguimiento} onOpen={onOpenSeg} />

        {/* dimensiones */}
        <SectionTitle t={t}>¿Cómo estás por dentro?</SectionTitle>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
          {(asis.dimensiones || []).map((d, i) => {
            const col = estadoColor(t, d.estado);
            const ic = Icon[DIM_ICON[d.icono] || d.icono] || Icon.heart;
            return (
              <div key={i} style={{ borderRadius: 18, padding: 14, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ width: 38, height: 38, borderRadius: 12, display: 'grid', placeItems: 'center', background: hexA(col, 0.14) }}>{ic({ s: 20, c: col })}</div>
                  <span style={{ width: 11, height: 11, borderRadius: '50%', background: col, boxShadow: `0 0 0 4px ${hexA(col, 0.16)}` }} />
                </div>
                <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginTop: 11 }}>{d.nombre}</div>
                <div style={{ fontSize: 12, fontWeight: 700, color: col, marginTop: 1 }}>{estadoLabel(d.estado)}</div>
                <div style={{ fontSize: 12.5, color: t.muted, marginTop: 4, lineHeight: 1.35, fontWeight: 450 }}>{d.nota}</div>
              </div>
            );
          })}
        </div>

        {/* prioridades */}
        <SectionTitle t={t}>Lo que vamos a cuidar</SectionTitle>
        <div style={{ borderRadius: 20, overflow: 'hidden', background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}`, marginBottom: 18 }}>
          {(asis.prioridades || []).map((p, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 16px', borderTop: i ? `1px solid ${t.stroke}` : 'none' }}>
              <span style={{ width: 28, height: 28, borderRadius: 9, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(persona.accent, 0.14), color: persona.accent, fontWeight: 800, fontSize: 14 }}>{i + 1}</span>
              <span style={{ fontSize: 14.5, color: t.text, fontWeight: 500, lineHeight: 1.35 }}>{p}</span>
            </div>
          ))}
        </div>

        {/* seguro + documentos */}
        <SectionTitle t={t}>Tu seguro y documentos</SectionTitle>
        {plan && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 16, marginBottom: 10, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
            <span style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(persona.accent, 0.13) }}>{Icon.card({ s: 21, c: persona.accent })}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: t.muted }}>Tu cobertura</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{[profile.eps, profile.prepagada && profile.prepagada !== 'Ninguna' ? profile.prepagada : null].filter(Boolean).join(' · ') || plan}</div>
            </div>
          </div>
        )}
        <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4 }}>
          <button onClick={onAddInfo} style={{ flexShrink: 0, width: 96, height: 96, borderRadius: 16, cursor: 'pointer', border: `1.5px dashed ${t.strokeStrong}`, background: 'transparent', color: persona.accent, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            {Icon.plus({ s: 22, c: persona.accent })}
            <span style={{ fontSize: 11.5, fontWeight: 600, color: t.textSoft }}>Agregar</span>
          </button>
          {(docs && docs.length ? docs : ['Sin documentos aún']).map((d, i) => (
            docs && docs.length ? (
              <div key={i} style={{ flexShrink: 0, width: 96, height: 96, borderRadius: 16, padding: 11, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}`, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                {Icon.doc({ s: 22, c: persona.accent })}
                <span style={{ fontSize: 11.5, fontWeight: 600, color: t.text, lineHeight: 1.25, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>{d}</span>
              </div>
            ) : (
              <div key={i} style={{ display: 'flex', alignItems: 'center', color: t.muted, fontSize: 13, fontWeight: 450, paddingLeft: 4 }}>{d}</div>
            )
          ))}
        </div>
      </div>

      {/* bottom nav */}
      <BottomNav t={t} persona={persona} active="inicio" onTalk={onTalk} onShowHistory={onShowHistory} onOpenHistory={onOpenHistory} onOpenProfile={onOpenProfile} onOpenServices={onOpenServices} onShowSecurity={onShowSecurity} onAddInfo={onAddInfo} />
    </Stage>
  );
}

function SectionTitle({ t, children }) {
  return <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: t.muted, margin: '4px 4px 10px' }}>{children}</div>;
}

function BottomNav({ t, persona, onTalk, onShowHistory, onShowSecurity, onOpenHome, onOpenHistory, onOpenProfile, onOpenServices, active = 'inicio' }) {
  const item = (icon, label, isActive, onClick) => (
    <button onClick={onClick} style={{ flex: 1, border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '4px 0', color: isActive ? persona.accent : t.muted, WebkitTapHighlightColor: 'transparent' }}>
      {icon(isActive)}
      <span style={{ fontSize: 10.5, fontWeight: isActive ? 700 : 500 }}>{label}</span>
    </button>
  );
  return (
    <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, paddingBottom: 26, paddingTop: 8, display: 'flex', alignItems: 'center',
      background: t.dark ? 'linear-gradient(180deg, transparent, rgba(6,18,43,0.92) 40%)' : 'linear-gradient(180deg, transparent, rgba(244,247,251,0.95) 40%)', backdropFilter: 'blur(8px)' }}>
      {item((a) => Icon.home({ s: 23, c: a ? persona.accent : t.muted, fill: a ? hexA(persona.accent, 0.18) : 'none' }), 'Inicio', active === 'inicio', onOpenHome || (() => {}))}
      {item((a) => Icon.doc({ s: 23, c: a ? persona.accent : t.muted }), 'Historia', active === 'historia', onOpenHistory || onShowHistory)}
      <button onClick={onTalk} style={{ flexShrink: 0, margin: '0 6px', width: 60, height: 60, borderRadius: '50%', border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', marginTop: -22,
        background: `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})`, boxShadow: `0 10px 26px ${hexA(persona.accent, 0.5)}`, color: t.onAccent }}>
        {Icon.mic({ s: 26, c: t.onAccent })}
      </button>
      {item((a) => Icon.grid({ s: 22, c: a ? persona.accent : t.muted, fill: a ? hexA(persona.accent, 0.18) : 'none' }), 'Servicios', active === 'servicios', onOpenServices || (() => {}))}
      {item((a) => Icon.user({ s: 22, c: a ? persona.accent : t.muted }), 'Perfil', active === 'perfil', onOpenProfile || onShowHistory)}
    </div>
  );
}

Object.assign(window, { AsisGenerating, HomeScreen });
