const loginForm = document.getElementById('loginForm');
const identifierInput = document.getElementById('identifier');
const passwordInput = document.getElementById('password');
const errorDisplay = document.getElementById('errorMessage');
const submitBtn = document.getElementById('submitBtn');
const submitBtnText = document.getElementById('submitBtnText');
const splashScreen = document.getElementById('splashScreen');
const togglePasswordBtn = document.getElementById('togglePassword');

document.addEventListener('DOMContentLoaded', () => {
    // Splash screen hide after page load
    window.setTimeout(() => {
        if (splashScreen) {
            splashScreen.classList.add('hidden-splash');
        }
    }, 1700);

    // Password toggle
    if (togglePasswordBtn && passwordInput) {
        togglePasswordBtn.addEventListener('click', () => {
            const icon = togglePasswordBtn.querySelector('i');
            const isPassword = passwordInput.type === 'password';

            passwordInput.type = isPassword ? 'text' : 'password';

            if (icon) {
                icon.className = isPassword ? 'fa-regular fa-eye-slash' : 'fa-regular fa-eye';
            }
        });
    }

    // Hide error when typing again
    [identifierInput, passwordInput].forEach(input => {
        if (input) {
            input.addEventListener('input', () => {
                errorDisplay.classList.add('hidden');
                errorDisplay.textContent = '';
            });
        }
    });
});

loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const identifier = identifierInput.value.trim();
    const password = passwordInput.value;
    const originalBtnText = 'Access Portal';

    errorDisplay.classList.add('hidden');
    errorDisplay.textContent = '';

    // Visual feedback: disable button during request
    submitBtn.disabled = true;
    submitBtn.classList.add('opacity-90', 'cursor-not-allowed');
    submitBtnText.innerHTML = '<span class="submit-spinner"></span><span>Authenticating...</span>';

    try {
        const response = await fetch('api/login.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ identifier, password })
        });

        const contentType = response.headers.get('content-type');

        if (!contentType || !contentType.includes('application/json')) {
            throw new TypeError("Oops, we haven't got JSON!");
        }

        const data = await response.json();

        if (data.success) {
            localStorage.setItem('user', JSON.stringify(data.user));

            // Optional remember choice without breaking current features
            const keepLoggedIn = document.getElementById('keepLoggedIn');
            if (keepLoggedIn) {
                localStorage.setItem('safe_step_keep_logged_in', keepLoggedIn.checked ? '1' : '0');
            }

            // Show splash again during redirect for a polished feel
            if (splashScreen) {
                splashScreen.classList.remove('hidden-splash');
            }

            submitBtnText.innerHTML = '<span class="submit-spinner"></span><span>Redirecting...</span>';

            setTimeout(() => {
                window.location.href = 'dashboard/dashboard.html';
            }, 700);
        } else {
            errorDisplay.textContent = data.message || 'Invalid login credentials.';
            errorDisplay.classList.remove('hidden');
            errorDisplay.classList.add('error-shake');

            setTimeout(() => {
                errorDisplay.classList.remove('error-shake');
            }, 400);

            submitBtn.disabled = false;
            submitBtn.classList.remove('opacity-90', 'cursor-not-allowed');
            submitBtnText.textContent = originalBtnText;
        }
    } catch (err) {
        console.error('Login Error:', err);
        errorDisplay.textContent = 'Server communication error. Please try again.';
        errorDisplay.classList.remove('hidden');
        errorDisplay.classList.add('error-shake');

        setTimeout(() => {
            errorDisplay.classList.remove('error-shake');
        }, 400);

        submitBtn.disabled = false;
        submitBtn.classList.remove('opacity-90', 'cursor-not-allowed');
        submitBtnText.textContent = originalBtnText;
    }
});
