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

function Login({ onLogin }) {
  const [mode, setMode]       = useState(null); // null=loading, 'register', 'login'
  const [busy, setBusy]       = useState(false);
  const [error, setError]     = useState('');

  useEffect(() => {
    API.get('/auth/credentials-exist')
      .then(d => setMode(d.exists ? 'login' : 'register'))
      .catch(() => setMode('register'));
  }, []);

  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 handleLogin() {
    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); }
  }

  if (mode === 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>

        {mode === 'register' ? (
          <>
            <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>
          </>
        ) : (
          <>
            <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={handleLogin} disabled={busy}>
              {busy ? 'Waiting for passkey…' : 'Sign in with passkey →'}
            </button>
            <div style={{marginTop:12,fontSize:11,color:'var(--fg-subtle)'}}>
              <span style={{cursor:'pointer',textDecoration:'underline'}} onClick={() => setMode('register')}>Register a new device</span>
            </div>
          </>
        )}

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