// Authentication Modal JavaScript

window.afterLoginSuccess = null;

// Modal Management Functions
function openLoginModal() {
    document.getElementById('loginModal').classList.remove('hidden');
    resetLoginModal();
}

function closeLoginModal() {
    window.afterLoginSuccess = null;
    window.loginContext = 'general';
    document.getElementById('loginModal').classList.add('hidden');
    resetLoginModal();
}

function resetLoginModal() {
    document.getElementById('loginPhoneStep').classList.remove('hidden');
    document.getElementById('loginChoiceStep').classList.add('hidden');
    document.getElementById('loginLastOtpStep').classList.add('hidden');
    document.getElementById('loginNewOtpStep').classList.add('hidden');
    hideErrors('loginErrors');
    hideSuccess('loginSuccess');
    hideErrors('loginChoiceErrors');
    hideErrors('loginLastOtpErrors');
    hideErrors('loginNewOtpErrors');
    document.getElementById('loginForm').reset();
    document.getElementById('loginLastOtpForm').reset();
    document.getElementById('loginNewOtpForm').reset();
}

function openRegisterModal() {
    document.getElementById('registerModal').classList.remove('hidden');
    clearForm('registerForm');
    hideErrors('registerErrors');
    hideSuccess('registerSuccess');
}

function closeRegisterModal() {
    document.getElementById('registerModal').classList.add('hidden');
}

function openOtpModal(phone) {
    openOtpChoiceModal(phone);
}

function openOtpChoiceModal(phone) {
    if (rateLimitCountdownInterval) {
        clearInterval(rateLimitCountdownInterval);
        rateLimitCountdownInterval = null;
    }
    
    const modal = document.getElementById('otpChoiceModal');
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    
    const phoneInput = document.getElementById('otpChoiceOtpPhone');
    const typeInput = document.getElementById('otpChoiceOtpType');
    if (phoneInput) phoneInput.value = phone;
    if (typeInput) typeInput.value = 'auth_verification';
    
    hideErrors('otpChoiceErrors');
    const loadingEl = document.getElementById('sendNewOtpLoading');
    const btnEl = document.getElementById('sendNewOtpBtn');
    if (loadingEl) loadingEl.classList.add('hidden');
    if (btnEl) btnEl.disabled = false;
}

function closeOtpChoiceModal() {
    const modal = document.getElementById('otpChoiceModal');
    modal.classList.add('hidden');
    document.body.style.overflow = '';
}

function openOtpModalDirect(phone) {
    if (rateLimitCountdownInterval) {
        clearInterval(rateLimitCountdownInterval);
        rateLimitCountdownInterval = null;
    }
    
    document.getElementById('otpModal').classList.remove('hidden');
    document.getElementById('otpPhoneNumber').textContent = phone;
    document.getElementById('otp_phone').value = phone;
    clearForm('otpForm');
    hideErrors('otpErrors');
    hideSuccess('otpSuccess');
    startResendTimer();
}

function closeOtpModal() {
    document.getElementById('otpModal').classList.add('hidden');
}

// Modal Switching Functions
function switchToRegisterModal() {
    closeLoginModal();
    openRegisterModal();
}

function switchToLoginModal() {
    closeRegisterModal();
    openLoginModal();
}

// Form Helper Functions
function clearForm(formId) {
    const form = document.getElementById(formId);
    if (form) {
        form.reset();
    }
}

function showErrors(containerId, errors) {
    const container = document.getElementById(containerId);
    const errorsList = document.getElementById(containerId + 'List');
    
    errorsList.innerHTML = '';
    
    if (errors.general) {
        errors.general.forEach(error => {
            const li = document.createElement('li');
            li.textContent = error;
            errorsList.appendChild(li);
        });
    }
    
    if (errors.phone) {
        errors.phone.forEach(error => {
            const li = document.createElement('li');
            li.textContent = error;
            errorsList.appendChild(li);
        });
    }
    
    if (errors.message) {
        const li = document.createElement('li');
        li.textContent = errors.message;
        errorsList.appendChild(li);
    }
    
    container.classList.remove('hidden');
}

