// vita-auth.jsx — first view: sign in / create account, with the PREVENT heart logo

function HeartLogo({ t, accent, size = 184 }) {
  return (
    <div style={{ position: 'relative', width: size, height: size * 0.78, display: 'grid', placeItems: 'center' }}>
      {/* soft glow — no hard circle */}
      <div style={{
        position: 'absolute', inset: '-22% -14%', borderRadius: '50%',
        background: `radial-gradient(closest-side, ${hexA(accent, 0.30)} 0%, ${hexA(accent, 0.10)} 45%, transparent 72%)`,
        filter: 'blur(8px)',
      }} />
      <img src="brand/heart2.png" alt="PREVENT" style={{
        position: 'relative', width: '100%', height: 'auto',
        filter: `saturate(1.1) drop-shadow(0 16px 34px ${hexA(accent, 0.45)})`,
      }} />
    </div>
  );
}

function AuthField({ t, icon, prefix, type = 'text', inputMode, value, onChange, placeholder, autoComplete, trailing, error, onBlur }) {
  const [focus, setFocus] = React.useState(false);
  return (
    <div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '0 12px', height: 54, borderRadius: 15,
        background: t.dark ? 'rgba(255,255,255,0.06)' : '#FFFFFF',
        border: `1.5px solid ${error ? t.coral : focus ? t.accent : t.stroke}`,
        transition: 'border-color .18s', boxShadow: focus ? `0 0 0 4px ${hexA(t.accent, 0.12)}` : 'none',
      }}>
        <span style={{ color: error ? t.coral : focus ? t.accent : t.muted, display: 'flex' }}>{icon}</span>
        {prefix && <span style={{ fontSize: 16, fontWeight: 600, color: t.textSoft, fontFamily: 'Hanken Grotesk, sans-serif', whiteSpace: 'nowrap' }}>{prefix}</span>}
        <input
          type={type} inputMode={inputMode} value={value} autoComplete={autoComplete}
          onChange={e => onChange(e.target.value)}
          onFocus={() => setFocus(true)}
          onBlur={() => { setFocus(false); onBlur && onBlur(); }}
          placeholder={placeholder}
          style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent', minWidth: 0,
            fontSize: 16, color: t.text, fontFamily: 'Hanken Grotesk, sans-serif', fontWeight: 500,
          }} />
        {trailing}
      </div>
      {error && <div style={{ fontSize: 12.5, color: t.coral, margin: '6px 4px 0', fontWeight: 500 }}>{error}</div>}
    </div>
  );
}

