// vita-history.jsx — Clinical history: patient-friendly dashboard + norm-compliant medical view

const DOCTYPE = 'CC';
function pacienteEdad(profile) { return profile.edad ? (String(profile.edad).replace(/\D/g, '') || profile.edad) : '—'; }
function folio(profile) {
  const base = (profile.nombre || 'PREVENT').replace(/\s/g, '').toUpperCase();
  let h = 0; for (let i = 0; i < base.length; i++) h = (h * 31 + base.charCodeAt(i)) % 1000000;
  return 'HC-' + String(100000 + h).slice(0, 6);
}
function hoy() { return new Date().toLocaleDateString('es-CO', { day: '2-digit', month: '2-digit', year: 'numeric' }); }
function arrify(v) { return Array.isArray(v) ? v : (v ? [v] : []); }

// ── Build the patient timeline from session state ───────────────
function buildTimeline(profile, asis, docs, seguimiento, version) {
  const ev = [];
  ev.push({ icon: 'mic', color: 'accent', titulo: 'Primer triage con Vita', detalle: 'Tu historia de salud quedó registrada', cuando: 'Inicio' });
  if (docs && docs.length) ev.push({ icon: 'doc', color: 'accent', titulo: docs.length + ' documento' + (docs.length > 1 ? 's' : '') + ' guardado' + (docs.length > 1 ? 's' : ''), detalle: docs.slice(0, 3).join(' · '), cuando: 'Inicio' });
  ev.push({ icon: 'sparkle', color: 'green', titulo: 'Vita preparó tu análisis (ASIS)', detalle: asis ? asis.estadoTexto : 'Análisis de tu situación de salud', cuando: 'Inicio' });
  (seguimiento || []).forEach(s => {
    const done = ['agendado', 'activo', 'completado'].includes(s.estado);
    ev.push({ icon: (window.SEG_ICON && window.SEG_ICON[s.tipo]) || 'calendar', color: done ? 'green' : 'amber', titulo: s.titulo, detalle: done ? 'Vita lo gestionó' : 'Vita está pendiente', cuando: 'En curso' });
  });
  if (version > 1) ev.push({ icon: 'refresh', color: 'accent', titulo: 'Historia actualizada (v' + version + ')', detalle: 'Sumaste información nueva', cuando: 'Reciente' });
  return ev;
}

