/* YeYe Expat Portal — Login screen */

function LoginScreen({ error, checking }) {
  const { lang, t } = useT();
  const [email, setEmail] = useState(() => {
    try { return localStorage.getItem('yeye-last-email') || ''; } catch (_) { return ''; }
  });
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(() => {
    try { return localStorage.getItem('yeye-remember-me') === '1'; } catch (_) { return false; }
  });
  const [busy, setBusy] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [resetOpen, setResetOpen] = useState(false);
  const [resetEmail, setResetEmail] = useState('');
  const [resetBusy, setResetBusy] = useState(false);
  const [resetMsg, setResetMsg] = useState(null);
  const onSubmit = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      if (remember) {
        localStorage.setItem('yeye-last-email', email);
        localStorage.setItem('yeye-remember-me', '1');
      } else {
        localStorage.removeItem('yeye-last-email');
        localStorage.removeItem('yeye-remember-me');
      }
    } catch (_) {}
    try {
      await window.YEYE_AUTH.signIn(email, password, lang, remember);
    } finally {
      setBusy(false);
    }
  };
  const onResetSubmit = async (e) => {
    e.preventDefault();
    setResetBusy(true);
    setResetMsg(null);
    try {
      const target = String(resetEmail || email || '').trim();
      const result = await window.YEYE_AUTH.sendPasswordReset(target);
      if (result && result.ok) {
        setResetMsg({ kind: 'ok', text: t('auth.resetSent') });
      } else {
        setResetMsg({ kind: 'bad', text: t('auth.resetFailed') });
      }
    } catch (err) {
      setResetMsg({ kind: 'bad', text: t('auth.resetFailed') });
    } finally {
      setResetBusy(false);
    }
  };
  const showSpinner = busy || checking;
  const label = showSpinner ? t('auth.signingIn') : t('auth.signIn');
  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--surface, #f7f6f1)', padding: 24,
    }}>
      <div style={{
        width: 'min(420px, 100%)', background: 'var(--surface-2, #fff)',
        border: '1px solid var(--line, #e5e3da)', borderRadius: 20,
        padding: '36px 32px', textAlign: 'center',
        boxShadow: '0 24px 60px -24px rgba(10,14,19,.18), 0 6px 14px -4px rgba(10,14,19,.06)',
      }}>
        <div style={{ width: 64, height: 64, margin: '0 auto 18px', borderRadius: 18, background: 'var(--brand-50,#fbeede)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <BrandLogo mini />
        </div>
        <h1 style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>YeYe Expat Centre</h1>
        <p style={{ marginTop: 8, color: 'var(--muted, #6b7280)', fontSize: 14 }}>
          {t('auth.loginIntro')}
        </p>

        {error && (
          <div className="alert bad" style={{ marginTop: 18, textAlign: 'left' }}>
            <div className="a-ic"><Icon name="alert-triangle" size={16} /></div>
            <div className="grow"><div className="a-t">{error}</div></div>
          </div>
        )}

        <form onSubmit={onSubmit} style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 12, textAlign: 'left' }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 7, color: 'var(--ink-700)', fontSize: 12, fontWeight: 700 }}>
            {t('auth.email')}
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t('auth.emailPlaceholder')}
              required
              autoComplete="email"
              style={{
                height: 46, borderRadius: 12, border: '1px solid var(--line, #e5e3da)',
                padding: '0 13px', fontSize: 14, background: 'var(--surface, #f7f6f1)',
                color: 'var(--ink, #111827)', outline: 'none',
              }}
            />
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 7, color: 'var(--ink-700)', fontSize: 12, fontWeight: 700 }}>
            {t('auth.password')}
            <div style={{ position: 'relative' }}>
              <input
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t('auth.passwordPlaceholder')}
                required
                autoComplete="current-password"
                style={{
                  width: '100%', boxSizing: 'border-box',
                  height: 46, borderRadius: 12, border: '1px solid var(--line, #e5e3da)',
                  padding: '0 44px 0 13px', fontSize: 14, background: 'var(--surface, #f7f6f1)',
                  color: 'var(--ink, #111827)', outline: 'none',
                }}
              />
              <button
                type="button"
                onClick={() => setShowPassword((v) => !v)}
                aria-label={showPassword ? t('auth.hidePassword') : t('auth.showPassword')}
                style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', padding: 6, cursor: 'pointer', color: 'var(--muted, #6b7280)', display: 'inline-flex' }}
              >
                <Icon name={showPassword ? 'eye-off' : 'eye'} size={18} />
              </button>
            </div>
          </label>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink-700)', fontSize: 13, fontWeight: 500, cursor: 'pointer', userSelect: 'none' }}>
              <input
                type="checkbox"
                checked={remember}
                onChange={(e) => setRemember(e.target.checked)}
                style={{ width: 16, height: 16, accentColor: '#0f1115', cursor: 'pointer' }}
              />
              {t('auth.rememberMe')}
            </label>
            <button
              type="button"
              onClick={() => { setResetEmail(email); setResetOpen(true); setResetMsg(null); }}
              style={{ background: 'transparent', border: 'none', padding: 0, color: 'var(--brand, #d97706)', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
            >
              {t('auth.forgotPassword')}
            </button>
          </div>
          <button
            type="submit"
            disabled={showSpinner}
            style={{
              marginTop: 8, width: '100%', height: 48, borderRadius: 12,
              background: '#0f1115', color: '#fff', fontSize: 14.5, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              border: '1px solid #0f1115', cursor: showSpinner ? 'not-allowed' : 'pointer',
            }}>
            {showSpinner && <Icon name="loader" size={18} className="spin" />}
            {label}
          </button>
        </form>

        {resetOpen && (
          <form onSubmit={onResetSubmit} style={{ marginTop: 18, padding: 16, background: 'var(--surface, #f7f6f1)', borderRadius: 12, border: '1px solid var(--line, #e5e3da)', textAlign: 'left' }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>{t('auth.resetTitle')}</div>
            <div style={{ fontSize: 12, color: 'var(--muted, #6b7280)', marginBottom: 10 }}>{t('auth.resetIntro')}</div>
            <input
              type="email"
              value={resetEmail}
              onChange={(e) => setResetEmail(e.target.value)}
              placeholder={t('auth.emailPlaceholder')}
              required
              autoComplete="email"
              style={{ width: '100%', height: 42, borderRadius: 10, border: '1px solid var(--line, #e5e3da)', padding: '0 12px', fontSize: 14, background: '#fff', outline: 'none' }}
            />
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              <button
                type="submit"
                disabled={resetBusy}
                style={{ flex: 1, height: 40, borderRadius: 10, background: '#0f1115', color: '#fff', fontSize: 13.5, fontWeight: 600, border: '1px solid #0f1115', cursor: resetBusy ? 'not-allowed' : 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}
              >
                {resetBusy && <Icon name="loader" size={16} className="spin" />}
                {t('auth.resetSubmit')}
              </button>
              <button
                type="button"
                onClick={() => { setResetOpen(false); setResetMsg(null); }}
                style={{ height: 40, borderRadius: 10, background: 'transparent', color: 'var(--ink-700)', fontSize: 13, fontWeight: 500, border: '1px solid var(--line, #e5e3da)', padding: '0 14px', cursor: 'pointer' }}
              >
                {t('auth.cancel')}
              </button>
            </div>
            {resetMsg && (
              <div className={'alert ' + (resetMsg.kind === 'ok' ? 'ok' : 'bad')} style={{ marginTop: 10, fontSize: 13 }}>
                {resetMsg.text}
              </div>
            )}
          </form>
        )}

        <p style={{ marginTop: 18, color: 'var(--muted, #6b7280)', fontSize: 11.5, lineHeight: 1.6 }}>
          {t('auth.demoNote')}
        </p>
      </div>
    </div>
  );
}

function ForceChangePasswordScreen({ email }) {
  const { t } = useT();
  const [next, setNext] = useState('');
  const [confirm, setConfirm] = useState('');
  const [showNext, setShowNext] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [busy, setBusy] = useState(false);
  const [status, setStatus] = useState(null);
  const submit = async (e) => {
    e.preventDefault();
    setStatus(null);
    if (next.length < 6) { setStatus({ ok: false, code: 'too-short' }); return; }
    if (next !== confirm) { setStatus({ ok: false, code: 'mismatch' }); return; }
    setBusy(true);
    try {
      const res = await window.YEYE_AUTH.setInitialPassword(next);
      if (res && res.ok) {
        setStatus({ ok: true });
        setNext(''); setConfirm('');
      } else {
        setStatus({ ok: false, code: (res && res.code) || 'unknown' });
      }
    } catch (err) {
      setStatus({ ok: false, code: 'unknown' });
    } finally {
      setBusy(false);
    }
  };
  const errText = (code) => {
    switch (code) {
      case 'too-short': return t('set.pwTooShort');
      case 'mismatch': return t('set.pwMismatch');
      case 'same-as-demo': return t('auth.forceSameAsDemo');
      case 'requires-recent-login': return t('auth.forceReauth');
      default: return t('set.pwGeneric');
    }
  };
  const inputWrap = { position: 'relative' };
  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    height: 46, borderRadius: 12, border: '1px solid var(--line, #e5e3da)',
    padding: '0 44px 0 13px', fontSize: 14, background: 'var(--surface, #f7f6f1)',
    color: 'var(--ink, #111827)', outline: 'none',
  };
  const eyeBtn = { position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', padding: 6, cursor: 'pointer', color: 'var(--muted, #6b7280)', display: 'inline-flex' };
  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--surface, #f7f6f1)', padding: 24,
    }}>
      <div style={{
        width: 'min(440px, 100%)', background: 'var(--surface-2, #fff)',
        border: '1px solid var(--line, #e5e3da)', borderRadius: 20,
        padding: '32px 30px', textAlign: 'center',
        boxShadow: '0 24px 60px -24px rgba(10,14,19,.18), 0 6px 14px -4px rgba(10,14,19,.06)',
      }}>
        <div style={{ width: 60, height: 60, margin: '0 auto 14px', borderRadius: 16, background: 'var(--brand-50,#fbeede)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="shield-check" size={26} />
        </div>
        <h1 style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>{t('auth.forceTitle')}</h1>
        <p style={{ marginTop: 8, color: 'var(--muted, #6b7280)', fontSize: 13.5, lineHeight: 1.5 }}>
          {t('auth.forceIntro')}
        </p>
        {email && (
          <div style={{ marginTop: 12, padding: '8px 12px', background: 'var(--surface, #f7f6f1)', borderRadius: 10, fontSize: 13, color: 'var(--ink-700)' }}>{email}</div>
        )}
        {status && status.ok && (
          <div className="alert ok" style={{ marginTop: 16, textAlign: 'left', fontSize: 13 }}>{t('set.pwUpdated')}</div>
        )}
        {status && !status.ok && (
          <div className="alert bad" style={{ marginTop: 16, textAlign: 'left', fontSize: 13 }}>{errText(status.code)}</div>
        )}
        <form onSubmit={submit} style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12, textAlign: 'left' }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 7, color: 'var(--ink-700)', fontSize: 12, fontWeight: 700 }}>
            {t('set.newPassword')}
            <div style={inputWrap}>
              <input
                type={showNext ? 'text' : 'password'}
                value={next}
                onChange={(e) => setNext(e.target.value)}
                placeholder={t('set.newPassword')}
                required
                minLength={6}
                autoComplete="new-password"
                style={inputStyle}
              />
              <button type="button" onClick={() => setShowNext((v) => !v)} style={eyeBtn} aria-label={showNext ? t('auth.hidePassword') : t('auth.showPassword')}>
                <Icon name={showNext ? 'eye-off' : 'eye'} size={18} />
              </button>
            </div>
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 7, color: 'var(--ink-700)', fontSize: 12, fontWeight: 700 }}>
            {t('set.confirmPassword')}
            <div style={inputWrap}>
              <input
                type={showConfirm ? 'text' : 'password'}
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                placeholder={t('set.confirmPassword')}
                required
                minLength={6}
                autoComplete="new-password"
                style={inputStyle}
              />
              <button type="button" onClick={() => setShowConfirm((v) => !v)} style={eyeBtn} aria-label={showConfirm ? t('auth.hidePassword') : t('auth.showPassword')}>
                <Icon name={showConfirm ? 'eye-off' : 'eye'} size={18} />
              </button>
            </div>
          </label>
          <button
            type="submit"
            disabled={busy}
            style={{
              marginTop: 6, width: '100%', height: 46, borderRadius: 12,
              background: '#0f1115', color: '#fff', fontSize: 14.5, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              border: '1px solid #0f1115', cursor: busy ? 'not-allowed' : 'pointer',
            }}>
            {busy && <Icon name="loader" size={18} className="spin" />}
            {t('set.savePassword')}
          </button>
          <button
            type="button"
            onClick={() => window.YEYE_AUTH.signOut()}
            style={{ marginTop: 2, height: 40, background: 'transparent', color: 'var(--muted, #6b7280)', fontSize: 13, fontWeight: 500, border: 'none', cursor: 'pointer' }}
          >
            {t('auth.signOutOther')}
          </button>
        </form>
      </div>
    </div>
  );
}
