/* global React, PORTAL */
const { useState } = React;

// base64url helpers for WebAuthn ceremony
function b64url(buf) {
  const bytes = new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer || buf);
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,'');
}
function toBuffer(s) {
  s = s.replace(/-/g,'+').replace(/_/g,'/');
  while (s.length % 4) s += '=';
  return Uint8Array.from(atob(s), c=>c.charCodeAt(0)).buffer;
}

function Login({ onLogin }) {
  const [email, setEmail]         = useState('');
  const [sent, setSent]           = useState(false);
  const [busy, setBusy]           = useState(false);
  const [error, setError]         = useState('');
  const [passkeyBusy, setPasskeyBusy] = useState(false);

  const hasWebAuthn = typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials?.get;

  async function submit(e) {
    e.preventDefault(); setError(''); setBusy(true);
    try {
      await PORTAL.post('/auth/magic', { email });
      setSent(true);
    } catch (ex) {
      setError(ex?.error || 'Something went wrong');
    } finally { setBusy(false); }
  }

  async function loginWithPasskey() {
    setError(''); setPasskeyBusy(true);
    try {
      // Step 1: Get challenge from server
      const options = await PORTAL.post('/auth/passkey/login-options', email ? { email } : {});

      // Step 2: Convert base64url challenge to ArrayBuffer for browser API
      const publicKey = {
        challenge: toBuffer(options.challenge),
        rpId: options.rpId,
        timeout: options.timeout || 60000,
        userVerification: options.userVerification || 'preferred',
        allowCredentials: (options.allowCredentials||[]).map(c => ({
          type: 'public-key',
          id: toBuffer(c.id),
        })),
      };

      // Step 3: Browser prompts for passkey
      const assertion = await navigator.credentials.get({ publicKey });

      // Step 4: Serialize and send to server
      await PORTAL.post('/auth/passkey/login-verify', {
        id: assertion.id,
        rawId: b64url(assertion.rawId),
        type: assertion.type,
        response: {
          authenticatorData: b64url(assertion.response.authenticatorData),
          clientDataJSON:    b64url(assertion.response.clientDataJSON),
          signature:         b64url(assertion.response.signature),
          userHandle: assertion.response.userHandle ? b64url(assertion.response.userHandle) : null,
        },
      });

      onLogin();
    } catch (ex) {
      if (ex?.name === 'NotAllowedError') setError('Passkey request was cancelled.');
      else setError(ex?.error || ex?.message || 'Passkey sign-in failed');
    } finally { setPasskeyBusy(false); }
  }

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

        {sent ? (
          <div className="login-success">
            Check your inbox — we've sent a login link to <strong>{email}</strong>.<br />
            <span style={{fontSize:11,opacity:0.8}}>The link expires in 10 minutes.</span>
          </div>
        ) : (
          <>
            <p className="login-prompt">Enter your email address to receive a secure login link.</p>
            {error && <div className="alert alert--error">{error}</div>}
            <form onSubmit={submit}>
              <div style={{marginBottom:12}}>
                <label className="field-label">Email address</label>
                <input className="field-input" type="email" required autoFocus
                  value={email} onChange={e=>setEmail(e.target.value)}
                  placeholder="you@company.com" />
              </div>
              <button type="submit" className="btn btn--primary" style={{width:'100%',justifyContent:'center'}} disabled={busy}>
                {busy ? 'Sending…' : 'Send login link →'}
              </button>
            </form>

            {hasWebAuthn && (
              <div style={{marginTop:16}}>
                <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:12}}>
                  <div style={{flex:1,height:1,background:'var(--border)'}} />
                  <span style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)'}}>or</span>
                  <div style={{flex:1,height:1,background:'var(--border)'}} />
                </div>
                <button
                  type="button"
                  className="btn btn--ghost"
                  style={{width:'100%',justifyContent:'center'}}
                  disabled={passkeyBusy}
                  onClick={loginWithPasskey}>
                  {passkeyBusy ? 'Waiting for passkey…' : 'Sign in with passkey'}
                </button>
                <div style={{fontSize:11,color:'var(--fg-subtle)',textAlign:'center',marginTop:8}}>
                  Use Face ID, Touch ID, or security key
                </div>
              </div>
            )}
          </>
        )}
      </div>
      <div style={{textAlign:'center',marginTop:16}}>
        <a href="https://lake-project.com/trust" target="_blank" rel="noopener noreferrer"
           style={{fontSize:10,fontFamily:'var(--font-mono)',letterSpacing:'0.08em',color:'var(--fg-faint)',textDecoration:'none'}}>
          Privacy &amp; legal
        </a>
      </div>
    </div>
  );
}
window.Login = Login;
