// LoginScreen — Persian login form, gates the app.

const { useState: useStateL } = React;

function LoginScreen() {
  const [mode, setMode]         = useStateL('login'); // 'login' | 'register'
  const [username, setUsername] = useStateL('');
  const [password, setPassword] = useStateL('');
  const [showPw, setShowPw]     = useStateL(false);
  const [error, setError]       = useStateL(null);
  const [loading, setLoading]   = useStateL(false);
  const [showHint, setShowHint] = useStateL(true);

  if (mode === 'register') {
    return <RegisterScreen onBack={() => setMode('login')} />;
  }

  const submit = (e) => {
    e?.preventDefault?.();
    if (!username || !password) {
      setError('نام کاربری و گذرواژه را وارد کنید');
      return;
    }
    setLoading(true);
    setError(null);
    window.appActions.login(username, password).then(r => {
      if (!r.ok) {
        setError(r.error);
        setLoading(false);
      }
      // on success, App will re-render and unmount this
    }).catch(() => {
      setError('خطا در ارتباط با سرور');
      setLoading(false);
    });
  };

  const fillCred = (u, p) => {
    setUsername(u); setPassword(p); setError(null);
  };

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)', height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* hero band */}
      <div style={{
        flexShrink: 0,
        background: `linear-gradient(155deg, var(--accent) 0%, color-mix(in oklab, var(--accent) 70%, #000) 100%)`,
        padding: '36px 24px 28px',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* decorative shapes */}
        <div style={{
          position: 'absolute', top: -40, right: -40,
          width: 140, height: 140, borderRadius: '50%',
          background: 'rgba(255,255,255,0.08)',
        }} />
        <div style={{
          position: 'absolute', bottom: -60, left: -30,
          width: 180, height: 180, borderRadius: '50%',
          background: 'rgba(0,0,0,0.10)',
        }} />

        <div style={{
          position: 'relative', display: 'flex', alignItems: 'center', gap: 10,
          marginBottom: 22,
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 11,
            background: 'rgba(255,255,255,0.18)',
            border: '1px solid rgba(255,255,255,0.25)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 17, fontWeight: 700,
            letterSpacing: '-0.04em',
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
          }}>FF</div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#fff' }}>FieldForce</div>
            <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.65)' }}>ATPG · فیلد فورس</div>
          </div>
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{
            fontSize: 22, fontWeight: 700, color: '#fff', lineHeight: 1.3,
            marginBottom: 6, textWrap: 'pretty',
          }}>خوش آمدید</div>
          <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.75)', lineHeight: 1.6 }}>
            برای ورود، نام کاربری و گذرواژه خود را وارد کنید
          </div>
        </div>
      </div>

      {/* form card */}
      <div style={{
        flex: 1, overflowY: 'auto', padding: '20px 22px 18px',
      }}>
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* username field */}
          <Field
            label="نام کاربری"
            icon={<window.IconUser size={16} color="currentColor" />}
          >
            <input
              autoComplete="username"
              value={username}
              onChange={e => { setUsername(e.target.value); setError(null); }}
              placeholder="مثلاً ali"
              style={inputStyle}
              dir="ltr"
            />
          </Field>

          {/* password field */}
          <Field
            label="گذرواژه"
            icon={<window.IconLock size={16} color="currentColor" />}
            trailing={
              <button type="button" onClick={() => setShowPw(s => !s)} style={{
                all: 'unset', cursor: 'pointer', padding: 4,
                color: 'var(--muted)',
              }}>
                <window.IconEye size={16} off={showPw} color="currentColor" />
              </button>
            }
          >
            <input
              type={showPw ? 'text' : 'password'}
              autoComplete="current-password"
              value={password}
              onChange={e => { setPassword(e.target.value); setError(null); }}
              placeholder="••••"
              style={inputStyle}
              dir="ltr"
            />
          </Field>

          {/* forgot link */}
          <div style={{
            display: 'flex', justifyContent: 'flex-end',
            marginTop: -4, marginBottom: 6,
          }}>
            <button type="button" style={{
              all: 'unset', cursor: 'pointer',
              fontSize: 11.5, color: 'var(--accent)', fontWeight: 600,
            }}>گذرواژه را فراموش کرده‌ام</button>
          </div>

          {/* error */}
          {error && (
            <div style={{
              padding: '10px 12px', borderRadius: 11,
              background: 'color-mix(in oklab, var(--danger) 8%, transparent)',
              border: '1px solid color-mix(in oklab, var(--danger) 35%, transparent)',
              color: 'var(--danger)', fontSize: 12, fontWeight: 600,
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <window.IconXCircle size={15} color="currentColor" />
              <span>{error}</span>
            </div>
          )}

          {/* submit */}
          <button
            type="submit"
            disabled={loading}
            style={{
              all: 'unset', cursor: loading ? 'wait' : 'pointer', textAlign: 'center',
              padding: '14px 16px',
              borderRadius: 14,
              background: 'var(--accent)',
              color: '#fff', fontSize: 14, fontWeight: 700,
              opacity: loading ? 0.7 : 1,
              transition: 'opacity 200ms ease',
              marginTop: 4,
              boxShadow: '0 8px 22px -10px color-mix(in oklab, var(--accent) 70%, transparent)',
            }}>
            {loading ? 'در حال ورود…' : 'ورود به حساب'}
          </button>
        </form>

        {/* sign-up link */}
        <div style={{
          marginTop: 14, textAlign: 'center',
          fontSize: 12, color: 'var(--muted)',
        }}>
          حساب کاربری ندارید؟{' '}
          <button type="button" onClick={() => setMode('register')} style={{
            all: 'unset', cursor: 'pointer',
            color: 'var(--accent)', fontWeight: 700,
          }}>ثبت نام کنید</button>
        </div>

        {/* test credentials hint */}
        <div style={{
          marginTop: 18,
          background: 'var(--surface)', border: '1px dashed var(--border)',
          borderRadius: 12, padding: '10px 12px',
        }}>
          <button
            onClick={() => setShowHint(s => !s)}
            style={{
              all: 'unset', cursor: 'pointer', width: '100%',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              fontSize: 11.5, fontWeight: 600, color: 'var(--muted)',
            }}>
            <span>حساب‌های آزمایشی</span>
            <span style={{
              transform: showHint ? 'rotate(180deg)' : 'rotate(0deg)',
              transition: 'transform 200ms ease',
              display: 'inline-flex',
            }}><window.IconChevron size={12} dir="left" /></span>
          </button>
          {showHint && (
            <div style={{
              marginTop: 8, display: 'flex', flexDirection: 'column', gap: 4,
            }}>
              <CredRow label="کاربر فیلد" user="ali"   pass="1234"  onUse={() => fillCred('ali', '1234')} />
              <CredRow label="مدیر"        user="admin" pass="admin" onUse={() => fillCred('admin', 'admin')} />
            </div>
          )}
        </div>

        {/* footer */}
        <div style={{
          textAlign: 'center', marginTop: 24,
          fontSize: 10.5, color: 'var(--muted)',
        }}>
          ATPG FieldForce v۱٫۰ · ساخت ایران
        </div>
      </div>
    </div>
  );
}