function HistoryScreen({ t, persona, profile, asis, docs, seguimiento, version, hcFormal, hcLoading, onGenerateFormal, onShare, onBack, onTalk, onOpenSeg, onShowSecurity, onToggleTheme, onOpenHome, onOpenProfile, onOpenServices }) {
  const [mode, setMode] = React.useState('paciente'); // paciente | medica
  const accent = persona.accent;
  const colorMap = { accent: accent, green: t.green, amber: '#E6A93C' };

  React.useEffect(() => {
    if (mode === 'medica' && !hcFormal && !hcLoading) onGenerateFormal();
  }, [mode]);

  return (
    <Stage t={t}>
      {/* header */}
      <div style={{ paddingTop: 58, padding: '58px 18px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <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>
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 24, color: t.text, lineHeight: 1 }}>Historia clínica</div>
            <div style={{ fontSize: 11.5, color: t.muted, fontWeight: 500, marginTop: 2 }}>Administrada por Vita · {folio(profile)}</div>
          </div>
        </div>
        <IconBtn t={t} onClick={onShare} title="Compartir">{Icon.upload({ s: 18, c: accent })}</IconBtn>
      </div>

      {/* mode toggle */}
      <div style={{ padding: '10px 18px 6px' }}>
        <div style={{ display: 'flex', gap: 4, padding: 4, borderRadius: 14, background: t.dark ? 'rgba(255,255,255,0.05)' : 'rgba(10,26,51,0.04)', border: `1px solid ${t.stroke}` }}>
          {[['paciente', 'Para ti', 'heart'], ['medica', 'Para tu médico', 'doc']].map(([m, label, ic]) => (
            <button key={m} onClick={() => setMode(m)} style={{
              flex: 1, padding: '10px 0', borderRadius: 10, cursor: 'pointer', border: 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
              background: mode === m ? `linear-gradient(135deg, ${accent}, ${persona.accentDeep})` : 'transparent',
              color: mode === m ? t.onAccent : t.textSoft, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 14, fontWeight: 700,
              boxShadow: mode === m ? `0 6px 16px ${hexA(accent, 0.3)}` : 'none', transition: 'all .2s',
            }}>{Icon[ic]({ s: 16, c: mode === m ? t.onAccent : t.muted })}{label}</button>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '12px 18px 96px' }}>
        {mode === 'paciente'
          ? <PacienteView t={t} persona={persona} profile={profile} asis={asis} docs={docs} seguimiento={seguimiento} version={version} colorMap={colorMap} onOpenSeg={onOpenSeg} />
          : <MedicaView t={t} persona={persona} profile={profile} hc={hcFormal} loading={hcLoading} onShare={onShare} />}
      </div>

      <BottomNav t={t} persona={persona} active="historia" onTalk={onTalk} onOpenHome={onOpenHome} onOpenHistory={() => {}} onOpenProfile={onOpenProfile} onOpenServices={onOpenServices} onShowSecurity={onShowSecurity} onAddInfo={onTalk} />
    </Stage>
  );
}

// ── Patient-friendly view ───────────────────────────────────────
function PacienteView({ t, persona, profile, asis, docs, seguimiento, version, colorMap, onOpenSeg }) {
  const accent = persona.accent;
  const timeline = buildTimeline(profile, asis, docs, seguimiento, version);
  const cards = [
    { icon: 'heart', label: 'Lo que cuidamos', items: arrify(profile.condiciones), empty: 'Sin condiciones registradas' },
    { icon: 'pill', label: 'Tus medicamentos', items: arrify(profile.medicamentos), empty: 'Sin medicamentos' },
    { icon: 'alert', label: 'Tus alergias', items: arrify(profile.alergias), empty: 'Sin alergias conocidas' },
    { icon: 'animo', label: 'En tu familia', items: arrify(profile.antecedentes), empty: 'Sin antecedentes' },
  ];
  return (
    <div>
      {/* patient summary */}
      <div style={{ borderRadius: 20, padding: 16, marginBottom: 16, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}`, display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 52, height: 52, borderRadius: 16, flexShrink: 0, display: 'grid', placeItems: 'center', background: `linear-gradient(135deg, ${accent}, ${persona.accentDeep})`, color: t.onAccent, fontFamily: 'Instrument Serif, serif', fontSize: 24 }}>
          {(profile.nombre || 'P').charAt(0)}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: t.text }}>{profile.nombre || 'Paciente'}</div>
          <div style={{ fontSize: 13, color: t.muted, fontWeight: 500 }}>{[pacienteEdad(profile) !== '—' ? pacienteEdad(profile) + ' años' : null, profile.sexo, profile.eps].filter(Boolean).join(' · ')}</div>
        </div>
      </div>

      {/* key cards */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
        {cards.map((c, i) => (
          <div key={i} style={{ borderRadius: 18, padding: 14, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(accent, 0.13), marginBottom: 9 }}>{Icon[c.icon]({ s: 19, c: accent })}</div>
            <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.3, textTransform: 'uppercase', color: t.muted, marginBottom: 6 }}>{c.label}</div>
            {c.items.length ? c.items.map((it, j) => (
              <div key={j} style={{ fontSize: 13.5, color: t.text, fontWeight: 500, lineHeight: 1.4, marginBottom: 2 }}>• {it}</div>
            )) : <div style={{ fontSize: 13, color: t.muted, fontWeight: 450 }}>{c.empty}</div>}
          </div>
        ))}
      </div>

      {/* timeline */}
      <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase', color: t.muted, margin: '4px 4px 12px' }}>Tu línea de tiempo</div>
      <div style={{ position: 'relative', paddingLeft: 6 }}>
        {timeline.map((e, i) => {
          const col = colorMap[e.color] || accent;
          return (
            <div key={i} style={{ display: 'flex', gap: 13, paddingBottom: i === timeline.length - 1 ? 0 : 16, position: 'relative' }}>
              {i !== timeline.length - 1 && <div style={{ position: 'absolute', left: 17, top: 36, bottom: 0, width: 2, background: t.stroke }} />}
              <div style={{ width: 36, height: 36, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(col, 0.15), zIndex: 1 }}>{Icon[e.icon]({ s: 18, c: col })}</div>
              <div style={{ flex: 1, paddingTop: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, lineHeight: 1.3 }}>{e.titulo}</div>
                  <div style={{ fontSize: 11, color: t.muted, fontWeight: 600, flexShrink: 0, marginTop: 2 }}>{e.cuando}</div>
                </div>
                <div style={{ fontSize: 13, color: t.textSoft, lineHeight: 1.4, marginTop: 2, fontWeight: 450 }}>{e.detalle}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Medical / norm-compliant view ───────────────────────────────
function MedicaView({ t, persona, profile, hc, loading, onShare }) {
  if (loading || !hc) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '60px 20px', textAlign: 'center' }}>
        <Spinner c={persona.accent} />
        <div style={{ fontSize: 14.5, color: t.textSoft, marginTop: 14, fontWeight: 500 }}>Vita está estructurando tu historia<br/>en formato clínico oficial…</div>
      </div>
    );
  }
  const ant = hc.antecedentes || {};
  // formal document — white "paper" regardless of theme for that official feel
  const paper = '#FFFFFF', ink = '#0A1A33', sub = '#5A6B86', line = 'rgba(10,26,51,0.10)';
  return (
    <div>
      {/* compliance banner */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
        {['Res. 1995/1999', 'Res. 866/2021 · HCE', 'HL7 FHIR', 'CIE-10'].map(b => (
          <span key={b} style={{ fontSize: 11, fontWeight: 700, color: persona.accent, background: hexA(persona.accent, 0.12), padding: '5px 9px', borderRadius: 8, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            {Icon.shield({ s: 12, c: persona.accent })}{b}
          </span>
        ))}
      </div>

      {/* the document */}
      <div style={{ borderRadius: 16, overflow: 'hidden', border: `1px solid ${line}`, background: paper, boxShadow: '0 12px 30px rgba(10,26,51,0.16)' }}>
        {/* doc header */}
        <div style={{ padding: '16px 18px', borderBottom: `2px solid ${ink}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, display: 'grid', placeItems: 'center', background: `linear-gradient(135deg, ${persona.accent}, ${persona.accentDeep})` }}>{Icon.pulse({ s: 17, c: '#fff', w: 2.4 })}</div>
            <div>
              <div style={{ fontFamily: 'Hanken Grotesk, sans-serif', fontWeight: 800, letterSpacing: 1.5, fontSize: 12, color: ink, textTransform: 'uppercase' }}>prevent</div>
              <div style={{ fontSize: 9.5, color: sub, fontWeight: 600, letterSpacing: 0.3 }}>HISTORIA CLÍNICA ELECTRÓNICA</div>
            </div>
          </div>
          <div style={{ textAlign: 'right', fontSize: 9.5, color: sub, fontWeight: 600, lineHeight: 1.5 }}>
            <div>Folio {folio(profile)}</div>
            <div>{hoy()}</div>
          </div>
        </div>

        <div style={{ padding: '14px 18px 18px' }}>
          {/* 1. Identificación */}
          <DocSection ink={ink} sub={sub} line={line} n="1" titulo="Identificación del usuario">
            <IdGrid ink={ink} sub={sub} rows={[
              ['Nombre', profile.nombre || '—'], ['Documento', DOCTYPE + ' · Pendiente de verificación'],
              ['Edad', pacienteEdad(profile) !== '—' ? pacienteEdad(profile) + ' años' : '—'], ['Sexo', profile.sexo || '—'],
              ['EPS', profile.eps || '—'], ['Plan / Prepagada', profile.prepagada || 'No refiere'],
            ]} />
          </DocSection>

          {/* 2. Motivo de consulta */}
          <DocSection ink={ink} sub={sub} line={line} n="2" titulo="Motivo de consulta">
            <P ink={ink}>{hc.motivoConsulta}</P>
          </DocSection>

          {/* 3. Enfermedad actual */}
          <DocSection ink={ink} sub={sub} line={line} n="3" titulo="Enfermedad actual / Anamnesis">
            <P ink={ink}>{hc.enfermedadActual}</P>
          </DocSection>

          {/* 4. Revisión por sistemas */}
          <DocSection ink={ink} sub={sub} line={line} n="4" titulo="Revisión por sistemas">
            <P ink={ink}>{hc.revisionSistemas}</P>
          </DocSection>

          {/* 5. Antecedentes */}
          <DocSection ink={ink} sub={sub} line={line} n="5" titulo="Antecedentes">
            {[['Personales / patológicos', ant.personales], ['Familiares', ant.familiares], ['Alérgicos', ant.alergicos], ['Farmacológicos', ant.farmacologicos], ['Hábitos / estilo de vida', ant.habitos]].map(([lab, items], i) => (
              <div key={i} style={{ marginBottom: 7 }}>
                <span style={{ fontSize: 11.5, fontWeight: 700, color: sub }}>{lab}: </span>
                <span style={{ fontSize: 12.5, color: ink, fontWeight: 500 }}>{arrify(items).length ? arrify(items).join('; ') : 'No refiere'}</span>
              </div>
            ))}
          </DocSection>

          {/* 6. Diagnósticos CIE-10 */}
          <DocSection ink={ink} sub={sub} line={line} n="6" titulo="Diagnósticos (CIE-10)">
            {arrify(hc.diagnosticos).length ? arrify(hc.diagnosticos).map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 9, padding: '7px 0', borderTop: i ? `1px solid ${line}` : 'none' }}>
                <span style={{ fontSize: 11.5, fontWeight: 800, color: persona.accentDeep, background: hexA(persona.accent, 0.13), padding: '3px 7px', borderRadius: 6, flexShrink: 0, fontFamily: 'monospace', letterSpacing: 0.3 }}>{d.cie10 || '—'}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, color: ink, fontWeight: 600, lineHeight: 1.35 }}>{d.descripcion}</div>
                  <div style={{ fontSize: 10.5, color: sub, fontWeight: 600, marginTop: 1 }}>{d.tipo || ''}</div>
                </div>
              </div>
            )) : <P ink={ink}>Sin diagnósticos codificados.</P>}
          </DocSection>

          {/* 7. Plan de manejo */}
          <DocSection ink={ink} sub={sub} line={line} n="7" titulo="Plan de manejo / Conducta">
            {arrify(hc.planManejo).map((p, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 5 }}><span style={{ color: persona.accentDeep, fontWeight: 800, fontSize: 12.5 }}>{i + 1}.</span><span style={{ fontSize: 12.5, color: ink, fontWeight: 500, lineHeight: 1.4 }}>{p}</span></div>
            ))}
          </DocSection>

          {/* 8. Órdenes / pendientes */}
          {arrify(hc.ordenesPendientes).length > 0 && (
            <DocSection ink={ink} sub={sub} line={line} n="8" titulo="Órdenes y solicitudes" last>
              {arrify(hc.ordenesPendientes).map((o, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 5, alignItems: 'center' }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: persona.accent }} /><span style={{ fontSize: 12.5, color: ink, fontWeight: 500 }}>{o}</span></div>
              ))}
            </DocSection>
          )}

          {/* signature footer */}
          <div style={{ marginTop: 16, paddingTop: 12, borderTop: `1px dashed ${line}`, display: 'flex', alignItems: 'center', gap: 9 }}>
            {Icon.shield({ s: 16, c: persona.accentDeep })}
            <div style={{ fontSize: 10.5, color: sub, fontWeight: 500, lineHeight: 1.45 }}>
              Registro generado y custodiado por <b style={{ color: ink }}>Vita · PREVENT</b>. Documento con trazabilidad y firma digital. La verificación de identidad documental se completa en la primera atención presencial.
            </div>
          </div>
        </div>
      </div>

      <button onClick={onShare} style={{ width: '100%', marginTop: 16, padding: '15px', borderRadius: 15, border: 'none', cursor: 'pointer', background: `linear-gradient(135deg, ${persona.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 24px ${hexA(persona.accent, 0.4)}` }}>
        {Icon.upload({ s: 18, c: t.onAccent })} Compartir con mi médico
      </button>
    </div>
  );
}

