// vita-app.jsx — flow orchestration: splash → choose Vita → conversation → clinical history

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "persona": "calida",
  "waveStyle": "barras",
  "dark": true,
  "tts": true,
  "voiceURI": ""
}/*EDITMODE-END*/;

// ── Screen background wrapper ───────────────────────────────────
function Stage({ t, children, pad = true }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, overflow: 'hidden',
      background: t.dark
        ? `radial-gradient(120% 80% at 50% -10%, ${t.bg2} 0%, ${t.bg1} 45%, ${t.bg0} 100%)`
        : `radial-gradient(120% 80% at 50% -10%, #FFFFFF 0%, ${t.bg1} 55%, ${t.bg0} 100%)`,
      fontFamily: 'Hanken Grotesk, sans-serif',
      display: 'flex', flexDirection: 'column',
    }}>
      {children}
    </div>
  );
}

// ── 1. Splash ───────────────────────────────────────────────────
function Splash({ t, persona, waveStyle, onStart }) {
  return (
    <Stage t={t}>
      <div style={{ paddingTop: 64, paddingLeft: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingRight: 20 }}>
        <PreventMark t={t} size={15} />
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 30px', textAlign: 'center' }}>
        <Waveform state="speaking" variant={waveStyle} accent={persona.accent} accentDeep={persona.accentDeep} size={210} />
        <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 19, color: t.accent, letterSpacing: 0.5, marginTop: 6 }}>Conoce a</div>
        <h1 style={{ fontFamily: 'Instrument Serif, serif', fontSize: 76, lineHeight: 0.9, fontWeight: 400, color: t.text, margin: '2px 0 0' }}>Vita</h1>
        <p style={{ fontSize: 16.5, lineHeight: 1.5, color: t.textSoft, maxWidth: 290, margin: '20px 0 0', fontWeight: 450 }}>
          Tu médica de confianza, por voz. Te acompaña, recuerda tu historia y cuida tu longevidad — <span style={{ color: t.text, fontWeight: 600 }}>24 horas, todos los días.</span>
        </p>
      </div>
      <div style={{ padding: '0 24px 46px' }}>
        <BigButton t={t} onClick={onStart}>Empezar a conocernos</BigButton>
        <div style={{ textAlign: 'center', marginTop: 16, fontSize: 12.5, color: t.muted, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          {Icon.shield({ s: 14, c: t.muted })} Tus datos son tuyos. PREVENT solo los custodia.
        </div>
      </div>
    </Stage>
  );
}

function BigButton({ t, onClick, children, secondary }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '17px 20px', borderRadius: 18, cursor: 'pointer',
      border: secondary ? `1.5px solid ${t.strokeStrong}` : 'none',
      background: secondary ? 'transparent' : `linear-gradient(135deg, ${t.accent}, ${t.accentDeep})`,
      color: secondary ? t.text : t.onAccent,
      fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 16.5, fontWeight: 700, letterSpacing: 0.2,
      boxShadow: secondary ? 'none' : `0 12px 30px ${hexA(t.accent, 0.4)}`,
      WebkitTapHighlightColor: 'transparent', transition: 'transform .15s',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
    }}
    onMouseDown={e => e.currentTarget.style.transform = 'scale(0.98)'}
    onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
    >{children}</button>
  );
}

