import { login, register, logout, getUser, onAuthChange } from '../auth/client.js';

let overlay, modal, statusEl, tabLogin, tabRegister, form, submitBtn, usernameInput, passwordInput, closeBtn;
let badge, signInBtn, teacherLink;
let mode = 'login';

function setStatus(msg, ok = false) {
  if (!statusEl) return;
  statusEl.textContent = msg || '';
  statusEl.className = 'login-status ' + (msg ? (ok ? 'status-ok' : 'status-err') : '');
}

function openOverlay(startMode = 'login') {
  mode = startMode;
  updateTabs();
  setStatus('');
  overlay.classList.remove('hidden');
  setTimeout(() => usernameInput?.focus(), 0);
}

function closeOverlay() {
  overlay.classList.add('hidden');
}

function updateTabs() {
  tabLogin.classList.toggle('active', mode === 'login');
  tabRegister.classList.toggle('active', mode === 'register');
  submitBtn.textContent = mode === 'login' ? 'Sign in' : 'Create account';
}

function renderAuthState() {
  const user = getUser();
  if (badge) {
    if (user) {
      badge.classList.remove('hidden');
      badge.textContent = `${user.username}${user.role === 'teacher' ? ' (teacher)' : ''}`;
    } else {
      badge.classList.add('hidden');
      badge.textContent = '';
    }
  }
  if (signInBtn) {
    if (user) {
      signInBtn.textContent = 'Sign out';
      signInBtn.title = `Sign out (${user.username})`;
    } else {
      signInBtn.textContent = 'Sign in';
      signInBtn.title = 'Sign in with your account (optional)';
    }
  }
  if (teacherLink) {
    teacherLink.classList.toggle('hidden', !user || user.role !== 'teacher');
  }
}

async function submit(e) {
  e?.preventDefault();
  const u = usernameInput.value.trim();
  const p = passwordInput.value;
  if (!u || !p) {
    setStatus('Enter a username and password.');
    return;
  }
  submitBtn.disabled = true;
  setStatus('Working…');
  try {
    if (mode === 'login') await login(u, p);
    else await register(u, p);
    setStatus('Signed in!', true);
    passwordInput.value = '';
    setTimeout(closeOverlay, 300);
  } catch (err) {
    setStatus(err.message || 'Failed');
  } finally {
    submitBtn.disabled = false;
  }
}

export function initLoginDialog({ onAuthChanged } = {}) {
  overlay = document.getElementById('login-overlay');
  modal = document.getElementById('login-modal');
  statusEl = document.getElementById('login-status');
  tabLogin = document.getElementById('login-tab-login');
  tabRegister = document.getElementById('login-tab-register');
  form = document.getElementById('login-form');
  submitBtn = document.getElementById('login-submit');
  usernameInput = document.getElementById('login-username');
  passwordInput = document.getElementById('login-password');
  closeBtn = document.getElementById('login-close');
  badge = document.getElementById('user-badge');
  signInBtn = document.getElementById('btn-signin');
  teacherLink = document.getElementById('btn-teacher-view');

  if (!overlay || !form) return;

  tabLogin.addEventListener('click', () => { mode = 'login'; updateTabs(); setStatus(''); });
  tabRegister.addEventListener('click', () => { mode = 'register'; updateTabs(); setStatus(''); });
  form.addEventListener('submit', submit);
  closeBtn.addEventListener('click', closeOverlay);
  overlay.addEventListener('click', (e) => { if (e.target === overlay) closeOverlay(); });

  if (signInBtn) {
    signInBtn.addEventListener('click', async () => {
      if (getUser()) {
        await logout();
      } else {
        openOverlay('login');
      }
    });
  }

  if (teacherLink) {
    teacherLink.addEventListener('click', () => {
      const base = import.meta.env.BASE_URL || '/';
      window.location.href = base + 'teacher.html';
    });
  }

  onAuthChange(() => {
    renderAuthState();
    try { onAuthChanged?.(getUser()); } catch { /* ignore */ }
  });

  renderAuthState();
}

export function openLogin() {
  if (overlay) openOverlay('login');
}
