document.addEventListener('DOMContentLoaded', function () {
    // Tags Tooltip Modal
    (function() {
        var moreTagsButton = document.getElementById('more-tags');
        var tooltip = document.getElementById('additional-tags');
        var overlay;

        moreTagsButton.addEventListener('click', function () {
            tooltip.style.display = 'block';
            overlay = document.createElement('div');
            overlay.className = 'tooltip-overlay';
            document.body.appendChild(overlay);
        });

        // Close the tooltip when clicking outside
        document.addEventListener('click', function (event) {
            if (!tooltip.contains(event.target) && !moreTagsButton.contains(event.target)) {
                tooltip.style.display = 'none';
                if (overlay) {
                    document.body.removeChild(overlay);
                    overlay = null;
                }
            }
        });
    })();

    // Item Thumbnail Modal and Item Add to Cart Modal
    (function() {
        const imageModal = document.getElementById("image-modal");
        const fullImage = document.getElementById("full-image");
        const caption = document.getElementById("caption");
        const cartModal = document.getElementById('cart-modal');
        const quantityInput = document.getElementById('item-quantity');
        const priceElement = document.getElementById('item-price');
        const totalPriceElement = document.getElementById('total-price');
        const itemIdInput = document.getElementById('item-id');
        let currentPrice = 0;

        // Event delegation for image links and add-to-cart buttons
        document.body.addEventListener('click', function (event) {
            if (event.target.closest('.image-link')) {
                event.preventDefault();
                const link = event.target.closest('.image-link');
                fullImage.src = link.dataset.fullImage;
                caption.innerHTML = link.querySelector('img').alt || '';
                imageModal.style.display = "block";
            } else if (event.target.closest('.add-to-cart')) {
                const button = event.target.closest('.add-to-cart');
                const itemId = button.getAttribute('data-item-id');
                const itemName = button.getAttribute('data-item-name');
                currentPrice = parseFloat(button.getAttribute('data-item-price'));
                quantityInput.value = 1;
                document.querySelector('.cart-modal-header h2').innerText = itemName;
                priceElement.innerText = currentPrice.toFixed(2);
                totalPriceElement.innerText = currentPrice.toFixed(2);
                itemIdInput.value = itemId;
                cartModal.style.display = 'block';
            } else if (event.target.matches('.image-modal-close')) {
                imageModal.style.display = "none";
            } else if (event.target.matches('.cart-modal-close')) {
                cartModal.style.display = 'none';
            }
        });

        // Close modals when clicking outside
        window.onclick = function (event) {
            if (event.target == imageModal) {
                imageModal.style.display = "none";
            } else if (event.target == cartModal) {
                cartModal.style.display = 'none';
            }
        };

        // Quantity selectors
        document.getElementById('quantity-minus').addEventListener('click', function() {
            let quantity = parseInt(quantityInput.value, 10);
            if (quantity > 1) {
                quantity--;
                quantityInput.value = quantity;
                updateTotalPrice(quantity);
            }
        });

        document.getElementById('quantity-plus').addEventListener('click', function() {
            let quantity = parseInt(quantityInput.value, 10);
            quantity++;
            quantityInput.value = quantity;
            updateTotalPrice(quantity);
        });

        function updateTotalPrice(quantity) {
            const totalPrice = (currentPrice * quantity).toFixed(2);
            totalPriceElement.innerText = totalPrice;
        }

        // Handle confirm-add button click
        document.getElementById('confirm-add').addEventListener('click', function() {
            const itemId = itemIdInput.value;
            const quantity = quantityInput.value;
            const totalPrice = totalPriceElement.textContent;

            if (!itemId || !quantity || !totalPrice) {
                console.error('Missing required fields');
                return;
            }

            const data = {
                action: 'add_to_cart',
                itemId: itemId,
                quantity: quantity,
                totalPrice: totalPrice
            };

            fetch('index.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('添加商品成功');
                    cartModal.style.display = 'none';
                    window.location.href = 'index.php?view=cart';
                } else {
                    alert('添加商品失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('错误:', error);
            });
        });
    })();
});