const inputStyle = {
  width: '100%', flex: 1, minWidth: 0,
  border: 'none', outline: 'none', background: 'transparent',
  fontSize: 14, fontWeight: 500,
  color: 'var(--ink)',
  fontFamily: 'inherit',
  padding: 0,
};

function Field({ label, icon, trailing, children }) {
  return (
    <div>
      <div style={{
        fontSize: 11, color: 'var(--muted)', letterSpacing: '0.02em',
        marginBottom: 6, fontWeight: 500, padding: '0 2px',
      }}>{label}</div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '12px 14px',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 12,
      }}>
        <span style={{ color: 'var(--muted)', display: 'flex' }}>{icon}</span>
        <div style={{ flex: 1, minWidth: 0, display: 'flex' }}>{children}</div>
        {trailing}
      </div>
    </div>
  );
}

function CredRow({ label, user, pass, onUse }) {
  return (
    <button onClick={onUse} style={{
      all: 'unset', cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '6px 8px', borderRadius: 8,
      transition: 'background 140ms ease',
    }}
    onMouseEnter={e => e.currentTarget.style.background = 'var(--icon-bg)'}
    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <span style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600 }}>{label}</span>
      <span style={{
        fontSize: 11, fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        color: 'var(--ink)', fontWeight: 600,
      }}>
        {user} <span style={{ color: 'var(--muted)' }}>·</span> {pass}
      </span>
    </button>
  );
}

