// Full-page auth screens shown when there is no valid session: login,
// register and recover. Reuses the existing .field/.btn-*/.authcard styles.

const { useState: authUseState } = React;

const LANG_NAMES = { en: 'English', es: 'Español', ca: 'Català', nl: 'Nederlands' };

function LoginView({ onLoggedIn, onGoRegister, onGoRecover }) {
  const [username, setUsername] = authUseState('');
  const [password, setPassword] = authUseState('');
  const [error, setError] = authUseState('');
  const [busy, setBusy] = authUseState(false);

  function submit(e) {
    e.preventDefault();
    setError(''); setBusy(true);
    fetch('/api/auth/login', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
      body: JSON.stringify({ username, password }),
    })
      .then(r => (r.ok ? r.json() : Promise.reject()))
      .then(data => onLoggedIn(data))
      .catch(() => { setError(t('auth.login.error')); setBusy(false); });
  }

  return (
    <div className="authpage">
      <form className="authcard" onSubmit={submit}>
        <div className="authcard-title">{t('auth.login.title')}</div>
        <label className="field">
          <span className="field-lbl">{t('auth.login.username')}</span>
          <input type="text" value={username} onChange={e => setUsername(e.target.value)} autoFocus required/>
        </label>
        <label className="field" style={{ marginTop: 12 }}>
          <span className="field-lbl">{t('auth.login.password')}</span>
          <input type="password" value={password} onChange={e => setPassword(e.target.value)} required/>
        </label>
        {error && <div className="authcard-error">{error}</div>}
        <div className="authcard-actions">
          <button className="btn-primary" type="submit" disabled={busy} style={{ justifyContent: 'center' }}>
            {t('auth.login.submit')}
          </button>
        </div>
        <div className="authcard-foot">
          {t('auth.login.noAccount')} <button type="button" className="authcard-link" onClick={onGoRegister}>{t('auth.login.registerLink')}</button>
          <br/>
          <button type="button" className="authcard-link" onClick={onGoRecover}>{t('auth.login.forgot')}</button>
        </div>
      </form>
    </div>
  );
}

function RegisterView({ onRegistered, onGoLogin }) {
  const [username, setUsername] = authUseState('');
  const [password, setPassword] = authUseState('');
  const [language, setLanguageSel] = authUseState(getLang());
  const [website, setWebsite] = authUseState('');
  const [error, setError] = authUseState('');
  const [busy, setBusy] = authUseState(false);
  const [step, setStep] = authUseState('form'); // form | recovery | mcp
  const [result, setResult] = authUseState(null);

  function submit(e) {
    e.preventDefault();
    setError(''); setBusy(true);
    fetch('/api/auth/register', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
      body: JSON.stringify({ username, password, language, website }),
    })
      .then(r => {
        if (r.status === 409) { setError(t('auth.register.usernameTaken')); setBusy(false); return null; }
        if (!r.ok) { setError(t('auth.register.error')); setBusy(false); return null; }
        return r.json();
      })
      .then(data => { if (data) { setResult(data); setStep('recovery'); } })
      .catch(() => { setError(t('auth.register.error')); setBusy(false); });
  }

  if (step === 'recovery' && result) {
    return (
      <div className="authpage"><div className="authcard">
        <div className="authcard-title">{t('auth.register.recoverySaveTitle')}</div>
        <p className="account-note">{t('auth.register.recoverySaveBody')}</p>
        <div className="recovery-box">{result.recoveryCode}</div>
        <div className="authcard-actions">
          <button className="btn-primary" style={{ justifyContent: 'center' }} onClick={() => setStep('mcp')}>
            {t('auth.register.recoveryContinue')}
          </button>
        </div>
      </div></div>
    );
  }
  if (step === 'mcp' && result) {
    return (
      <div className="authpage"><div className="authcard">
        <div className="authcard-title">{t('auth.register.mcpTitle')}</div>
        <p className="account-note">{t('auth.register.mcpBody')}</p>
        <div className="mcp-url-box">{result.mcpUrl}</div>
        <div className="authcard-actions">
          <button className="btn-primary" style={{ justifyContent: 'center' }} onClick={() => onRegistered(result)}>
            {t('auth.register.finish')}
          </button>
        </div>
      </div></div>
    );
  }

  return (
    <div className="authpage">
      <form className="authcard" onSubmit={submit}>
        <div className="authcard-title">{t('auth.register.title')}</div>
        <label className="field">
          <span className="field-lbl">{t('auth.register.username')}</span>
          <input type="text" value={username} onChange={e => setUsername(e.target.value)} autoFocus required
                 pattern="[a-zA-Z0-9_-]{3,32}"/>
          <span className="authcard-hint">{t('auth.register.usernameHint')}</span>
        </label>
        <label className="field" style={{ marginTop: 12 }}>
          <span className="field-lbl">{t('auth.register.password')}</span>
          <input type="password" value={password} onChange={e => setPassword(e.target.value)} required minLength={8}/>
          <span className="authcard-hint">{t('auth.register.passwordHint')}</span>
        </label>
        <div className="field" style={{ marginTop: 12 }}>
          <span className="field-lbl">{t('auth.register.language')}</span>
          <div className="lang-pills">
            {SUPPORTED_LANGS.map(l => (
              <button key={l} type="button"
                      className={`lang-pill ${language === l ? 'lang-pill-sel' : ''}`}
                      onClick={() => { setLanguageSel(l); setLang(l); }}>
                {LANG_NAMES[l]}
              </button>
            ))}
          </div>
        </div>
        {/* Honeypot — hidden from real users, bots tend to fill every field */}
        <input type="text" name="website" value={website} onChange={e => setWebsite(e.target.value)}
               style={{ position: 'absolute', left: '-9999px', width: 1, height: 1 }}
               tabIndex={-1} autoComplete="off" aria-hidden="true"/>
        {error && <div className="authcard-error">{error}</div>}
        <div className="authcard-actions">
          <button className="btn-primary" type="submit" disabled={busy} style={{ justifyContent: 'center' }}>
            {t('auth.register.submit')}
          </button>
        </div>
        <div className="authcard-foot">
          {t('auth.register.haveAccount')} <button type="button" className="authcard-link" onClick={onGoLogin}>{t('auth.register.loginLink')}</button>
        </div>
      </form>
    </div>
  );
}

