/* global React, API */
const { useState, useEffect } = React;

function Login({ onLogin }) {
  const [hasKeys, setHasKeys]   = useState(null);  // null=loading
  const [tab, setTab]           = useState('passkey'); // 'passkey' | 'magic' | 'token'
  const [email, setEmail]       = useState('');
  const [sent, setSent]         = useState(false);
  const [accessToken, setAccessToken] = useState('');
  const [busy, setBusy]         = useState(false);
  const [error, setError]       = useState('');

  useEffect(() => {
    API.get('/auth/credentials-exist')
      .then(d => setHasKeys(d.exists))
      .catch(() => setHasKeys(false));
  }, []);

  // First-time setup: no passkeys registered yet, skip the tab UI
  const firstRun = hasKeys === false;

  async function handleRegister() {
    setError(''); setBusy(true);
    try {
      const { challenge } = await API.post('/auth/challenge');
      const credential = await navigator.credentials.create({
        publicKey: {
          challenge: API.fromb64url(challenge),
          rp: { id: location.hostname.replace(/^admin\./, ''), name: 'Lake-Project Admin' },
          user: { id: new Uint8Array(16), name: 'alexander', displayName: 'Alexander van der Plas' },
          pubKeyCredParams: [{ type: 'public-key', alg: -7 }],
          authenticatorSelection: { authenticatorAttachment: 'platform', requireResidentKey: true, userVerification: 'required' },
          attestation: 'none',
          timeout: 60000,
        },
      });
      await API.post('/auth/register', {
        challenge,
        id: credential.id,
        rawId: API.b64url(credential.rawId),
        response: {
          attestationObject: API.b64url(credential.response.attestationObject),
          clientDataJSON: API.b64url(credential.response.clientDataJSON),
        },
      });
      onLogin();
    } catch (e) { setError(e.error || e.message || 'Registration failed'); }
    finally { setBusy(false); }
  }

  async function handlePasskey() {
    setError(''); setBusy(true);
    try {
      const { challenge } = await API.post('/auth/challenge');
      const assertion = await navigator.credentials.get({
        publicKey: {
          challenge: API.fromb64url(challenge),
          rpId: location.hostname.replace(/^admin\./, ''),
          userVerification: 'required',
          timeout: 60000,
        },
      });
      await API.post('/auth/login', {
        challenge,
        id: assertion.id,
        rawId: API.b64url(assertion.rawId),
        response: {
          authenticatorData: API.b64url(assertion.response.authenticatorData),
          clientDataJSON:    API.b64url(assertion.response.clientDataJSON),
          signature:         API.b64url(assertion.response.signature),
        },
      });
      onLogin();
    } catch (e) { setError(e.error || e.message || 'Authentication failed'); }
    finally { setBusy(false); }
  }

  async function handleMagic() {
    if (!email.trim()) { setError('Enter your email address'); return; }
    setError(''); setBusy(true);
    try {
      await API.post('/auth/magic-request', { email: email.trim() });
      setSent(true);
    } catch (e) { setError(e.error || 'Failed to send link'); }
    finally { setBusy(false); }
  }

  async function handleToken() {
    if (!accessToken.trim()) { setError('Enter your access token'); return; }
    setError(''); setBusy(true);
    try {
      await API.post('/auth/token-login', { token: accessToken.trim() });
      onLogin();
    } catch (e) { setError(e.error || 'Invalid token'); }
    finally { setBusy(false); }
  }

  if (hasKeys === null) return (
    <div className="login-wrap">
      <div className="login-box">
        <div className="login-logo">Lake-Project</div>
        <div className="login-sub">Admin</div>
        <div className="text-muted text-mono" style={{fontSize:11}}>Loading…</div>
      </div>
    </div>
  );

  return (
    <div className="login-wrap">
      <div className="login-box">
        <div className="login-logo">Lake-Project</div>
        <div className="login-sub">Admin</div>

        <svg className="login-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
        </svg>

        {firstRun ? (
          <>
            <div className="login-title">Set up passkey</div>
            <div className="login-hint">Register your Touch ID, Face ID, or hardware key. This is a one-time step.</div>
            <button className="login-btn" onClick={handleRegister} disabled={busy}>
              {busy ? 'Waiting for passkey…' : 'Register passkey →'}
            </button>
          </>
        ) : (
          <>
            {/* Tab switcher */}
            <div style={{display:'flex',gap:0,marginBottom:20,border:'1px solid var(--border)',borderRadius:6,overflow:'hidden'}}>
              {[['passkey','Passkey'],['magic','Magic link'],['token','Token']].map(([v,l]) => (
                <button key={v}
                  style={{flex:1,padding:'8px 0',fontSize:12,fontFamily:'var(--font-mono)',border:'none',cursor:'pointer',
                    background: tab===v ? 'var(--signal)' : 'transparent',
                    color: tab===v ? '#000' : 'var(--fg-subtle)',
                    fontWeight: tab===v ? 600 : 400,
                    transition:'background 0.15s'}}
                  onClick={() => { setTab(v); setError(''); setSent(false); }}>
                  {l}
                </button>
              ))}
            </div>

            {tab === 'passkey' && (
              <>
                <div className="login-title">Sign in</div>
                <div className="login-hint">Use your registered passkey — Touch ID, Face ID, or hardware key.</div>
                <button className="login-btn" onClick={handlePasskey} disabled={busy}>
                  {busy ? 'Waiting for passkey…' : 'Sign in with passkey →'}
                </button>
              </>
            )}

            {tab === 'magic' && !sent && (
              <>
                <div className="login-title">Email magic link</div>
                <div className="login-hint">Enter your email — we'll send a sign-in link valid for 15 minutes.</div>
                <input
                  type="email" autoFocus
                  className="field-input"
                  style={{marginBottom:12,textAlign:'center'}}
                  placeholder="your@email.com"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && handleMagic()}
                />
                <button className="login-btn" onClick={handleMagic} disabled={busy || !email.trim()}>
                  {busy ? 'Sending…' : 'Send magic link →'}
                </button>
              </>
            )}

            {tab === 'magic' && sent && (
              <>
                <div className="login-title">Check your email</div>
                <div className="login-hint" style={{color:'var(--signal)'}}>
                  A sign-in link was sent to <strong>{email}</strong>.
                  The link expires in 15 minutes.
                </div>
                <button className="login-btn" style={{background:'transparent',border:'1px solid var(--border)',color:'var(--fg-muted)'}}
                  onClick={() => { setSent(false); setError(''); }}>
                  ← Send to a different address
                </button>
              </>
            )}

            {tab === 'token' && (
              <>
                <div className="login-title">Access token</div>
                <div className="login-hint">Enter your one-time access token. It rotates automatically after use — find the next one in Settings.</div>
                <input
                  type="password" autoFocus
                  className="field-input"
                  style={{marginBottom:12,textAlign:'center',fontFamily:'var(--font-mono)',letterSpacing:2}}
                  placeholder="Paste token here"
                  value={accessToken}
                  onChange={e => setAccessToken(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && handleToken()}
                />
                <button className="login-btn" onClick={handleToken} disabled={busy || !accessToken.trim()}>
                  {busy ? 'Verifying…' : 'Sign in with token →'}
                </button>
              </>
            )}
          </>
        )}

        {error && <div className="login-error">{error}</div>}
      </div>
    </div>
  );
}
window.Login = Login;
