// vita-root.jsx — Done screen, profile sheet, root state + conversation engine + tweaks

// ── 4. Done — the clinical history Vita built ───────────────────
function DoneScreen({ t, persona, profile, onRestart, onReopen }) {
  const name = profile.nombre || 'tu historia';
  const entries = Object.entries(profile);
  return (
    <Stage t={t}>
      <div style={{ flex: 1, overflow: 'auto', padding: '64px 22px 20px' }}>
        <PreventMark t={t} size={14} />
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', marginTop: 18 }}>
          <Waveform state="speaking" variant="espejo" accent={persona.accent} accentDeep={persona.accentDeep} size={120} />
          <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, marginTop: 4 }}>
            {Icon.check({ s: 14, c: t.green, w: 3 })} Historia iniciada
          </div>
          <h2 style={{ fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 32, lineHeight: 1.08, color: t.text, margin: '14px 0 6px' }}>
            Encantada,<br/>{profile.nombre ? profile.nombre.split(' ')[0] : 'ya nos conocemos'}.
          </h2>
          <p style={{ fontSize: 15, color: t.textSoft, lineHeight: 1.5, maxWidth: 300, margin: 0, fontWeight: 450 }}>
            Ya empecé a construir tu historia clínica. De ahora en adelante <span style={{ color: t.text, fontWeight: 600 }}>yo la administro y la mantengo al día</span> en cada paso de tu salud.
          </p>
        </div>

        {/* clinical history card */}
        <div style={{ marginTop: 22, borderRadius: 22, padding: 18, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', boxShadow: t.shadow }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            {Icon.heart({ s: 18, c: persona.accent, fill: persona.accent })}
            <span style={{ fontSize: 13, fontWeight: 800, letterSpacing: 1, textTransform: 'uppercase', color: t.text }}>Tu historia con Vita</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {entries.map(([k, v], i) => (
              <div key={k} style={{ display: 'flex', gap: 14, padding: '11px 0', borderTop: i ? `1px solid ${t.stroke}` : 'none' }}>
                <div style={{ width: 128, flexShrink: 0, fontSize: 13, fontWeight: 600, color: t.muted }}>{PROFILE_LABELS[k] || k}</div>
                <div style={{ flex: 1, fontSize: 14, color: t.text, fontWeight: 500, lineHeight: 1.4 }}>{Array.isArray(v) ? v.join(' · ') : v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* longevity baseline */}
        <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <BaselineStat t={t} label="Línea base de longevidad" value="Establecida" accent={persona.accent} icon={Icon.pulse} />
          <BaselineStat t={t} label="Seguimiento continuo" value="Activo 24/7" accent={t.green} icon={Icon.shield} />
        </div>

        <p style={{ fontSize: 13, color: t.muted, lineHeight: 1.5, textAlign: 'center', margin: '18px 12px 0' }}>
          Cada examen, síntoma y avance que compartas, lo registro y lo conecto con tu historia. Estoy aquí cuando me necesites.
        </p>
      </div>

      <div style={{ padding: '8px 22px 40px', display: 'flex', gap: 12 }}>
        <BigButton t={t} secondary onClick={onReopen}>Seguir hablando</BigButton>
        <BigButton t={t} onClick={onRestart}>Reiniciar demo</BigButton>
      </div>
    </Stage>
  );
}

function BaselineStat({ t, label, value, accent, icon }) {
  return (
    <div style={{ borderRadius: 18, padding: 14, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF' }}>
      <div style={{ width: 32, height: 32, borderRadius: 10, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14), marginBottom: 10 }}>
        {icon({ s: 18, c: accent })}
      </div>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: t.muted, lineHeight: 1.3 }}>{label}</div>
      <div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginTop: 3 }}>{value}</div>
    </div>
  );
}