function RecoverView({ onRecovered, onGoLogin }) {
  const [username, setUsername] = authUseState('');
  const [recoveryCode, setRecoveryCode] = authUseState('');
  const [newPassword, setNewPassword] = authUseState('');
  const [error, setError] = authUseState('');
  const [busy, setBusy] = authUseState(false);
  const [result, setResult] = authUseState(null);

  function submit(e) {
    e.preventDefault();
    setError(''); setBusy(true);
    fetch('/api/auth/recover', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
      body: JSON.stringify({ username, recoveryCode, newPassword }),
    })
      .then(r => (r.ok ? r.json() : Promise.reject()))
      .then(data => setResult(data))
      .catch(() => { setError(t('auth.recover.error')); setBusy(false); });
  }

  if (result) {
    return (
      <div className="authpage"><div className="authcard">
        <div className="authcard-title">{t('auth.recover.success')}</div>
        <div className="recovery-box">{result.recoveryCode}</div>
        <div className="authcard-actions">
          <button className="btn-primary" style={{ justifyContent: 'center' }} onClick={() => onRecovered(result)}>
            {t('auth.register.finish')}
          </button>
        </div>
      </div></div>
    );
  }

  return (
    <div className="authpage">
      <form className="authcard" onSubmit={submit}>
        <div className="authcard-title">{t('auth.recover.title')}</div>
        <label className="field">
          <span className="field-lbl">{t('auth.recover.username')}</span>
          <input type="text" value={username} onChange={e => setUsername(e.target.value)} autoFocus required/>
        </label>
        <label className="field" style={{ marginTop: 12 }}>
          <span className="field-lbl">{t('auth.recover.recoveryCode')}</span>
          <input type="text" value={recoveryCode} onChange={e => setRecoveryCode(e.target.value)} required/>
        </label>
        <label className="field" style={{ marginTop: 12 }}>
          <span className="field-lbl">{t('auth.recover.newPassword')}</span>
          <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)} required minLength={8}/>
        </label>
        {error && <div className="authcard-error">{error}</div>}
        <div className="authcard-actions">
          <button className="btn-primary" type="submit" disabled={busy} style={{ justifyContent: 'center' }}>
            {t('auth.recover.submit')}
          </button>
        </div>
        <div className="authcard-foot">
          <button type="button" className="authcard-link" onClick={onGoLogin}>{t('auth.recover.backToLogin')}</button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { LoginView, RegisterView, RecoverView });
