// vita-telemed2.jsx — Live call (patient POV) + Vita copilot + AI-generated closing note

// The scripted consult — drives live captions + Vita's copilot. (Live insights scripted; closing note = real AI.)
function buildConsultScript(profile) {
  const n = (profile.nombre || 'Daniela').split(' ')[0];
  const med = (Array.isArray(profile.medicamentos) ? profile.medicamentos[0] : profile.medicamentos) || 'Losartán 50mg';
  return [
    { t: 0, speaker: 'doctor', text: `Hola ${n}, qué gusto verte. ¿Cómo te has sentido estas semanas?` },
    { t: 3.4, vita: { tipo: 'prompt', text: 'Cuéntale del dolor de cabeza en las mañanas 💛' } },
    { t: 5.2, speaker: 'paciente', text: 'Bien doctora, aunque he amanecido con dolor de cabeza varios días.' },
    { t: 8.6, vita: { tipo: 'data', text: 'Compartí con la Dra.: PA promedio 7 días — 138/88 mmHg' } },
    { t: 10.4, speaker: 'doctor', text: '¿Has tomado el ' + med + ' todos los días?' },
    { t: 13, vita: { tipo: 'data', text: 'Adherencia confirmada: 12 días consecutivos ✓' } },
    { t: 14.6, speaker: 'paciente', text: 'Sí, sin falta, todas las mañanas.' },
    { t: 17.4, vita: { tipo: 'alert', text: 'Bandera: sueño ~5 h/noche puede elevar la presión y dar cefalea' } },
    { t: 20, speaker: 'doctor', text: 'Tu presión está casi en meta. La cefalea puede venir del poco sueño. Vamos a cuidarlo.' },
    { t: 24, vita: { tipo: 'prompt', text: 'Pregúntale si sigues con la misma dosis' } },
    { t: 26, speaker: 'paciente', text: '¿Sigo con la misma dosis entonces?' },
    { t: 28.6, speaker: 'doctor', text: 'Sí, mantenemos la dosis. Pediré un perfil lipídico de control y te veo en tres meses.' },
    { t: 32.6, vita: { tipo: 'order', text: 'Orden creada: Perfil lipídico (control 1 mes)' } },
    { t: 34.4, vita: { tipo: 'order', text: 'Control agendado: Cardiología en 3 meses' } },
    { t: 36.2, speaker: 'doctor', text: 'Cuídate mucho, ' + n + '. Vita te deja todo anotado.' },
    { t: 39, end: true },
  ];
}

function scriptToTranscript(script) {
  return script.filter(s => s.speaker).map(s => (s.speaker === 'doctor' ? 'Dra. Gómez' : 'Paciente') + ': ' + s.text).join('\n');
}

const VITA_EVENT = {
  prompt: { label: 'Para ti', color: '#3DD9D6', icon: 'heart' },
  data: { label: 'Vita → Dra.', color: '#5BC0EB', icon: 'pulse' },
  alert: { label: 'Atención', color: '#E6A93C', icon: 'alert' },
  order: { label: 'Orden', color: '#73C58E', icon: 'check' },
};

