
// ── Login Screen — Responsive ─────────────────────────────────────────────────
const { useState: useStateAuthR, useEffect: useEffectAuthR } = React;
const WAUTH_KEY = 'salud_webauthn_registered';

async function registerBiometric(username) {
  if (!window.PublicKeyCredential) throw new Error('WebAuthn no soportado');
  const challenge = crypto.getRandomValues(new Uint8Array(32));
  const cred = await navigator.credentials.create({
    publicKey: {
      challenge, rp: { name: 'Salud App', id: location.hostname },
      user: { id: new TextEncoder().encode(username), name: username, displayName: username },
      pubKeyCredParams: [{ alg:-7, type:'public-key' }, { alg:-257, type:'public-key' }],
      authenticatorSelection: { authenticatorAttachment:'platform', userVerification:'required', residentKey:'preferred' },
      timeout: 60000,
    },
  });
  localStorage.setItem('salud_cred_id', btoa(String.fromCharCode(...new Uint8Array(cred.rawId))));
  localStorage.setItem(WAUTH_KEY, 'true');
  return cred;
}

async function authenticateBiometric() {
  if (!window.PublicKeyCredential) throw new Error('WebAuthn no soportado');
  const challenge = crypto.getRandomValues(new Uint8Array(32));
  const credIdB64 = localStorage.getItem('salud_cred_id');
  const allowCreds = credIdB64 ? [{ type:'public-key', id: Uint8Array.from(atob(credIdB64), c=>c.charCodeAt(0)) }] : [];
  await navigator.credentials.get({ publicKey: { challenge, allowCredentials:allowCreds, userVerification:'required', timeout:60000 } });
  return true;
}

function ScreenLogin({ onLogin }) {
  const [user, setUser]      = useStateAuthR('ruben');
  const [pass, setPass]      = useStateAuthR('');
  const [error, setError]    = useStateAuthR('');
  const [loading, setLoading]= useStateAuthR(false);
  const [showPass, setShowP] = useStateAuthR(false);
  const webauthnAvail = !!window.PublicKeyCredential && localStorage.getItem(WAUTH_KEY) === 'true';

  const handleLogin = async () => {
    setError(''); setLoading(true);
    try {
      const { token, username } = await api.login(user, pass);
      api.setToken(token);
      onLogin(username);
    } catch (e) {
      setError(e.message || 'Usuario o contraseña incorrectos');
    } finally { setLoading(false); }
  };

  const handleFaceId = async () => {
    setLoading(true); setError('');
    try {
      await authenticateBiometric();
      const token = api.getToken();
      if (!token) { setError('Inicia sesión primero con contraseña'); setLoading(false); return; }
      const { username } = await api.me();
      onLogin(username);
    } catch(e) {
      if (e.name !== 'NotAllowedError') setError('Error: ' + e.message);
    } finally { setLoading(false); }
  };

  return (
    <div style={{ minHeight:'100%', display:'flex', alignItems:'center', justifyContent:'center', background:'#F5F5F0', padding:'24px 16px' }}>
      <div style={{ width:'100%', maxWidth:400 }}>
        {/* Logo */}
        <div style={{ textAlign:'center', marginBottom:40 }}>
          <div style={{ width:80, height:80, borderRadius:22, background:'linear-gradient(145deg,#FF6B35,#FF3B30)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:40, margin:'0 auto 12px', boxShadow:'0 8px 24px rgba(255,107,53,.3)' }}>🥗</div>
          <div style={{ fontSize:30, fontWeight:800, color:'#1C1C1E' }}>Salud</div>
          <div style={{ fontSize:14, color:'#8E8E93', marginTop:4 }}>salud.rubenfer.es</div>
        </div>

        <div className="card" style={{ padding:'28px 24px' }}>
          <div className="form-group">
            <label className="form-label">Usuario</label>
            <input className="form-input" value={user} onChange={e=>setUser(e.target.value)} placeholder="usuario" autoCapitalize="none" autoComplete="username" />
          </div>
          <div className="form-group" style={{ position:'relative' }}>
            <label className="form-label">Contraseña</label>
            <input className="form-input" type={showPass?'text':'password'} value={pass}
              onChange={e=>setPass(e.target.value)} placeholder="••••••••"
              autoComplete="current-password" onKeyDown={e=>e.key==='Enter'&&handleLogin()} />
            <button style={{ position:'absolute', right:12, top:36, background:'none', border:'none', fontSize:18, cursor:'pointer', color:'#8E8E93' }}
              onClick={()=>setShowP(p=>!p)}>{showPass?'🙈':'👁'}</button>
          </div>
          {error && <div className="msg-err">{error}</div>}
          <button className="btn-primary" style={{ width:'100%', padding:'14px', fontSize:17, marginTop:4, opacity:loading?.8:1 }}
            onClick={handleLogin} disabled={loading}>
            {loading?'Entrando…':'Entrar'}
          </button>
          {webauthnAvail && (
            <button style={{ width:'100%', padding:'13px', borderRadius:12, border:'1.5px solid #E5E5EA', background:'#fff', fontWeight:600, fontSize:15, marginTop:10, display:'flex', alignItems:'center', justifyContent:'center', gap:8, cursor:'pointer' }}
              onClick={handleFaceId} disabled={loading}>
              🔒 Face ID / Touch ID
            </button>
          )}
        </div>

        <div style={{ textAlign:'center', fontSize:12, color:'#AEAEB2', marginTop:16 }}>
          {webauthnAvail ? '✓ Biometría activada' : 'Activa Face ID desde Ajustes'}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenLogin, registerBiometric, authenticateBiometric, WAUTH_KEY });
