/* RDR2RP — модалка входа/регистрации по email+паролю (+ Discord на переходный
   период). Рендерится в App; открывается из любого места через
   window.openAuthModal(returnTo). */

const authInputStyle = {
  width: '100%', padding: '10px 12px', background: 'var(--bg-0, #0C0A08)',
  border: '1px solid var(--line-2, #38301F)', borderRadius: 4,
  color: 'var(--fg-0, #EFE6D4)', fontFamily: 'inherit', fontSize: 14, marginBottom: 10,
};

function AuthField({ label, ...rest }) {
  return (
    <label style={{ display: 'block' }}>
      <span className="t-body-sm" style={{ display: 'block', marginBottom: 4, opacity: 0.8 }}>{label}</span>
      <input style={authInputStyle} {...rest} />
    </label>
  );
}

function AuthModalHost({ onAuthed, resetToken, onResetDone }) {
  // open: null | { mode: 'login'|'register'|'forgot'|'reset', returnTo }
  const [open, setOpen] = React.useState(null);
  const [cfg, setCfg] = React.useState({ discordLoginEnabled: true, registrationEnabled: true });
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [notice, setNotice] = React.useState(null);
  const [form, setForm] = React.useState({ login: '', email: '', password: '', password2: '' });

  React.useEffect(() => {
    if (window.api.getAuthConfig) {
      window.api.getAuthConfig().then(setCfg).catch(() => {});
    }
  }, []);

  // Глобальный «открыватель» — для шапки, витрины, личного кабинета.
  React.useEffect(() => {
    window.openAuthModal = (returnTo) => {
      setError(null); setNotice(null);
      setForm({ login: '', email: '', password: '', password2: '' });
      setOpen({ mode: 'login', returnTo: returnTo || null });
    };
    return () => { delete window.openAuthModal; };
  }, []);

  // Пришли по ссылке сброса пароля из письма.
  React.useEffect(() => {
    if (resetToken) {
      setError(null); setNotice(null);
      setForm({ login: '', email: '', password: '', password2: '' });
      setOpen({ mode: 'reset', returnTo: null });
    }
  }, [resetToken]);

  if (!open) return null;

  const close = () => { if (!busy) { setOpen(null); if (open.mode === 'reset' && onResetDone) onResetDone(); } };
  const switchMode = (mode) => { setError(null); setNotice(null); setOpen({ ...open, mode }); };
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const finishLogin = async () => {
    const d = await window.api.me();
    if (onAuthed) onAuthed(d.user);
    setOpen(null);
  };

  const submitLogin = async (e) => {
    e.preventDefault();
    setBusy(true); setError(null);
    try {
      await window.api.emailLogin(form.login.trim(), form.password);
      await finishLogin();
    } catch (err) { setError(err.message); } finally { setBusy(false); }
  };

  const submitRegister = async (e) => {
    e.preventDefault();
    setError(null);
    if (!/^[a-zA-Z0-9_-]{3,32}$/.test(form.login.trim())) {
      setError('Логин: 3–32 символа — латиница, цифры, «-» и «_»'); return;
    }
    if (form.password.length < 8) { setError('Пароль не короче 8 символов'); return; }
    if (form.password !== form.password2) { setError('Пароли не совпадают'); return; }
    setBusy(true);
    try {
      await window.api.register(form.login.trim(), form.email, form.password);
      await finishLogin();
    } catch (err) { setError(err.message); setBusy(false); }
  };

  const submitForgot = async (e) => {
    e.preventDefault();
    setBusy(true); setError(null);
    try {
      await window.api.requestPasswordReset(form.login.trim());
      setNotice('Если такой аккаунт существует — мы отправили письмо со ссылкой для сброса пароля на его почту.');
    } catch (err) { setError(err.message); } finally { setBusy(false); }
  };

  const submitReset = async (e) => {
    e.preventDefault();
    setError(null);
    if (form.password.length < 8) { setError('Пароль не короче 8 символов'); return; }
    if (form.password !== form.password2) { setError('Пароли не совпадают'); return; }
    setBusy(true);
    try {
      await window.api.confirmPasswordReset(resetToken, form.password);
      setNotice('Пароль изменён! Теперь войдите с новым паролем.');
      setTimeout(() => { setNotice(null); switchMode('login'); if (onResetDone) onResetDone(); }, 1500);
    } catch (err) { setError(err.message); } finally { setBusy(false); }
  };

  const discordLogin = () => {
    window.location.href = window.api.loginUrl(open.returnTo || undefined);
  };

  const titles = { login: 'Вход', register: 'Регистрация', forgot: 'Сброс пароля', reset: 'Новый пароль' };

  return (
    <div className="modal-scrim" onClick={close}>
      <div className="prod-modal" onClick={(e) => e.stopPropagation()}
        style={{ display: 'block', maxWidth: 420, padding: 24 }}>
        <button className="modal-x" onClick={close} disabled={busy} aria-label="Закрыть"><Icon name="x" /></button>
        <h3 className="t-h3" style={{ marginBottom: 14 }}>{titles[open.mode]}</h3>

        {error && (
          <div className="t-body-sm" role="alert"
            style={{ background: 'rgba(190,52,42,.12)', border: '1px solid var(--red, #BE342A)',
              borderRadius: 4, padding: '8px 12px', marginBottom: 12 }}>{error}</div>
        )}
        {notice && (
          <div className="t-body-sm"
            style={{ background: 'rgba(90,140,60,.12)', border: '1px solid #5a8c3c',
              borderRadius: 4, padding: '8px 12px', marginBottom: 12 }}>{notice}</div>
        )}

        {open.mode === 'login' && (
          <form onSubmit={submitLogin}>
            <AuthField label="Логин или почта" type="text" required autoComplete="username"
              value={form.login} onChange={set('login')} placeholder="Логин или почта" />
            <AuthField label="Пароль" type="password" required autoComplete="current-password"
              value={form.password} onChange={set('password')} placeholder="••••••••" />
            <button className="btn btn-primary" style={{ width: '100%', marginTop: 4 }} disabled={busy}>
              {busy ? 'Входим…' : 'Войти'}
            </button>
            <div className="t-body-sm" style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
              <a style={{ cursor: 'pointer', opacity: 0.85 }} onClick={() => switchMode('forgot')}>Забыли пароль?</a>
              {cfg.registrationEnabled && (
                <a style={{ cursor: 'pointer', opacity: 0.85 }} onClick={() => switchMode('register')}>Регистрация</a>
              )}
            </div>
            {cfg.discordLoginEnabled && (
              <>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '14px 0' }}>
                  <span style={{ flex: 1, height: 1, background: 'var(--line-2, #38301F)' }}></span>
                  <span className="t-body-sm" style={{ opacity: 0.6 }}>или</span>
                  <span style={{ flex: 1, height: 1, background: 'var(--line-2, #38301F)' }}></span>
                </div>
                <button type="button" className="btn btn-discord" style={{ width: '100%' }}
                  onClick={discordLogin} disabled={busy}>
                  <DiscordIcon size={16} />Войти через Discord
                </button>
              </>
            )}
          </form>
        )}

        {open.mode === 'register' && (
          <form onSubmit={submitRegister}>
            <AuthField label="Логин (уникальный, латиница/цифры)" type="text" required maxLength={32}
              autoComplete="username" value={form.login} onChange={set('login')} placeholder="Ваш логин" />
            <AuthField label="Почта" type="email" required autoComplete="email"
              value={form.email} onChange={set('email')} placeholder="you@example.ru" />
            <AuthField label="Пароль (не короче 8 символов)" type="password" required autoComplete="new-password"
              value={form.password} onChange={set('password')} placeholder="••••••••" />
            <AuthField label="Пароль ещё раз" type="password" required autoComplete="new-password"
              value={form.password2} onChange={set('password2')} placeholder="••••••••" />
            <button className="btn btn-primary" style={{ width: '100%', marginTop: 4 }} disabled={busy}>
              {busy ? 'Создаём аккаунт…' : 'Зарегистрироваться'}
            </button>
            <div className="t-body-sm" style={{ marginTop: 10, textAlign: 'center' }}>
              <a style={{ cursor: 'pointer', opacity: 0.85 }} onClick={() => switchMode('login')}>Уже есть аккаунт? Войти</a>
            </div>
          </form>
        )}

        {open.mode === 'forgot' && (
          <form onSubmit={submitForgot}>
            <p className="t-body-sm" style={{ marginBottom: 12, opacity: 0.85 }}>
              Укажите логин или почту аккаунта — пришлём на его почту ссылку для сброса пароля.
            </p>
            <AuthField label="Логин или почта" type="text" required autoComplete="username"
              value={form.login} onChange={set('login')} placeholder="Логин или почта" />
            <button className="btn btn-primary" style={{ width: '100%', marginTop: 4 }} disabled={busy}>
              {busy ? 'Отправляем…' : 'Отправить письмо'}
            </button>
            <div className="t-body-sm" style={{ marginTop: 10, textAlign: 'center' }}>
              <a style={{ cursor: 'pointer', opacity: 0.85 }} onClick={() => switchMode('login')}>Назад ко входу</a>
            </div>
          </form>
        )}

        {open.mode === 'reset' && (
          <form onSubmit={submitReset}>
            <AuthField label="Новый пароль (не короче 8 символов)" type="password" required autoComplete="new-password"
              value={form.password} onChange={set('password')} placeholder="••••••••" />
            <AuthField label="Пароль ещё раз" type="password" required autoComplete="new-password"
              value={form.password2} onChange={set('password2')} placeholder="••••••••" />
            <button className="btn btn-primary" style={{ width: '100%', marginTop: 4 }} disabled={busy}>
              {busy ? 'Сохраняем…' : 'Сохранить пароль'}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AuthModalHost });
