/* YeYe Expat Portal — Login screen */

function LoginScreen({ error, checking }) {
  const { lang, t, setLang, currency, setCurrency } = useT();
  const [email, setEmail] = useState(() => {
    try {
      const params = new URLSearchParams(window.location.search || '');
      return params.get('email') || 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 [mode, setMode] = useState('login');
  const [showPassword, setShowPassword] = useState(false);
  const [showSignupPassword, setShowSignupPassword] = useState(false);
  const [showSignupConfirm, setShowSignupConfirm] = useState(false);
  const [signup, setSignup] = useState({
    firstName: '', lastName: '', email: '',
    phoneCountry: 'CZ', phoneLocal: '',
    password: '', confirm: '',
    maritalStatus: '',
    langCode: lang,
    currency: (() => { try { return localStorage.getItem('yeye-currency') || 'EUR'; } catch (_) { return 'EUR'; } })(),
    avatar: null,
    passportFile: null,
    residenceCertificateFile: null,
    biometricPhotoFile: null,
    criminalRecordFile: null,
  });
  const [signupMsg, setSignupMsg] = useState(() => {
    try {
      const params = new URLSearchParams(window.location.search || '');
      return params.get('verified') === '1' ? { kind: 'ok', text: null } : null;
    } catch (_) { return null; }
  });
  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 onSignupSubmit = async (e) => {
    e.preventDefault();
    setSignupMsg(null);
    if (signup.password.length < 6) {
      setSignupMsg({ kind: 'bad', text: t('auth.signupPwShort') });
      return;
    }
    if (signup.password !== signup.confirm) {
      setSignupMsg({ kind: 'bad', text: t('auth.signupPwMismatch') });
      return;
    }
    setBusy(true);
    try {
      const phoneE164 = window.YEYE_PHONE ? window.YEYE_PHONE.toE164(signup.phoneCountry, signup.phoneLocal) : '';
      const country = window.YEYE_PHONE ? window.YEYE_PHONE.findByCode(signup.phoneCountry) : null;
      const result = await window.YEYE_AUTH.register({
        firstName: signup.firstName.trim(),
        lastName: signup.lastName.trim(),
        email: signup.email.trim(),
        phone: phoneE164,
        country: country ? country.code : undefined,
        maritalStatus: '',
        langCode: signup.langCode || 'en',
        currency: signup.currency || 'EUR',
        avatar: signup.avatar,
        passportFile: null,
        residenceCertificateFile: null,
        biometricPhotoFile: null,
        criminalRecordFile: null,
      }, signup.password, lang, remember);
      if (result && result.ok) {
        setSignupMsg({ kind: result.contactSynced ? 'ok' : 'warn', text: result.contactSynced ? t('auth.signupOk') : t('auth.signupOkGhlPending') });
        setPassword('');
        setEmail(signup.email.trim());
        setMode('login');
      } else {
        setSignupMsg({ kind: 'bad', text: (result && result.message) || t('auth.signupFailed') });
      }
    } catch (err) {
      setSignupMsg({ kind: 'bad', text: t('auth.signupFailed') });
    } finally {
      setBusy(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, boxSizing: 'border-box',
	    }}>
	      <div style={{
	        width: '100%', maxWidth: 420, background: 'var(--surface-2, #fff)',
	        border: '1px solid var(--line, #e5e3da)', borderRadius: 20,
	        padding: '36px 32px', textAlign: 'center',
	        boxSizing: 'border-box',
	        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, margin: 0 }}>YeYe Expats Centre</h1>
        <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center', gap: 8, flexWrap: 'wrap' }}>
          <LangMenu lang={lang} onChange={(nextLang) => {
            setLang(nextLang);
            setSignup((v) => ({ ...v, langCode: nextLang }));
          }} />
          <CurrencyMenu currency={currency} onChange={(nextCurrency) => {
            setCurrency(nextCurrency);
            setSignup((v) => ({ ...v, currency: nextCurrency }));
          }} />
        </div>
        <p style={{ marginTop: 8, color: 'var(--muted, #6b7280)', fontSize: 14 }}>
          {mode === 'login' ? t('auth.loginIntro') : t('auth.signupIntro')}
        </p>

        <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, padding: 4, border: '1px solid var(--line, #e5e3da)', borderRadius: 14, background: 'var(--surface, #f7f6f1)' }}>
          {[
            ['login', t('auth.signIn')],
            ['signup', t('auth.signUp')],
          ].map(([id, text]) => (
            <button
              key={id}
              type="button"
              onClick={() => { setMode(id); setSignupMsg(null); }}
              style={{
                height: 38, borderRadius: 10, border: '1px solid ' + (mode === id ? '#0f1115' : 'transparent'),
                background: mode === id ? '#0f1115' : 'transparent', color: mode === id ? '#fff' : 'var(--ink-700)',
                fontSize: 13.5, fontWeight: 700, cursor: 'pointer',
              }}
            >
              {text}
            </button>
          ))}
        </div>

        {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>
        )}

        {signupMsg && (
          <div className={'alert ' + (signupMsg.kind === 'ok' ? 'ok' : (signupMsg.kind === 'warn' ? 'warn' : 'bad'))} style={{ marginTop: 18, textAlign: 'left', fontSize: 13 }}>
            {signupMsg.text || t('auth.verifiedLogin')}
          </div>
        )}

        {mode === 'login' && <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>}

        {mode === 'signup' && <form onSubmit={onSignupSubmit} style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 12, textAlign: 'left' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 7, color: 'var(--ink-700)', fontSize: 12, fontWeight: 700 }}>
              {t('auth.firstName')}
              <input type="text" value={signup.firstName} onChange={(e) => setSignup((v) => ({ ...v, firstName: e.target.value }))} required autoComplete="given-name" 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.lastName')}
              <input type="text" value={signup.lastName} onChange={(e) => setSignup((v) => ({ ...v, lastName: e.target.value }))} required autoComplete="family-name" 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>
          </div>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 7, color: 'var(--ink-700)', fontSize: 12, fontWeight: 700 }}>
            {t('auth.email')}
            <input type="email" value={signup.email} onChange={(e) => setSignup((v) => ({ ...v, email: 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.phone')}
            {window.YEYE_PhoneInput ? (
              <window.YEYE_PhoneInput
                countryCode={signup.phoneCountry}
                localNumber={signup.phoneLocal}
                onCountryChange={(code) => setSignup((v) => ({ ...v, phoneCountry: code }))}
                onLocalChange={(digits) => setSignup((v) => ({ ...v, phoneLocal: digits }))}
                required
                autoComplete="tel-national"
              />
            ) : (
              <input type="tel" value={signup.phoneLocal} onChange={(e) => setSignup((v) => ({ ...v, phoneLocal: e.target.value }))} required autoComplete="tel" 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={showSignupPassword ? 'text' : 'password'} value={signup.password} onChange={(e) => setSignup((v) => ({ ...v, password: e.target.value }))} required minLength={6} autoComplete="new-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={() => setShowSignupPassword((v) => !v)} aria-label={showSignupPassword ? 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={showSignupPassword ? '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('auth.confirmPassword')}
            <div style={{ position: 'relative' }}>
              <input type={showSignupConfirm ? 'text' : 'password'} value={signup.confirm} onChange={(e) => setSignup((v) => ({ ...v, confirm: e.target.value }))} required minLength={6} autoComplete="new-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={() => setShowSignupConfirm((v) => !v)} aria-label={showSignupConfirm ? 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={showSignupConfirm ? 'eye-off' : 'eye'} size={18} /></button>
            </div>
          </label>
          {(() => {
            const LANG_OPTS = [
              { code: 'en', label: 'English', flag: '🇬🇧' },
              { code: 'tr', label: 'Türkçe', flag: '🇹🇷' },
              { code: 'cs', label: 'Čeština', flag: '🇨🇿' },
            ];
            const CUR_OPTS = [
              { code: 'EUR', label: 'EUR', symbol: '€' },
              { code: 'CZK', label: 'CZK', symbol: 'Kč' },
              { code: 'TRY', label: 'TL', symbol: '₺' },
            ];
            const AVATAR_OPTS = ['🙂', '😎', '🤩', '🥳', '🦸', '🧑‍💻', '🐱', '🐶', '🦊', '🐼', '🌟', '⚡', '🚀', '🎨', '☕', '🍀'];
            const btnStyle = (active) => ({
              flex: 1, height: 42, borderRadius: 10, cursor: 'pointer',
              border: '1px solid ' + (active ? '#0f1115' : 'var(--line, #e5e3da)'),
              background: active ? '#0f1115' : 'var(--surface, #f7f6f1)',
              color: active ? '#fff' : 'var(--ink, #111827)',
              fontSize: 13, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            });
            const secTitle = { fontSize: 12, fontWeight: 700, color: 'var(--ink-700)', margin: 0 };
            return (
              <>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <label style={secTitle}>{t('auth.language') || 'Language'}</label>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {LANG_OPTS.map((opt) => (
                      <button key={opt.code} type="button" onClick={() => setSignup((v) => ({ ...v, langCode: opt.code }))} style={btnStyle(signup.langCode === opt.code)}>
                        <span style={{ fontSize: 16 }}>{opt.flag}</span>{opt.label}
                      </button>
                    ))}
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <label style={secTitle}>{t('auth.currency') || 'Currency'}</label>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {CUR_OPTS.map((opt) => (
                      <button key={opt.code} type="button" onClick={() => setSignup((v) => ({ ...v, currency: opt.code }))} style={btnStyle(signup.currency === opt.code)}>
                        <span style={{ opacity: .75 }}>{opt.symbol}</span>{opt.label}
                      </button>
                    ))}
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <label style={secTitle}>{t('auth.avatar') || 'Pick your avatar'}</label>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 6 }}>
                    {AVATAR_OPTS.map((emo) => {
                      const active = signup.avatar && signup.avatar.type === 'emoji' && signup.avatar.value === emo;
                      return (
                        <button key={emo} type="button"
                          onClick={() => setSignup((v) => ({ ...v, avatar: active ? null : { type: 'emoji', value: emo } }))}
                          style={{
                            aspectRatio: '1', border: '1px solid ' + (active ? '#0f1115' : 'var(--line, #e5e3da)'),
                            borderRadius: 10, background: active ? '#EEF2FF' : 'var(--surface, #f7f6f1)',
                            fontSize: 20, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                          }}>{emo}</button>
                      );
                    })}
                  </div>
                </div>
              </>
            );
          })()}
          <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="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" />}
            {showSpinner ? t('auth.creating') : t('auth.createAccount')}
          </button>
        </form>}

        {mode === 'login' && 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>
        )}
      </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>
  );
}
