// T2 Falcon — Screens

const { useState, useEffect, useRef, useMemo } = React;

// ============ shared helpers ============
const Alert = ({ kind = 'error', title, children }) => (
  <div className={`alert alert-${kind}`} role="alert">
    <div className="alert-icon">
      <Icon name={kind === 'error' ? 'alert' : kind === 'warn' ? 'alert-tri' : 'info'} size={18} />
    </div>
    <div className="alert-body">
      {title && <div className="alert-title">{title}</div>}
      <div>{children}</div>
    </div>
  </div>
);

const BackLink = ({ t, onClick }) => (
  <a href="#" className="back-link" onClick={(e) => { e.preventDefault(); onClick?.(); }}>
    <Icon name="arrow-left" size={14} />
    {t.backToLogin}
  </a>
);

// ============ LOGIN ============
const LoginScreen = ({ t, error, onSubmit, onForgot, loading }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [remember, setRemember] = useState(true);
  const [capsOn, setCapsOn] = useState(false);
  const [touched, setTouched] = useState({});

  const handleKey = (e) => {
    if (e.getModifierState) setCapsOn(e.getModifierState('CapsLock'));
  };

  const requiredMissing = error === 'required';
  const usernameErr = requiredMissing && !username;
  const passwordErr = requiredMissing && !password;

  return (
    <>
      <div className="form-header">
        <div className="form-eyebrow">{t.loginEyebrow}</div>
        <h1 className="form-title">{t.loginTitle}</h1>
        <p className="form-subtitle">{t.loginSubtitle}</p>
      </div>

      {error === 'incorrect'   && <Alert kind="error">{t.errIncorrect}</Alert>}
      {error === 'usernameWrong' && <Alert kind="error">{t.errUsernameIncorrect}</Alert>}
      {error === 'ip'          && <Alert kind="error" title="IP restricted">{t.errIp}</Alert>}
      {error === 'pending'     && <Alert kind="warn"  title="Pending activation">{t.errPending}</Alert>}
      {error === 'locked'      && <Alert kind="error" title="Account locked">{t.errLocked}</Alert>}
      {error === 'lockedAttempts' && <Alert kind="error" title="Account locked">{t.errLockedAttempts}</Alert>}
      {error === 'suspended'   && <Alert kind="error" title="Account suspended">{t.errSuspended}</Alert>}
      {error === 'suspendedAlt'&& <Alert kind="error" title="Account suspended">{t.errSuspendedAlt}</Alert>}
      {error === 'deleted'     && <Alert kind="error" title="Account deleted">{t.errDeleted}</Alert>}
      {error === 'attempts2'   && <Alert kind="warn"  title="Login failed">{t.errIncorrect}. {t.attemptsWarning.replace('{n}', '2')}</Alert>}
      {error === 'attempts1'   && <Alert kind="warn"  title="Login failed">{t.errIncorrect}. {t.attemptsWarning.replace('{n}', '1')}</Alert>}

      <form onSubmit={(e) => { e.preventDefault(); onSubmit({ username, password, remember }); }} noValidate>
        <div className="field">
          <label className="field-label">{t.username}<span className="req">*</span></label>
          <div className={`input-wrap ${usernameErr ? 'error' : ''}`}>
            <span className="icon"><Icon name="user" size={18} /></span>
            <input
              type="text"
              placeholder={t.usernamePh}
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              onBlur={() => setTouched(s => ({ ...s, username: true }))}
              autoComplete="username"
            />
          </div>
          {usernameErr && <div className="field-error"><Icon name="alert" size={12} />{t.errRequired}</div>}
        </div>

        <div className="field">
          <label className="field-label">{t.password}<span className="req">*</span></label>
          <div className={`input-wrap ${passwordErr ? 'error' : ''}`}>
            <span className="icon"><Icon name="lock" size={18} /></span>
            <input
              type={showPw ? 'text' : 'password'}
              placeholder={t.passwordPh}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onKeyUp={handleKey}
              onKeyDown={handleKey}
              onBlur={() => { setTouched(s => ({ ...s, password: true })); setCapsOn(false); }}
              autoComplete="current-password"
            />
            <button type="button" className="trailing" onClick={() => setShowPw(v => !v)} aria-label="Toggle password visibility">
              <Icon name={showPw ? 'eye-off' : 'eye'} size={18} />
            </button>
          </div>
          {passwordErr && <div className="field-error"><Icon name="alert" size={12} />{t.errRequired}</div>}
          {capsOn && !passwordErr && (
            <div className="field-error" style={{ color: 'var(--warn-700)' }}>
              <Icon name="alert-tri" size={12} />Caps Lock is on
            </div>
          )}
        </div>

        <div className="form-row">
          <label className="checkbox">
            <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
            <span className="box"></span>
            {t.remember}
          </label>
          <a href="#" className="forgot-link" onClick={(e) => { e.preventDefault(); onForgot(); }}>{t.forgot}</a>
        </div>

        <button type="submit" className={`btn btn-primary ${loading ? 'loading' : ''}`} disabled={loading}>
          {loading ? t.signingIn : t.loginBtn}
        </button>
      </form>
    </>
  );
};