// RegisterScreen — phone sign-up: collect details → verify OTP → enter app.
function RegisterScreen({ onBack }) {
  const [step, setStep]         = useStateL('form'); // 'form' | 'otp'
  const [name, setName]         = useStateL('');
  const [phone, setPhone]       = useStateL('');
  const [national, setNational] = useStateL('');
  const [code, setCode]         = useStateL('');
  const [sentPhone, setSentPhone] = useStateL(''); // normalized phone from server
  const [devCode, setDevCode]   = useStateL(null);
  const [error, setError]       = useStateL(null);
  const [loading, setLoading]   = useStateL(false);

  const submitForm = (e) => {
    e?.preventDefault?.();
    if (!name.trim() || !phone.trim() || !national.trim()) {
      setError('همه فیلدها را تکمیل کنید');
      return;
    }
    setLoading(true); setError(null);
    window.appActions.register({ name, phone, nationalCode: national }).then(r => {
      setLoading(false);
      if (!r.ok) { setError(r.error); return; }
      setSentPhone(r.phone); setDevCode(r.devCode || null);
      setCode(''); setStep('otp');
    }).catch(() => { setLoading(false); setError('خطا در ارتباط با سرور'); });
  };

  const submitOtp = (e) => {
    e?.preventDefault?.();
    if (!code.trim()) { setError('کد تایید را وارد کنید'); return; }
    setLoading(true); setError(null);
    window.appActions.verifyOtp({ phone: sentPhone, code }).then(r => {
      if (!r.ok) { setError(r.error); setLoading(false); }
      // on success, App re-renders and unmounts this screen
    }).catch(() => { setLoading(false); setError('خطا در ارتباط با سرور'); });
  };

  const resend = () => {
    setLoading(true); setError(null);
    window.appActions.register({ name, phone, nationalCode: national }).then(r => {
      setLoading(false);
      if (!r.ok) { setError(r.error); return; }
      setSentPhone(r.phone); setDevCode(r.devCode || null); setCode('');
    }).catch(() => { setLoading(false); setError('خطا در ارتباط با سرور'); });
  };

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)', height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* hero band */}
      <div style={{
        flexShrink: 0,
        background: `linear-gradient(155deg, var(--accent) 0%, color-mix(in oklab, var(--accent) 70%, #000) 100%)`,
        padding: '32px 24px 26px', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 140, height: 140,
          borderRadius: '50%', background: 'rgba(255,255,255,0.08)',
        }} />
        <div style={{
          position: 'absolute', bottom: -60, left: -30, width: 180, height: 180,
          borderRadius: '50%', background: 'rgba(0,0,0,0.10)',
        }} />
        <button type="button" onClick={onBack} style={{
          all: 'unset', cursor: 'pointer', position: 'relative',
          display: 'inline-flex', alignItems: 'center', gap: 6,
          color: 'rgba(255,255,255,0.85)', fontSize: 12, fontWeight: 600,
          marginBottom: 16,
        }}>
          <window.IconChevron size={13} dir="right" />
          <span>بازگشت به ورود</span>
        </button>
        <div style={{ position: 'relative' }}>
          <div style={{
            fontSize: 21, fontWeight: 700, color: '#fff', lineHeight: 1.3, marginBottom: 6,
          }}>{step === 'form' ? 'ثبت نام' : 'تایید شماره'}</div>
          <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.75)', lineHeight: 1.6 }}>
            {step === 'form'
              ? 'اطلاعات خود را وارد کنید تا کد تایید برای شما ارسال شود'
              : `کد تایید پیامک‌شده به ${window.faNumS(sentPhone)} را وارد کنید`}
          </div>
        </div>
      </div>

      {/* body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px 18px' }}>
        {step === 'form' ? (
          <form onSubmit={submitForm} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Field label="نام و نام خانوادگی" icon={<window.IconUser size={16} color="currentColor" />}>
              <input
                value={name}
                onChange={e => { setName(e.target.value); setError(null); }}
                placeholder="مثلاً علی رضایی"
                style={inputStyle}
              />
            </Field>
            <Field label="شماره تلفن همراه" icon={<window.IconMessage size={16} color="currentColor" />}>
              <input
                value={phone}
                onChange={e => { setPhone(e.target.value); setError(null); }}
                placeholder="۰۹۱۲۳۴۵۶۷۸۹"
                inputMode="numeric"
                style={inputStyle}
                dir="ltr"
              />
            </Field>
            <Field label="کد ملی" icon={<window.IconDocuments size={16} color="currentColor" />}>
              <input
                value={national}
                onChange={e => { setNational(e.target.value); setError(null); }}
                placeholder="۱۰ رقم"
                inputMode="numeric"
                style={inputStyle}
                dir="ltr"
              />
            </Field>

            {error && <ErrorBox text={error} />}

            <button type="submit" disabled={loading} style={submitBtnStyle(loading)}>
              {loading ? 'در حال ارسال…' : 'ارسال کد تایید'}
            </button>
          </form>
        ) : (
          <form onSubmit={submitOtp} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {devCode && (
              <div style={{
                padding: '10px 12px', borderRadius: 11,
                background: 'color-mix(in oklab, var(--accent) 8%, transparent)',
                border: '1px dashed color-mix(in oklab, var(--accent) 40%, transparent)',
                color: 'var(--accent)', fontSize: 12, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              }}>
                <span>کد تایید (حالت نمایشی)</span>
                <span style={{
                  fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                  fontSize: 15, letterSpacing: '0.15em',
                }}>{devCode}</span>
              </div>
            )}

            <Field label="کد تایید" icon={<window.IconLock size={16} color="currentColor" />}>
              <input
                value={code}
                onChange={e => { setCode(e.target.value); setError(null); }}
                placeholder="------"
                inputMode="numeric"
                style={{ ...inputStyle, letterSpacing: '0.3em', textAlign: 'center' }}
                dir="ltr"
              />
            </Field>

            {error && <ErrorBox text={error} />}

            <button type="submit" disabled={loading} style={submitBtnStyle(loading)}>
              {loading ? 'در حال تایید…' : 'تایید و ورود'}
            </button>

            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 2 }}>
              <button type="button" onClick={() => { setStep('form'); setError(null); }} style={{
                all: 'unset', cursor: 'pointer', fontSize: 11.5, color: 'var(--muted)', fontWeight: 600,
              }}>تغییر شماره</button>
              <button type="button" onClick={resend} disabled={loading} style={{
                all: 'unset', cursor: loading ? 'wait' : 'pointer',
                fontSize: 11.5, color: 'var(--accent)', fontWeight: 600,
              }}>ارسال مجدد کد</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function ErrorBox({ text }) {
  return (
    <div style={{
      padding: '10px 12px', borderRadius: 11,
      background: 'color-mix(in oklab, var(--danger) 8%, transparent)',
      border: '1px solid color-mix(in oklab, var(--danger) 35%, transparent)',
      color: 'var(--danger)', fontSize: 12, fontWeight: 600,
      display: 'flex', alignItems: 'center', gap: 8,
    }}>
      <window.IconXCircle size={15} color="currentColor" />
      <span>{text}</span>
    </div>
  );
}

const submitBtnStyle = (loading) => ({
  all: 'unset', cursor: loading ? 'wait' : 'pointer', textAlign: 'center',
  padding: '14px 16px', borderRadius: 14, background: 'var(--accent)',
  color: '#fff', fontSize: 14, fontWeight: 700,
  opacity: loading ? 0.7 : 1, transition: 'opacity 200ms ease', marginTop: 4,
  boxShadow: '0 8px 22px -10px color-mix(in oklab, var(--accent) 70%, transparent)',
});

// SetupCredentials — first login after OTP sign-up: pick a username + password.
function SetupCredentials() {
  const [username, setUsername] = useStateL('');
  const [password, setPassword] = useStateL('');
  const [confirm, setConfirm]   = useStateL('');
  const [showPw, setShowPw]     = useStateL(false);
  const [error, setError]       = useStateL(null);
  const [loading, setLoading]   = useStateL(false);

  const submit = (e) => {
    e?.preventDefault?.();
    if (!username.trim() || !password) {
      setError('نام کاربری و گذرواژه را وارد کنید');
      return;
    }
    if (password !== confirm) {
      setError('گذرواژه و تکرار آن یکسان نیستند');
      return;
    }
    setLoading(true); setError(null);
    window.appActions.setupCredentials({ username: username.trim(), password }).then(r => {
      if (!r.ok) { setError(r.error); setLoading(false); }
      // on success, App re-renders into the dashboard
    }).catch(() => { setLoading(false); setError('خطا در ارتباط با سرور'); });
  };

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)', height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <div style={{
        flexShrink: 0,
        background: `linear-gradient(155deg, var(--accent) 0%, color-mix(in oklab, var(--accent) 70%, #000) 100%)`,
        padding: '36px 24px 28px', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 140, height: 140,
          borderRadius: '50%', background: 'rgba(255,255,255,0.08)',
        }} />
        <div style={{
          position: 'absolute', bottom: -60, left: -30, width: 180, height: 180,
          borderRadius: '50%', background: 'rgba(0,0,0,0.10)',
        }} />
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 21, fontWeight: 700, color: '#fff', lineHeight: 1.3, marginBottom: 6 }}>
            تکمیل حساب کاربری
          </div>
          <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.75)', lineHeight: 1.6 }}>
            برای ورودهای بعدی، یک نام کاربری و گذرواژه انتخاب کنید
          </div>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px 18px' }}>
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Field label="نام کاربری" icon={<window.IconUser size={16} color="currentColor" />}>
            <input
              autoComplete="username"
              value={username}
              onChange={e => { setUsername(e.target.value); setError(null); }}
              placeholder="مثلاً ali123"
              style={inputStyle}
              dir="ltr"
            />
          </Field>

          <Field
            label="گذرواژه"
            icon={<window.IconLock size={16} color="currentColor" />}
            trailing={
              <button type="button" onClick={() => setShowPw(s => !s)} style={{
                all: 'unset', cursor: 'pointer', padding: 4, color: 'var(--muted)',
              }}>
                <window.IconEye size={16} off={showPw} color="currentColor" />
              </button>
            }
          >
            <input
              type={showPw ? 'text' : 'password'}
              autoComplete="new-password"
              value={password}
              onChange={e => { setPassword(e.target.value); setError(null); }}
              placeholder="حداقل ۴ نویسه"
              style={inputStyle}
              dir="ltr"
            />
          </Field>

          <Field label="تکرار گذرواژه" icon={<window.IconLock size={16} color="currentColor" />}>
            <input
              type={showPw ? 'text' : 'password'}
              autoComplete="new-password"
              value={confirm}
              onChange={e => { setConfirm(e.target.value); setError(null); }}
              placeholder="گذرواژه را دوباره وارد کنید"
              style={inputStyle}
              dir="ltr"
            />
          </Field>

          {error && <ErrorBox text={error} />}

          <button type="submit" disabled={loading} style={submitBtnStyle(loading)}>
            {loading ? 'در حال ذخیره…' : 'ذخیره و ادامه'}
          </button>
        </form>

        <div style={{ textAlign: 'center', marginTop: 14 }}>
          <button type="button" onClick={() => window.appActions.logout()} style={{
            all: 'unset', cursor: 'pointer', fontSize: 11.5, color: 'var(--muted)', fontWeight: 600,
          }}>خروج از حساب</button>
        </div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
window.SetupCredentials = SetupCredentials;
