// ─────────────────────────────────────────────────────────────
// Sign-In Gate — email + 6-digit code (mock, no real auth)
// ─────────────────────────────────────────────────────────────

function SignInScreen({ onSignedIn }) {
  const [step, setStep] = useState('email'); // 'email' | 'code'
  const [email, setEmail] = useState('');
  const [code, setCode] = useState(['', '', '', '', '', '']);
  const [error, setError] = useState(null);
  const [sending, setSending] = useState(false);
  const [resentAt, setResentAt] = useState(null);
  const inputRefs = useRef([]);

  function validateEmail(v) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());
  }

  async function sendCode() {
    setError(null);
    if (!validateEmail(email)) {
      setError('Please enter a valid email address.');
      return;
    }
    setSending(true);
    try {
      await window.TwApi.ClientAuth.sendCode(email.trim().toLowerCase());
      setStep('code');
      setResentAt(Date.now());
      setTimeout(() => inputRefs.current[0]?.focus(), 100);
    } catch (err) {
      setError(err?.body?.error === 'invalid_email' ? 'Please enter a valid email address.' : 'We couldn\'t send the code. Please try again.');
    } finally {
      setSending(false);
    }
  }

  async function resend() {
    setSending(true);
    setError(null);
    try {
      await window.TwApi.ClientAuth.sendCode(email.trim().toLowerCase());
      setResentAt(Date.now());
      setCode(['', '', '', '', '', '']);
      inputRefs.current[0]?.focus();
    } catch {
      setError('Couldn\'t resend. Try again in a moment.');
    } finally {
      setSending(false);
    }
  }

  function handleCodeChange(idx, val) {
    const cleaned = val.replace(/\D/g, '').slice(0, 1);
    const next = [...code];
    next[idx] = cleaned;
    setCode(next);
    setError(null);
    if (cleaned && idx < 5) inputRefs.current[idx + 1]?.focus();
  }

  function handleCodePaste(e) {
    const pasted = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 6);
    if (pasted.length === 6) {
      e.preventDefault();
      setCode(pasted.split(''));
      inputRefs.current[5]?.focus();
    }
  }

  function handleCodeKeyDown(idx, e) {
    if (e.key === 'Backspace' && !code[idx] && idx > 0) {
      inputRefs.current[idx - 1]?.focus();
    }
  }

  const [verifying, setVerifying] = useState(false);
  async function verifyCode() {
    const joined = code.join('');
    if (joined.length !== 6) {
      setError('Enter all 6 digits.');
      return;
    }
    if (verifying) return;
    setVerifying(true);
    setError(null);
    try {
      const out = await window.TwApi.ClientAuth.verifyCode(email.trim().toLowerCase(), joined);
      onSignedIn({ email: out.email || email, clientId: out.clientId || null });
    } catch (err) {
      const code = err?.body?.error;
      if (code === 'expired') setError('That code has expired. Request a new one.');
      else if (code === 'bad_code') setError('That code didn\'t match. Try again or request a new one.');
      else if (code === 'no_code') setError('No code on record. Request a new one.');
      else setError('We couldn\'t verify the code. Please try again.');
    } finally {
      setVerifying(false);
    }
  }

  // Auto-submit when 6 digits entered
  useEffect(() => {
    if (code.every(d => d !== '') && code.join('').length === 6 && !verifying) {
      const t = setTimeout(verifyCode, 200);
      return () => clearTimeout(t);
    }
  }, [code.join('')]);

  return (
    <div className="signin-page">
      <FFHeader />
      <div className="signin-wrap">
        <div className="signin-card">
          <img src="/assets/mark-primary.png" alt="" className="signin-card-mark" />
          <div className="signin-eyebrow">Secure Client Portal</div>
          <h1 className="signin-title">
            {step === 'email' ? 'Sign in to continue' : 'Check your email'}
          </h1>
          <p className="signin-sub">
            {step === 'email'
              ? <>Enter the <u>Email address</u> your adviser used to invite you. We'll send a 6-digit verification code.</>
              : <>We sent a 6-digit code to <strong>{email}</strong>. It expires in 10 minutes.</>}
          </p>

          {step === 'email' && (
            <form className="signin-form" onSubmit={(e) => { e.preventDefault(); sendCode(); }}>
              <Field label="Email address" required>
                <Input type="email" autoFocus value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@email.com"
                  autoComplete="email"
                  spellCheck={false} />
              </Field>
              {error && <div className="signin-error">{error}</div>}
              <button type="submit" className="btn btn-primary signin-btn" disabled={sending}>
                {sending ? 'Sending code…' : 'Send verification code →'}
              </button>
              <div className="signin-help">
                Don't have an invite yet?{' '}
                <a href={'mailto:tallowwood@tallowwoodwealth.com.au?subject=' + encodeURIComponent('Fact Find invite request') + '&body=' + encodeURIComponent('Hi Tallowwood,\n\nCould you please send me a link to start my fact find?\n\nThanks.')}>
                  Request one from your adviser
                </a>.
              </div>
            </form>
          )}

          {step === 'code' && (
            <div className="signin-form">
              <div className="otp-row" onPaste={handleCodePaste}>
                {code.map((d, i) => (
                  <input
                    key={i}
                    ref={(el) => inputRefs.current[i] = el}
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={1}
                    className={cx('otp-input', error && 'err')}
                    value={d}
                    onChange={(e) => handleCodeChange(i, e.target.value)}
                    onKeyDown={(e) => handleCodeKeyDown(i, e)}
                  />
                ))}
              </div>
              {error && <div className="signin-error">{error}</div>}
              <button type="button" className="btn btn-primary signin-btn" onClick={verifyCode}>
                Verify and continue →
              </button>
              <div className="signin-help">
                <button type="button" className="link-btn" onClick={() => { setStep('email'); setCode(['','','','','','']); setError(null); }}>← Use a different email</button>
                <span className="dot-sep">·</span>
                <button type="button" className="link-btn" onClick={resend} disabled={sending}>
                  {sending ? 'Sending…' : 'Resend code'}
                </button>
              </div>
              <div className="signin-tip">
                Didn't get the code? Check your spam folder or click <em>Resend code</em>.
              </div>
            </div>
          )}
        </div>

        <div className="signin-meta">
          <div className="signin-meta-item">
            <div className="signin-meta-icon">🔒</div>
            <div>
              <strong>Bank-grade encryption.</strong> Your data is encrypted in transit and at rest.
            </div>
          </div>
          <div className="signin-meta-item">
            <div className="signin-meta-icon">🇦🇺</div>
            <div>
              <strong>Australian-hosted.</strong> Stored on Sydney servers, Privacy Act 1988 compliant.
            </div>
          </div>
          <div className="signin-meta-item">
            <div className="signin-meta-icon">⏱</div>
            <div>
              <strong>Auto-saves every change.</strong> Sign back in any time to continue.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SignInScreen });
