document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const captchaResponse = grecaptcha.getResponse();
    // / /2. Check if it is empty
    if (captchaResponse.length === 0) {
        document.getElementById('responseMsg').innerHTML = 
            `<div class="alert alert-warning">Please check the reCAPTCHA box.</div>`;
        return; // STOP the function here
    }
    const submitBtn = document.getElementById('submitBtn');
    const responseMsg = document.getElementById('responseMsg');
    const loginForm = document.getElementById('loginForm');
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...';

    const formData = new FormData(loginForm);

    try {
        const response = await fetch('api/adminLogin/login_action.php', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.status === 'success') {
            responseMsg.innerHTML = `<div class="alert alert-success">Login Successful!</div>`;
            window.location.href = 'dashboard.php';
        } 
        else if (result.status === 'pending') {
            responseMsg.innerHTML = `<div class="alert alert-info">${result.message}</div>`;
            
            // Transform the form into an OTP form with Resend Button
            loginForm.innerHTML = `
                <div class="mb-3 text-center">
                    <label class="form-label fw-bold">Enter 6-Digit Code</label>
                    <input type="text" id="otp_code" name="otp_code" 
                           class="form-control text-center fw-bold" 
                           style="font-size: 2rem; letter-spacing: 8px;" 
                           placeholder="000000" maxlength="6" required>
                </div>
                <button type="button" id="verifyBtn" class="btn btn-login w-100">Verify OTP</button>
                
                <div class="text-center mt-3">
                    <p class="small text-muted mb-1">Didn't get the code?</p>
                    <button type="button" id="resendBtn" class="btn btn-link btn-sm text-decoration-none p-0" disabled>
                        Resend in <span id="timer">30</span>s
                    </button>
                </div>

                <div class="text-center mt-2">
                    <a href="index.php" class="small text-muted">Back to Login</a>
                </div>
            `;

            // Start Timer Logic
            startResendTimer();

            // Add Event Listeners
            document.getElementById('verifyBtn').addEventListener('click', verifyOTP);
            document.getElementById('resendBtn').addEventListener('click', resendOTP);
        } 
        else {
            responseMsg.innerHTML = `<div class="alert alert-danger">${result.message}</div>`;
            if(typeof grecaptcha !== 'undefined') grecaptcha.reset();
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Sign In';
        }
    } catch (error) {
        responseMsg.innerHTML = `<div class="alert alert-danger">Connection Error 1st login action.</div>`;
        submitBtn.disabled = false;
        submitBtn.innerHTML = 'Sign In';
    }
});

// Function to handle OTP Verification
async function verifyOTP() {
    const otp = document.getElementById('otp_code').value;
    const responseMsg = document.getElementById('responseMsg');
    const verifyBtn = document.getElementById('verifyBtn');

    if (otp.length !== 6) {
        responseMsg.innerHTML = `<div class="alert alert-warning">Please enter 6 digits.</div>`;
        return;
    }

    verifyBtn.disabled = true;
    verifyBtn.innerHTML = 'Verifying...';

    const formData = new FormData();
    formData.append('otp_code', otp);

    try {
        const response = await fetch('api/adminLogin/verify_otp_action.php', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.status === 'success') {
            responseMsg.innerHTML = `<div class="alert alert-success">Verified! Redirecting...</div>`;
            window.location.href = 'dashboard.php';
        } else {
            responseMsg.innerHTML = `<div class="alert alert-danger">${result.message}</div>`;
            verifyBtn.disabled = false;
            verifyBtn.innerHTML = 'Verify OTP';
        }
    } catch (error) {
        responseMsg.innerHTML = `<div class="alert alert-danger">Verification Failed.</div>`;
        verifyBtn.disabled = false;
    }
}

// Function to handle Resend OTP
async function resendOTP() {
    const responseMsg = document.getElementById('responseMsg');
    const resendBtn = document.getElementById('resendBtn');
    
    resendBtn.disabled = true;
    resendBtn.innerText = "Sending...";

    try {
        const response = await fetch('api/adminLogin/resend_otp_action.php', { 
            method: 'POST' 
        });
        const result = await response.json();

        if (result.status === 'success') {
            responseMsg.innerHTML = `<div class="alert alert-success">A new OTP has been sent to your email.</div>`;
            startResendTimer(); // Restart the 30s timer
        } else {
            responseMsg.innerHTML = `<div class="alert alert-danger">${result.message}</div>`;
            resendBtn.disabled = false;
            resendBtn.innerText = "Resend OTP Now";
        }
    } catch (error) {
        responseMsg.innerHTML = `<div class="alert alert-danger">Error resending OTP.</div>`;
    }
}

// Timer Helper Function
function startResendTimer() {
    const resendBtn = document.getElementById('resendBtn');
    const timerDisplay = document.getElementById('timer');
    let timeLeft = 30;

    resendBtn.disabled = true;
    
    const countdown = setInterval(() => {
        timeLeft--;
        if (timerDisplay) timerDisplay.innerText = timeLeft;
        
        if (timeLeft <= 0) {
            clearInterval(countdown);
            resendBtn.disabled = false;
            resendBtn.innerText = "Resend OTP Now";
        }
    }, 1000);
}