// Auth screen – sign-in / sign-up (visual prototype only, no real flow)
// Social buttons (Google / Apple / Facebook) and email+password are wired to
// the same fake "login" handler that flips parent App.user state and routes
// to dashboard. Backend integration (Supabase / OAuth providers) is deferred.
function AuthScreen({ lang, setRoute, onLogin }) {
  const t = (ru, en) => (lang === 'ru' ? ru : en);
  const [mode, setMode] = React.useState('signin'); // signin | signup
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [passwordRepeat, setPasswordRepeat] = React.useState('');
  const [consent, setConsent] = React.useState(false);
  const [name, setName] = React.useState('');

  const isSignup = mode === 'signup';
  const canSubmit = isSignup
    ? (name && email && password && password === passwordRepeat && consent)
    : (email && password);

  const fakeLogin = (providerOrEmail) => {
    // Visual-only: build a demo user. Real OAuth/email-pwd hookup is out of scope.
    const demoName = isSignup && name
      ? name
      : (providerOrEmail === 'google' ? 'Anna Letayeva'
        : providerOrEmail === 'apple' ? 'Mikhail K.'
        : providerOrEmail === 'facebook' ? 'Elena Rivera'
        : email.split('@')[0] || 'Demo User');
    onLogin({ name: demoName, email: email || `${demoName.split(' ')[0].toLowerCase()}@migronis.demo`, provider: providerOrEmail || 'email' });
    setRoute({ name: 'dashboard' });
  };

  return (
    <div style={{ paddingTop: 32, paddingBottom: 80, animation: 'fade-up .4s var(--ease-out)' }}>
      <div className="container" style={{ maxWidth: 980 }}>
        {/* Back */}
        <div style={{ marginBottom: 32 }}>
          <window.BackButton lang={lang} />
        </div>

        {/* Header */}
        <div style={{ marginBottom: 40 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>
            {t('– Личный кабинет', '– Client area')}
          </div>
          <h1 className="display" style={{ fontSize: 'clamp(32px, 4vw, 52px)', margin: 0, maxWidth: 700 }}>
            {isSignup
              ? <>{t('Создайте ', 'Create your ')}<em>{t('аккаунт', 'account')}</em></>
              : <>{t('Войдите в ', 'Sign in to ')}<em>{t('Migronis', 'Migronis')}</em></>}
          </h1>
          <p style={{ color: 'var(--fg-muted)', fontSize: 15, marginTop: 14, maxWidth: 540, lineHeight: 1.55 }}>
            {isSignup
              ? t('Доступ к вашему кейсу: документы, платежи, прямой чат с консультантом, статус по этапам.',
                  'Access to your case: documents, payments, direct chat with your advisor, stage tracking.')
              : t('Все ваши кейсы и документы – в одном месте. Без бумажной волокиты.',
                  'All your cases and documents in one place. No paper shuffling.')}
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 48, alignItems: 'start' }}>
          {/* LEFT: form */}
          <div className="glass" style={{ padding: 32, borderRadius: 'var(--r-xl)', background: 'var(--bg-elev)' }}>
            {/* Social providers */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <SocialButton provider="google" onClick={() => fakeLogin('google')} label={t('Войти через Google', 'Continue with Google')} />
              <SocialButton provider="apple"  onClick={() => fakeLogin('apple')}  label={t('Войти через Apple',  'Continue with Apple')} />
              <SocialButton provider="facebook" onClick={() => fakeLogin('facebook')} label={t('Войти через Facebook', 'Continue with Facebook')} />
            </div>

            {/* Divider */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '24px 0', color: 'var(--fg-dim)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
              <span>{t('или по e-mail', 'or with e-mail')}</span>
              <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
            </div>

            {/* Email form */}
            <form onSubmit={(e) => { e.preventDefault(); if (canSubmit) fakeLogin('email'); }}
                  style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {isSignup && (
                <div className="field">
                  <input value={name} onChange={(e) => setName(e.target.value)}
                         placeholder={t('Имя и фамилия', 'Full name')} autoComplete="name" />
                </div>
              )}
              <div className="field">
                <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                       placeholder="email@example.com" autoComplete="email" />
              </div>
              <div className="field">
                <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
                       placeholder={t('Пароль', 'Password')}
                       autoComplete={isSignup ? 'new-password' : 'current-password'} />
              </div>
              {isSignup && (
                <div className="field">
                  <input type="password" value={passwordRepeat} onChange={(e) => setPasswordRepeat(e.target.value)}
                         placeholder={t('Повторите пароль', 'Repeat password')} autoComplete="new-password" />
                </div>
              )}

              {isSignup && (
                <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>
                  <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)}
                         style={{ marginTop: 3, accentColor: 'var(--accent)' }} />
                  <span>{t('Согласен с обработкой персональных данных. Migronis не передаёт данные третьим лицам.',
                          'I agree to data processing. Migronis does not share data with third parties.')}</span>
                </label>
              )}

              {!isSignup && (
                <div style={{ textAlign: 'right' }}>
                  <button type="button"
                          onClick={() => alert(t('Восстановление пароля будет доступно после подключения бэкенда.',
                                                 'Password reset will be available once the backend is wired up.'))}
                          style={{ background: 'transparent', border: 0, color: 'var(--accent)', fontSize: 12, cursor: 'pointer' }}>
                    {t('Забыли пароль?', 'Forgot password?')}
                  </button>
                </div>
              )}

              <button type="submit" className="btn btn-primary"
                      disabled={!canSubmit}
                      style={{ opacity: canSubmit ? 1 : 0.4, marginTop: 8, height: 52 }}>
                {isSignup ? t('Создать аккаунт', 'Create account') : t('Войти', 'Sign in')} →
              </button>
            </form>

            {/* Toggle mode */}
            <div style={{ marginTop: 22, textAlign: 'center', fontSize: 13, color: 'var(--fg-muted)' }}>
              {isSignup
                ? t('Уже есть аккаунт? ', 'Already have an account? ')
                : t('Нет аккаунта? ', 'New here? ')}
              <button type="button" onClick={() => setMode(isSignup ? 'signin' : 'signup')}
                      style={{ background: 'transparent', border: 0, color: 'var(--accent)', cursor: 'pointer', fontSize: 13, padding: 0 }}>
                {isSignup ? t('Войти', 'Sign in') : t('Зарегистрироваться', 'Sign up')}
              </button>
            </div>

            <div style={{ marginTop: 18, padding: '10px 12px', background: 'var(--accent-soft)', border: '1px dashed var(--accent)', fontSize: 11, color: 'var(--fg-muted)', lineHeight: 1.5 }}>
              {t('Прототип: вход и регистрация работают как макет для согласования с клиентом. Реальная авторизация подключается отдельно через Supabase Auth + OAuth.',
                 'Prototype: sign-in and sign-up are mock-only for client review. Real auth is wired separately via Supabase Auth + OAuth.')}
            </div>
          </div>

          {/* RIGHT: value strip */}
          <aside style={{
            padding: 28, background: 'var(--bg-elev)', border: '1px solid var(--border)',
            borderRadius: 'var(--r-lg)', display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <div className="eyebrow">{t('В личном кабинете', 'Inside the dashboard')}</div>
            {[
              { i: '◐', t: t('Статус кейса по этапам', 'Stage-by-stage case status'), d: t('От Pre-DD до выдачи документа – в реальном времени.', 'From Pre-DD to issuance – in real time.') },
              { i: '◇', t: t('Документы в одном месте', 'All documents in one place'), d: t('Apostille, KYC, retainer – загружено, проверено, подписано.', 'Apostille, KYC, retainer – uploaded, reviewed, signed.') },
              { i: '≡', t: t('Платежи и инвойсы', 'Payments and invoices'), d: t('Прозрачная разбивка: что оплачено, что запланировано.', 'Transparent breakdown: what is paid, what is scheduled.') },
              { i: '✦', t: t('Прямой чат с менеджером', 'Direct chat with your advisor'), d: t('Без e-mail цепочек. Ответ – в течение рабочего дня.', 'No more email chains. Same-day replies on business days.') },
            ].map((row, i) => (
              <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                <div style={{
                  width: 36, height: 36, flexShrink: 0,
                  background: 'var(--accent-soft)', color: 'var(--accent)',
                  display: 'grid', placeItems: 'center',
                  fontFamily: 'var(--f-display)', fontSize: 18,
                }}>{row.i}</div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{row.t}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4, lineHeight: 1.5 }}>{row.d}</div>
                </div>
              </div>
            ))}

            <div className="hr" />
            <div style={{ fontSize: 12, color: 'var(--fg-dim)', lineHeight: 1.6 }}>
              {t('🔒 Шифрование TLS. Двухфакторная аутентификация (после подключения бэкенда).',
                 '🔒 TLS encryption. Two-factor authentication (after backend wiring).')}
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

// Pure-CSS social button with inline SVG mark – no external icons.
function SocialButton({ provider, onClick, label }) {
  const ICONS = {
    google: (
      <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden>
        <path fill="#4285F4" d="M22.5 12.27c0-.79-.07-1.54-.2-2.27H12v4.51h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.22-4.74 3.22-8.32z"/>
        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.99.66-2.25 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
        <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/>
        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/>
      </svg>
    ),
    apple: (
      <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden fill="currentColor">
        <path d="M17.05 12.04c-.03-2.93 2.39-4.34 2.5-4.41-1.36-1.99-3.48-2.26-4.24-2.29-1.8-.18-3.52 1.06-4.44 1.06-.92 0-2.34-1.04-3.85-1.01-1.98.03-3.81 1.15-4.83 2.92-2.06 3.58-.53 8.87 1.49 11.78.99 1.42 2.16 3.02 3.69 2.96 1.48-.06 2.04-.96 3.83-.96 1.79 0 2.29.96 3.85.93 1.59-.03 2.6-1.45 3.57-2.88 1.13-1.65 1.6-3.25 1.62-3.33-.04-.02-3.11-1.19-3.14-4.72zM14.51 3.78c.81-.98 1.36-2.35 1.21-3.71-1.17.05-2.59.78-3.42 1.76-.74.87-1.4 2.26-1.23 3.6 1.31.1 2.65-.66 3.44-1.65z"/>
      </svg>
    ),
    facebook: (
      <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden>
        <path fill="#1877F2" d="M24 12c0-6.63-5.37-12-12-12S0 5.37 0 12c0 5.99 4.39 10.95 10.13 11.85V15.47H7.08V12h3.05V9.36c0-3.01 1.79-4.67 4.53-4.67 1.31 0 2.69.23 2.69.23v2.96h-1.51c-1.49 0-1.96.93-1.96 1.87V12h3.33l-.53 3.47h-2.79v8.38C19.61 22.95 24 17.99 24 12z"/>
        <path fill="#FFFFFF" d="M16.67 15.47L17.2 12h-3.33V9.75c0-.95.47-1.87 1.96-1.87h1.51V4.92s-1.37-.23-2.69-.23c-2.74 0-4.53 1.66-4.53 4.67V12H7.08v3.47h3.05v8.38c.61.1 1.24.15 1.87.15s1.26-.05 1.87-.15v-8.38h2.8z"/>
      </svg>
    ),
  };
  return (
    <button onClick={onClick} className="lift"
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
        height: 48, padding: '0 18px',
        background: 'var(--surface)', border: '1px solid var(--border-strong)',
        color: 'var(--fg)', fontSize: 14, fontWeight: 500,
        cursor: 'pointer', transition: 'background .15s, border-color .15s',
      }}>
      {ICONS[provider]}
      <span>{label}</span>
    </button>
  );
}

window.AuthScreen = AuthScreen;
