// vita-telemed.jsx — Telemedicine (patient POV): orchestrator + waiting room + camera hook
// HealthSings modeled as the underlying RTC/API layer. Vita is the patient's copilot.

// ── Camera hook (real getUserMedia, graceful fallback) ──────────
function useCamera(active) {
  const videoRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const [status, setStatus] = React.useState('idle'); // idle | granted | denied | unavailable
  const [camOn, setCamOn] = React.useState(true);
  const [micOn, setMicOn] = React.useState(true);

  React.useEffect(() => {
    let cancelled = false;
    if (!active) return;
    async function start() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { setStatus('unavailable'); return; }
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } }, audio: true });
        if (cancelled) { stream.getTracks().forEach(t => t.stop()); return; }
        streamRef.current = stream;
        setStatus('granted');
        if (videoRef.current) { videoRef.current.srcObject = stream; videoRef.current.play().catch(() => {}); }
      } catch (e) { setStatus('denied'); }
    }
    start();
    return () => { cancelled = true; if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; } };
  }, [active]);

  const toggleCam = () => {
    const s = streamRef.current; if (!s) { setCamOn(c => !c); return; }
    s.getVideoTracks().forEach(t => { t.enabled = !t.enabled; }); setCamOn(s.getVideoTracks()[0] ? s.getVideoTracks()[0].enabled : false);
  };
  const toggleMic = () => {
    const s = streamRef.current; if (!s) { setMicOn(m => !m); return; }
    s.getAudioTracks().forEach(t => { t.enabled = !t.enabled; }); setMicOn(s.getAudioTracks()[0] ? s.getAudioTracks()[0].enabled : false);
  };

  return { videoRef, status, camOn, micOn, toggleCam, toggleMic };
}

// ── HealthSings connection chip (technical layer) ───────────────
function HealthSingsChip({ t, state = 'secure', compact }) {
  const map = {
    connecting: { label: 'Conectando · HealthSings', color: '#E6A93C', bars: 1 },
    secure: { label: 'Sala segura · HealthSings RTC', color: '#73C58E', bars: 3 },
    e2e: { label: 'Cifrado E2E · HealthSings', color: '#73C58E', bars: 3 },
  };
  const s = map[state] || map.secure;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: compact ? '4px 9px' : '5px 11px', borderRadius: 999, background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.14)' }}>
      <span style={{ display: 'flex', alignItems: 'flex-end', gap: 1.5, height: 11 }}>
        {[5, 8, 11].map((h, i) => <span key={i} style={{ width: 2.5, height: h, borderRadius: 1, background: i < s.bars ? s.color : 'rgba(255,255,255,0.25)' }} />)}
      </span>
      <span style={{ fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.92)', letterSpacing: 0.2 }}>{s.label}</span>
    </div>
  );
}

