// Account settings overlay: language, password, MCP token, logout.
// Reuses the .modal/.modal-back styling already used by EditorModal.

const { useState: acctUseState } = React;

function AccountSettings({ user, onClose, onUserChange, onLanguageChange, onLoggedOut }) {
  const [language, setLanguageSel] = acctUseState(user.language);
  const [langSaved, setLangSaved] = acctUseState(false);
  const [currentPassword, setCurrentPassword] = acctUseState('');
  const [newPassword, setNewPassword] = acctUseState('');
  const [pwError, setPwError] = acctUseState('');
  const [pwSuccess, setPwSuccess] = acctUseState(false);
  const [mcpUrl, setMcpUrl] = acctUseState(user.mcpUrl);
  const [regenerating, setRegenerating] = acctUseState(false);

  function changeLanguage(l) {
    setLanguageSel(l);
    fetch('/api/auth/change-language', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
      body: JSON.stringify({ language: l }),
    })
      .then(r => (r.ok ? r.json() : Promise.reject()))
      .then(() => {
        onLanguageChange(l);
        onUserChange({ ...user, language: l });
        setLangSaved(true);
        setTimeout(() => setLangSaved(false), 2000);
      })
      .catch(() => {});
  }

  function changePassword(e) {
    e.preventDefault();
    setPwError(''); setPwSuccess(false);
    fetch('/api/auth/change-password', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
      body: JSON.stringify({ currentPassword, newPassword }),
    })
      .then(r => (r.ok ? r.json() : Promise.reject()))
      .then(() => { setPwSuccess(true); setCurrentPassword(''); setNewPassword(''); })
      .catch(() => setPwError(t('account.changePasswordError')));
  }

  function regenerateToken() {
    if (!window.confirm(t('account.mcpRegenerateConfirm'))) return;
    setRegenerating(true);
    fetch('/api/auth/regenerate-mcp-token', { method: 'POST', credentials: 'same-origin' })
      .then(r => r.json())
      .then(data => { setMcpUrl(data.mcpUrl); onUserChange({ ...user, mcpUrl: data.mcpUrl }); setRegenerating(false); })
      .catch(() => setRegenerating(false));
  }

  function logout() {
    fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' }).finally(onLoggedOut);
  }

  return (
    <div className="modal-back" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-h">
          <div className="modal-h-title">{t('account.title')}</div>
          <button className="icon-btn sm" onClick={onClose} aria-label={t('editor.close')}>
            <Icon.close width="14" height="14"/>
          </button>
        </div>
        <div className="modal-body">
          <div className="account-section">
            <div className="account-section-title">{t('account.username')}</div>
            <div>{user.username}</div>
          </div>

          <div className="account-section">
            <div className="account-section-title">{t('account.changeLanguage')}</div>
            <div className="lang-pills">
              {SUPPORTED_LANGS.map(l => (
                <button key={l} className={`lang-pill ${language === l ? 'lang-pill-sel' : ''}`}
                        onClick={() => changeLanguage(l)}>
                  {LANG_NAMES[l]}
                </button>
              ))}
            </div>
            {langSaved && <div className="account-note">{t('account.changeLanguageSaved')}</div>}
          </div>

          <form className="account-section" onSubmit={changePassword}>
            <div className="account-section-title">{t('account.changePasswordTitle')}</div>
            <label className="field">
              <span className="field-lbl">{t('account.currentPassword')}</span>
              <input type="password" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} required/>
            </label>
            <label className="field" style={{ marginTop: 10 }}>
              <span className="field-lbl">{t('account.newPassword')}</span>
              <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)} required minLength={8}/>
            </label>
            {pwError && <div className="authcard-error">{pwError}</div>}
            {pwSuccess && <div className="account-note">{t('account.changePasswordSuccess')}</div>}
            <div style={{ marginTop: 10 }}>
              <button className="btn-ghost" type="submit">{t('account.changePasswordSubmit')}</button>
            </div>
          </form>

          <div className="account-section">
            <div className="account-section-title">{t('account.mcpTitle')}</div>
            <p className="account-note">{t('account.mcpBody')}</p>
            <div className="mcp-url-box">{mcpUrl}</div>
            <button className="btn-ghost" onClick={regenerateToken} disabled={regenerating}>
              {t('account.mcpRegenerate')}
            </button>
          </div>

          <div className="account-section">
            <button className="btn-danger" onClick={logout}>{t('account.logout')}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.AccountSettings = AccountSettings;