// ── Live call ───────────────────────────────────────────────────
function CallScreen({ t, persona, profile, cam, onEnd }) {
  const accent = persona.accent;
  const script = React.useMemo(() => buildConsultScript(profile), [profile]);
  const [elapsed, setElapsed] = React.useState(0);
  const [caption, setCaption] = React.useState(null);
  const [feed, setFeed] = React.useState([]); // vita events
  const [docSpeaking, setDocSpeaking] = React.useState(true);
  const feedRef = React.useRef(null);
  const firedRef = React.useRef(new Set());
  const startRef = React.useRef(Date.now());

  React.useEffect(() => {
    const iv = setInterval(() => {
      const sec = (Date.now() - startRef.current) / 1000;
      setElapsed(sec);
      script.forEach((ev, i) => {
        if (ev.t <= sec && !firedRef.current.has(i)) {
          firedRef.current.add(i);
          if (ev.end) { setTimeout(() => onEnd(scriptToTranscript(script)), 600); return; }
          if (ev.speaker) { setCaption({ speaker: ev.speaker, text: ev.text }); setDocSpeaking(ev.speaker === 'doctor'); }
          if (ev.vita) setFeed(f => [...f, { ...ev.vita, id: i }]);
        }
      });
    }, 200);
    return () => clearInterval(iv);
  }, [script]);

  React.useEffect(() => { if (feedRef.current) feedRef.current.scrollTop = feedRef.current.scrollHeight; }, [feed]);

  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(Math.floor(elapsed % 60)).padStart(2, '0');

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', background: '#05101f', display: 'flex', flexDirection: 'column', fontFamily: 'Hanken Grotesk, sans-serif' }}>
      {/* doctor "video" presence */}
      <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(110% 70% at 50% 30%, ${hexA(persona.accentDeep, 0.4)} 0%, #071426 55%, #04101f 100%)` }}>
        <div style={{ position: 'absolute', top: '26%', left: 0, right: 0, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <div style={{ position: 'relative', width: 128, height: 128 }}>
            {docSpeaking && <span style={{ position: 'absolute', inset: -10, borderRadius: '50%', border: `2px solid ${hexA(accent, 0.5)}`, animation: 'vitaRipple 1.6s ease-out infinite' }} />}
            <div style={{ width: 128, height: 128, borderRadius: '50%', background: `linear-gradient(135deg, ${accent}, ${persona.accentDeep})`, display: 'grid', placeItems: 'center', color: '#fff', fontFamily: 'Instrument Serif, serif', fontSize: 52, boxShadow: `0 16px 50px ${hexA(accent, 0.45)}`, transform: docSpeaking ? 'scale(1.04)' : 'scale(1)', transition: 'transform .4s' }}>LG</div>
          </div>
          <div style={{ marginTop: 16, fontFamily: 'Instrument Serif, serif', fontSize: 23, color: '#fff' }}>Dra. Liliana Gómez</div>
          <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.5)', fontWeight: 500, marginTop: 1 }}>Cardiología · Hablando contigo</div>
        </div>
      </div>

      {/* top bar */}
      <div style={{ position: 'relative', paddingTop: 54, padding: '54px 16px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', zIndex: 5 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 12px', borderRadius: 999, background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(10px)' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#E15554', animation: 'vitaPulse 1.4s infinite' }} />
          <span style={{ fontSize: 12.5, fontWeight: 700, color: '#fff', fontVariantNumeric: 'tabular-nums' }}>{mm}:{ss}</span>
        </div>
        <HealthSingsChip t={t} state="e2e" compact />
      </div>

      {/* patient self-view PiP */}
      <div style={{ position: 'absolute', top: 96, right: 16, width: 92, height: 124, borderRadius: 16, overflow: 'hidden', zIndex: 6, border: '1.5px solid rgba(255,255,255,0.2)', boxShadow: '0 8px 24px rgba(0,0,0,0.4)', background: '#0a1830' }}>
        <video ref={cam.videoRef} muted playsInline style={{ width: '100%', height: '100%', objectFit: 'cover', transform: 'scaleX(-1)', opacity: cam.status === 'granted' && cam.camOn ? 1 : 0 }} />
        {(cam.status !== 'granted' || !cam.camOn) && <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', background: `linear-gradient(135deg, ${persona.accentDeep}, #0a1830)`, color: '#fff', fontFamily: 'Instrument Serif, serif', fontSize: 30 }}>{(profile.nombre || 'T').charAt(0)}</div>}
        <span style={{ position: 'absolute', bottom: 5, left: 6, fontSize: 9.5, fontWeight: 700, color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,0.6)' }}>Tú</span>
      </div>

      {/* spacer */}
      <div style={{ flex: 1 }} />

      {/* live caption */}
      {caption && (
        <div style={{ position: 'relative', zIndex: 5, padding: '0 18px 10px', animation: 'vitaIn .3s both' }} key={caption.text}>
          <div style={{ maxWidth: '90%', margin: '0 auto', padding: '10px 15px', borderRadius: 16, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(12px)', textAlign: 'center' }}>
            <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: 0.5, textTransform: 'uppercase', color: caption.speaker === 'doctor' ? hexA(accent, 0.95) : 'rgba(255,255,255,0.6)' }}>{caption.speaker === 'doctor' ? 'Dra. Gómez' : 'Tú'}</span>
            <div style={{ fontSize: 14.5, color: '#fff', lineHeight: 1.4, fontWeight: 450, marginTop: 2 }}>{caption.text}</div>
          </div>
        </div>
      )}

      {/* Vita copilot panel */}
      <div style={{ position: 'relative', zIndex: 5, margin: '0 12px', borderRadius: '20px 20px 0 0', background: t.dark ? 'rgba(10,22,42,0.9)' : 'rgba(12,26,48,0.92)', backdropFilter: 'blur(20px)', border: '1px solid rgba(255,255,255,0.1)', borderBottom: 'none', maxHeight: 188, display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 15px 8px' }}>
          <VitaDot t={t} size={22} active />
          <span style={{ fontSize: 12.5, fontWeight: 800, color: '#fff', letterSpacing: 0.3 }}>Vita te acompaña</span>
          <span style={{ marginLeft: 'auto', fontSize: 10.5, fontWeight: 600, color: 'rgba(255,255,255,0.45)' }}>en vivo · sin que escribas nada</span>
        </div>
        <div ref={feedRef} style={{ overflowY: 'auto', padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: 7 }}>
          {feed.length === 0 && <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.4)', padding: '4px 4px 8px', fontWeight: 450 }}>Estoy escuchando. Te voy ayudando con lo importante…</div>}
          {feed.map(ev => {
            const m = VITA_EVENT[ev.tipo] || VITA_EVENT.data;
            return (
              <div key={ev.id} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', padding: '9px 11px', borderRadius: 12, background: hexA(m.color, 0.12), border: `1px solid ${hexA(m.color, 0.3)}`, animation: 'vitaIn .35s both' }}>
                <span style={{ width: 22, height: 22, borderRadius: 7, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(m.color, 0.22), marginTop: 1 }}>{Icon[m.icon]({ s: 13, c: m.color })}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase', color: m.color, marginBottom: 1 }}>{m.label}</div>
                  <div style={{ fontSize: 13, color: '#fff', lineHeight: 1.35, fontWeight: 450 }}>{ev.text}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* controls */}
      <div style={{ position: 'relative', zIndex: 5, padding: '12px 18px 30px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, background: t.dark ? 'rgba(10,22,42,0.9)' : 'rgba(12,26,48,0.92)', backdropFilter: 'blur(20px)' }}>
        <CallBtn onClick={cam.toggleMic} off={!cam.micOn} icon="mic" />
        <CallBtn onClick={cam.toggleCam} off={!cam.camOn} icon="video" />
        <button onClick={() => onEnd(scriptToTranscript(script))} style={{ width: 64, height: 64, borderRadius: '50%', border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: '#E15554', boxShadow: '0 10px 26px rgba(225,85,84,0.5)', color: '#fff', transform: 'rotate(135deg)' }}>{Icon.video({ s: 26, c: '#fff' })}</button>
        <CallBtn onClick={() => {}} icon="volume" />
        <CallBtn onClick={() => {}} icon="mic" hidden />
      </div>
    </div>
  );
}

function CallBtn({ onClick, off, icon, hidden }) {
  if (hidden) return <div style={{ width: 52 }} />;
  return (
    <button onClick={onClick} style={{ width: 52, height: 52, borderRadius: '50%', border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: off ? '#E15554' : 'rgba(255,255,255,0.16)', backdropFilter: 'blur(10px)', color: '#fff', position: 'relative', WebkitTapHighlightColor: 'transparent' }}>
      {Icon[icon]({ s: 22, c: '#fff' })}
      {off && <span style={{ position: 'absolute', width: 2, height: 30, background: '#fff', transform: 'rotate(45deg)', borderRadius: 2 }} />}
    </button>
  );
}

// ── Closing summary (Vita generated note + orders via real AI) ──
function ClosingSummary({ t, persona, profile, nota, loading, onDone }) {
  const accent = persona.accent;
  return (
    <Stage t={t}>
      <div style={{ flex: 1, overflow: 'auto', padding: '64px 20px 20px' }}>
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}><Waveform state="speaking" variant="espejo" accent={accent} accentDeep={persona.accentDeep} size={104} /></div>
          <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: 8 }}>{Icon.check({ s: 14, c: t.green, w: 3 })} Consulta terminada</div>
          <h2 style={{ fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 28, lineHeight: 1.1, color: t.text, margin: '0 0 6px' }}>Yo me encargo del resto</h2>
          <p style={{ fontSize: 14.5, color: t.textSoft, lineHeight: 1.5, maxWidth: 300, margin: '0 auto', fontWeight: 450 }}>No tuviste que escribir nada. Tomé nota de todo y dejé lo importante listo en tu historia.</p>
        </div>

        {loading || !nota ? (
          <div style={{ textAlign: 'center', padding: '30px 20px' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}><Spinner c={accent} /></div>
            <div style={{ fontSize: 14, color: t.textSoft, fontWeight: 500 }}>Vita está escribiendo tu nota clínica…</div>
          </div>
        ) : (
          <div style={{ animation: 'vitaIn .4s both' }}>
            {/* resumen */}
            <div style={{ borderRadius: 18, padding: 16, marginBottom: 12, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
              <SecTitle t={t}>Resumen de tu consulta</SecTitle>
              <p style={{ fontSize: 14, color: t.text, lineHeight: 1.5, margin: 0, fontWeight: 450 }}>{nota.resumen}</p>
            </div>

            {/* indicaciones */}
            {nota.indicaciones && nota.indicaciones.length > 0 && (
              <div style={{ borderRadius: 18, padding: 16, marginBottom: 12, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
                <SecTitle t={t}>Lo que te indicó la doctora</SecTitle>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {nota.indicaciones.map((ind, i) => (
                    <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                      <span style={{ width: 22, height: 22, flexShrink: 0, borderRadius: 7, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14), color: accent, marginTop: 1 }}>{Icon.check({ s: 13, c: accent, w: 3 })}</span>
                      <span style={{ fontSize: 14, color: t.text, fontWeight: 450, lineHeight: 1.4 }}>{ind}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* ordenes → seguimiento */}
            {nota.ordenes && nota.ordenes.length > 0 && (
              <div style={{ borderRadius: 18, padding: 16, marginBottom: 12, background: hexA(accent, t.dark ? 0.1 : 0.06), border: `1px solid ${hexA(accent, 0.25)}` }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 11 }}>{Icon.sparkle({ s: 16, c: accent })}<span style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.5, textTransform: 'uppercase', color: accent }}>Vita ya gestionó por ti</span></div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                  {nota.ordenes.map((o, i) => (
                    <div key={i} style={{ display: 'flex', gap: 11, alignItems: 'center', padding: '10px 12px', borderRadius: 12, background: t.dark ? 'rgba(255,255,255,0.05)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
                      <span style={{ width: 36, height: 36, flexShrink: 0, borderRadius: 10, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14) }}>{Icon[o.tipo === 'laboratorio' ? 'lab' : o.tipo === 'cita' ? 'calendar' : o.tipo === 'medicamento' ? 'pill' : 'scan']({ s: 18, c: accent })}</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{o.titulo}</div>
                        <div style={{ fontSize: 12.5, color: t.muted, fontWeight: 500 }}>{o.detalle}</div>
                      </div>
                      {Icon.check({ s: 16, c: t.green, w: 3 })}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
      <div style={{ padding: '8px 20px 40px' }}>
        <button onClick={onDone} style={{ width: '100%', padding: '16px', borderRadius: 16, border: 'none', cursor: 'pointer', background: `linear-gradient(135deg, ${accent}, ${persona.accentDeep})`, color: t.onAccent, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 16, fontWeight: 700, boxShadow: `0 12px 30px ${hexA(accent, 0.4)}` }}>Listo, gracias Vita</button>
      </div>
    </Stage>
  );
}

// ── Orchestrator: waiting → call → closing ──────────────────────
function TelemedExperience({ t, persona, profile, asis, cita, onExit, onAddOrders }) {
  const [phase, setPhase] = React.useState('waiting'); // waiting | call | closing
  const [prep, setPrep] = React.useState(null);
  const [prepLoading, setPrepLoading] = React.useState(true);
  const [nota, setNota] = React.useState(null);
  const [notaLoading, setNotaLoading] = React.useState(false);
  const cam = useCamera(phase === 'waiting' || phase === 'call');
  const ordersAddedRef = React.useRef(false);

  React.useEffect(() => {
    let alive = true;
    prepConsulta(profile, asis, cita && cita.motivo).then(p => { if (alive) { setPrep(p); setPrepLoading(false); } });
    return () => { alive = false; };
  }, []);

  const endCall = (transcript) => {
    setPhase('closing');
    setNotaLoading(true);
    generateConsultaNota(profile, asis, transcript, cita && cita.motivo).then(nt => {
      setNota(nt); setNotaLoading(false);
      // push orders to seguimiento once
      if (!ordersAddedRef.current && onAddOrders) {
        ordersAddedRef.current = true;
        const items = (nt.ordenes || []).map((o, i) => ({
          id: 'tm-' + Date.now() + '-' + i,
          tipo: o.tipo === 'laboratorio' ? 'laboratorio' : o.tipo === 'cita' ? 'cita' : o.tipo === 'medicamento' ? 'medicamento' : 'examen',
          titulo: o.titulo, detalle: (o.detalle || '') + ' · de tu teleconsulta', estado: 'agendado',
        }));
        onAddOrders(items);
      }
    });
  };

  if (phase === 'waiting') return <WaitingRoom t={t} persona={persona} profile={profile} prep={prep} prepLoading={prepLoading} cam={cam} cita={cita} onEnter={() => setPhase('call')} onCancel={() => onExit()} />;
  if (phase === 'call') return <CallScreen t={t} persona={persona} profile={profile} cam={cam} onEnd={endCall} />;
  return <ClosingSummary t={t} persona={persona} profile={profile} nota={nota} loading={notaLoading} onDone={() => onExit(nota)} />;
}

Object.assign(window, { buildConsultScript, scriptToTranscript, CallScreen, ClosingSummary, TelemedExperience });