function hideErrors(containerId) {
    document.getElementById(containerId).classList.add('hidden');
}

function showSuccess(containerId, message) {
    const container = document.getElementById(containerId);
    const messageElement = document.getElementById(containerId.replace('Success', 'SuccessMessage'));
    
    messageElement.textContent = message;
    container.classList.remove('hidden');
}

function hideSuccess(containerId) {
    document.getElementById(containerId).classList.add('hidden');
}

function setLoading(buttonId, textId, loadingId, isLoading) {
    const button = document.getElementById(buttonId);
    if (!button) return;
    
    const text = textId ? document.getElementById(textId) : null;
    const loading = loadingId ? document.getElementById(loadingId) : null;
    
    if (isLoading) {
        button.disabled = true;
        if (text) text.classList.add('hidden');
        if (loading) loading.classList.remove('hidden');
    } else {
        button.disabled = false;
        if (text) text.classList.remove('hidden');
        if (loading) loading.classList.add('hidden');
    }
}

// AJAX Functions

let rateLimitCountdownInterval = null;

function formatRateLimitTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;

    if (mins >= 30) {
        return mins + ' মিনিট';
    } else if (mins > 0) {
        return mins + ' মিনিট ' + secs + ' সেকেন্ড';
    } else {
        return secs + ' সেকেন্ড';
    }
}

function showRateLimitModal(retryAfter, businessContact) {
    const remaining = Math.max(0, retryAfter || 3600);
    const business = businessContact || '01913988543';

    if (rateLimitCountdownInterval) {
        clearInterval(rateLimitCountdownInterval);
        rateLimitCountdownInterval = null;
    }

    const getMessage = (seconds) => {
        return 'অনুরোধের সীমা অতিক্রম করা হয়েছে!\n\nআপনার ১ ঘণ্টায় সর্বচ্চ ৩টি OTP প্রেরণের অনুমতি রয়েছে। দয়া করে ' + formatRateLimitTime(seconds) + ' পরে আবার চেষ্টা করুন।\n\nআরও সহায়তার জন্য আমাদের সাথে যোগাযোগ করুন:\n📞 ' + business;
    };

    if (window.modernModal) {
        window.modernModal.alert(getMessage(remaining), 'Too Many Requests', 'warning');

        rateLimitCountdownInterval = setInterval(() => {
            const currentRemaining = window.__otpRateLimitRemaining;
            if (typeof currentRemaining !== 'number') {
                clearInterval(rateLimitCountdownInterval);
                rateLimitCountdownInterval = null;
                window.modernModal.hide();
                return;
            }

            const nextRemaining = currentRemaining - 1;
            window.__otpRateLimitRemaining = nextRemaining;

            if (nextRemaining <= 0) {
                clearInterval(rateLimitCountdownInterval);
                rateLimitCountdownInterval = null;
                window.modernModal.hide();
                return;
            }

            window.modernModal.updateMessage(getMessage(nextRemaining));
        }, 1000);
    } else {
        alert(getMessage(remaining));
    }
}

function handleRateLimit(response) {
    if (response.status === 429) {
        response.json().then(data => {
            window.__otpRateLimitRemaining = Math.max(0, data.retry_after || 3600);
            showRateLimitModal(window.__otpRateLimitRemaining, data.business_contact);
        }).catch(() => {
            window.__otpRateLimitRemaining = 3600;
            showRateLimitModal(3600, null);
        });
        return true;
    }
    return false;
}

function handleLogin(event) {
    event.preventDefault();
    
    const phone = document.getElementById('login_phone').value.trim();
    const phonePattern = /^01[3-9][0-9]{8}$/;
    
    if (!phone || !phonePattern.test(phone)) {
        showErrors('loginErrors', { message: ['সঠিক মোবাইল নম্বর লিখুন (01XXXXXXXXX)'] });
        return;
    }
    
    document.getElementById('loginPhoneStep').classList.add('hidden');
    document.getElementById('loginChoiceStep').classList.remove('hidden');
    hideErrors('loginErrors');
    hideSuccess('loginSuccess');
    hideErrors('loginChoiceErrors');
}