// ── Profile bottom-sheet ────────────────────────────────────────
function ProfileSheet({ t, persona, profile, progress, onClose }) {
  const entries = Object.entries(profile);
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 80, background: 'rgba(3,10,24,0.5)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-end', animation: 'vitaFade .2s ease both' }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxHeight: '78%', overflow: 'auto', borderRadius: '26px 26px 0 0',
        background: t.dark ? t.bg1 : '#FFFFFF', border: `1px solid ${t.stroke}`, borderBottom: 'none',
        padding: '14px 22px 40px', animation: 'vitaSheet .32s cubic-bezier(.2,.8,.2,1) both',
      }}>
        <div style={{ width: 40, height: 5, borderRadius: 999, background: t.strokeStrong, margin: '0 auto 16px' }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
          <h3 style={{ fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 27, color: t.text, margin: 0 }}>Tu historia clínica</h3>
          <IconBtn t={t} onClick={onClose}>{Icon.x({ s: 18, c: t.textSoft })}</IconBtn>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
          <ProgressRing value={progress} size={30} stroke={3.5} color={persona.accent} track={t.stroke} />
          <span style={{ fontSize: 13.5, color: t.textSoft, fontWeight: 500 }}>Vita la actualiza mientras conversan</span>
        </div>
        {entries.length === 0 ? (
          <div style={{ padding: '30px 0', textAlign: 'center', color: t.muted, fontSize: 14 }}>Cuéntale algo a Vita y aparecerá aquí.</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {entries.map(([k, v], i) => (
              <div key={k} style={{ display: 'flex', gap: 14, padding: '12px 0', borderTop: i ? `1px solid ${t.stroke}` : 'none' }}>
                <div style={{ width: 130, flexShrink: 0, fontSize: 13, fontWeight: 600, color: t.muted }}>{PROFILE_LABELS[k] || k}</div>
                <div style={{ flex: 1, fontSize: 14.5, color: t.text, fontWeight: 500, lineHeight: 1.4 }}>{Array.isArray(v) ? v.join(' · ') : v}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Root ────────────────────────────────────────────────────────
function VitaApp() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const persona = VITA_PERSONAS[tw.persona] || VITA_PERSONAS.calida;
  const t = getTheme(tw.dark, persona.accent, persona.accentDeep);

  // ── session memory ──────────────────────────────────────────
  const SAVE_KEY = 'vita_session_v1';
  const saved = React.useMemo(() => {
    try { return JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); } catch (e) { return null; }
  }, []);
  const resuming = !!(saved && saved.triageDone && saved.asis);

  const [flow, setFlow] = React.useState(resuming ? 'home' : 'auth'); // auth | facescan | splash | choose | chat | collect | asis | home
  const [sheet, setSheet] = React.useState(false);
  const [secSheet, setSecSheet] = React.useState(false);
  const [pendingAuth, setPendingAuth] = React.useState(null);
  const voice = useVitaVoice();

  // conversation state
  const [messages, setMessages] = React.useState(resuming ? (saved.messages || []) : []);
  const [profile, setProfile] = React.useState(resuming ? (saved.profile || {}) : {});
  const [progress, setProgress] = React.useState(resuming ? (saved.progress || 100) : 0);
  const [loading, setLoading] = React.useState(false);
  const [done, setDone] = React.useState(resuming);
  const [triageDone, setTriageDone] = React.useState(resuming);
  const [docs, setDocs] = React.useState(resuming ? (saved.docs || []) : []);
  const [asis, setAsis] = React.useState(resuming ? saved.asis : null);
  const [seguimiento, setSeguimiento] = React.useState(resuming ? (saved.seguimiento || []) : []);
  const [pic, setPic] = React.useState(resuming ? (saved.pic || null) : null);
  const [picReady, setPicReady] = React.useState(resuming ? (saved.picReady || false) : false);
  const [picGenerating, setPicGenerating] = React.useState(false);
  const [changelog, setChangelog] = React.useState(null); // { cambios, version }
  const [reanalyzing, setReanalyzing] = React.useState(null); // label of new info
  const [segItem, setSegItem] = React.useState(null);
  const [addSheet, setAddSheet] = React.useState(false);
  const [picSheet, setPicSheet] = React.useState(false);
  const [shareSheet, setShareSheet] = React.useState(false);
  const [hcFormal, setHcFormal] = React.useState(resuming ? (saved.hcFormal || null) : null);
  const [hcLoading, setHcLoading] = React.useState(false);
  const [family, setFamily] = React.useState(resuming ? (saved.family || []) : []);
  const [activeId, setActiveId] = React.useState('titular');
  const [pendingSwitch, setPendingSwitch] = React.useState(null);
  const [addMemberOpen, setAddMemberOpen] = React.useState(false);
  const [dataSheet, setDataSheet] = React.useState(false);
  const [nutricion, setNutricion] = React.useState(resuming ? (saved.nutricion || null) : null);
  const [nutLoading, setNutLoading] = React.useState(false);
  const [serviceView, setServiceView] = React.useState(null);
  const [telemedCita, setTelemedCita] = React.useState(null);
  // proactive care
  const [careDone, setCareDone] = React.useState(resuming && saved.careDone && saved.careDone.day === todayKey() ? saved.careDone.map : {});
  const [postCitaSheet, setPostCitaSheet] = React.useState(false);
  const [postCitaDone, setPostCitaDone] = React.useState(resuming ? (saved.postCitaDone || false) : false);
  // notifications
  const [notifRead, setNotifRead] = React.useState(resuming && saved.notifRead && saved.notifRead.day === todayKey() ? saved.notifRead.map : {});
  const [notifSettings, setNotifSettings] = React.useState(resuming ? (saved.notifSettings || {}) : {});
  const [toastQueue, setToastQueue] = React.useState([]);
  const [activeToast, setActiveToast] = React.useState(null);
  const [notifSheet, setNotifSheet] = React.useState(false);
  const simRef = React.useRef(null); // null | 'citas' | 'nutricion' | 'psicologia' | 'diagnostico'
  const startedRef = React.useRef(resuming);
  const asisRef = React.useRef(resuming ? saved.asis : null); asisRef.current = asis;
  const versionRef = React.useRef(resuming ? (saved.version || 1) : 1);

  const ttsRef = React.useRef(tw.tts);
  ttsRef.current = tw.tts;
  const personaRef = React.useRef(persona);
  personaRef.current = persona;

  const speakReply = (txt) => {
    if (ttsRef.current) voice.speak(txt, personaRef.current);
  };

  const runTurn = async (nextMessages) => {
    setLoading(true);
    const res = await askVita(personaRef.current, profile, nextMessages);
    setProfile(prev => mergeProfile(prev, res.profile));
    setMessages([...nextMessages, { role: 'vita', text: res.reply }]);
    if (res.progress != null) setProgress(res.progress);
    else setProgress(p => Math.min(100, Math.max(p, Object.keys(profile).length * 9)));
    if (res.done) setDone(true);
    setLoading(false);
    speakReply(res.reply);
  };

  const startConversation = () => {
    if (startedRef.current) return;
    startedRef.current = true;
    runTurn([]); // empty → Vita greets
  };

  const send = (userText) => {
    const next = [...messages, { role: 'user', text: userText }];
    setMessages(next);
    runTurn(next);
  };

  const attachDoc = (label) => {
    setDocs(d => (d.includes(label) ? d : [...d, label]));
    send('📎 Adjunté: ' + label);
  };

  const finishTriage = () => {
    voice.stopSpeaking();
    setFlow('collect');
  };

  // collect screen done → store plan + docs + pendings, then build ASIS
  const completeCollect = async ({ docs: newDocs, eps, prepagada, pendings }) => {
    setProfile(p => ({ ...p, ...(eps ? { eps } : {}), ...(prepagada ? { prepagada } : {}) }));
    const mergedDocs = [...new Set([...docs, ...(newDocs || [])])];
    setDocs(mergedDocs);
    setFlow('asis');
    const profForAsis = { ...profile, ...(eps ? { eps } : {}), ...(prepagada ? { prepagada } : {}) };
    const [result, suggested] = await Promise.all([
      generateAsis(personaRef.current, profForAsis, messages, mergedDocs),
      suggestSeguimiento(profForAsis, messages),
      new Promise(r => setTimeout(r, 3200)),
    ]);
    versionRef.current = 1;
    setAsis(result);
    // merge user pendings + AI-suggested, dedupe by titulo
    const all = [...(pendings || []), ...suggested];
    const seen = new Set();
    const dedup = all.filter(x => { const k = (x.titulo || '').toLowerCase(); if (seen.has(k)) return false; seen.add(k); return true; }).slice(0, 5);
    setSeguimiento(dedup);
    setPicReady(true);   // ASIS has the minimum info → Vita can build the PIC
    setChangelog(null);
    setTriageDone(true); // Vita now remembers: triage is done
    setFlow('home');
  };

  // living ASIS — feed new info, re-analyze, show changelog
  const addInfo = async (label) => {
    setAddSheet(false);
    setReanalyzing(label);
    setDocs(d => (d.includes(label) ? d : [...d, label]));
    const updated = await generateAsis(personaRef.current, profile, messages, [...docs, label], {
      prev: asisRef.current, nuevoInput: label, seguimiento,
    });
    versionRef.current += 1;
    setAsis(updated);
    setChangelog({ cambios: updated.cambios && updated.cambios.length ? updated.cambios : ['Registré lo que subiste y lo sumé a tu historia.'], version: versionRef.current });
    // if we already have a PIC, refresh it quietly with the new picture
    if (pic) {
      const np = await generatePic(personaRef.current, profile, updated, { prev: pic });
      setPic(np);
    }
    setReanalyzing(null);
  };

  // Vita takes charge of a pending item
  const advanceSeg = (item) => {
    setSeguimiento(list => list.map(x => x.id === item.id ? { ...x, estado: 'gestionando' } : x));
    setSegItem(it => it && it.id === item.id ? { ...it, estado: 'gestionando' } : it);
    setTimeout(() => {
      const doneState = item.tipo === 'medicamento' ? 'activo' : 'agendado';
      setSeguimiento(list => list.map(x => x.id === item.id ? { ...x, estado: doneState } : x));
      setSegItem(it => it && it.id === item.id ? { ...it, estado: doneState } : it);
    }, 1900);
  };

  // activate the PIC (preventive plan)
  const activatePic = async () => {
    setPicGenerating(true);
    const p = await generatePic(personaRef.current, profile, asisRef.current);
    setPic(p);
    setPicReady(false);
    setPicGenerating(false);
    setPicSheet(true);
  };

  // generate the formal clinical history (Colombian norms) — lazily, cached
  const generateFormalHC = async () => {
    if (hcFormal || hcLoading) return;
    setHcLoading(true);
    const hc = await generateHistoriaClinica(profile, asisRef.current, messages, docs, seguimiento);
    setHcFormal(hc);
    setHcLoading(false);
  };

  // ── family / patient switching ──────────────────────────────
  const activeMember = activeId === 'titular' ? null : family.find(m => m.id === activeId);
  const requestSwitch = (target) => {
    if (!target || target.id === 'titular') { setActiveId('titular'); setFlow('home'); return; }
    if (target.id === activeId) return;
    setPendingSwitch(target);
    setFlow('switchface');
  };
  const confirmSwitch = () => {
    if (pendingSwitch) setActiveId(pendingSwitch.id);
    setPendingSwitch(null);
    setFlow('home');
  };
  const addMember = (m) => { setFamily(f => [...f, m]); setAddMemberOpen(false); };

  // services: nutrition plan (lazy, cached) + add anything to seguimiento
  const generateNutPlan = async () => {
    if (nutricion || nutLoading) return;
    setNutLoading(true);
    const n = await generateNutricion(profile, asisRef.current);
    setNutricion(n);
    setNutLoading(false);
  };
  const addToSeguimiento = (item) => {
    setSeguimiento(list => {
      if (list.some(x => x.id === item.id)) return list;
      return [...list, item];
    });
  };

  // ── proactive care ──────────────────────────────────────────
  const careTasks = React.useMemo(() => triageDone ? buildTodayPlan({ profile, asis, pic, seguimiento }) : [], [triageDone, profile, asis, pic, seguimiento]);
  const careDetails = React.useMemo(() => triageDone ? buildCareDetails({ profile, seguimiento }) : { streaks: [], terapias: [], controles: [] }, [triageDone, profile, seguimiento]);
  const toggleCare = (id) => setCareDone(d => ({ ...d, [id]: !d[id] }));
  // a post-cita check-in surfaces when there's a scheduled cita and it hasn't been resolved
  const postCitaItem = React.useMemo(() => {
    if (postCitaDone) return null;
    const cita = (seguimiento || []).find(s => s.tipo === 'cita' && ['agendado', 'completado'].includes(s.estado));
    return cita || null;
  }, [seguimiento, postCitaDone]);
  const resolvePostCita = (nuevos) => {
    (nuevos || []).forEach(addToSeguimiento);
    setPostCitaDone(true);
  };

  // ── notifications: Vita as a daily presence ─────────────────
  const notifs = React.useMemo(() => {
    if (!triageDone) return [];
    const built = buildNotifications({ profile, personaId: persona.id, careTasks, seguimiento, careDetails });
    // filter by settings + reflect done state from careDone
    return built.filter(nf => {
      if (nf.tipo === 'medicamento' && notifSettings.medicamento === false) return false;
      if ((nf.tipo === 'cita') && notifSettings.citas === false) return false;
      if ((nf.tipo === 'habito' || nf.tipo === 'actividad') && notifSettings.habitos === false) return false;
      if ((nf.tipo === 'proactivo' || nf.tipo === 'logro') && notifSettings.proactivo === false) return false;
      return true;
    }).map(nf => ({ ...nf, done: nf.taskId ? !!careDone[nf.taskId] : !!notifRead[nf.id] }));
  }, [triageDone, profile, persona.id, careTasks, seguimiento, careDetails, notifSettings, careDone, notifRead]);

  const handleNotifAction = (k, nf) => {
    if (k === 'done' && nf.taskId) setCareDone(d => ({ ...d, [nf.taskId]: true }));
    else if (k === 'done') setNotifRead(r => ({ ...r, [nf.id]: true }));
    else if (k === 'snooze') {
      // re-show after a short delay (demo)
      setTimeout(() => setToastQueue(q => [...q, nf]), 4000);
    } else if (k === 'reply') {
      setActiveToast(null); setToastQueue([]); if (simRef.current) { clearTimeout(simRef.current); simRef.current = null; }
      setFlow('chat');
    } else if (k === 'view') {
      setActiveToast(null); setToastQueue([]); if (simRef.current) { clearTimeout(simRef.current); simRef.current = null; }
      if (nf.tipo === 'cita') setFlow('home'); else if (nf.tipo === 'terapia') setFlow('care'); else setFlow('home');
    }
  };

  // banner queue: show one at a time
  React.useEffect(() => {
    if (!activeToast && toastQueue.length) {
      setActiveToast(toastQueue[0]);
      setToastQueue(q => q.slice(1));
    }
  }, [activeToast, toastQueue]);

  const enqueueToasts = (arr) => setToastQueue(q => [...q, ...arr]);

  // "Vivir un día con Vita": fire the day's notifications as a sequence
  const simulateDay = () => {
    if (simRef.current) clearTimeout(simRef.current);
    setActiveToast(null);
    const seq = notifs.filter(nf => !nf.done).slice(0, 6);
    if (!seq.length) { enqueueToasts(notifs.slice(0, 3)); return; }
    let i = 0;
    const fire = () => {
      setToastQueue(q => [...q, seq[i]]);
      i++;
      if (i < seq.length) simRef.current = setTimeout(fire, 2600);
    };
    fire();
  };

  const reset = () => {
    voice.stopSpeaking();
    startedRef.current = false;
    try { localStorage.removeItem(SAVE_KEY); } catch (e) {}
    setMessages([]); setProfile({}); setProgress(0); setDone(false); setTriageDone(false);
    setDocs([]); setAsis(null); setSeguimiento([]); setPic(null); setPicReady(false);
    setChangelog(null); setReanalyzing(null); setSegItem(null); setAddSheet(false); setPicSheet(false);
    setShareSheet(false); setHcFormal(null); setHcLoading(false);
    setFamily([]); setActiveId('titular'); setPendingSwitch(null); setAddMemberOpen(false); setDataSheet(false);
    setNutricion(null); setNutLoading(false); setServiceView(null);
    setCareDone({}); setPostCitaSheet(false); setPostCitaDone(false);
    setNotifRead({}); setNotifSettings({}); setToastQueue([]); setActiveToast(null); setNotifSheet(false);
    if (simRef.current) { clearTimeout(simRef.current); simRef.current = null; }
    versionRef.current = 1;
    setFlow('auth');
  };

  // ── persist session whenever memory changes ─────────────────
  React.useEffect(() => {
    if (!triageDone) return;
    try {
      localStorage.setItem(SAVE_KEY, JSON.stringify({
        triageDone: true, profile, docs, asis, seguimiento, pic, picReady, hcFormal, family, nutricion,
        careDone: { day: todayKey(), map: careDone }, postCitaDone,
        notifRead: { day: todayKey(), map: notifRead }, notifSettings,
        progress, version: versionRef.current, messages: messages.slice(-40),
      }));
    } catch (e) {}
  }, [triageDone, profile, docs, asis, seguimiento, pic, picReady, progress, messages, hcFormal, family, nutricion, careDone, postCitaDone, notifRead, notifSettings]);

  React.useEffect(() => {
    if (flow === 'chat') startConversation();
  }, [flow]);

  // apply the chosen voice whenever it changes
  React.useEffect(() => {
    voice.setPreferredVoice(tw.voiceURI);
  }, [tw.voiceURI, voice.spanishVoices.length]);

  const conv = {
    voice, messages, profile, progress, loading, done, docs,
    send, attach: attachDoc, onFinish: finishTriage,
  };

  const toggleTheme = () => setTweak('dark', !tw.dark);
  const toggleTTS = () => { if (tw.tts) voice.stopSpeaking(); setTweak('tts', !tw.tts); };

  // responsive scale of the fixed-size device
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const fit = () => {
      const m = 28;
      setScale(Math.min(1, (window.innerWidth - m) / 402, (window.innerHeight - m) / 874));
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  const startFaceScan = (payload) => { setPendingAuth(payload || null); setFlow('facescan'); };

  const onAuthed = ({ name }) => {
    if (name) setProfile(p => (p.nombre ? p : { ...p, nombre: name }));
    setFlow('splash');
  };

  return (
    <div style={{ position: 'fixed', inset: 0, display: 'grid', placeItems: 'center', overflow: 'hidden',
      background: tw.dark ? 'radial-gradient(140% 100% at 50% 0%, #0c1c3a 0%, #060d1c 70%)' : 'radial-gradient(140% 100% at 50% 0%, #ffffff 0%, #dde6f2 75%)' }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'center center' }}>
        <IOSDevice dark={tw.dark}>
          <div style={{ position: 'absolute', inset: 0 }}>
            {flow === 'auth' && <AuthScreen t={t} persona={persona} onAuthed={onAuthed} onToggleTheme={toggleTheme} onFaceScan={startFaceScan} onShowSecurity={() => setSecSheet(true)} />}
            {flow === 'facescan' && <FaceScan t={t} persona={persona} enroll={pendingAuth && pendingAuth.enroll} onDone={() => onAuthed(pendingAuth || { method: 'face' })} onCancel={() => setFlow('auth')} />}
            {flow === 'splash' && <Splash t={t} persona={persona} waveStyle={tw.waveStyle} onStart={() => setFlow('choose')} />}
            {flow === 'choose' && <ChooseVita t={t} current={persona} waveStyle={tw.waveStyle} onPick={(id) => setTweak('persona', id)} onContinue={() => setFlow('chat')} onBack={() => setFlow('splash')} />}
            {flow === 'chat' && <Conversation t={t} persona={persona} waveStyle={tw.waveStyle} tts={tw.tts} returning={triageDone} conv={conv} onToggleTheme={toggleTheme} onToggleTTS={toggleTTS} onShowProfile={() => setSheet(true)} onBack={triageDone ? () => setFlow('home') : null} />}
            {flow === 'collect' && <CollectScreen t={t} persona={persona} profile={profile} onComplete={completeCollect} />}
            {flow === 'asis' && <AsisGenerating t={t} persona={persona} waveStyle={tw.waveStyle} />}
            {flow === 'home' && (activeMember
              ? <MemberHome t={t} persona={persona} member={activeMember} titularName={(profile.nombre || 'Tú').split(' ')[0]}
                  onBackToTitular={() => { setActiveId('titular'); }} onStartTriage={() => setFlow('chat')}
                  onToggleTheme={toggleTheme} onOpenProfile={() => setFlow('profile')} onTalk={() => setFlow('chat')} />
              : <HomeScreen t={t} persona={persona} profile={profile} asis={asis} docs={docs}
                  seguimiento={seguimiento} pic={pic} picReady={picReady} picGenerating={picGenerating} changelog={changelog}
                  onTalk={() => setFlow('chat')} onAddInfo={() => setAddSheet(true)} onOpenSeg={(it) => setSegItem(it)}
                  careTasks={careTasks} careDone={careDone} onToggleCare={toggleCare} onOpenCare={() => setFlow('care')}
                  postCita={postCitaItem} onOpenPostCita={() => setPostCitaSheet(true)} onDismissPostCita={() => setPostCitaDone(true)}
                  notifCount={notifs.filter(nf => !nf.done).length} onOpenNotifs={() => setFlow('notifs')}
                  onActivatePic={activatePic} onOpenPic={() => setPicSheet(true)} onDismissChangelog={() => setChangelog(null)}
                  onShowHistory={() => setSheet(true)} onOpenHistory={() => setFlow('history')} onOpenProfile={() => setFlow('profile')} onOpenServices={() => { setServiceView(null); setFlow('services'); }} onShowSecurity={() => setSecSheet(true)} onToggleTheme={toggleTheme} />)}
            {flow === 'profile' && <ProfileScreen t={t} persona={persona} profile={profile} family={family} activeId={activeId}
              onSwitch={requestSwitch} onAdd={() => setAddMemberOpen(true)} onOpenData={() => setDataSheet(true)}
              onShowSecurity={() => setSecSheet(true)} onTalk={() => setFlow('chat')} onToggleTheme={toggleTheme} onLogout={reset}
              onOpenHome={() => setFlow('home')} onOpenHistory={() => setFlow('history')} onOpenProfile={() => setFlow('profile')} onOpenServices={() => { setServiceView(null); setFlow('services'); }} />}
            {flow === 'switchface' && <FaceScan t={t} persona={persona} mode="switch"
              badgeText={pendingSwitch && pendingSwitch.menor ? 'AUTORIZACIÓN DE ACUDIENTE' : 'CAMBIO DE PACIENTE'}
              alignText={pendingSwitch && pendingSwitch.menor ? ((profile.nombre || 'Acudiente').split(' ')[0] + ', confirma tu identidad') : ('¿Eres ' + (pendingSwitch ? pendingSwitch.nombre.split(' ')[0] : '') + '?')}
              subtitleText={pendingSwitch && pendingSwitch.menor ? ('Autorizas gestionar la salud de ' + (pendingSwitch ? pendingSwitch.nombre.split(' ')[0] : '')) : 'Verificación facial para proteger su información'}
              doneText={'Ahora gestionas a ' + (pendingSwitch ? pendingSwitch.nombre.split(' ')[0] : '')}
              onDone={confirmSwitch} onCancel={() => { setPendingSwitch(null); setFlow('profile'); }} />}
            {flow === 'history' && <HistoryScreen t={t} persona={persona} profile={profile} asis={asis} docs={docs} seguimiento={seguimiento} version={versionRef.current}
              hcFormal={hcFormal} hcLoading={hcLoading} onGenerateFormal={generateFormalHC} onShare={() => setShareSheet(true)}
              onBack={() => setFlow('home')} onTalk={() => setFlow('chat')} onOpenSeg={(it) => setSegItem(it)}
              onShowSecurity={() => setSecSheet(true)} onToggleTheme={toggleTheme} onOpenHome={() => setFlow('home')} onOpenProfile={() => setFlow('profile')} onOpenServices={() => { setServiceView(null); setFlow('services'); }} />}
            {flow === 'services' && (
              serviceView === 'citas' ? <CitasService t={t} persona={persona} profile={profile} onBack={() => setServiceView(null)} onSchedule={(it) => { addToSeguimiento(it); setServiceView(null); setFlow('home'); }} onEnterCall={(cita) => { setTelemedCita(cita); setServiceView(null); setFlow('telemed'); }} />
              : serviceView === 'nutricion' ? <NutricionService t={t} persona={persona} profile={profile} asis={asis} nutricion={nutricion} loading={nutLoading} onGenerate={generateNutPlan} onBack={() => setServiceView(null)} onSchedule={(it) => { addToSeguimiento(it); setServiceView(null); setFlow('home'); }} />
              : serviceView === 'psicologia' ? <PsicologiaService t={t} persona={persona} onBack={() => setServiceView(null)} onSchedule={addToSeguimiento} />
              : serviceView === 'diagnostico' ? <DiagnosticoService t={t} persona={persona} profile={profile} onBack={() => setServiceView(null)} onSchedule={(it) => { addToSeguimiento(it); }} />
              : <ServicesScreen t={t} persona={persona} profile={profile} onOpen={(id) => setServiceView(id)} onTalk={() => setFlow('chat')} onToggleTheme={toggleTheme} onOpenHome={() => setFlow('home')} onOpenHistory={() => setFlow('history')} onOpenProfile={() => setFlow('profile')} />
            )}
            {flow === 'care' && <CareScreen t={t} persona={persona} profile={profile} tasks={careTasks} done={careDone} streaks={careDetails.streaks} terapias={careDetails.terapias} controles={careDetails.controles}
              postCita={postCitaItem} onOpenPostCita={() => setPostCitaSheet(true)} onToggle={toggleCare}
              onBack={() => setFlow('home')} onTalk={() => setFlow('chat')} onOpenHome={() => setFlow('home')} onOpenHistory={() => setFlow('history')} onOpenProfile={() => setFlow('profile')} onOpenServices={() => { setServiceView(null); setFlow('services'); }} />}
            {flow === 'notifs' && <NotificationCenter t={t} persona={persona} profile={profile} notifs={notifs} onAction={handleNotifAction} onBack={() => setFlow('home')} onSettings={() => setNotifSheet(true)} onSimulate={() => { setFlow('home'); setTimeout(simulateDay, 350); }} onLockPreview={() => setFlow('lock')} />}
            {flow === 'lock' && <LockScreen t={t} persona={persona} profile={profile} notifs={notifs} onUnlock={(nf) => { setFlow('home'); if (nf) setTimeout(() => handleNotifAction(nf.actions && nf.actions[0] === 'done' ? 'view' : (nf.actions ? nf.actions[0] : 'view'), nf), 300); }} onAction={handleNotifAction} />}
            {flow === 'done' && <DoneScreen t={t} persona={persona} profile={profile} onRestart={reset} onReopen={() => setFlow('chat')} />}
            {flow === 'telemed' && <TelemedExperience t={t} persona={persona} profile={profile} asis={asis} cita={telemedCita}
              onAddOrders={(items) => items.forEach(addToSeguimiento)}
              onExit={() => { setTelemedCita(null); setPostCitaDone(false); setFlow('home'); }} />}
            {sheet && <ProfileSheet t={t} persona={persona} profile={profile} progress={progress} onClose={() => setSheet(false)} />}
            {secSheet && <SecuritySheet t={t} persona={persona} onClose={() => setSecSheet(false)} />}
            {segItem && <SegActionSheet t={t} persona={persona} item={segItem} onClose={() => setSegItem(null)} onAdvance={advanceSeg} />}
            {addSheet && <AddInfoSheet t={t} persona={persona} onClose={() => setAddSheet(false)} onAdd={addInfo} />}
            {picSheet && <PicSheet t={t} persona={persona} pic={pic} onClose={() => setPicSheet(false)} />}
            {shareSheet && <ShareSheet t={t} persona={persona} profile={profile} onClose={() => setShareSheet(false)} />}
            {addMemberOpen && <AddMemberFlow t={t} persona={persona} titularName={(profile.nombre || 'Tú').split(' ')[0]} voice={voice} tts={tw.tts} onDone={addMember} onClose={() => setAddMemberOpen(false)} />}
            {dataSheet && <PersonalDataSheet t={t} persona={persona} profile={profile} onClose={() => setDataSheet(false)} />}
            {postCitaSheet && postCitaItem && <PostCitaSheet t={t} persona={persona} cita={postCitaItem} voice={voice} tts={tw.tts} onClose={() => setPostCitaSheet(false)} onResolve={resolvePostCita} />}
            {notifSheet && <NotifSettingsSheet t={t} persona={persona} settings={notifSettings} onChange={(k, v) => setNotifSettings(s => ({ ...s, [k]: v }))} onClose={() => setNotifSheet(false)} />}
            {/* push banner overlay — above everything inside the device */}
            {activeToast && triageDone && flow !== 'lock' && <PushBanner t={t} persona={persona} notif={activeToast} onAction={handleNotifAction} onDismiss={() => setActiveToast(null)} />}
            {reanalyzing && <ReanalyzeOverlay t={t} persona={persona} waveStyle={tw.waveStyle} nuevo={reanalyzing} />}
          </div>
        </IOSDevice>
      </div>

      <TweaksPanel>
        <TweakSection label="Personalidad de Vita" />
        <TweakRadio label="Estilo" value={tw.persona} options={['calida', 'serena', 'coach']} onChange={v => setTweak('persona', v)} />
        <TweakSection label="Voz" />
        <TweakSelect label="Voz de Vita"
          value={tw.voiceURI}
          options={[{ value: '', label: 'Automática · mejor colombiana ✨' }].concat((voice.spanishVoices || []).map(v => ({ value: v.uri, label: v.label })))}
          onChange={v => setTweak('voiceURI', v)} />
        <TweakButton label="▶  Escuchar a Vita" onClick={() => { voice.setPreferredVoice(tw.voiceURI); voice.speak('Hola, soy Vita. ¿Vos cómo te sentís hoy, pues? Contame y arrancamos.', persona); }} />
        <TweakRadio label="Visualización" value={tw.waveStyle} options={['barras', 'espejo', 'linea']} onChange={v => setTweak('waveStyle', v)} />
        <TweakToggle label="Vita habla (voz)" value={tw.tts} onChange={v => { if (!v) voice.stopSpeaking(); setTweak('tts', v); }} />
        <TweakSection label="Apariencia" />
        <TweakToggle label="Tema oscuro" value={tw.dark} onChange={v => setTweak('dark', v)} />
        <TweakSection label="Demo" />
        <TweakButton label="↺  Reiniciar demo (borrar memoria)" secondary onClick={reset} />
      </TweaksPanel>
    </div>
  );
}

Object.assign(window, { DoneScreen, ProfileSheet, VitaApp });