// ============ FORGOT PASSWORD ============
const ForgotScreen = ({ t, onSubmit, onBack }) => {
  const [username, setUsername] = useState('');
  const [mobile, setMobile] = useState('');
  const mobileValid = /^5\d{8}$/.test(mobile.replace(/\s/g, ''));
  const canSubmit = username.trim().length > 0 && mobileValid;

  return (
    <>
      <BackLink t={t} onClick={onBack} />

      <div className="stepper" aria-hidden="true">
        <div className="step active"></div>
        <div className="step"></div>
        <div className="step"></div>
      </div>

      <div className="form-header">
        <div className="form-eyebrow">{t.forgotEyebrow}</div>
        <h1 className="form-title">{t.forgotTitle}</h1>
        <p className="form-subtitle">{t.forgotSubtitle}</p>
      </div>

      <form onSubmit={(e) => { e.preventDefault(); if (canSubmit) onSubmit({ username, mobile }); }}>
        <div className="field">
          <label className="field-label">{t.username}<span className="req">*</span></label>
          <div className="input-wrap">
            <span className="icon"><Icon name="user" size={18} /></span>
            <input type="text" placeholder={t.usernamePh} value={username} onChange={(e) => setUsername(e.target.value)} />
          </div>
        </div>

        <div className="field">
          <label className="field-label">{t.mobile}<span className="req">*</span></label>
          <div className="phone-wrap">
            <div className="country-code">
              <span className="flag" aria-hidden="true"></span>
              <span>+966</span>
            </div>
            <div className="input-wrap" style={{ flex: 1 }}>
              <span className="icon"><Icon name="phone" size={18} /></span>
              <input
                type="tel"
                placeholder={t.mobilePh}
                value={mobile}
                maxLength={11}
                onChange={(e) => setMobile(e.target.value.replace(/[^\d\s]/g, ''))}
                dir="ltr"
              />
            </div>
          </div>
          <div className="field-hint">Format: starts with 5, 9 digits total.</div>
        </div>

        <button type="submit" className="btn btn-primary" disabled={!canSubmit} style={{ marginTop: 8 }}>
          {t.next} <Icon name="arrow-right" size={16} />
        </button>
      </form>
    </>
  );
};