function useLastOtp() {
    const phone = document.getElementById('login_phone').value.trim();
    document.getElementById('lastOtpPhone').value = phone;
    document.getElementById('lastOtpCode').value = '';
    document.getElementById('lastOtpPhoneDisplay').textContent = phone;
    
    document.getElementById('loginChoiceStep').classList.add('hidden');
    document.getElementById('loginLastOtpStep').classList.remove('hidden');
    hideErrors('loginLastOtpErrors');
    
    setTimeout(function () { document.getElementById('lastOtpCode').focus(); }, 100);
}

function sendNewOtp() {
    const phone = document.getElementById('login_phone').value.trim();
    const type = 'auth_verification';
    
    document.getElementById('sendNewOtpLoading').classList.remove('hidden');
    document.getElementById('sendNewOtpBtn').disabled = true;
    hideErrors('loginChoiceErrors');
    
    fetch('/ajax/resend-otp', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, type })
    })
    .then(response => {
        if (handleRateLimit(response)) return;
        document.getElementById('sendNewOtpLoading').classList.add('hidden');
        document.getElementById('sendNewOtpBtn').disabled = false;
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            document.getElementById('newOtpPhone').value = phone;
            document.getElementById('newOtpCode').value = '';
            
            document.getElementById('loginChoiceStep').classList.add('hidden');
            document.getElementById('loginNewOtpStep').classList.remove('hidden');
            hideErrors('loginNewOtpErrors');
            
            startResendTimer();
            setTimeout(function () { document.getElementById('newOtpCode').focus(); }, 100);
        } else if (data) {
            showErrors('loginChoiceErrors', data.errors || { message: [data.message] });
        }
    })
    .catch(error => {
        console.error('Send new OTP error:', error);
        document.getElementById('sendNewOtpLoading').classList.add('hidden');
        document.getElementById('sendNewOtpBtn').disabled = false;
        showErrors('loginChoiceErrors', { general: ['একটি সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।'] });
    });
}

function backToChoice() {
    document.getElementById('loginLastOtpStep').classList.add('hidden');
    document.getElementById('loginNewOtpStep').classList.add('hidden');
    document.getElementById('loginChoiceStep').classList.remove('hidden');
    hideErrors('loginChoiceErrors');
    hideErrors('loginLastOtpErrors');
    hideErrors('loginNewOtpErrors');
    
    if (resendTimer) {
        clearInterval(resendTimer);
        resendTimer = null;
    }
}

function verifyLastOtp(event) {
    event.preventDefault();
    
    setLoading('lastOtpSubmitBtn', 'lastOtpBtnText', 'lastOtpBtnLoading', true);
    hideErrors('loginLastOtpErrors');
    
    const phone = document.getElementById('lastOtpPhone').value;
    const password = document.getElementById('lastOtpCode').value;
    
    fetch('/ajax/auth/login', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, password, source: window.loginContext || 'general' })
    })
    .then(response => {
        if (handleRateLimit(response)) return;
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            showSuccess('loginSuccess', data.message || 'লগইন সফল হয়েছে!');
            setTimeout(() => {
                if (typeof window.afterLoginSuccess === 'function') {
                    const callback = window.afterLoginSuccess;
                    window.afterLoginSuccess = null;
                    closeLoginModal();
                    callback();
                    return;
                }
                closeLoginModal();
                window.location.reload();
            }, 1200);
        } else if (data) {
            showErrors('loginLastOtpErrors', data.errors || { message: [data.message] });
        }
    })
    .catch(error => {
        console.error('Last OTP verification error:', error);
        showErrors('loginLastOtpErrors', { general: ['একটি সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।'] });
    })
    .finally(() => {
        setLoading('lastOtpSubmitBtn', 'lastOtpBtnText', 'lastOtpBtnLoading', false);
    });
}

