/**
 * ==============================================================================
 * MODULE: Files/auth.js
 * ARCHITECTURE: Client Auth Manager with Workspace Cloud Hydration
 * Pulls the user's personal flashcards and notes from Supabase upon login.
 * Strictly under 200 lines in compliance with project rules.
 * ==============================================================================
 */

import { store } from './state.js';
import { WorkspaceSyncManager } from './workspace-sync.js';

export class AuthManager {
  constructor(app) {
    this.app = app;
    this.mount = document.getElementById('auth-mount');
    this.mode = 'signin';
  }

  init() {
    const user = store?.state?.current_user;
    if (user && user.id) {
      if (this.mount) {
        this.mount.classList.add('hidden');
        this.mount.innerHTML = '';
      }
      return true;
    }
    this.render();
    return false;
  }

  render() {
    if (!this.mount) return;
    this.mount.classList.remove('hidden');
    const isSignUp = this.mode === 'signup';

    this.mount.innerHTML = `
      <div class="auth-overlay">
        <div class="auth-card">
          <h2 class="auth-title">${isSignUp ? 'Create Account' : 'Sign In'}</h2>
          <div id="auth-error-box" class="auth-error-box hidden"></div>

          <div class="auth-input-group">
            <label class="auth-label">${isSignUp ? 'New Username' : 'Username'}</label>
            <input type="text" id="auth-username" class="auth-input" autocomplete="username" />
          </div>

          <div class="auth-input-group">
            <label class="auth-label">${isSignUp ? 'New Password' : 'Password'}</label>
            <input type="text" id="auth-password" class="auth-input" autocomplete="off" />
          </div>

          ${isSignUp ? `
            <div class="auth-input-group">
              <label class="auth-label">Repeat Password</label>
              <input type="text" id="auth-password-repeat" class="auth-input" autocomplete="off" />
            </div>
          ` : ''}

          <button type="button" id="btn-auth-submit" class="auth-btn-primary">
            ${isSignUp ? 'Sign Up' : 'Sign In'}
          </button>

          <button type="button" id="btn-auth-toggle" class="auth-toggle-link">
            ${isSignUp ? 'Already have an account? Sign In' : "Don't have an account? Sign Up"}
          </button>
        </div>
      </div>
    `;

    this.bindEvents();
  }

  showError(msg) {
    const box = document.getElementById('auth-error-box');
    if (box) { box.textContent = msg; box.classList.remove('hidden'); }
  }

  bindEvents() {
    const submitBtn = document.getElementById('btn-auth-submit');
    const toggleBtn = document.getElementById('btn-auth-toggle');
    const uInput = document.getElementById('auth-username');
    const pInput = document.getElementById('auth-password');
    const repInput = document.getElementById('auth-password-repeat');

    if (toggleBtn) {
      toggleBtn.onclick = () => {
        this.mode = this.mode === 'signin' ? 'signup' : 'signin';
        this.render();
      };
    }

    const triggerSubmit = () => this.handleSubmit();
    if (submitBtn) submitBtn.onclick = triggerSubmit;

    [uInput, pInput, repInput].forEach(el => {
      if (el) el.onkeydown = (e) => { if (e.key === 'Enter') triggerSubmit(); };
    });
  }

  async handleSubmit() {
    const u = document.getElementById('auth-username')?.value.trim();
    const p = document.getElementById('auth-password')?.value.trim();
    const rep = document.getElementById('auth-password-repeat')?.value.trim();
    const submitBtn = document.getElementById('btn-auth-submit');

    const errBox = document.getElementById('auth-error-box');
    if (errBox) errBox.classList.add('hidden');

    if (!u || !p) { this.showError('Username and password are required.'); return; }
    if (this.mode === 'signup' && p !== rep) { this.showError('Passwords do not match.'); return; }

    if (submitBtn) {
      submitBtn.disabled = true;
      submitBtn.textContent = this.mode === 'signup' ? 'Creating account...' : 'Signing in...';
    }

    const endpoint = this.mode === 'signup' ? '/api/auth/register' : '/api/auth/login';

    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: u, password: p })
      });

      const data = await res.json();
      if (!res.ok || !data.ok) throw new Error(data.error || 'Authentication failed.');

      // Purge previous local session
      store.state.chat_history = [];
      store.state.current_user = data.user;
      store.state.active_user = {
        firstName: data.user.first_name || '',
        lastName: data.user.last_name || '',
        slug: data.user.id
      };
      store.save();

      if (this.mount) {
        this.mount.classList.add('hidden');
        this.mount.innerHTML = '';
      }

      // Re-hydrate this user's cloud workspace (notes & flashcards) from Supabase
      await WorkspaceSyncManager.pullWorkspace(this.app);

      if (this.app?.diary) {
        this.app.diary.history = [];
        this.app.diary.activeUser = store.state.active_user;
        this.app.diary.step = data.user.first_name ? 'READY' : 'FIRST_NAME';
        this.app.diary.initSession();
      }

      if (this.app?.showToast) this.app.showToast(`Welcome, ${data.user.username}!`, 'success');
      if (this.app?.render) this.app.render();
    } catch (err) {
      this.showError(err.message);
      if (submitBtn) {
        submitBtn.disabled = false;
        submitBtn.textContent = this.mode === 'signup' ? 'Sign Up' : 'Sign In';
      }
    }
  }

  logout() {
    store.state.current_user = null;
    store.state.active_user = null;
    store.state.chat_history = [];
    store.state.memora_cards = [];
    store.state.notebook_notes = [{ id: "note-1", title: "Welcome Notebook 📝", content: "• " }];
    store.save();

    if (this.app?.diary) {
      this.app.diary.history = [];
      this.app.diary.activeUser = null;
      this.app.diary.step = 'FIRST_NAME';
      this.app.diary.render();
    }
    if (this.app?.memora) this.app.memora.render();
    if (this.app?.notebook) {
      this.app.notebook.notes = store.state.notebook_notes;
      this.app.notebook.render();
    }

    this.mode = 'signin';
    this.render();
  }
}