// vita-security.jsx — facial recognition scan + data-security sheet

function FaceScan({ t, persona, onDone, onCancel, enroll, mode, badgeText, alignText, doneText, subtitleText }) {
  const accent = persona.accent;
  const videoRef = React.useRef(null);
  const [hasCam, setHasCam] = React.useState(false);
  const [phase, setPhase] = React.useState('align'); // align | scanning | done
  const [progress, setProgress] = React.useState(0);
  const progRef = React.useRef(0);

  // camera (graceful fallback if denied/unavailable)
  React.useEffect(() => {
    let stream;
    const md = navigator.mediaDevices;
    if (md && md.getUserMedia) {
      md.getUserMedia({ video: { facingMode: 'user' }, audio: false })
        .then(s => { stream = s; if (videoRef.current) { videoRef.current.srcObject = s; videoRef.current.play().catch(() => {}); } setHasCam(true); })
        .catch(() => setHasCam(false));
    }
    return () => { if (stream) stream.getTracks().forEach(tr => tr.stop()); };
  }, []);

  // scan sequence (setInterval — reliable in preview)
  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase('scanning'), 900);
    let iv;
    const t2 = setTimeout(() => {
      iv = setInterval(() => {
        progRef.current = Math.min(100, progRef.current + 3.2);
        setProgress(progRef.current);
        if (progRef.current >= 100) {
          clearInterval(iv);
          setPhase('done');
          setTimeout(() => onDone && onDone(), 1100);
        }
      }, 70);
    }, 950);
    return () => { clearTimeout(t1); clearTimeout(t2); clearInterval(iv); };
  }, []);

  const done = phase === 'done';
  const ring = done ? t.green : accent;
  const status = phase === 'align' ? (mode === 'switch' ? (alignText || 'Confirma tu identidad') : enroll ? 'Registra tu rostro' : 'Centra tu rostro en el marco')
    : phase === 'scanning' ? (mode === 'switch' ? 'Verificando…' : enroll ? 'Creando tu identidad biométrica…' : 'Verificando tu identidad…')
    : (mode === 'switch' ? (doneText || 'Identidad confirmada') : enroll ? 'Rostro registrado' : 'Identidad verificada');

  const V = 248; // viewport size

  return (
    <Stage t={t}>
      <div style={{ position: 'absolute', top: 60, left: 12, zIndex: 6 }}>
        <IconBtn t={t} onClick={onCancel} title="Atrás"><span style={{ display: 'flex', transform: 'rotate(180deg)' }}>{Icon.chevron({ s: 18, c: t.textSoft, w: 2.5 })}</span></IconBtn>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 30px' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 13px', borderRadius: 999, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.05)' : 'rgba(10,26,51,0.04)', marginBottom: 26 }}>
          {Icon.faceid({ s: 16, c: accent })}
          <span style={{ fontSize: 12.5, fontWeight: 700, color: t.textSoft, letterSpacing: 0.3 }}>{badgeText || 'RECONOCIMIENTO FACIAL'}</span>
        </div>

        {/* viewport */}
        <div style={{
          position: 'relative', width: V, height: V, borderRadius: '50%', overflow: 'hidden',
          background: 'radial-gradient(circle at 50% 38%, #11254c, #07142e)',
          boxShadow: `0 0 0 2px ${hexA(ring, 0.5)}, 0 0 60px ${hexA(ring, done ? 0.5 : 0.3)}, inset 0 0 40px rgba(0,0,0,0.5)`,
          transition: 'box-shadow .5s', animation: phase === 'scanning' ? 'vitaBreathe 2.4s ease-in-out infinite' : 'none',
        }}>
          {/* camera feed */}
          <video ref={videoRef} muted playsInline style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
            transform: 'scaleX(-1)', opacity: hasCam ? (done ? 0.85 : 0.95) : 0,
            filter: done ? 'none' : 'saturate(1.05)',
          }} />
          {/* fallback silhouette */}
          {!hasCam && (
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', color: hexA('#9fb4d6', 0.35) }}>
              <svg viewBox="0 0 24 24" width={120} height={120} fill="currentColor"><circle cx="12" cy="8.5" r="4.2" /><path d="M3.5 21c0-4.6 4-7.2 8.5-7.2s8.5 2.6 8.5 7.2z" /></svg>
            </div>
          )}
          {/* tint */}
          <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(circle at 50% 45%, transparent 45%, ${hexA('#06122B', 0.55)} 100%)` }} />

          {/* face oval guide */}
          <svg viewBox="0 0 248 248" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
            <ellipse cx="124" cy="120" rx="76" ry="96" fill="none" stroke={hexA(ring, 0.85)} strokeWidth="2.5"
              strokeDasharray="10 12" style={{ animation: phase === 'scanning' ? 'vitaDash 3s linear infinite' : 'none' }} />
          </svg>

          {/* corner brackets */}
          {[[18, 18, 0], [230, 18, 90], [230, 230, 180], [18, 230, 270]].map(([x, y, r], i) => (
            <div key={i} style={{ position: 'absolute', left: x - 18, top: y - 18, width: 26, height: 26,
              borderTop: `3px solid ${ring}`, borderLeft: `3px solid ${ring}`, borderTopLeftRadius: 6,
              transform: `rotate(${r}deg)`, transformOrigin: 'center', opacity: 0.9, transition: 'border-color .4s' }} />
          ))}

          {/* sweep line */}
          {phase === 'scanning' && (
            <div style={{ position: 'absolute', left: '8%', right: '8%', height: 3, borderRadius: 3,
              background: `linear-gradient(90deg, transparent, ${accent}, transparent)`,
              boxShadow: `0 0 16px 3px ${hexA(accent, 0.7)}`, animation: 'vitaScan 2.2s ease-in-out infinite' }} />
          )}

          {/* success check */}
          {done && (
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', animation: 'vitaIn .4s both' }}>
              <div style={{ width: 76, height: 76, borderRadius: '50%', background: t.green, display: 'grid', placeItems: 'center', boxShadow: `0 8px 30px ${hexA(t.green, 0.6)}` }}>
                {Icon.check({ s: 42, c: '#fff', w: 3 })}
              </div>
            </div>
          )}

          {/* progress ring overlay */}
          <div style={{ position: 'absolute', inset: -7, pointerEvents: 'none' }}>
            <svg width={V + 14} height={V + 14} style={{ transform: 'rotate(-90deg)' }}>
              <circle cx={(V + 14) / 2} cy={(V + 14) / 2} r={V / 2 + 2} fill="none" stroke={ring} strokeWidth="3.5"
                strokeDasharray={2 * Math.PI * (V / 2 + 2)} strokeDashoffset={2 * Math.PI * (V / 2 + 2) * (1 - progress / 100)}
                strokeLinecap="round" style={{ transition: 'stroke-dashoffset .12s linear, stroke .4s' }} />
            </svg>
          </div>
        </div>

        <h2 style={{ fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 27, color: t.text, margin: '30px 0 6px', textAlign: 'center' }}>{status}</h2>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, color: t.muted, fontSize: 12.5, fontWeight: 500, textAlign: 'center', padding: '0 20px', justifyContent: 'center' }}>
          {!done && subtitleText ? <span>{subtitleText}</span> : <>{Icon.lock({ s: 14, c: t.muted })} Tu rostro nunca sale de tu dispositivo · Cifrado E2E</>}
        </div>
      </div>

      <div style={{ padding: '0 30px 40px' }}>
        <button onClick={onCancel} disabled={done} style={{
          width: '100%', padding: '14px', borderRadius: 16, cursor: done ? 'default' : 'pointer',
          border: `1.5px solid ${t.strokeStrong}`, background: 'transparent', color: t.textSoft,
          fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15, fontWeight: 600, opacity: done ? 0.4 : 1,
        }}>{mode === 'switch' ? 'Cancelar' : enroll ? 'Volver' : 'Usar contraseña'}</button>
      </div>
    </Stage>
  );
}

// ── Security / data-protection bottom sheet ─────────────────────
const SECURITY_ITEMS = [
  { icon: 'lock', title: 'Cifrado de extremo a extremo', desc: 'Tus datos viajan y se guardan cifrados (AES-256 · TLS). Nadie los lee en el camino.' },
  { icon: 'user', title: 'Tú eres el dueño de tu información', desc: 'Otorgas y revocas el acceso cuando quieras. Ley 1581 de 2012 — Habeas Data.' },
  { icon: 'faceid', title: 'Acceso solo con tu biometría', desc: 'Tu historia se abre con tu rostro o huella. Nadie más entra.' },
  { icon: 'shield', title: 'PREVENT es custodio neutral', desc: 'Orquestamos tus datos entre instituciones — no los vendemos ni comercializamos.' },
];

function SecuritySheet({ t, persona, onClose }) {
  const accent = persona.accent;
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 80, background: 'rgba(3,10,24,0.55)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-end', animation: 'vitaFade .2s ease both' }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxHeight: '86%', overflow: 'auto', borderRadius: '26px 26px 0 0',
        background: t.dark ? t.bg1 : '#FFFFFF', border: `1px solid ${t.stroke}`, borderBottom: 'none',
        padding: '14px 22px 38px', animation: 'vitaSheet .32s cubic-bezier(.2,.8,.2,1) both',
      }}>
        <div style={{ width: 40, height: 5, borderRadius: 999, background: t.strokeStrong, margin: '0 auto 18px' }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <div style={{ width: 40, height: 40, borderRadius: 12, display: 'grid', placeItems: 'center', background: hexA(accent, 0.14) }}>{Icon.shield({ s: 22, c: accent })}</div>
          <h3 style={{ fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 27, color: t.text, margin: 0 }}>Tu información está blindada</h3>
        </div>
        <p style={{ fontSize: 14, color: t.textSoft, lineHeight: 1.5, margin: '6px 2px 18px', fontWeight: 450 }}>
          La salud es lo más íntimo que tienes. Por eso la seguridad no es una función — es la base de PREVENT.
        </p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {SECURITY_ITEMS.map((s, i) => (
            <div key={i} style={{ display: 'flex', gap: 13, padding: 14, borderRadius: 16, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#FBFCFE' }}>
              <div style={{ width: 38, height: 38, flexShrink: 0, borderRadius: 11, display: 'grid', placeItems: 'center', background: hexA(accent, 0.13) }}>{Icon[s.icon]({ s: 20, c: accent })}</div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginBottom: 2 }}>{s.title}</div>
                <div style={{ fontSize: 13, color: t.textSoft, lineHeight: 1.45, fontWeight: 450 }}>{s.desc}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase', color: t.muted, margin: '20px 2px 10px' }}>Cumplimiento y estándares</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {['HL7 FHIR', 'ISO 27799', 'Habeas Data', 'Resolución 866/2021', 'AES-256'].map(b => (
            <span key={b} style={{ fontSize: 12, fontWeight: 600, color: t.textSoft, padding: '7px 12px', borderRadius: 10, border: `1px solid ${t.stroke}`, background: t.dark ? 'rgba(255,255,255,0.04)' : '#fff', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              {Icon.check({ s: 13, c: t.green, w: 3 })}{b}
            </span>
          ))}
        </div>

        <button onClick={onClose} style={{ width: '100%', marginTop: 22, 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>
    </div>
  );
}

Object.assign(window, { FaceScan, SecuritySheet });
