// vita-collect.jsx — end-of-triage collection: documents + health plan (EPS) + pending items

const EPS_LIST = ['Sura', 'Nueva EPS', 'Sanitas', 'Salud Total', 'Compensar', 'Famisanar', 'Coosalud', 'Otra'];
const PREPAGADA_LIST = ['Colsanitas', 'Sura', 'MedPlus', 'Coomeva', 'Plan complementario', 'Ninguna'];

const DOC_REQUESTS = [
  { key: 'historia', label: 'Última historia clínica', hint: 'Tu resumen médico más reciente' },
  { key: 'examenes', label: 'Exámenes recientes', hint: 'Laboratorios, imágenes, resultados' },
  { key: 'visita', label: 'Última visita al médico', hint: 'Epicrisis, orden o recomendaciones' },
  { key: 'formula', label: 'Fórmulas y medicamentos', hint: 'Lo que te recetaron' },
];

const UPLOAD_METHODS = [
  { m: 'PDF', icon: 'doc' }, { m: 'Foto', icon: 'camera' }, { m: 'Escanear', icon: 'scan' },
];

const PENDING_TYPES = [
  { tipo: 'cita', label: 'Cita médica', icon: 'calendar' },
  { tipo: 'examen', label: 'Examen', icon: 'scan' },
  { tipo: 'laboratorio', label: 'Laboratorio', icon: 'lab' },
  { tipo: 'medicamento', label: 'Medicamento', icon: 'pill' },
];

