<?php
/** @var \Magento\Framework\View\Element\Template $block */
$loginUrl = $block->getUrl('customer/ajax/login');
$checkoutUrl = $block->getUrl('checkout') . '#shipping';
$forgotUrl = $block->getUrl('customer/account/forgotpassword');

$messages = $block->getLayout()->createBlock(Magento\Framework\View\Element\Messages::class)->toHtml();
?>
<div class="container mx-auto max-w-screen-md py-12 p-0" x-data="loginForm()" x-init="$watch('errorMessage', () => scrollToTop())">
    <template x-if="errorMessage">
        <div class="messages sticky top-0 z-10 mb-4 bg-white pt-4">
            <div class="message message-error error w-full">
                <div x-text="errorMessage" class="px-4 py-2"></div>
            </div>
        </div>
    </template>
    <?= $messages ?>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-10">
        <!-- Login Column -->
        <div class="card mt-4 border border-gray-300 p-6 rounded-lg shadow bg-white">
            <h2 class="text-2xl font-semibold mb-4"><?= __('Returning Customer') ?></h2>
            <form @submit.prevent="submitLogin" class="space-y-4">
                <div>
                    <label class="block mb-1 text-sm font-medium"><?= __('Email Address') ?></label>
                    <input type="email" x-model="email" class="w-full border border-gray-300 p-2 rounded">
                </div>
                <div>
                    <label class="block mb-1 text-sm font-medium"><?= __('Password') ?></label>
                    <input type="password" x-model="password" class="w-full border border-gray-300 p-2 rounded">
                </div>
                <button type="submit" class="btn btn-primary btn-size-lg justify-center w-full">
                    <?= __('Login') ?>
                </button>
            </form>
            <div class="mt-4 text-sm">
                <a href="<?= $forgotUrl ?>" class="text-blue-600 hover:underline">
                    <?= __('Forgot your password?') ?>
                </a>
            </div>
        </div>

        <!-- Guest Checkout / Register -->
        <div class="card mt-4 border border-gray-300 p-6 rounded-lg shadow bg-white">
            <h2 class="text-2xl font-semibold mb-4"><?= __('New Customer') ?></h2>
            <p class="mb-4"><?= __('Checkout without creating an account. You’ll have the option to register during checkout.') ?></p>
            <a href="<?= $checkoutUrl ?>" class="btn btn-primary btn-size-lg justify-center block text-center w-full">
                <?= __('Continue as Guest') ?>
            </a>
        </div>
    </div>
</div>

