
document.addEventListener('DOMContentLoaded', function() {

    if (typeof BASE_URL === 'undefined') {
        console.error("Auth.js Error: Global variable BASE_URL is not defined when DOM is ready!");
        const registerMsgDiv = document.getElementById('register-message');
        const loginMsgDiv = document.getElementById('login-message');
        const errMsg = 'Kesalahan konfigurasi frontend (URL). Tidak dapat mengirim form.';
        if(registerMsgDiv) displayGeneralMessage('register-message', errMsg, 'error');
        if(loginMsgDiv) displayGeneralMessage('login-message', errMsg, 'error');
    } else {
    }
    function escapeHTML(str) { if (typeof str !== 'string') return str; const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return str.replace(/[&<>"']/g, function(m) { return map[m]; }); } function displayFieldError(fieldId, message) { const errorSpan = document.getElementById(fieldId + '-error'); const inputField = document.getElementById(fieldId); if (errorSpan) { errorSpan.textContent = message || ''; } if (inputField) { if (message) { inputField.classList.add('border-red-500'); inputField.classList.remove('border-gray-300'); } else { inputField.classList.remove('border-red-500'); inputField.classList.add('border-gray-300'); } } } function clearFieldErrors(formElement) { formElement.querySelectorAll('.input-field').forEach(input => { displayFieldError(input.id, ''); }); } function displayGeneralMessage(containerId, message, type = 'error') { const messageDiv = document.getElementById(containerId); if (messageDiv) { messageDiv.innerHTML = ''; if (message) { const alertClass = type === 'success' ? 'bg-green-100 border-green-300 text-green-700' : 'bg-red-100 border-red-300 text-red-700'; messageDiv.className = 'mb-4 p-3 border rounded-lg text-sm ' + alertClass; messageDiv.innerHTML = escapeHTML(message); } else { messageDiv.className = 'mb-4 text-sm'; } } } function setButtonLoading(buttonId, textId, spinnerHTMLId, isLoading, loadingText = 'Memproses...') { const button = document.getElementById(buttonId); const textSpan = document.getElementById(textId); const spinner = document.getElementById(spinnerHTMLId); if (button && textSpan && spinner) { if (isLoading) { button.disabled = true; textSpan.textContent = loadingText; spinner.classList.remove('hidden'); } else { button.disabled = false; textSpan.textContent = button.dataset.originalText || 'Submit'; spinner.classList.add('hidden'); } } }

    function setupPasswordToggle(inputId, buttonId) { const passwordInput = document.getElementById(inputId); const toggleButton = document.getElementById(buttonId); if (passwordInput && toggleButton) { const toggleIcon = toggleButton.querySelector('i'); toggleButton.addEventListener('click', function () { const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password'; passwordInput.setAttribute('type', type); toggleIcon.classList.toggle('fa-eye', type === 'password'); toggleIcon.classList.toggle('fa-eye-slash', type === 'text'); }); } }

    setupPasswordToggle('password', 'togglePassword');
    setupPasswordToggle('confirm_password', 'toggleConfirmPassword');


    // ========================================================
    // Validasi & AJAX untuk Form Registrasi
    // ========================================================
    const registerForm = document.getElementById('register-form');
    const registerButton = document.getElementById('register-button');
    if (registerForm && registerButton) {
        const registerButtonTextEl = document.getElementById('register-button-text');
        if(registerButtonTextEl) registerButton.dataset.originalText = registerButtonTextEl.textContent;

        registerForm.addEventListener('submit', function(event) {
            event.preventDefault();
            clearFieldErrors(registerForm);
            displayGeneralMessage('register-message', '');
            let isValid = true;
            const formData = new FormData(registerForm);
            const username = formData.get('username')?.trim() ?? ''; const email = formData.get('email')?.trim() ?? ''; const password = formData.get('password') ?? ''; const confirmPassword = formData.get('confirm_password') ?? ''; if (!username) { isValid = false; displayFieldError('username', 'Username wajib diisi.'); } else if (username.length < 4) { isValid = false; displayFieldError('username', 'Username minimal 4 karakter.'); } else if (!/^[a-zA-Z0-9_]+$/.test(username)) { isValid = false; displayFieldError('username', 'Username hanya boleh huruf, angka, dan underscore.'); } if (!email) { isValid = false; displayFieldError('email', 'Email wajib diisi.'); } else if (!/^\S+@\S+\.\S+$/.test(email)) { isValid = false; displayFieldError('email', 'Format email tidak valid.'); } if (!password) { isValid = false; displayFieldError('password', 'Password wajib diisi.'); } else if (password.length < 6) { isValid = false; displayFieldError('password', 'Password minimal 6 karakter.'); } if (!confirmPassword) { isValid = false; displayFieldError('confirm_password', 'Konfirmasi password wajib diisi.'); } else if (password && password !== confirmPassword) { isValid = false; displayFieldError('confirm_password', 'Konfirmasi password tidak cocok.'); }

            if (!isValid) { return; }
            setButtonLoading('register-button', 'register-button-text', 'register-spinner', true, 'Mendaftar...');

            if (typeof BASE_URL === 'undefined' || !BASE_URL) {
                 console.error("Fetch Error (Register): BASE_URL JS variable is not defined!");
                 displayGeneralMessage('register-message', 'Kesalahan konfigurasi frontend (URL).', 'error');
                 setButtonLoading('register-button', 'register-button-text', 'register-spinner', false);
                 return;
            }

            // ========================================================
            // PASTIKAN MENGGUNAKAN BASE_URL (HURUF BESAR) DI SINI
            // ========================================================
            const ajaxUrl = BASE_URL + '/ajax/register'; 
            // ========================================================


            fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(response => { if (!response.ok) { throw new Error(`Server error: ${response.status} ${response.statusText}`); } return response.json().catch(e => { throw new Error("Respons server tidak valid (bukan JSON)."); }); })
            .then(data => {
                if (data.success) {
                    displayGeneralMessage('register-message', data.message || 'Registrasi berhasil!', 'success');
                    registerForm.reset();
                    if (data.redirectUrl) {
                        setButtonLoading('register-button', 'register-button-text', 'register-spinner', true, 'Mengalihkan...');
                        const redirectTarget = data.redirectUrl.startsWith('http') ? data.redirectUrl : BASE_URL + '/' + data.redirectUrl.replace(/^\//, '');
                        setTimeout(() => { window.location.href = redirectTarget; }, 1500);
                    } else { setButtonLoading('register-button', 'register-button-text', 'register-spinner', false); }
                } else {
                    if (data.errors && data.errors.general) { displayGeneralMessage('register-message', data.errors.general, 'error'); }
                    else { displayGeneralMessage('register-message', 'Registrasi gagal, periksa kembali isian Anda.', 'error'); }
                    if (data.errors) { for (const field in data.errors) { if (field !== 'general') { displayFieldError(field, data.errors[field]); } } }
                    setButtonLoading('register-button', 'register-button-text', 'register-spinner', false);
                }
            })
            .catch(error => {
                console.error('Fetch Error (Register):', error);
                displayGeneralMessage('register-message', `Terjadi masalah: ${error.message}. Coba lagi nanti.`, 'error');
                setButtonLoading('register-button', 'register-button-text', 'register-spinner', false);
            });
        });
    }


    // ========================================================
    // Validasi & AJAX untuk Form Login
    // ========================================================
    const loginForm = document.getElementById('login-form');
    const loginButton = document.getElementById('login-button');
    if (loginForm && loginButton) {
        const loginButtonTextEl = document.getElementById('login-button-text');
        if(loginButtonTextEl) loginButton.dataset.originalText = loginButtonTextEl.textContent;

        loginForm.addEventListener('submit', function(event) {
             event.preventDefault();
             clearFieldErrors(loginForm);
             displayGeneralMessage('login-message', '');
             let isValid = true;
             const formData = new FormData(loginForm);
             const identifier = formData.get('email')?.trim() ?? ''; const password = formData.get('password') ?? ''; if (!identifier) { isValid = false; displayFieldError('email', 'Email atau Username wajib diisi.'); } if (!password) { isValid = false; displayFieldError('password', 'Password wajib diisi.'); }

             if (!isValid) { return; }
             setButtonLoading('login-button', 'login-button-text', 'login-spinner', true, 'Memproses...');

             if (typeof BASE_URL === 'undefined' || !BASE_URL) {
                 console.error("Fetch Error (Login): BASE_URL JS variable is not defined!");
                 displayGeneralMessage('login-message', 'Kesalahan konfigurasi frontend (URL).', 'error');
                 setButtonLoading('login-button', 'login-button-text', 'login-spinner', false);
                 return;
             }

             // ========================================================
             // PASTIKAN MENGGUNAKAN BASE_URL (HURUF BESAR) DI SINI
             // ========================================================
             const ajaxLoginUrl = BASE_URL + '/ajax/login';
             // ========================================================

             fetch(ajaxLoginUrl, { method: 'POST', body: formData })
             .then(response => { if (!response.ok) { throw new Error(`Server error: ${response.status} ${response.statusText}`); } return response.json().catch(e => { throw new Error("Respons server tidak valid (bukan JSON)."); }); })
             .then(data => {
                  if (data.success) {
                     displayGeneralMessage('login-message', data.message || 'Login berhasil!', 'success');
                     loginForm.reset();
                     if (data.redirectUrl) {
                         setButtonLoading('login-button', 'login-button-text', 'login-spinner', true, 'Mengalihkan...');
                         const redirectTarget = data.redirectUrl.startsWith('http') ? data.redirectUrl : BASE_URL + '/' + data.redirectUrl.replace(/^\//, '');
                         setTimeout(() => { window.location.href = redirectTarget; }, 1000);
                     } else { setButtonLoading('login-button', 'login-button-text', 'login-spinner', false); }
                 } else {
                     displayGeneralMessage('login-message', data.errors?.general || 'Login gagal. Periksa kredensial Anda.', 'error');
                     if (data.errors) { for (const field in data.errors) { if (field !== 'general') displayFieldError(field, data.errors[field]); } }
                      setButtonLoading('login-button', 'login-button-text', 'login-spinner', false);
                 }
             })
             .catch(error => {
                 console.error('Fetch Error (Login):', error);
                 displayGeneralMessage('login-message', `Terjadi masalah: ${error.message}. Coba lagi nanti.`, 'error');
                 setButtonLoading('login-button', 'login-button-text', 'login-spinner', false);
             });
         });
     }

}); 