function CollectScreen({ t, persona, profile, onComplete }) {
  const accent = persona.accent;
  const [uploaded, setUploaded] = React.useState({});   // key -> method
  const [pickerFor, setPickerFor] = React.useState(null);
  const [eps, setEps] = React.useState(profile.eps || '');
  const [prepagada, setPrepagada] = React.useState(profile.prepagada || '');
  const [pendings, setPendings] = React.useState([]);
  const [addType, setAddType] = React.useState(null);
  const [addText, setAddText] = React.useState('');

  const docs = Object.entries(uploaded).map(([k, m]) => {
    const d = DOC_REQUESTS.find(x => x.key === k);
    return (d ? d.label : k) + ' (' + m + ')';
  });

  const addPending = () => {
    if (!addText.trim()) return;
    const meta = PENDING_TYPES.find(p => p.tipo === addType);
    setPendings(ps => [...ps, { id: 'sg' + Date.now(), tipo: addType, titulo: addText.trim(), detalle: meta.label + ' por gestionar', estado: 'pendiente' }]);
    setAddText(''); setAddType(null);
  };

  return (
    <Stage t={t}>
      <div style={{ flex: 1, overflow: 'auto', padding: '58px 20px 16px' }}>
        {/* Vita intro */}
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 20 }}>
          <VitaDot t={t} size={40} active />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 25, color: t.text, lineHeight: 1.15 }}>Ahora yo me encargo</div>
            <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '6px 0 0', fontWeight: 450 }}>
              Súbeme lo que tengas a la mano — PDF, foto o escaneado. Yo lo guardo, lo organizo y le hago seguimiento a cada cosa por vos.
            </p>
          </div>
        </div>

        {/* Documents */}
        <CollectTitle t={t} icon="upload" accent={accent}>Sube tus documentos</CollectTitle>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 22 }}>
          {DOC_REQUESTS.map(d => {
            const done = uploaded[d.key];
            return (
              <button key={d.key} onClick={() => setPickerFor(d.key)} style={{
                display: 'flex', alignItems: 'center', gap: 13, padding: 14, borderRadius: 16, cursor: 'pointer', textAlign: 'left',
                border: `1.5px solid ${done ? hexA(t.green, 0.5) : t.stroke}`, background: done ? hexA(t.green, t.dark ? 0.1 : 0.07) : (t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF'),
                WebkitTapHighlightColor: 'transparent', transition: 'all .2s',
              }}>
                <span style={{ width: 42, height: 42, flexShrink: 0, borderRadius: 12, display: 'grid', placeItems: 'center', background: done ? t.green : hexA(accent, 0.13) }}>
                  {done ? Icon.check({ s: 22, c: '#fff', w: 3 }) : Icon.doc({ s: 21, c: accent })}
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{d.label}</div>
                  <div style={{ fontSize: 12.5, color: done ? t.green : t.muted, fontWeight: 500, marginTop: 1 }}>{done ? 'Subido por ' + done : d.hint}</div>
                </div>
                {!done && Icon.plus({ s: 20, c: accent })}
              </button>
            );
          })}
        </div>

        {/* Health plan */}
        <CollectTitle t={t} icon="card" accent={accent}>Tu seguro de salud</CollectTitle>
        <div style={{ fontSize: 13, color: t.muted, marginBottom: 9, fontWeight: 500 }}>EPS</div>
        <ChipRow items={EPS_LIST} value={eps} onPick={setEps} t={t} accent={accent} />
        <div style={{ fontSize: 13, color: t.muted, margin: '16px 0 9px', fontWeight: 500 }}>Medicina prepagada o plan</div>
        <ChipRow items={PREPAGADA_LIST} value={prepagada} onPick={setPrepagada} t={t} accent={accent} />

        {/* Pending items */}
        <div style={{ height: 22 }} />
        <CollectTitle t={t} icon="bell" accent={accent}>¿Te dejaron pendientes?</CollectTitle>
        <p style={{ fontSize: 13, color: t.muted, margin: '0 0 12px', lineHeight: 1.45, fontWeight: 450 }}>
          Citas por pedir, exámenes, laboratorios o medicamentos. Yo me encargo de que se cumplan.
        </p>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
          {PENDING_TYPES.map(p => (
            <button key={p.tipo} onClick={() => { setAddType(p.tipo); setAddText(''); }} style={{
              display: 'flex', alignItems: 'center', gap: 7, padding: '9px 13px', borderRadius: 12, cursor: 'pointer',
              border: `1.5px solid ${addType === p.tipo ? accent : t.stroke}`, background: addType === p.tipo ? hexA(accent, 0.12) : 'transparent',
              color: addType === p.tipo ? accent : t.textSoft, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 13.5, fontWeight: 600, WebkitTapHighlightColor: 'transparent',
            }}>
              {Icon[p.icon]({ s: 16, c: addType === p.tipo ? accent : t.muted })}{p.label}
            </button>
          ))}
        </div>
        {addType && (
          <div style={{ display: 'flex', gap: 8, marginBottom: 12, animation: 'vitaIn .2s both' }}>
            <input autoFocus value={addText} onChange={e => setAddText(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addPending(); }}
              placeholder={'Ej. ' + (addType === 'cita' ? 'Control con cardiólogo' : addType === 'examen' ? 'Ecografía abdominal' : addType === 'laboratorio' ? 'Perfil lipídico' : 'Losartán 50mg')}
              style={{ flex: 1, padding: '12px 14px', borderRadius: 13, border: `1.5px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.05)' : '#fff', color: t.text, fontSize: 14.5, fontFamily: 'Hanken Grotesk, sans-serif', outline: 'none' }} />
            <button onClick={addPending} style={{ width: 46, borderRadius: 13, border: 'none', cursor: 'pointer', background: `linear-gradient(135deg, ${accent}, ${persona.accentDeep})`, color: t.onAccent, display: 'grid', placeItems: 'center' }}>{Icon.plus({ s: 22, c: t.onAccent })}</button>
          </div>
        )}
        {pendings.length > 0 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {pendings.map(p => {
              const meta = PENDING_TYPES.find(x => x.tipo === p.tipo);
              return (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', borderRadius: 13, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FFFFFF', border: `1px solid ${t.stroke}` }}>
                  <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: 'grid', placeItems: 'center', background: hexA(accent, 0.13) }}>{Icon[meta.icon]({ s: 17, c: accent })}</span>
                  <span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: t.text }}>{p.titulo}</span>
                  <button onClick={() => setPendings(ps => ps.filter(x => x.id !== p.id))} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: t.muted, display: 'grid', placeItems: 'center' }}>{Icon.x({ s: 17, c: t.muted })}</button>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* upload method picker */}
      {pickerFor && (
        <div onClick={() => setPickerFor(null)} style={{ position: 'absolute', inset: 0, zIndex: 30, background: 'rgba(3,10,24,0.55)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-end', animation: 'vitaFade .2s both' }}>
          <div onClick={e => e.stopPropagation()} style={{ width: '100%', borderRadius: '24px 24px 0 0', background: t.dark ? t.bg1 : '#fff', border: `1px solid ${t.stroke}`, padding: '14px 20px 36px', animation: 'vitaSheet .3s cubic-bezier(.2,.8,.2,1) both' }}>
            <div style={{ width: 40, height: 5, borderRadius: 999, background: t.strokeStrong, margin: '0 auto 16px' }} />
            <div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginBottom: 14 }}>¿Cómo quieres subirlo?</div>
            <div style={{ display: 'flex', gap: 10 }}>
              {UPLOAD_METHODS.map(u => (
                <button key={u.m} onClick={() => { setUploaded(s => ({ ...s, [pickerFor]: u.m })); setPickerFor(null); }} style={{
                  flex: 1, padding: '18px 8px', borderRadius: 16, cursor: 'pointer', border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FBFCFE',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9, color: t.text, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 13.5, fontWeight: 600, WebkitTapHighlightColor: 'transparent',
                }}>
                  <span style={{ width: 46, height: 46, borderRadius: 14, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14) }}>{Icon[u.icon]({ s: 24, c: accent })}</span>
                  {u.m}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* CTA */}
      <div style={{ padding: '8px 20px 30px', background: t.dark ? 'linear-gradient(180deg, transparent, rgba(6,18,43,0.9) 30%)' : 'linear-gradient(180deg, transparent, rgba(244,247,251,0.95) 30%)' }}>
        <BigButton t={t} onClick={() => onComplete({ docs, eps, prepagada, pendings })}>
          {Icon.sparkle({ s: 17, c: t.onAccent })} Generar mi análisis (ASIS)
        </BigButton>
        <button onClick={() => onComplete({ docs, eps, prepagada, pendings })} style={{ width: '100%', marginTop: 9, border: 'none', background: 'transparent', cursor: 'pointer', color: t.muted, fontSize: 13, fontWeight: 500, fontFamily: 'Hanken Grotesk, sans-serif' }}>
          Omitir por ahora — lo subo después
        </button>
      </div>
    </Stage>
  );
}

function CollectTitle({ t, icon, accent, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '0 0 12px' }}>
      <span style={{ width: 26, height: 26, borderRadius: 8, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14) }}>{Icon[icon]({ s: 15, c: accent })}</span>
      <span style={{ fontSize: 13, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase', color: t.text }}>{children}</span>
    </div>
  );
}

function ChipRow({ items, value, onPick, t, accent }) {
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      {items.map(it => {
        const on = value === it;
        return (
          <button key={it} onClick={() => onPick(on ? '' : it)} style={{
            padding: '9px 14px', borderRadius: 11, cursor: 'pointer', border: `1.5px solid ${on ? accent : t.stroke}`,
            background: on ? hexA(accent, 0.13) : 'transparent', color: on ? accent : t.textSoft,
            fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 13.5, fontWeight: on ? 700 : 500, WebkitTapHighlightColor: 'transparent', transition: 'all .15s',
          }}>{it}</button>
        );
      })}
    </div>
  );
}

Object.assign(window, { CollectScreen });
