class AuthForms {
  constructor() {
    this.API = (window.API_BASE || window.location.origin + '/api.php') + '?route=';
    this.init();
  }

  $(id) { return document.getElementById(id); }

  init() {
    this.showForm('formLogin');
    this.bindLogin();
    this.bindRegister();
    this.bindForgot();
    this.bindSwitches();
    this.checkAuth();
    this.handleResetToken();
  }

  showForm(formId) {
    ['formLogin', 'formRegister', 'formForgot'].forEach(id => {
      const el = document.getElementById(id);
      if (el) el.style.display = 'none';
    });
    const target = document.getElementById(formId);
    if (target) target.style.display = 'block';
    document.querySelectorAll('.auth-error').forEach(e => e.style.display = 'none');
    document.querySelectorAll('.auth-success').forEach(e => e.style.display = 'none');
  }

  showError(elId, msg) {
    const el = document.getElementById(elId);
    if (!el) return;
    el.textContent = msg;
    el.style.display = 'block';
    const form = el.closest('.auth-form');
    if (form) {
      form.classList.remove('shake');
      void form.offsetWidth;
      form.classList.add('shake');
    }
  }

  showSuccess(elId, msg) {
    const el = document.getElementById(elId);
    if (!el) return;
    el.textContent = msg;
    el.style.display = 'block';
  }

  async checkAuth() {
    try {
      const res = await fetch(this.API + '/auth/me', { credentials: 'include' });
      const data = await res.json();
      if (data.authenticated) window.location.href = 'dashboard.html';
    } catch (e) {}
  }

  bindLogin() {
    const btn = this.$('loginBtn');
    const pwd = this.$('loginPassword');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      const email = this.$('loginEmail').value.trim();
      const password = this.$('loginPassword').value;
      if (!email || !password) { this.showError('loginError', 'Please enter your email and password.'); return; }
      btn.classList.add('loading');
      btn.textContent = 'Signing in...';
      try {
        const res = await fetch(this.API + '/auth/login', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          credentials: 'include', body: JSON.stringify({ email, password })
        });
        const data = await res.json();
        if (data.success) { window.location.href = 'dashboard.html'; }
        else { this.showError('loginError', data.error || 'Invalid email or password.'); }
      } catch (e) { this.showError('loginError', 'Connection error. Make sure the server is running.'); }
      btn.classList.remove('loading');
      btn.textContent = 'Sign In';
    });
    if (pwd) pwd.addEventListener('keydown', e => { if (e.key === 'Enter') btn.click(); });
  }

  bindRegister() {
    const btn = this.$('sendCodeBtn');
    const pwd = this.$('regPassword');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      const name = this.$('regName').value.trim();
      const email = this.$('regEmail').value.trim();
      const password = this.$('regPassword').value;
      if (!name || !email || !password) { this.showError('regError', 'All fields are required.'); return; }
      if (password.length < 6) { this.showError('regError', 'Password must be at least 6 characters.'); return; }
      btn.classList.add('loading');
      btn.textContent = 'Creating account...';
      try {
        const res = await fetch(this.API + '/auth/send-verification', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          credentials: 'include', body: JSON.stringify({ full_name: name, email, password })
        });
        const data = await res.json();
        if (data.success) { window.location.href = 'dashboard.html'; }
        else { this.showError('regError', data.error || 'Registration failed.'); }
      } catch (e) { this.showError('regError', 'Connection error.'); }
      btn.classList.remove('loading');
      btn.textContent = 'Create Account';
    });
    if (pwd) pwd.addEventListener('keydown', e => { if (e.key === 'Enter') btn.click(); });
  }

  bindForgot() {
    const btn = this.$('forgotBtn');
    const email = this.$('forgotEmail');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      const emailVal = email.value.trim();
      if (!emailVal) { this.showError('forgotError', 'Please enter your email.'); return; }
      btn.classList.add('loading');
      btn.textContent = 'Sending...';
      try {
        const res = await fetch(this.API + '/auth/forgot-password', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: emailVal })
        });
        const data = await res.json();
        this.showSuccess('forgotSuccess', data.message || 'If the email exists, a reset link has been sent.');
      } catch (e) { this.showError('forgotError', 'Connection error.'); }
      btn.classList.remove('loading');
      btn.textContent = 'Send Reset Link';
    });
    if (email) email.addEventListener('keydown', e => { if (e.key === 'Enter') btn.click(); });
  }

  bindSwitches() {
    const showReg = this.$('showRegister');
    const showLogin = this.$('showLogin');
    const forgotLink = this.$('forgotLink');
    const backToLogin = this.$('backToLogin');
    if (showReg) showReg.addEventListener('click', e => { e.preventDefault(); this.showForm('formRegister'); });
    if (showLogin) showLogin.addEventListener('click', e => { e.preventDefault(); this.showForm('formLogin'); });
    if (forgotLink) forgotLink.addEventListener('click', e => { e.preventDefault(); this.showForm('formForgot'); });
    if (backToLogin) backToLogin.addEventListener('click', e => { e.preventDefault(); this.showForm('formLogin'); });
  }

  handleResetToken() {
    const params = new URLSearchParams(window.location.search);
    const resetToken = params.get('reset');
    if (!resetToken) return;
    this.showForm('formForgot');
    const successEl = this.$('forgotSuccess');
    if (successEl) successEl.style.display = 'none';
    const form = this.$('formForgot');
    if (!form) return;
    form.innerHTML = `
      <h1>Set new password</h1>
      <p>Choose a new password for your account</p>
      <div class="auth-error" id="resetError"></div>
      <div class="auth-success" id="resetSuccess"></div>
      <div class="inputbox">
        <input type="password" id="resetPassword" required="required" autocomplete="new-password" placeholder=" ">
        <span>New password</span>
        <i></i>
      </div>
      <button class="btn-primary auth-btn btn-action" id="resetBtn">Reset Password</button>
      <p class="auth-switch"><a href="#" id="backToLoginReset">Back to sign in</a></p>
    `;
    const resetBtn = this.$('resetBtn');
    const resetPwd = this.$('resetPassword');
    const backReset = this.$('backToLoginReset');
    if (resetBtn) {
      resetBtn.addEventListener('click', async () => {
        const password = resetPwd.value;
        if (!password || password.length < 6) { this.showError('resetError', 'Password must be at least 6 characters.'); return; }
        resetBtn.classList.add('loading');
        resetBtn.textContent = 'Resetting...';
        try {
          const res = await fetch(this.API + '/auth/reset-password', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token: resetToken, password })
          });
          const data = await res.json();
          if (data.success) {
            this.showSuccess('resetSuccess', 'Password reset successfully!');
            setTimeout(() => { this.showForm('formLogin'); }, 2000);
          } else { this.showError('resetError', data.error || 'Reset failed.'); }
        } catch (e) { this.showError('resetError', 'Connection error.'); }
        resetBtn.classList.remove('loading');
        resetBtn.textContent = 'Reset Password';
      });
    }
    if (resetPwd) resetPwd.addEventListener('keydown', e => { if (e.key === 'Enter' && resetBtn) resetBtn.click(); });
    if (backReset) backReset.addEventListener('click', e => { e.preventDefault(); this.showForm('formLogin'); });
  }
}