// ============ OTP ============
const OtpScreen = ({ t, error, onVerify, onResend, onBack, mobileTail = '54' }) => {
  const [digits, setDigits] = useState(['', '', '', '', '', '']);
  const [seconds, setSeconds] = useState(60);
  const [shake, setShake] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const inputs = useRef([]);

  useEffect(() => {
    if (seconds <= 0) return;
    const id = setTimeout(() => setSeconds(s => s - 1), 1000);
    return () => clearTimeout(id);
  }, [seconds]);

  useEffect(() => {
    if (error === 'invalid') {
      setShake(true);
      const id = setTimeout(() => setShake(false), 400);
      return () => clearTimeout(id);
    }
  }, [error]);

  const mm = String(Math.floor(seconds / 60)).padStart(2, '0');
  const ss = String(seconds % 60).padStart(2, '0');

  const setDigit = (i, v) => {
    const val = v.replace(/\D/g, '').slice(-1);
    const next = [...digits];
    next[i] = val;
    setDigits(next);
    if (val && i < 5) inputs.current[i + 1]?.focus();
  };

  const onKeyDown = (i, e) => {
    if (e.key === 'Backspace' && !digits[i] && i > 0) {
      inputs.current[i - 1]?.focus();
    } else if (e.key === 'ArrowLeft' && i > 0) inputs.current[i - 1]?.focus();
    else if (e.key === 'ArrowRight' && i < 5) inputs.current[i + 1]?.focus();
  };

  const onPaste = (e) => {
    const txt = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 6);
    if (!txt) return;
    e.preventDefault();
    const next = ['', '', '', '', '', ''];
    for (let i = 0; i < txt.length; i++) next[i] = txt[i];
    setDigits(next);
    inputs.current[Math.min(txt.length, 5)]?.focus();
  };

  const complete = digits.every(d => d !== '');
  const code = digits.join('');

  const handleVerify = (e) => {
    e?.preventDefault();
    if (!complete) return;
    setVerifying(true);
    setTimeout(() => { setVerifying(false); onVerify(code); }, 700);
  };

  const handleResend = () => {
    setDigits(['', '', '', '', '', '']);
    setSeconds(60);
    onResend?.();
    inputs.current[0]?.focus();
  };

  return (
    <>
      <BackLink t={t} onClick={onBack} />

      <div className="stepper" aria-hidden="true">
        <div className="step done"></div>
        <div className="step active"></div>
        <div className="step"></div>
      </div>

      <div className="form-header">
        <div className="form-eyebrow">{t.otpEyebrow}</div>
        <h1 className="form-title">{t.otpTitle}</h1>
        <p className="form-subtitle">{t.otpSent.replace('54', mobileTail)}</p>
      </div>

      <form onSubmit={handleVerify}>
        <div className={`otp-row ${error === 'invalid' ? 'error' : ''} ${shake ? 'error' : ''}`} onPaste={onPaste} dir="ltr">
          {digits.map((d, i) => (
            <input
              key={i}
              ref={(el) => (inputs.current[i] = el)}
              className={`otp-box ${d ? 'filled' : ''}`}
              inputMode="numeric"
              maxLength={1}
              value={d}
              onChange={(e) => setDigit(i, e.target.value)}
              onKeyDown={(e) => onKeyDown(i, e)}
              autoFocus={i === 0}
            />
          ))}
        </div>

        {error === 'invalid' && (
          <div className="field-error" style={{ marginTop: 8 }}>
            <Icon name="alert" size={12} />{t.invalidOtp}
          </div>
        )}

        <div className="otp-meta">
          <span className="otp-countdown">
            <Icon name="clock" size={14} />
            {seconds > 0 ? <>{t.resendIn} <span className="timer">{mm}:{ss}</span></> : <span style={{ color: 'var(--ink-500)', fontWeight: 500 }}>Didn’t receive the code?</span>}
          </span>
          <button type="button" className="otp-resend" disabled={seconds > 0} onClick={handleResend}>
            <Icon name="refresh" size={14} />
            {t.resend}
          </button>
        </div>

        <button type="submit" className={`btn btn-primary ${verifying ? 'loading' : ''}`} disabled={!complete || verifying} style={{ marginTop: 20 }}>
          {verifying ? t.verifying : t.verify}
        </button>
      </form>
    </>
  );
};

// ============ SUCCESS ============
const SuccessScreen = ({ t, onContinue }) => (
  <div className="success-card">
    <div className="stepper" aria-hidden="true">
      <div className="step done"></div>
      <div className="step done"></div>
      <div className="step active"></div>
    </div>
    <div className="success-mark">
      <Icon name="check-big" size={48} style={{ color: 'white' }} />
    </div>
    <h1 className="form-title" style={{ marginBottom: 10 }}>{t.successTitle}</h1>
    <p className="form-subtitle" style={{ marginBottom: 28 }}>{t.successBody}</p>
    <button className="btn btn-primary" onClick={onContinue} style={{ maxWidth: 260, margin: '0 auto', display: 'flex' }}>
      {t.continue} <Icon name="arrow-right" size={16} />
    </button>
  </div>
);