function DocSection({ ink, sub, line, n, titulo, children, last }) {
  return (
    <div style={{ marginBottom: last ? 0 : 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 7 }}>
        <span style={{ width: 18, height: 18, borderRadius: 5, flexShrink: 0, display: 'grid', placeItems: 'center', background: ink, color: '#fff', fontSize: 10.5, fontWeight: 800 }}>{n}</span>
        <span style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: 0.5, textTransform: 'uppercase', color: ink }}>{titulo}</span>
      </div>
      <div style={{ paddingLeft: 25 }}>{children}</div>
    </div>
  );
}
function P({ ink, children }) { return <div style={{ fontSize: 12.5, color: ink, fontWeight: 500, lineHeight: 1.5 }}>{children}</div>; }
function IdGrid({ ink, sub, rows }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '7px 12px' }}>
      {rows.map(([k, v], i) => (
        <div key={i}>
          <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: 0.3, textTransform: 'uppercase', color: sub }}>{k}</div>
          <div style={{ fontSize: 12.5, color: ink, fontWeight: 600, lineHeight: 1.3 }}>{v}</div>
        </div>
      ))}
    </div>
  );
}

// ── Share sheet ─────────────────────────────────────────────────
function ShareSheet({ t, persona, profile, onClose }) {
  const [sent, setSent] = React.useState(false);
  const accent = persona.accent;
  const options = [
    { icon: 'doc', label: 'Descargar PDF oficial', desc: 'Formato historia clínica · Res. 1995/1999' },
    { icon: 'mail', label: 'Enviar a mi médico', desc: 'Por correo seguro y cifrado' },
    { icon: 'card', label: 'Código QR temporal', desc: 'El médico lo escanea en consulta' },
    { icon: 'shield', label: 'Acceso por interoperabilidad', desc: 'HL7 FHIR a la institución (Res. 866/2021)' },
  ];
  return (
    <Sheet t={t} onClose={onClose}>
      {!sent ? (
        <>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 26, color: t.text, marginBottom: 4 }}>Compartir con tu médico</div>
          <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '0 0 16px', fontWeight: 450 }}>Tú decides qué se comparte y por cuánto tiempo. Vita entrega tu historia en formato clínico oficial.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {options.map((o, i) => (
              <button key={i} onClick={() => setSent(o.label)} style={{
                display: 'flex', alignItems: 'center', gap: 13, padding: 14, borderRadius: 15, cursor: 'pointer', textAlign: 'left', width: '100%',
                border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', WebkitTapHighlightColor: 'transparent',
              }}>
                <span style={{ width: 42, height: 42, flexShrink: 0, borderRadius: 12, display: 'grid', placeItems: 'center', background: hexA(accent, 0.13) }}>{Icon[o.icon]({ s: 21, c: accent })}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{o.label}</div>
                  <div style={{ fontSize: 12.5, color: t.muted, fontWeight: 500, marginTop: 1 }}>{o.desc}</div>
                </div>
                {Icon.chevron({ s: 17, c: t.muted })}
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 14, color: t.muted, fontSize: 12, fontWeight: 500, justifyContent: 'center' }}>
            {Icon.lock({ s: 13, c: t.muted })} Acceso revocable en cualquier momento
          </div>
        </>
      ) : (
        <div style={{ textAlign: 'center', padding: '14px 0 6px' }}>
          <div style={{ width: 72, height: 72, borderRadius: '50%', background: t.green, display: 'grid', placeItems: 'center', margin: '0 auto 16px', boxShadow: `0 10px 26px ${hexA(t.green, 0.5)}` }}>{Icon.check({ s: 40, c: '#fff', w: 3 })}</div>
          <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 25, color: t.text, marginBottom: 6 }}>Listo, ya lo compartí</div>
          <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '0 auto 18px', maxWidth: 280, fontWeight: 450 }}>
            “{sent}” quedó disponible en formato clínico oficial. Tu médico verá una historia completa y conforme a la norma.
          </p>
          <button onClick={onClose} 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 }}>Entendido</button>
        </div>
      )}
    </Sheet>
  );
}

Object.assign(window, { HistoryScreen, ShareSheet });