// ── 2. Choose your Vita ─────────────────────────────────────────
function ChooseVita({ t, current, waveStyle, onPick, onContinue, onBack }) {
  return (
    <Stage t={t}>
      <div style={{ paddingTop: 64, padding: '64px 24px 0' }}>
        <PreventMark t={t} size={15} />
        <h2 style={{ fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 34, lineHeight: 1.05, color: t.text, margin: '22px 0 6px' }}>
          ¿Cómo quieres<br/>que te acompañe?
        </h2>
        <p style={{ fontSize: 14.5, color: t.textSoft, margin: 0, fontWeight: 450 }}>Misma Vita, distinta forma de estar contigo. Puedes cambiarla cuando quieras.</p>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 18px 8px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {Object.values(VITA_PERSONAS).map(p => {
          const sel = p.id === current.id;
          return (
            <button key={p.id} onClick={() => onPick(p.id)} style={{
              display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left', cursor: 'pointer',
              padding: 14, borderRadius: 20, width: '100%',
              border: `1.5px solid ${sel ? p.accent : t.stroke}`,
              background: sel ? hexA(p.accent, t.dark ? 0.12 : 0.08) : (t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF'),
              boxShadow: sel ? `0 10px 26px ${hexA(p.accent, 0.28)}` : 'none',
              transition: 'all .2s', WebkitTapHighlightColor: 'transparent',
            }}>
              <div style={{ width: 64, height: 64, flexShrink: 0, display: 'grid', placeItems: 'center', borderRadius: 16, overflow: 'hidden', background: t.dark ? 'rgba(0,0,0,0.2)' : hexA(p.accent, 0.06) }}>
                <Waveform state={sel ? 'speaking' : 'idle'} variant={waveStyle} accent={p.accent} accentDeep={p.accentDeep} size={64} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: 'Instrument Serif, serif', fontSize: 23, color: t.text }}>Vita</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: p.accent, padding: '2px 9px', borderRadius: 999, background: hexA(p.accent, 0.14) }}>{p.name}</span>
                </div>
                <div style={{ fontSize: 13, color: t.textSoft, lineHeight: 1.4, marginTop: 3, fontWeight: 450 }}>{p.desc}</div>
              </div>
              <div style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, border: `2px solid ${sel ? p.accent : t.strokeStrong}`, background: sel ? p.accent : 'transparent', display: 'grid', placeItems: 'center' }}>
                {sel && Icon.check({ s: 13, c: t.onAccent, w: 3 })}
              </div>
            </button>
          );
        })}
      </div>
      <div style={{ padding: '8px 24px 46px', display: 'flex', gap: 12 }}>
        <BigButton t={t} secondary onClick={onBack}>Atrás</BigButton>
        <BigButton t={t} onClick={onContinue}>Continuar {Icon.chevron({ s: 17, c: t.onAccent })}</BigButton>
      </div>
    </Stage>
  );
}

