// Auth Modal Component - OTP email verification flow

const inputStyle = {
  width: '100%', padding: '10px 12px',
  border: '1px solid var(--k-line)', borderRadius: 8,
  fontSize: 14, fontFamily: 'var(--k-sans)',
  background: 'var(--k-surface)', color: 'var(--k-ink)',
  outline: 'none', boxSizing: 'border-box',
};

function AuthModal({ mode, onClose, onAuth }) {
  const [view, setView]   = React.useState(mode);   // 'signup' | 'signin'
  const [step, setStep]   = React.useState('form');  // 'form' | 'otp'
  const [form, setForm]   = React.useState({ first: '', last: '', email: '', org: '', role: '' });
  const [otp, setOtp]     = React.useState('');
  const [pending, setPending] = React.useState('');  // email awaiting verification
  const [devCode, setDevCode] = React.useState(''); // pilot: code shown on screen
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const isValidEmail = v => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v);
  const cap = v => v ? v.charAt(0).toUpperCase() + v.slice(1) : v;
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const switchView = (v) => { setView(v); setStep('form'); setError(''); setOtp(''); };

  // ── Step 1: send OTP ────────────────────────────────────────────────
  const handleSendCode = async () => {
    const { first, last, email, org, role } = form;
    const isSignup = view === 'signup';

    if (isSignup) {
      if (!first)               { setError('Please enter your first name.');                             return; }
      if (!last)                { setError('Please enter your last name.');                              return; }
      if (!email)               { setError('Please enter your email address.');                          return; }
      if (!isValidEmail(email)) { setError("That email address doesn't look right — please check it."); return; }
      if (!org)                 { setError('Please enter your organisation.');                           return; }
      if (!role)                { setError('Please enter your job title or role.');                      return; }
    } else {
      if (!email || !isValidEmail(email)) { setError('Please enter a valid email address.'); return; }
    }

    setError(''); setLoading(true);
    try {
      const body = isSignup
        ? { email, name: cap(first) + ' ' + cap(last), org, role }
        : { email };
      const res = await fetch('/auth/otp/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.detail || 'Could not send verification code. Please try again.');
        return;
      }
      setPending(email);
      setDevCode(data.dev_code || '');
      setStep('otp');
    } catch(e) { setError('Something went wrong. Please try again.'); }
    finally { setLoading(false); }
  };

  // ── Step 2: verify OTP ──────────────────────────────────────────────
  const handleVerify = async () => {
    if (!otp || otp.length < 6) { setError('Please enter the 6-digit code.'); return; }
    setError(''); setLoading(true);
    try {
      const res = await fetch('/auth/otp/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: pending, code: otp }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.detail || 'Verification failed. Please try again.');
        return;
      }
      const name = data.name || '';
      const user = {
        id: data.user_id, name, email: data.email,
        org: data.org || '', role: data.role || '',
        firstName: name.split(' ')[0],
        lastName: name.split(' ').slice(1).join(' '),
      };
      localStorage.setItem('kalibr.user', JSON.stringify(user));
      localStorage.setItem('kalibr.session_token', data.access_token);
      onAuth();
    } catch(e) { setError('Verification failed. Please try again.'); }
    finally { setLoading(false); }
  };

  const Logo = () => (
    <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 28 }}>
      <svg width="40" height="40" viewBox="0 0 32 32" fill="none">
        <circle cx="16" cy="16" r="14" stroke="currentColor" strokeWidth="1.4" opacity="0.35"/>
        <path d="M16 4 V28" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
        <path d="M6 16 A10 10 0 0 1 16 6" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round"/>
        <path d="M16 26 A10 10 0 0 0 26 16" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
        <circle cx="16" cy="16" r="1.6" fill="currentColor"/>
      </svg>
    </div>
  );

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(31,27,22,0.55)', backdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 420, margin: '0 24px',
          background: 'var(--k-bg)', borderRadius: 20,
          padding: '40px 36px', boxShadow: 'var(--sh-3)',
          position: 'relative',
        }}>

        <button onClick={onClose} style={{
          position: 'absolute', top: 14, right: 14,
          background: 'none', border: 'none', cursor: 'pointer',
          color: 'var(--k-ink-3)', fontSize: 16, padding: 6, lineHeight: 1,
        }}>✕</button>

        <Logo />

        {/* ── OTP step (shared for sign-up and sign-in) ─────────────── */}
        {step === 'otp' ? (
          <>
            <h2 className="k-serif" style={{ fontSize: 26, margin: '0 0 8px', letterSpacing: '-0.02em', textAlign: 'center' }}>
              Check your email
            </h2>
            <p style={{ fontSize: 13.5, color: 'var(--k-ink-3)', textAlign: 'center', margin: '0 0 24px', lineHeight: 1.5 }}>
              We sent a 6-digit code to<br /><strong style={{ color: 'var(--k-ink)' }}>{pending}</strong>
            </p>

            {devCode && (
              <div style={{ marginBottom: 16, padding: '12px 16px', borderRadius: 10, background: 'var(--k-bg-2)', border: '1px solid var(--k-line)', textAlign: 'center' }}>
                <div style={{ fontSize: 11, color: 'var(--k-ink-4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Pilot — your code</div>
                <div style={{ fontSize: 32, fontFamily: 'var(--k-mono)', fontWeight: 700, letterSpacing: '0.2em', color: 'var(--k-ink)' }}>{devCode}</div>
              </div>
            )}

            <div style={{ marginBottom: 12 }}>
              <div className="k-label" style={{ marginBottom: 6 }}>Verification code</div>
              <input
                type="text"
                inputMode="numeric"
                maxLength={6}
                value={otp}
                onChange={e => setOtp(e.target.value.replace(/\D/g, ''))}
                onKeyDown={e => e.key === 'Enter' && handleVerify()}
                placeholder="000000"
                autoFocus
                style={{ ...inputStyle, fontSize: 28, textAlign: 'center', letterSpacing: '0.25em', fontFamily: 'var(--k-mono)', padding: '14px 12px' }}
              />
            </div>

            {error && <div style={{ fontSize: 13, color: 'var(--k-rose-ink)', marginBottom: 10 }}>{error}</div>}

            <button className="k-btn k-btn--primary" onClick={handleVerify} disabled={loading}
              style={{ width: '100%', height: 44, fontSize: 15, marginTop: 4, opacity: loading ? 0.6 : 1 }}>
              {loading ? 'Verifying…' : 'Verify →'}
            </button>

            <div style={{ textAlign: 'center', marginTop: 16, fontSize: 13, color: 'var(--k-ink-3)' }}>
              Didn't receive it?{' '}
              <button
                onClick={() => { setStep('form'); setOtp(''); setError(''); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--k-ink)', textDecoration: 'underline', textUnderlineOffset: 2, padding: 0 }}>
                Go back
              </button>
            </div>
          </>

        ) : view === 'signup' ? (
          /* ── Sign up form ─────────────────────────────────────────── */
          <>
            <h2 className="k-serif" style={{ fontSize: 26, margin: '0 0 24px', letterSpacing: '-0.02em', textAlign: 'center' }}>Create account</h2>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
              <div>
                <div className="k-label" style={{ marginBottom: 6 }}>First name</div>
                <input value={form.first} onChange={e => set('first', cap(e.target.value))} placeholder="Alex" style={inputStyle} />
              </div>
              <div>
                <div className="k-label" style={{ marginBottom: 6 }}>Last name</div>
                <input value={form.last} onChange={e => set('last', cap(e.target.value))} placeholder="Rivera" style={inputStyle} />
              </div>
            </div>

            {[['email','Email','you@example.com','email'],['org','Organisation','Acme Corp','text'],['role','Job title / role','Head of Product','text']].map(([k,l,p,t]) => (
              <div key={k} style={{ marginBottom: 12 }}>
                <div className="k-label" style={{ marginBottom: 6 }}>{l}</div>
                <input type={t} value={form[k]} onChange={e => set(k, e.target.value)} placeholder={p} style={inputStyle}
                  onKeyDown={e => e.key === 'Enter' && handleSendCode()} />
              </div>
            ))}

            {error && <div style={{ fontSize: 13, color: 'var(--k-rose-ink)', marginBottom: 10 }}>{error}</div>}

            <button className="k-btn k-btn--primary" onClick={handleSendCode} disabled={loading}
              style={{ width: '100%', height: 44, fontSize: 15, marginTop: 4, opacity: loading ? 0.6 : 1 }}>
              {loading ? 'Sending code…' : 'Send verification code →'}
            </button>

            <div style={{ textAlign: 'center', marginTop: 18, fontSize: 13, color: 'var(--k-ink-3)' }}>
              Already have an account?{' '}
              <button onClick={() => switchView('signin')} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--k-ink)', textDecoration: 'underline', textUnderlineOffset: 2, padding: 0 }}>
                Sign in
              </button>
            </div>
          </>

        ) : (
          /* ── Sign in form ─────────────────────────────────────────── */
          <>
            <h2 className="k-serif" style={{ fontSize: 26, margin: '0 0 24px', letterSpacing: '-0.02em', textAlign: 'center' }}>Welcome back</h2>

            <div style={{ marginBottom: 12 }}>
              <div className="k-label" style={{ marginBottom: 6 }}>Email</div>
              <input type="email" value={form.email} onChange={e => set('email', e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleSendCode()}
                placeholder="you@example.com" style={inputStyle} autoFocus />
            </div>

            {error && <div style={{ fontSize: 13, color: 'var(--k-rose-ink)', marginBottom: 10 }}>{error}</div>}

            <button className="k-btn k-btn--primary" onClick={handleSendCode} disabled={loading}
              style={{ width: '100%', height: 44, fontSize: 15, marginTop: 4, opacity: loading ? 0.6 : 1 }}>
              {loading ? 'Sending code…' : 'Send code →'}
            </button>

            <div style={{ textAlign: 'center', marginTop: 18, fontSize: 13, color: 'var(--k-ink-3)' }}>
              Don't have an account?{' '}
              <button onClick={() => switchView('signup')} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--k-ink)', textDecoration: 'underline', textUnderlineOffset: 2, padding: 0 }}>
                Sign up
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
