(function(){
  'use strict';

  const $ = (s, p) => (p || document).querySelector(s);
  const $$ = (s, p) => Array.from((p || document).querySelectorAll(s));

  const navMenu   = $('#navMenu');
  const navToggle = $('#navToggle');
  if (navToggle && navMenu){
    navToggle.addEventListener('click', () => navMenu.classList.toggle('show'));
    // Close on link click (mobile)
    navMenu.querySelectorAll('a').forEach(a => a.addEventListener('click', () => navMenu.classList.remove('show')));
  }

  const loginModal  = $('#loginModal');
  const openLogin   = $('#openLogin');
  const loginCancel = $('#loginCancel');
  const loginForm   = $('#loginForm');
  const registerForm= $('#registerForm');
  const tabs        = $$('.sp-auth-tab');

  function openModal(tab){
    if (!loginModal) return;
    loginModal.classList.add('show');
    loginModal.style.display = 'flex';
    if (tab) setTab(tab);
  }
  function closeModal(){
    if (!loginModal) return;
    loginModal.classList.remove('show');
    loginModal.style.display = 'none';
  }
  function setTab(tab){
    tabs.forEach(t => t.classList.toggle('active', t.dataset.tab === tab));
    if (loginForm)    loginForm.style.display    = (tab === 'login')    ? '' : 'none';
    if (registerForm) registerForm.style.display = (tab === 'register') ? '' : 'none';
    const sub = $('#authSubtitle');
    if (sub) sub.textContent = tab === 'register' ? 'Daftar akun baru gratis!' : 'Login dulu untuk mulai bermain!';
  }

  if (openLogin)   openLogin.addEventListener('click', () => openModal('login'));
  if (loginCancel) loginCancel.addEventListener('click', closeModal);
  if (loginModal)  loginModal.addEventListener('click', (e) => { if (e.target === loginModal) closeModal(); });

  tabs.forEach(t => t.addEventListener('click', () => setTab(t.dataset.tab)));
  $$('[data-switch-tab]').forEach(el => el.addEventListener('click', (e) => {
    e.preventDefault();
    setTab(el.dataset.switchTab);
  }));

  // ---------- LOGIN SUBMIT ----------
  if (loginForm){
    loginForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const btn = $('#loginSubmit');
      const user = $('#loginUser').value.trim();
      const pass = $('#loginPass').value;
      if (!user || !pass) return;
      btn.disabled = true;
      btn.textContent = 'Memproses...';
      try {
        const res = await fetch('/api/auth/login.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'same-origin',
          body: JSON.stringify({ username: user, password: pass })
        });
        const data = await res.json();
        if (data.ok) {
          window.SpinPopup && SpinPopup.success('Selamat datang ' + data.user.username + '!', 'Login Berhasil');
          setTimeout(() => location.reload(), 800);
        } else {
          window.SpinPopup ? SpinPopup.error(data.message || 'Login gagal.') : alert(data.message || 'Login gagal');
        }
      } catch (err){
        window.SpinPopup ? SpinPopup.error('Tidak dapat terhubung ke server. Coba lagi.') : alert('Network error');
      } finally {
        btn.disabled = false;
        btn.textContent = 'MASUK';
      }
    });
  }

  // ---------- REGISTER SUBMIT ----------
  if (registerForm){
    registerForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const btn = $('#regSubmit');
      const user = $('#regUser').value.trim();
      const p1   = $('#regPass').value;
      const p2   = $('#regPass2').value;
      if (!user || !p1 || !p2) return;
      if (p1 !== p2) {
        window.SpinPopup ? SpinPopup.error('Konfirmasi password tidak cocok.') : alert('Password tidak cocok');
        return;
      }
      btn.disabled = true;
      btn.textContent = 'Memproses...';
      try {
        const res = await fetch('/api/auth/register.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'same-origin',
          body: JSON.stringify({ username: user, password: p1 })
        });
        const data = await res.json();
        if (data.ok) {
          window.SpinPopup && SpinPopup.success(data.message || 'Akun dibuat!', 'Pendaftaran Sukses');
          setTimeout(() => location.reload(), 900);
        } else {
          window.SpinPopup ? SpinPopup.error(data.message || 'Gagal mendaftar.') : alert(data.message || 'Gagal');
        }
      } catch (err){
        window.SpinPopup ? SpinPopup.error('Tidak dapat terhubung ke server.') : alert('Network error');
      } finally {
        btn.disabled = false;
        btn.textContent = 'DAFTAR';
      }
    });
  }

  // ---------- LOGOUT ----------
  const logoutBtn = $('#logoutBtn');
  if (logoutBtn){
    logoutBtn.addEventListener('click', async () => {
      const ok = window.SpinPopup
        ? await SpinPopup.confirm({ title: 'Logout', message: 'Yakin mau keluar dari akunmu?' })
        : confirm('Keluar?');
      if (!ok) return;
      try {
        await fetch('/api/auth/logout.php', { credentials: 'same-origin' });
      } catch(e){}
      location.reload();
    });
  }

  $$('[data-need-login]').forEach(el => {
    el.addEventListener('click', (e) => {
      if (!window.__ME__) {
        e.preventDefault();
        if (window.SpinPopup) {
          SpinPopup.needLogin();
        } else {
          openModal('login');
        }
      }
    });
  });

  window.openLoginModal = (tab) => openModal(tab || 'login');
})();