// ── Waiting room ────────────────────────────────────────────────
function WaitingRoom({ t, persona, profile, prep, prepLoading, cam, cita, onEnter, onCancel }) {
  const accent = persona.accent;
  const [phase, setPhase] = React.useState('prep'); // prep -> ready
  const steps = ['Estableciendo sala segura con HealthSings', 'Enviando tu resumen clínico al médico', 'Preparando tu acompañamiento con Vita'];
  const [stepN, setStepN] = React.useState(0);
  React.useEffect(() => {
    const iv = setInterval(() => setStepN(x => { if (x >= steps.length) { clearInterval(iv); return x; } return x + 1; }), 850);
    const tm = setTimeout(() => setPhase('ready'), 3100);
    return () => { clearInterval(iv); clearTimeout(tm); };
  }, []);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', background: t.dark ? '#05101f' : '#0a1830', display: 'flex', flexDirection: 'column', fontFamily: 'Hanken Grotesk, sans-serif' }}>
      {/* camera preview as background */}
      <div style={{ position: 'absolute', inset: 0 }}>
        <video ref={cam.videoRef} muted playsInline style={{ width: '100%', height: '100%', objectFit: 'cover', transform: 'scaleX(-1)', opacity: cam.status === 'granted' && cam.camOn ? 0.55 : 0 }} />
        <div style={{ position: 'absolute', inset: 0, background: cam.status === 'granted' ? 'linear-gradient(180deg, rgba(5,16,31,0.5) 0%, rgba(5,16,31,0.2) 35%, rgba(5,16,31,0.85) 100%)' : `radial-gradient(120% 80% at 50% 0%, ${hexA(accent, 0.18)}, #05101f 70%)` }} />
        {cam.status !== 'granted' && (
          <div style={{ position: 'absolute', top: '32%', left: 0, right: 0, textAlign: 'center', color: 'rgba(255,255,255,0.4)' }}>
            {Icon.video({ s: 38, c: 'rgba(255,255,255,0.3)' })}
            <div style={{ fontSize: 12.5, marginTop: 8, fontWeight: 500 }}>{cam.status === 'denied' ? 'Cámara desactivada' : 'Activando cámara…'}</div>
          </div>
        )}
      </div>

      {/* top */}
      <div style={{ position: 'relative', paddingTop: 56, padding: '56px 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <HealthSingsChip t={t} state={phase === 'ready' ? 'secure' : 'connecting'} />
        <button onClick={onCancel} style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(10px)', color: '#fff' }}>{Icon.x({ s: 17, c: '#fff' })}</button>
      </div>

      {/* doctor card */}
      <div style={{ position: 'relative', flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '0 18px 18px' }}>
        <div style={{ textAlign: 'center', marginBottom: 'auto', marginTop: 28 }}>
          <div style={{ width: 92, height: 92, borderRadius: '50%', margin: '0 auto 14px', background: `linear-gradient(135deg, ${accent}, ${persona.accentDeep})`, display: 'grid', placeItems: 'center', color: '#fff', fontFamily: 'Instrument Serif, serif', fontSize: 38, boxShadow: `0 0 0 6px ${hexA(accent, 0.18)}, 0 14px 40px ${hexA(accent, 0.4)}`, position: 'relative' }}>
            LG
            <span style={{ position: 'absolute', bottom: 4, right: 4, width: 18, height: 18, borderRadius: '50%', background: '#E6A93C', border: '3px solid #0a1830' }} />
          </div>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 27, color: '#fff' }}>Dra. Liliana Gómez</div>
          <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.6)', fontWeight: 500 }}>{cita ? cita.esp || 'Cardiología' : 'Cardiología'} · Telemedicina</div>
        </div>

        {/* prep / vita brief */}
        <div style={{ borderRadius: 24, padding: 18, background: 'rgba(10,26,51,0.72)', backdropFilter: 'blur(20px)', border: '1px solid rgba(255,255,255,0.1)' }}>
          {phase === 'prep' ? (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <VitaDot t={t} size={32} active /><span style={{ fontFamily: 'Instrument Serif, serif', fontSize: 19, color: '#fff' }}>Vita está preparando tu consulta</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                {steps.map((s, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, opacity: i < stepN ? 1 : 0.35, transition: 'opacity .3s' }}>
                    <span style={{ width: 20, height: 20, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: i < stepN ? '#73C58E' : 'transparent', border: i >= stepN ? '2px solid rgba(255,255,255,0.2)' : 'none' }}>{i < stepN ? Icon.check({ s: 12, c: '#fff', w: 3 }) : <Spinner c={accent} size={13} />}</span>
                    <span style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.85)', fontWeight: 500 }}>{s}</span>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div style={{ animation: 'vitaIn .4s both' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 12 }}>
                <VitaDot t={t} size={30} active />
                <div><div style={{ fontSize: 14.5, fontWeight: 700, color: '#fff' }}>Todo listo. Yo te acompaño.</div><div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>Le compartí tu historia a la doctora.</div></div>
              </div>
              {/* what to tell the doctor — the patient's cheat sheet */}
              <div style={{ borderRadius: 14, padding: '12px 13px', background: 'rgba(255,255,255,0.06)', border: `1px solid ${hexA(accent, 0.3)}`, marginBottom: 14 }}>
                <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase', color: accent, marginBottom: 8 }}>No olvides contarle</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                  {(prep ? prep.paraContar : []).slice(0, 3).map((p, i) => (
                    <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                      <span style={{ width: 6, height: 6, borderRadius: '50%', background: accent, marginTop: 6, flexShrink: 0 }} />
                      <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.92)', lineHeight: 1.35 }}><b style={{ color: '#fff' }}>{p.sintoma}</b>{p.detalle ? ' — ' + p.detalle : ''}</span>
                    </div>
                  ))}
                </div>
              </div>
              <button onClick={() => onEnter(prep)} 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: 16, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, boxShadow: `0 10px 26px ${hexA(accent, 0.45)}` }}>
                {Icon.video({ s: 20, c: t.onAccent })} Entrar a la consulta
              </button>
            </div>
          )}
        </div>
        {/* mic/cam pre-toggles */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 14 }}>
          <PreToggle on={cam.micOn} onClick={cam.toggleMic} icon={cam.micOn ? 'mic' : 'mic'} off={!cam.micOn} label="Micrófono" />
          <PreToggle on={cam.camOn} onClick={cam.toggleCam} icon="video" off={!cam.camOn} label="Cámara" />
        </div>
      </div>
    </div>
  );
}

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

Object.assign(window, { useCamera, HealthSingsChip, WaitingRoom, PreToggle });
