// vita-services.jsx — Services hub + 4 modules: Telemedicina, Nutrición, Psicología, Diagnóstico

const SERVICES = [
  { id: 'citas', icon: 'video', titulo: 'Citas y telemedicina', desc: 'Agenda con tu EPS o plan. Vita lo gestiona.', tag: 'HealthSings' },
  { id: 'nutricion', icon: 'food', titulo: 'Nutrición', desc: 'Tu plan y el nutriólogo ideal para ti.', tag: null },
  { id: 'psicologia', icon: 'brain', titulo: 'Psicología', desc: 'Seguimiento de tu ánimo y tu tratamiento.', tag: null },
  { id: 'diagnostico', icon: 'lab', titulo: 'Diagnóstico', desc: 'Laboratorios, estudios y dónde reclamar.', tag: null },
];

function ServiceHeader({ t, persona, titulo, sub, onBack, right }) {
  return (
    <div style={{ paddingTop: 58, padding: '58px 18px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        <IconBtn t={t} onClick={onBack} title="Volver"><span style={{ display: 'flex', transform: 'rotate(180deg)' }}>{Icon.chevron({ s: 18, c: t.textSoft, w: 2.5 })}</span></IconBtn>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 24, color: t.text, lineHeight: 1 }}>{titulo}</div>
          {sub && <div style={{ fontSize: 11.5, color: t.muted, fontWeight: 500, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>}
        </div>
      </div>
      {right}
    </div>
  );
}

// ── Hub ─────────────────────────────────────────────────────────
function ServicesScreen({ t, persona, profile, onOpen, onTalk, onToggleTheme, onOpenHome, onOpenHistory, onOpenProfile }) {
  return (
    <Stage t={t}>
      <div style={{ flex: 1, overflow: 'auto', padding: '58px 18px 96px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 30, color: t.text }}>Servicios</div>
          <IconBtn t={t} onClick={onToggleTheme} title="Tema">{t.dark ? Icon.sun({ s: 17 }) : Icon.moon({ s: 17 })}</IconBtn>
        </div>
        <p style={{ fontSize: 14.5, color: t.textSoft, margin: '0 2px 18px', fontWeight: 450, lineHeight: 1.5 }}>Vita coordina todo por ti, con tu EPS y nuestros aliados. Tú solo dices qué necesitas.</p>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {SERVICES.map(s => (
            <button key={s.id} onClick={() => onOpen(s.id)} style={{ textAlign: 'left', cursor: 'pointer', border: `1px solid ${t.stroke}`, borderRadius: 22, padding: 16, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', display: 'flex', flexDirection: 'column', gap: 10, minHeight: 150, WebkitTapHighlightColor: 'transparent', position: 'relative' }}>
              <div style={{ width: 46, height: 46, borderRadius: 14, display: 'grid', placeItems: 'center', background: `linear-gradient(135deg, ${hexA(persona.accent, 0.22)}, ${hexA(persona.accentDeep, 0.1)})` }}>{Icon[s.icon]({ s: 24, c: persona.accent })}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15.5, fontWeight: 700, color: t.text, lineHeight: 1.2 }}>{s.titulo}</div>
                <div style={{ fontSize: 12.5, color: t.muted, fontWeight: 450, lineHeight: 1.4, marginTop: 4 }}>{s.desc}</div>
              </div>
              {s.tag && <span style={{ position: 'absolute', top: 14, right: 14, fontSize: 9.5, fontWeight: 800, letterSpacing: 0.4, color: persona.accent, background: hexA(persona.accent, 0.14), padding: '3px 7px', borderRadius: 6 }}>{s.tag}</span>}
            </button>
          ))}
        </div>

        <button onClick={onTalk} style={{ width: '100%', marginTop: 16, display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 18, cursor: 'pointer', border: `1px solid ${hexA(persona.accent, 0.3)}`, background: hexA(persona.accent, t.dark ? 0.08 : 0.05), textAlign: 'left', WebkitTapHighlightColor: 'transparent' }}>
          <VitaDot t={t} size={34} active />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text }}>"Vita, agéndame una cita"</div>
            <div style={{ fontSize: 12.5, color: t.textSoft, fontWeight: 450 }}>Pídeme cualquier servicio por voz.</div>
          </div>
          {Icon.mic({ s: 20, c: persona.accent })}
        </button>
      </div>
      <BottomNav t={t} persona={persona} active="servicios" onTalk={onTalk} onOpenHome={onOpenHome} onOpenHistory={onOpenHistory} onOpenProfile={onOpenProfile} onOpenServices={() => {}} />
    </Stage>
  );
}

// ════ 1. CITAS / TELEMEDICINA (HealthSings) ════════════════════
const MOTIVOS_CITA = [
  { k: 'general', label: 'Medicina general', icon: 'pulse' },
  { k: 'especialista', label: 'Especialista', icon: 'heart' },
  { k: 'control', label: 'Control', icon: 'calendar' },
  { k: 'urgente', label: 'Me siento mal hoy', icon: 'alert' },
];
function CitasService({ t, persona, profile, onBack, onSchedule, onEnterCall }) {
  const [step, setStep] = React.useState('motivo'); // motivo | buscando | confirmada
  const [motivo, setMotivo] = React.useState(null);
  const accent = persona.accent;
  const cobertura = [profile.eps, profile.prepagada && profile.prepagada !== 'Ninguna' ? profile.prepagada : null].filter(Boolean).join(' · ') || 'Tu EPS';

  const pick = (m) => {
    setMotivo(m); setStep('buscando');
    setTimeout(() => setStep('confirmada'), 2600);
  };
  const slot = { fecha: 'Mañana', hora: '10:30 a.m.', modalidad: 'Videollamada', medico: 'Dra. Liliana Gómez', esp: motivo && motivo.k === 'especialista' ? 'Cardiología' : 'Medicina general' };

  return (
    <Stage t={t}>
      <ServiceHeader t={t} persona={persona} titulo="Citas y telemedicina" sub={cobertura} onBack={onBack} />
      <div style={{ flex: 1, overflow: 'auto', padding: '14px 18px 30px' }}>
        {/* HealthSings partner banner */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: 13, borderRadius: 16, marginBottom: 18, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
          <div style={{ width: 38, height: 38, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14) }}>{Icon.video({ s: 20, c: accent })}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: t.text }}>Telemedicina con IA · HealthSings</div>
            <div style={{ fontSize: 12, color: t.muted, fontWeight: 450 }}>PREVENT gestiona y conecta con tu plan</div>
          </div>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: t.green, boxShadow: `0 0 0 3px ${hexA(t.green, 0.2)}` }} />
        </div>

        {step === 'motivo' && (
          <>
            <div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginBottom: 4 }}>¿Para qué necesitas la cita?</div>
            <div style={{ fontSize: 13, color: t.muted, marginBottom: 16, fontWeight: 450 }}>Vita busca el cupo y la gestiona con tu EPS.</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {MOTIVOS_CITA.map(m => (
                <button key={m.k} onClick={() => pick(m)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: 15, borderRadius: 16, cursor: 'pointer', border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', textAlign: 'left', WebkitTapHighlightColor: 'transparent' }}>
                  <span style={{ width: 42, height: 42, borderRadius: 12, display: 'grid', placeItems: 'center', background: hexA(accent, 0.13) }}>{Icon[m.icon]({ s: 21, c: m.k === 'urgente' ? t.coral : accent })}</span>
                  <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: t.text }}>{m.label}</span>
                  {Icon.chevron({ s: 18, c: t.muted })}
                </button>
              ))}
            </div>
          </>
        )}

        {step === 'buscando' && (
          <div style={{ textAlign: 'center', padding: '50px 20px' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}><Spinner c={accent} /></div>
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 23, color: t.text, marginBottom: 8 }}>Conectando con HealthSings…</div>
            <ConnectingSteps t={t} accent={accent} steps={['Verificando tu cobertura con ' + (profile.eps || 'tu EPS'), 'Buscando el primer cupo disponible', 'Reservando tu videollamada']} />
          </div>
        )}

        {step === 'confirmada' && (
          <div style={{ animation: 'vitaIn .4s both' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 13px', borderRadius: 999, background: hexA(t.green, 0.16), color: t.green, fontSize: 12.5, fontWeight: 700, marginBottom: 14 }}>{Icon.check({ s: 14, c: t.green, w: 3 })} Cita confirmada</div>
            <div style={{ borderRadius: 22, overflow: 'hidden', border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', marginBottom: 16 }}>
              <div style={{ padding: 18, background: `linear-gradient(135deg, ${hexA(accent, 0.2)}, ${hexA(accent, 0.05)})`, display: 'flex', alignItems: 'center', gap: 13 }}>
                <div style={{ width: 50, height: 50, borderRadius: 14, display: 'grid', placeItems: 'center', background: accent }}>{Icon.video({ s: 26, c: t.onAccent })}</div>
                <div><div style={{ fontSize: 17, fontWeight: 700, color: t.text }}>{slot.medico}</div><div style={{ fontSize: 13, color: t.textSoft, fontWeight: 500 }}>{slot.esp} · {slot.modalidad}</div></div>
              </div>
              <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[['Cuándo', slot.fecha + ' · ' + slot.hora], ['Cómo', 'Videollamada con IA de apoyo (HealthSings)'], ['Cobertura', cobertura]].map(([k, v], i) => (
                  <div key={i} style={{ display: 'flex', gap: 12 }}><span style={{ width: 78, flexShrink: 0, fontSize: 12.5, color: t.muted, fontWeight: 600 }}>{k}</span><span style={{ fontSize: 13.5, color: t.text, fontWeight: 500 }}>{v}</span></div>
                ))}
              </div>
            </div>
            <button onClick={() => onEnterCall && onEnterCall({ esp: slot.esp, medico: slot.medico, motivo: motivo && motivo.k })} style={{ width: '100%', padding: '15px', borderRadius: 15, border: 'none', cursor: 'pointer', 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, boxShadow: `0 10px 26px ${hexA(accent, 0.4)}` }}>{Icon.video({ s: 19, c: t.onAccent })} Entrar a la consulta ahora</button>
            <button onClick={() => onSchedule && onSchedule({ id: 'cita' + Date.now(), tipo: 'cita', titulo: slot.esp + ' — ' + slot.medico, detalle: slot.fecha + ' ' + slot.hora + ' · videollamada', estado: 'agendado' })} style={{ width: '100%', marginTop: 9, padding: '14px', borderRadius: 14, border: `1px solid ${t.strokeStrong}`, cursor: 'pointer', background: 'transparent', color: t.text, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 14.5, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>{Icon.bell({ s: 17, c: t.textSoft })} Es más tarde · recúérdamela</button>
            <button onClick={() => { setStep('motivo'); setMotivo(null); }} style={{ width: '100%', marginTop: 8, border: 'none', background: 'transparent', cursor: 'pointer', color: t.muted, fontSize: 13, fontWeight: 500, fontFamily: 'Hanken Grotesk, sans-serif' }}>Agendar otra</button>
          </div>
        )}
      </div>
    </Stage>
  );
}

function ConnectingSteps({ t, accent, steps }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => { const iv = setInterval(() => setN(x => Math.min(steps.length, x + 1)), 750); return () => clearInterval(iv); }, []);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9, maxWidth: 270, margin: '0 auto', textAlign: 'left' }}>
      {steps.map((s, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 9, opacity: i <= n ? 1 : 0.3, transition: 'opacity .3s' }}>
          <span style={{ width: 20, height: 20, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: i < n ? t.green : 'transparent', border: i >= n ? `2px solid ${t.stroke}` : 'none' }}>{i < n && Icon.check({ s: 12, c: '#fff', w: 3 })}</span>
          <span style={{ fontSize: 13, color: t.textSoft, fontWeight: 500 }}>{s}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { SERVICES, ServicesScreen, ServiceHeader, CitasService, ConnectingSteps });