<script>
function loginForm() {
    return {
        email: '',
        password: '',
        errorMessage: '',
        isValidEmail(email) {
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
        },
        submitLogin() {
            if (!this.email && !this.password) {
                this.errorMessage = '<?= __('Please enter your email address and password.') ?>';
                return;
            }
            if (!this.email) {
                this.errorMessage = '<?= __('Please enter your email address.') ?>';
                return;
            }
            if (!this.isValidEmail(this.email)) {
                this.errorMessage = '<?= __('Please enter a valid email address.') ?>';
                return;
            }
            if (!this.password) {
                this.errorMessage = '<?= __('Please enter your password.') ?>';
                return;
            }

            this.errorMessage = '<?= __('Logging in…') ?>';

            fetch('<?= $loginUrl ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-Auth-Redirect': 'true'
                },
                body: JSON.stringify({ username: this.email, password: this.password })
            }).then(res => res.json())
              .then(data => {
                  if (data.errors) {
                      this.errorMessage = data.message || '<?= __('Email or password is incorrect.') ?>';
                  } else {
                      window.location.href = '<?= $checkoutUrl ?>';
                  }
              }).catch(() => {
                  this.errorMessage = '<?= __('Something went wrong. Please try again.') ?>';
              });
        }
    }
}
function scrollToTop() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Monitor cart for changes and redirect if emptied
document.addEventListener('DOMContentLoaded', function() {
    // Check if we're on the authredirect page
    if (window.location.pathname.includes('/authredirect')) {
        
        let checkInterval;
        let lastKnownCartCount = null;
        
        // Start monitoring immediately
        startCartMonitoring();
        
        function startCartMonitoring() {
            // Clear any existing interval
            if (checkInterval) {
                clearInterval(checkInterval);
            }
            
            // Check every 300ms for cart changes
            checkInterval = setInterval(checkCartAndRedirect, 300);
        }
        
        // Force refresh customer data sections
        function refreshCustomerData() {
            if (window.customerData && window.customerData.invalidate) {
                window.customerData.invalidate(['cart']);
                window.customerData.reload(['cart'], true);
            }
        }
        
        // Monitor for cart updates via AJAX
        const originalFetch = window.fetch;
        window.fetch = function(...args) {
            return originalFetch.apply(this, args).then(response => {
                const url = args[0];
                if (typeof url === 'string' && (
                    url.includes('/customer/section/load') || 
                    url.includes('/checkout/sidebar/removeItem') ||
                    url.includes('/checkout/cart/delete') ||
                    url.includes('/checkout/sidebar/updateItemQty')
                )) {
                    // Force refresh customer data
                    setTimeout(refreshCustomerData, 100);
                    // Intensify checking after cart operations
                    setTimeout(() => {
                        for (let i = 0; i < 20; i++) {
                            setTimeout(checkCartAndRedirect, i * 100);
                        }
                    }, 200);
                }
                return response;
            });
        };

        // Monitor jQuery AJAX calls
        if (window.jQuery) {
            jQuery(document).ajaxComplete(function(event, xhr, settings) {
                if (settings.url && (
                    settings.url.includes('/customer/section/load') || 
                    settings.url.includes('/checkout/sidebar/removeItem') ||
                    settings.url.includes('/checkout/cart/delete') ||
                    settings.url.includes('/checkout/sidebar/updateItemQty')
                )) {
                    // Force refresh customer data
                    setTimeout(refreshCustomerData, 100);
                    // Intensify checking after cart operations
                    for (let i = 0; i < 20; i++) {
                        setTimeout(checkCartAndRedirect, i * 100);
                    }
                }
            });
        }

        // Function to check cart status and redirect if empty
        function checkCartAndRedirect() {
            let isEmpty = false;
            let currentCartCount = 0;
            
            // Method 1: Check customerData (force reload if stale)
            if (window.customerData && window.customerData.get) {
                const cart = window.customerData.get('cart');
                if (cart && cart()) {
                    const cartData = cart();
                    
                    if (cartData.summary_count !== undefined) {
                        currentCartCount = parseInt(cartData.summary_count) || 0;
                        if (currentCartCount === 0) {
                            isEmpty = true;
                        }
                    }
                    if (cartData.items && Array.isArray(cartData.items)) {
                        if (cartData.items.length === 0) {
                            isEmpty = true;
                        }
                    }
                }
            }
            
            // Method 2: Check mini cart counter elements (most reliable)
            const counterElements = document.querySelectorAll('.counter-number, .counter.qty, [data-bind*="qty"], .minicart-wrapper .counter, .minicart-wrapper .counter-label, .header .minicart-wrapper [class*="counter"]');
            counterElements.forEach((element, index) => {
                const text = element.textContent.trim();
                const qty = parseInt(text) || 0;
                if (qty === 0 && text !== '') {
                    isEmpty = true;
                }
                if (text === '0' || text === '0 items') {
                    isEmpty = true;
                }
            });
            
            // Method 3: Check if cart count changed from positive to zero
            if (lastKnownCartCount !== null && lastKnownCartCount > 0 && currentCartCount === 0) {
                isEmpty = true;
            }
            lastKnownCartCount = currentCartCount;
            
            // Method 4: Look for "remove" success messages and force redirect
            const messages = document.querySelectorAll('.message-success, .messages .message, .page.messages .message');
            messages.forEach((message, index) => {
                const text = message.textContent.toLowerCase().trim();
                if (text.includes('removed') && text.includes('item')) {
                    // Force an immediate redirect check after a short delay
                    setTimeout(() => {
                        refreshCustomerData();
                        setTimeout(() => {
                            // More aggressive check - if we see a removal message, check more thoroughly
                            const finalCheck = document.querySelectorAll('.counter-number, .minicart-wrapper .counter');
                            let shouldRedirect = true;
                            finalCheck.forEach(el => {
                                const qty = parseInt(el.textContent.trim()) || 0;
                                if (qty > 0) {
                                    shouldRedirect = false;
                                }
                            });
                            if (shouldRedirect) {
                                clearInterval(checkInterval);
                                // Prevent further redirects by setting a flag
                                if (!window.__cartRedirected) {
                                    window.__cartRedirected = true;
                                    window.location.href = '<?= $block->getUrl('checkout/cart') ?>';
                                }
                            }
                        }, 50);
                    }, 50);
                }
            });
            
            // Method 5: Check minicart dropdown content
            const minicartDropdown = document.querySelector('.minicart-wrapper .minicart-items-wrapper, .minicart-wrapper .block-content');
            if (minicartDropdown) {
                const text = minicartDropdown.textContent.toLowerCase();
                if (text.includes('no items') || text.includes('empty') || text.includes('you have no items')) {
                    isEmpty = true;
                }
            }
            
            if (isEmpty) {
                clearInterval(checkInterval);
                // Prevent further redirects by setting a flag
                if (!window.__cartRedirected) {
                    window.__cartRedirected = true;
                    setTimeout(() => {
                        window.location.href = '<?= $block->getUrl('checkout/cart') ?>';
                    }, 100);
                }
            }
        }

        // Initial check when page loads
        setTimeout(checkCartAndRedirect, 1000);
        
        // Listen for DOM mutations (when cart UI updates)
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList' || mutation.type === 'characterData') {
                    // Check if the mutation affects cart-related elements
                    const target = mutation.target;
                    if (target.closest && (
                        target.closest('.minicart-wrapper') ||
                        target.closest('[data-block="minicart"]') ||
                        target.classList.contains('counter') ||
                        target.classList.contains('counter-number')
                    )) {
                        setTimeout(checkCartAndRedirect, 200);
                    }
                }
            });
        });
        
        // Start observing
        observer.observe(document.body, {
            childList: true,
            subtree: true,
            characterData: true
        });
        
        // Also listen for storage events
        window.addEventListener('storage', function(e) {
            if (e.key && e.key.includes('cart')) {
                setTimeout(checkCartAndRedirect, 100);
            }
        });
    }
});
</script>