function AuthScreen({ t, persona, onAuthed, onToggleTheme, onFaceScan, onShowSecurity }) {
  const [mode, setMode] = React.useState('login'); // login | signup
  const [method, setMethod] = React.useState('email'); // email | phone
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [terms, setTerms] = React.useState(false);
  const [touched, setTouched] = React.useState({});
  const [submit, setSubmit] = React.useState(null); // null | 'form' | 'face'

  const accent = persona.accent;
  const fmtPhone = (v) => {
    const dgt = v.replace(/\D/g, '').slice(0, 10);
    return dgt.replace(/(\d{3})(\d{0,3})(\d{0,4})/, (m, a, b, c) => [a, b, c].filter(Boolean).join(' ')).trim();
  };
  const phoneDigits = phone.replace(/\D/g, '');
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const phoneOk = /^3\d{9}$/.test(phoneDigits);
  const idOk = method === 'email' ? emailOk : phoneOk;
  const pwOk = pw.length >= 6;
  const nameOk = name.trim().length >= 2;
  const valid = mode === 'login' ? (idOk && pwOk) : (nameOk && idOk && pwOk && terms);

  const err = (k) => touched[k] || touched._submit;
  const emailErr = method === 'email' && err('email') && email && !emailOk ? 'Correo no válido' : null;
  const phoneErr = method === 'phone' && err('phone') && phone && !phoneOk ? 'Celular inválido — 10 dígitos, inicia en 3' : null;
  const pwErr = err('pw') && pw && !pwOk ? 'Mínimo 6 caracteres' : null;
  const nameErr = mode === 'signup' && err('name') && name && !nameOk ? 'Cuéntanos tu nombre' : null;

  const go = (kind) => {
    if (kind === 'face') { onFaceScan && onFaceScan({ mode: 'login', method: 'face' }); return; }
    setTouched(s => ({ ...s, _submit: true }));
    if (!valid) return;
    const ident = method === 'email' ? { email } : { phone: '+57 ' + phoneDigits };
    const payload = { name: name.trim(), mode, method, ...ident };
    if (mode === 'signup') { onFaceScan && onFaceScan({ ...payload, enroll: true }); return; } // face scan is mandatory to create the account
    setSubmit('form');
    setTimeout(() => onAuthed(payload), 850);
  };

  const switchMode = (m) => { setMode(m); setTouched({}); };

  return (
    <Stage t={t}>
      {/* theme toggle top-right */}
      <div style={{ position: 'absolute', top: 60, right: 16, zIndex: 5 }}>
        <IconBtn t={t} onClick={onToggleTheme} title="Tema">{t.dark ? Icon.sun({ s: 17 }) : Icon.moon({ s: 17 })}</IconBtn>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '70px 26px 0', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <HeartLogo t={t} accent={accent} size={188} />
        <div style={{ fontFamily: 'Hanken Grotesk, sans-serif', fontWeight: 800, letterSpacing: 4, fontSize: 22, color: t.text, textTransform: 'uppercase', marginTop: 14 }}>prevent</div>
        <div style={{ fontSize: 14.5, color: t.textSoft, marginTop: 5, fontWeight: 450 }}>Tu asistente médico digital</div>

        {/* segmented toggle */}
        <div style={{ display: 'flex', gap: 4, marginTop: 26, padding: 4, borderRadius: 14, width: '100%',
          background: t.dark ? 'rgba(255,255,255,0.05)' : 'rgba(10,26,51,0.04)', border: `1px solid ${t.stroke}` }}>
          {[['login', 'Ingresar'], ['signup', 'Crear cuenta']].map(([m, label]) => (
            <button key={m} onClick={() => switchMode(m)} style={{
              flex: 1, padding: '11px 0', borderRadius: 10, cursor: 'pointer', border: 'none',
              background: mode === m ? `linear-gradient(135deg, ${accent}, ${persona.accentDeep})` : 'transparent',
              color: mode === m ? t.onAccent : t.textSoft,
              fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 14.5, fontWeight: 700,
              boxShadow: mode === m ? `0 6px 16px ${hexA(accent, 0.35)}` : 'none', transition: 'all .2s',
            }}>{label}</button>
          ))}
        </div>

        {/* fields */}
        <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 12, marginTop: 18 }}>
          {mode === 'signup' && (
            <AuthField t={t} icon={Icon.user({ s: 19 })} value={name} onChange={setName} placeholder="Nombre completo"
              autoComplete="name" error={nameErr} onBlur={() => setTouched(s => ({ ...s, name: true }))} />
          )}

          {/* method toggle: email or phone */}
          <div style={{ display: 'flex', gap: 16, padding: '0 4px', marginTop: 2 }}>
            {[['email', 'Correo', Icon.mail], ['phone', 'Celular', Icon.phone]].map(([m, label, ic]) => {
              const on = method === m;
              return (
                <button key={m} onClick={() => setMethod(m)} style={{
                  display: 'flex', alignItems: 'center', gap: 6, border: 'none', background: 'transparent', cursor: 'pointer',
                  padding: '2px 0 7px', position: 'relative', WebkitTapHighlightColor: 'transparent',
                  color: on ? accent : t.muted, fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 14, fontWeight: on ? 700 : 500,
                  borderBottom: `2px solid ${on ? accent : 'transparent'}`,
                }}>
                  {ic({ s: 16, c: on ? accent : t.muted })}{label}
                </button>
              );
            })}
          </div>

          {method === 'email' ? (
            <AuthField t={t} icon={Icon.mail({ s: 19 })} type="email" value={email} onChange={setEmail} placeholder="Correo electrónico"
              autoComplete="email" inputMode="email" error={emailErr} onBlur={() => setTouched(s => ({ ...s, email: true }))} />
          ) : (
            <AuthField t={t} icon={Icon.phone({ s: 19 })} type="tel" inputMode="numeric" prefix="+57" value={phone}
              onChange={v => setPhone(fmtPhone(v))} placeholder="300 123 4567" autoComplete="tel"
              error={phoneErr} onBlur={() => setTouched(s => ({ ...s, phone: true }))} />
          )}

          <AuthField t={t} icon={Icon.lock({ s: 19 })} type={showPw ? 'text' : 'password'} value={pw} onChange={setPw}
            placeholder="Contraseña" autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
            error={pwErr} onBlur={() => setTouched(s => ({ ...s, pw: true }))}
            trailing={
              <button onClick={() => setShowPw(s => !s)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: t.muted, display: 'grid', placeItems: 'center', width: 34, height: 34 }}>
                {showPw ? Icon.eyeOff({ s: 19 }) : Icon.eye({ s: 19 })}
              </button>
            } />

          {mode === 'login' ? (
            <button onClick={() => {}} style={{ alignSelf: 'flex-end', border: 'none', background: 'transparent', cursor: 'pointer', color: accent, fontSize: 13.5, fontWeight: 600, fontFamily: 'Hanken Grotesk, sans-serif', padding: '2px 2px' }}>
              ¿Olvidaste tu contraseña?
            </button>
          ) : (
            <button onClick={() => setTerms(x => !x)} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left', padding: '2px 0' }}>
              <span style={{ width: 22, height: 22, flexShrink: 0, borderRadius: 7, marginTop: 1, border: `1.5px solid ${terms ? accent : t.strokeStrong}`, background: terms ? accent : 'transparent', display: 'grid', placeItems: 'center', transition: 'all .15s' }}>
                {terms && Icon.check({ s: 13, c: t.onAccent, w: 3 })}
              </span>
              <span style={{ fontSize: 13, color: t.textSoft, lineHeight: 1.4, fontWeight: 450 }}>
                Acepto que Vita administre mi historia clínica y los <span style={{ color: accent, fontWeight: 600 }}>Términos y la Política de datos</span>.
              </span>
            </button>
          )}
        </div>

        <div style={{ height: 18 }} />
      </div>

      {/* bottom actions */}
      <div style={{ padding: '8px 26px 30px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <BigButton t={t} onClick={() => go('form')}>
          {submit === 'form'
            ? <Spinner c={t.onAccent} />
            : (mode === 'login'
              ? <>Ingresar {Icon.chevron({ s: 17, c: t.onAccent })}</>
              : <>{Icon.faceid({ s: 19, c: t.onAccent })} Continuar al escaneo facial</>)}
        </BigButton>

        {mode === 'login' ? (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '2px 0' }}>
              <div style={{ flex: 1, height: 1, background: t.strokeStrong }} />
              <span style={{ fontSize: 12, color: t.muted, fontWeight: 500 }}>o</span>
              <div style={{ flex: 1, height: 1, background: t.strokeStrong }} />
            </div>
            <button onClick={() => go('face')} style={{
              width: '100%', padding: '14px', borderRadius: 16, cursor: 'pointer',
              border: `1.5px solid ${t.strokeStrong}`, background: 'transparent', color: t.text,
              fontFamily: 'Hanken Grotesk, sans-serif', fontSize: 15.5, fontWeight: 600,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, WebkitTapHighlightColor: 'transparent',
            }}>
              {Icon.faceid({ s: 21, c: accent })} Entrar con reconocimiento facial
            </button>
          </>
        ) : (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 9, padding: '11px 13px', borderRadius: 13, background: hexA(accent, t.dark ? 0.10 : 0.07), border: `1px solid ${hexA(accent, 0.25)}` }}>
            {Icon.faceid({ s: 18, c: accent })}
            <span style={{ fontSize: 12.5, color: t.textSoft, lineHeight: 1.4, fontWeight: 450 }}>
              Para crear tu cuenta confirmarás tu identidad con un <span style={{ color: t.text, fontWeight: 600 }}>escaneo facial</span>. Así solo tú accedes a tu historia.
            </span>
          </div>
        )}

        <button onClick={onShowSecurity} style={{
          textAlign: 'center', marginTop: 4, fontSize: 12.5, color: t.muted, border: 'none', background: 'transparent',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontFamily: 'Hanken Grotesk, sans-serif', fontWeight: 500,
        }}>
          {Icon.shield({ s: 14, c: persona.accent })} <span>Cifrado de extremo a extremo · <span style={{ color: persona.accent, fontWeight: 700 }}>cómo protegemos tus datos</span></span>
        </button>
      </div>
    </Stage>
  );
}

function Spinner({ c }) {
  return (
    <span style={{ width: 18, height: 18, borderRadius: '50%', border: `2.5px solid ${hexA(c, 0.3)}`, borderTopColor: c, display: 'inline-block', animation: 'vitaSpin 0.7s linear infinite' }} />
  );
}

Object.assign(window, { AuthScreen, HeartLogo, AuthField, Spinner });