function verifyNewOtp(event) {
    event.preventDefault();
    
    setLoading('newOtpSubmitBtn', 'newOtpBtnText', 'newOtpBtnLoading', true);
    hideErrors('loginNewOtpErrors');
    
    const formData = new FormData(event.target);
    formData.append('source', window.loginContext || 'general');
    
    fetch('/ajax/verify-otp', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
        },
        body: formData
    })
    .then(response => {
        if (handleRateLimit(response)) return;
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            showSuccess('loginSuccess', data.message);
            setTimeout(() => {
                if (typeof window.afterLoginSuccess === 'function') {
                    const callback = window.afterLoginSuccess;
                    window.afterLoginSuccess = null;
                    closeLoginModal();
                    callback();
                    return;
                }
                closeLoginModal();
                window.location.reload();
            }, 1200);
        } else if (data) {
            showErrors('loginNewOtpErrors', data.errors || { message: [data.message] });
        }
    })
    .catch(error => {
        console.error('New OTP verification error:', error);
        showErrors('loginNewOtpErrors', { general: ['একটি সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।'] });
    })
    .finally(() => {
        setLoading('newOtpSubmitBtn', 'newOtpBtnText', 'newOtpBtnLoading', false);
    });
}

function resendOtpFromChoice() {
    const phone = document.getElementById('newOtpPhone').value;
    const type = document.getElementById('newOtpType').value;
    
    fetch('/ajax/resend-otp', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, type })
    })
    .then(response => {
        if (handleRateLimit(response)) return;
        return response.json();
    })
    .then(data => {
        if (data.success) {
            const errorsList = document.getElementById('loginNewOtpErrorsList');
            errorsList.innerHTML = '<li>' + data.message + '</li>';
            document.getElementById('loginNewOtpErrors').classList.remove('hidden');
            startResendTimer();
        } else {
            showErrors('loginNewOtpErrors', data.errors || { message: [data.message] });
        }
    })
    .catch(error => {
        console.error('Resend OTP error:', error);
        showErrors('loginNewOtpErrors', { general: ['একটি সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।'] });
    });
}

function handleRegister(event) {
    event.preventDefault();
    
    setLoading('registerSubmitBtn', 'registerBtnText', 'registerBtnLoading', true);
    hideErrors('registerErrors');
    hideSuccess('registerSuccess');
    
    const name = document.getElementById('reg_name').value.trim();
    const phone = document.getElementById('reg_phone').value.trim();
    const phonePattern = /^01[3-9][0-9]{8}$/;
    
    if (!name) {
        showErrors('registerErrors', { message: ['পূর্ণ নাম লিখুন'] });
        setLoading('registerSubmitBtn', 'registerBtnText', 'registerBtnLoading', false);
        return;
    }
    
    if (!phone || !phonePattern.test(phone)) {
        showErrors('registerErrors', { message: ['সঠিক মোবাইল নম্বর লিখুন (01XXXXXXXXX)'] });
        setLoading('registerSubmitBtn', 'registerBtnText', 'registerBtnLoading', false);
        return;
    }
    
    closeRegisterModal();
    openOtpChoiceModal(phone);
    
    setLoading('registerSubmitBtn', 'registerBtnText', 'registerBtnLoading', false);
}

function handleOtpVerification(event) {
    event.preventDefault();
    
    setLoading('otpSubmitBtn', 'otpBtnText', 'otpBtnLoading', true);
    hideErrors('otpErrors');
    hideSuccess('otpSuccess');
    
    const formData = new FormData(event.target);
    
    fetch('/ajax/verify-otp', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
        },
        body: formData
    })
    .then(response => {
        if (handleRateLimit(response)) return;
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            showSuccess('otpSuccess', data.message);
            setTimeout(() => {
                closeOtpModal();
                window.location.reload();
            }, 1200);
        } else if (data) {
            showErrors('otpErrors', data.errors || { message: [data.message] });
        }
    })
    .catch(error => {
        console.error('OTP verification error:', error);
        showErrors('otpErrors', { general: ['একটি সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।'] });
    })
    .finally(() => {
        setLoading('otpSubmitBtn', 'otpBtnText', 'otpBtnLoading', false);
    });
}