// ── 3. Conversation ─────────────────────────────────────────────
function Conversation({ t, persona, waveStyle, tts, conv, returning, onToggleTheme, onToggleTTS, onShowProfile, onBack }) {
  const voice = conv.voice;
  const scrollRef = React.useRef(null);
  const [text, setText] = React.useState('');
  const [showDocs, setShowDocs] = React.useState(false);

  const DOC_TYPES = [
    { label: 'Exámenes de laboratorio', icon: 'pulse' },
    { label: 'Fórmula médica', icon: 'doc' },
    { label: 'Mi historia clínica', icon: 'doc' },
    { label: 'Carné de vacunas', icon: 'shield' },
    { label: 'Foto / imagen médica', icon: 'plus' },
  ];

  const phase = voice.listening ? 'listening' : conv.loading ? 'thinking' : voice.speaking ? 'speaking' : 'idle';

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [conv.messages, conv.loading]);

  const submit = (val) => {
    const v = (val != null ? val : text).trim();
    if (!v || conv.loading) return;
    setText('');
    conv.send(v);
  };

  const micTap = () => {
    if (voice.speaking) { voice.stopSpeaking(); return; }
    if (voice.listening) { voice.stopListening(); return; }
    const ok = voice.startListening((final) => submit(final));
    if (!ok) {
      const el = document.getElementById('vita-input');
      el && el.focus();
    }
  };

  const profileCount = Object.keys(conv.profile).length;

  return (
    <Stage t={t}>
      {/* header */}
      <div style={{ paddingTop: 60, padding: '60px 18px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          {returning && onBack
            ? <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>
            : <PreventMark t={t} size={13} withWord={false} />}
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: t.text, lineHeight: 1 }}>{returning ? 'Hablar con Vita' : 'Primer triage'}</div>
            <div style={{ fontSize: 11, color: t.muted, fontWeight: 500, marginTop: 2 }}>{returning ? 'Tu asistente de salud' : 'Hablado, con Vita'}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={onShowProfile} style={{
            display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer',
            padding: '5px 12px 5px 6px', borderRadius: 999, border: `1px solid ${t.stroke}`,
            background: t.dark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)', WebkitTapHighlightColor: 'transparent',
          }}>
            <ProgressRing value={conv.progress} size={26} stroke={3} color={t.accent} track={t.stroke} />
            <span style={{ fontSize: 12.5, fontWeight: 700, color: t.text }}>{profileCount}</span>
          </button>
          <IconBtn t={t} onClick={onToggleTTS} active={tts} title="Voz de Vita">
            {tts ? Icon.volume({ s: 17, c: t.accent }) : Icon.volumeOff({ s: 17, c: t.textSoft })}
          </IconBtn>
          <IconBtn t={t} onClick={onToggleTheme} title="Tema">
            {t.dark ? Icon.sun({ s: 17 }) : Icon.moon({ s: 17 })}
          </IconBtn>
        </div>
      </div>

      {/* waveform presence */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 2 }}>
        <Waveform state={phase} variant={waveStyle} accent={persona.accent} accentDeep={persona.accentDeep} size={128} />
        <StatePill phase={phase} t={t} persona={persona} />
      </div>

      {/* transcript */}
      <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '16px 18px 8px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {conv.messages.map((m, i) => (
          <MessageBubble key={i} m={m} t={t} latest={i === conv.messages.length - 1} />
        ))}
        {conv.loading && (
          <div style={{ display: 'flex', gap: 9, alignItems: 'flex-end' }}>
            <VitaDot t={t} size={24} active />
            <div style={{ padding: '13px 16px', borderRadius: '4px 17px 17px 17px', background: t.dark ? 'rgba(255,255,255,0.06)' : '#fff', border: `1px solid ${t.stroke}`, display: 'flex', gap: 5 }}>
              {[0,1,2].map(i => <span key={i} style={{ width: 7, height: 7, borderRadius: '50%', background: t.muted, animation: `vitaPulse 1.1s ${i*0.18}s ease-in-out infinite` }} />)}
            </div>
          </div>
        )}
        {conv.done && !conv.loading && !returning && (
          <button onClick={conv.onFinish} style={{
            margin: '6px auto 2px', padding: '13px 22px', borderRadius: 16, cursor: 'pointer', border: 'none',
            background: `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})`, color: t.onAccent,
            fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15.5, fontWeight: 700,
            boxShadow: `0 10px 26px ${hexA(persona.accent, 0.4)}`, display: 'flex', alignItems: 'center', gap: 8,
            animation: 'vitaIn .4s both', WebkitTapHighlightColor: 'transparent',
          }}>
            {Icon.sparkle({ s: 17, c: t.onAccent })} Ver mi análisis de salud
          </button>
        )}
        {!conv.done && !conv.loading && !returning && profileCount >= 6 && (
          <button onClick={conv.onFinish} style={{
            margin: '4px auto 0', padding: '9px 16px', borderRadius: 999, cursor: 'pointer',
            border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.7)',
            color: t.textSoft, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 12.5, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 6, WebkitTapHighlightColor: 'transparent', animation: 'vitaIn .4s both',
          }}>
            Ya terminé · ver mi análisis {Icon.arrowRight({ s: 14, c: t.textSoft })}
          </button>
        )}
      </div>

      {/* live profile peek */}
      {profileCount > 0 && (
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '4px 18px 10px', WebkitOverflowScrolling: 'touch' }}>
          {Object.entries(conv.profile).slice(0, 8).map(([k, v]) => (
            <ProfileChip key={k} label={PROFILE_LABELS[k] || k} value={v} t={t} />
          ))}
        </div>
      )}

      {/* input bar */}
      <div style={{ position: 'relative', padding: '6px 16px 30px', display: 'flex', alignItems: 'center', gap: 10 }}>
        {/* attach menu */}
        {showDocs && (
          <>
            <div onClick={() => setShowDocs(false)} style={{ position: 'absolute', inset: 0, zIndex: 1 }} />
            <div style={{ position: 'absolute', left: 16, bottom: 92, zIndex: 2, width: 256, borderRadius: 18, overflow: 'hidden',
              background: t.dark ? t.surfaceSolid : '#FFFFFF', border: `1px solid ${t.stroke}`, boxShadow: t.shadow, animation: 'vitaIn .2s both' }}>
              <div style={{ padding: '11px 14px 7px', fontSize: 11.5, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: t.muted }}>Comparte tus documentos</div>
              {DOC_TYPES.map((d, i) => (
                <button key={i} onClick={() => { conv.attach(d.label); setShowDocs(false); }} style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 11, padding: '11px 14px', cursor: 'pointer',
                  border: 'none', borderTop: `1px solid ${t.stroke}`, background: 'transparent', textAlign: 'left',
                  fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 14.5, fontWeight: 500, color: t.text, WebkitTapHighlightColor: 'transparent',
                }}>
                  <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(persona.accent, 0.14) }}>{Icon[d.icon]({ s: 17, c: persona.accent })}</span>
                  {d.label}
                </button>
              ))}
            </div>
          </>
        )}

        <button onClick={() => setShowDocs(s => !s)} title="Adjuntar documentos" style={{
          width: 44, height: 44, borderRadius: 13, flexShrink: 0, cursor: 'pointer', display: 'grid', placeItems: 'center',
          border: `1px solid ${showDocs ? hexA(persona.accent, 0.5) : t.stroke}`,
          background: showDocs ? hexA(persona.accent, 0.14) : (t.dark ? 'rgba(255,255,255,0.05)' : '#fff'),
          color: showDocs ? persona.accent : t.textSoft, WebkitTapHighlightColor: 'transparent',
        }}>{Icon.clip({ s: 20, c: showDocs ? persona.accent : t.textSoft })}</button>

        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', borderRadius: 16, padding: '4px 4px 4px 16px',
          background: t.dark ? 'rgba(255,255,255,0.06)' : '#FFFFFF', border: `1px solid ${t.stroke}`,
        }}>
          <input id="vita-input" value={voice.listening ? (voice.interim || '') : text}
            onChange={e => setText(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') submit(); }}
            placeholder={voice.listening ? 'Escuchando…' : 'Escribe o toca el micrófono…'}
            readOnly={voice.listening}
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 15.5, color: t.text, fontFamily: 'Hanken Grotesk, sans-serif', minWidth: 0,
            }} />
          {text.trim() && !voice.listening && (
            <button onClick={() => submit()} style={{ width: 40, height: 40, borderRadius: 12, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: hexA(t.accent, 0.15), color: t.accent }}>
              {Icon.send({ s: 20, c: t.accent })}
            </button>
          )}
        </div>
        <button onClick={micTap} style={{
          width: 56, height: 56, borderRadius: '50%', flexShrink: 0, cursor: 'pointer', border: 'none',
          display: 'grid', placeItems: 'center', position: 'relative',
          background: (voice.listening || voice.speaking) ? `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})` : (t.dark ? 'rgba(255,255,255,0.08)' : '#fff'),
          color: (voice.listening || voice.speaking) ? t.onAccent : t.accent,
          border: (voice.listening || voice.speaking) ? 'none' : `1px solid ${t.stroke}`,
          boxShadow: (voice.listening || voice.speaking) ? `0 8px 22px ${hexA(persona.accent, 0.5)}` : t.shadow,
          WebkitTapHighlightColor: 'transparent',
        }}>
          {voice.listening && <span style={{ position: 'absolute', inset: -4, borderRadius: '50%', border: `2px solid ${persona.accent}`, animation: 'vitaRipple 1.4s ease-out infinite' }} />}
          {voice.speaking ? Icon.volume({ s: 24, c: t.onAccent }) : Icon.mic({ s: 24 })}
        </button>
      </div>
    </Stage>
  );
}

Object.assign(window, { TWEAK_DEFAULTS, Stage, Splash, BigButton, ChooseVita, Conversation });