// ============ RESET PASSWORD ============
const ResetScreen = ({ t, mode = 'reset', onSubmit, onBack }) => {
  const [pw1, setPw1] = useState('');
  const [pw2, setPw2] = useState('');
  const [show1, setShow1] = useState(false);
  const [show2, setShow2] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const hasBoth = pw1.length > 0 && pw2.length > 0;
  const matches = hasBoth && pw1 === pw2;
  const mismatch = hasBoth && pw1 !== pw2;
  const canSubmit = matches && pw1.length >= 8;

  const ctaLabel = mode === 'change' ? t.changeBtn : t.resetBtn;
  const headline = mode === 'change' ? 'Change Password' : t.resetTitle;

  return (
    <>
      <BackLink t={t} onClick={onBack} />

      <div className="stepper" aria-hidden="true">
        <div className="step done"></div>
        <div className="step done"></div>
        <div className="step active"></div>
      </div>

      <div className="form-header">
        <div className="form-eyebrow">{t.resetEyebrow}</div>
        <h1 className="form-title">{headline}</h1>
        <p className="form-subtitle">{t.resetSubtitle}</p>
      </div>

      <form onSubmit={(e) => { e.preventDefault(); setSubmitted(true); if (canSubmit) onSubmit(); }}>
        <div className="field">
          <label className="field-label">{t.newPassword}<span className="req">*</span></label>
          <div className="input-wrap">
            <span className="icon"><Icon name="lock" size={18} /></span>
            <input type={show1 ? 'text' : 'password'} value={pw1} onChange={(e) => setPw1(e.target.value)} placeholder="••••••••" />
            <button type="button" className="trailing" onClick={() => setShow1(v => !v)}>
              <Icon name={show1 ? 'eye-off' : 'eye'} size={18} />
            </button>
          </div>
        </div>

        <div className="field">
          <label className="field-label">{t.confirmPassword}<span className="req">*</span></label>
          <div className={`input-wrap ${mismatch ? 'error' : ''}`}>
            <span className="icon"><Icon name="lock" size={18} /></span>
            <input type={show2 ? 'text' : 'password'} value={pw2} onChange={(e) => setPw2(e.target.value)} placeholder="••••••••" />
            <button type="button" className="trailing" onClick={() => setShow2(v => !v)}>
              <Icon name={show2 ? 'eye-off' : 'eye'} size={18} />
            </button>
          </div>
          {matches && (
            <div className="pw-match"><Icon name="check" size={12} />{t.passwordsMatch}</div>
          )}
          {mismatch && (
            <div className="pw-match mismatch"><Icon name="x" size={12} />{t.passwordsMismatch}</div>
          )}
        </div>

        <button type="submit" className="btn btn-primary" disabled={!canSubmit} style={{ marginTop: 8 }}>
          {ctaLabel}
        </button>
      </form>
    </>
  );
};

// ============ ALL DONE (final) ============
const AllDoneScreen = ({ t, onBackToLogin }) => (
  <div className="success-card">
    <div className="success-mark" style={{ background: 'linear-gradient(135deg, var(--teal-700), var(--cyan-400))' }}>
      <Icon name="check-big" size={48} style={{ color: 'white' }} />
    </div>
    <h1 className="form-title" style={{ marginBottom: 10 }}>Password updated</h1>
    <p className="form-subtitle" style={{ marginBottom: 28 }}>You can now sign in with your new password.</p>
    <button className="btn btn-primary" onClick={onBackToLogin} style={{ maxWidth: 260, margin: '0 auto', display: 'flex' }}>
      {t.backToLogin} <Icon name="arrow-right" size={16} />
    </button>
  </div>
);

Object.assign(window, {
  LoginScreen, ForgotScreen, OtpScreen, SuccessScreen, ResetScreen, AllDoneScreen
});