function resendOtp() {
    const phone = document.getElementById('otp_phone').value;
    const type = document.getElementById('otp_type').value;
    
    fetch('/ajax/resend-otp', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, type })
    })
    .then(response => {
        if (handleRateLimit(response)) return;
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showSuccess('otpSuccess', data.message);
            startResendTimer();
        } else {
            showErrors('otpErrors', data.errors || { message: [data.message] });
        }
    })
    .catch(error => {
        console.error('Resend OTP error:', error);
        showErrors('otpErrors', { general: ['একটি সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।'] });
    });
}

// Resend Timer Functions
let resendTimer;
function startResendTimer() {
    const resendBtn = document.getElementById('resendOtpBtn');
    const timerElement = document.getElementById('resendTimer');
    const countElement = document.getElementById('timerCount');
    
    let timeLeft = 60;
    
    resendBtn.style.display = 'none';
    timerElement.classList.remove('hidden');
    
    resendTimer = setInterval(() => {
        timeLeft--;
        countElement.textContent = timeLeft;
        
        if (timeLeft <= 0) {
            clearInterval(resendTimer);
            resendBtn.style.display = 'inline';
            timerElement.classList.add('hidden');
        }
    }, 1000);
}

// Event Listeners
document.addEventListener('DOMContentLoaded', function() {
    // Login form submission
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    // Register form submission
    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }
    
    // OTP form submission (legacy modal)
    const otpForm = document.getElementById('otpForm');
    if (otpForm) {
        otpForm.addEventListener('submit', handleOtpVerification);
    }
    
    // Last OTP form submission
    const lastOtpForm = document.getElementById('loginLastOtpForm');
    if (lastOtpForm) {
        lastOtpForm.addEventListener('submit', verifyLastOtp);
    }
    
    // New OTP form submission
    const newOtpForm = document.getElementById('loginNewOtpForm');
    if (newOtpForm) {
        newOtpForm.addEventListener('submit', verifyNewOtp);
    }
    
    // Close modals when clicking outside
    window.addEventListener('click', function(event) {
        const loginModal = document.getElementById('loginModal');
        const registerModal = document.getElementById('registerModal');
        const otpModal = document.getElementById('otpModal');
        const otpChoiceModal = document.getElementById('otpChoiceModal');
        
        if (event.target === loginModal) {
            closeLoginModal();
        }
        if (event.target === registerModal) {
            closeRegisterModal();
        }
        if (event.target === otpModal) {
            closeOtpModal();
        }
        if (event.target === otpChoiceModal) {
            closeOtpChoiceModal();
        }
    });
    
    // Auto-format OTP inputs
    const otpInput = document.getElementById('modal_otp_code');
    if (otpInput) {
        otpInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/[^0-9]/g, '');
        });
    }
    
    const lastOtpInput = document.getElementById('lastOtpCode');
    if (lastOtpInput) {
        lastOtpInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/[^0-9]/g, '');
        });
    }
    
    const newOtpInput = document.getElementById('newOtpCode');
    if (newOtpInput) {
        newOtpInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/[^0-9]/g, '');
        });
    }
});

// Global functions to be called from HTML
window.openLoginModal = openLoginModal;
window.closeLoginModal = closeLoginModal;
window.openRegisterModal = openRegisterModal;
window.closeRegisterModal = closeRegisterModal;
window.openOtpModal = openOtpModal;
window.closeOtpModal = closeOtpModal;
window.openOtpChoiceModal = openOtpChoiceModal;
window.closeOtpChoiceModal = closeOtpChoiceModal;
window.useLastOtp = useLastOtp;
window.sendNewOtp = sendNewOtp;
window.backToChoice = backToChoice;
window.verifyLastOtp = verifyLastOtp;
window.verifyNewOtp = verifyNewOtp;
window.resendOtpFromChoice = resendOtpFromChoice;
window.switchToRegisterModal = switchToRegisterModal;
window.switchToLoginModal = switchToLoginModal;
window.resendOtp = resendOtp;
