/**
 * Home Delivery Checkout Handler
 * Manages home delivery checkbox and product addition/removal
 */

(function () {
    "use strict";

    var HomeDeliveryManager = {
        deliveryProductId: null,
        deliveryProductPrice: 5.74,
        deliveryProductName: "Home Delivery", // Default fallback
        orderId: null,
        homeDeliveryEnabled: false,

        init: function () {
            // Get delivery product info from data attributes (from checkout or shop page)
            var checkoutPage = document.querySelector(".eskaera-checkout-page");
            var shopPage = document.querySelector(".eskaera-shop-page");
            var page = checkoutPage || shopPage;

            if (page) {
                var deliveryProductIdStr = page.getAttribute("data-delivery-product-id");
                // Parse to integer, filter out None/empty/invalid values
                if (
                    deliveryProductIdStr &&
                    deliveryProductIdStr !== "None" &&
                    deliveryProductIdStr !== ""
                ) {
                    this.deliveryProductId = parseInt(deliveryProductIdStr, 10);
                    if (isNaN(this.deliveryProductId)) {
                        this.deliveryProductId = null;
                    }
                }
                console.log(
                    "[HomeDelivery] deliveryProductId from attribute:",
                    deliveryProductIdStr,
                    "-> parsed:",
                    this.deliveryProductId,
                    "type:",
                    typeof this.deliveryProductId
                );

                var price = page.getAttribute("data-delivery-product-price");
                if (price) {
                    this.deliveryProductPrice = parseFloat(price);
                }

                // Get translated product name from data attribute (auto-translated by Odoo server)
                var productName = page.getAttribute("data-delivery-product-name");
                if (productName) {
                    this.deliveryProductName = productName;
                    console.log(
                        "[HomeDelivery] Using translated product name from server:",
                        this.deliveryProductName
                    );
                }

                // Check if home delivery is enabled for this order
                var homeDeliveryAttr = page.getAttribute("data-home-delivery-enabled");
                this.homeDeliveryEnabled =
                    homeDeliveryAttr === "true" || homeDeliveryAttr === "True";
                console.log("[HomeDelivery] Home delivery enabled:", this.homeDeliveryEnabled);

                // Show/hide home delivery section based on configuration (only on checkout)
                if (checkoutPage) {
                    this.toggleHomeDeliverySection();
                }
            }

            // Get order ID from multiple possible sources
            var confirmBtn = document.getElementById("confirm-order-btn");
            var cartContainer = document.getElementById("cart-items-container");
            var orderIdElement = confirmBtn || cartContainer;

            // The URL is not a fallback here: it carries the slug of the order,
            // not its id.
            if (orderIdElement) {
                this.orderId = orderIdElement.getAttribute("data-order-id");
            }

            console.log("[HomeDelivery] orderId resolved:", this.orderId);

            // Handle checkbox (only exists on checkout page)
            var checkbox = document.getElementById("home-delivery-checkbox");
            if (checkbox) {
                var self = this;
                checkbox.addEventListener("change", function () {
                    if (this.checked) {
                        self.addDeliveryProduct();
                        self.showDeliveryInfo();
                    } else {
                        self.removeDeliveryProduct();
                        self.hideDeliveryInfo();
                    }
                });

                // Check if delivery product is already in cart on page load
                this.checkDeliveryInCart();
            }

            // Vincular botón Home Delivery en el shop SOLO si hay un producto de delivery válido
            if (this.deliveryProductId && this.homeDeliveryEnabled) {
                this.bindShopHomeDeliveryButton();
            } else {
                console.log(
                    "[HomeDelivery] Shop button NOT bound - no delivery product or disabled"
                );
            }
        },

        bindShopHomeDeliveryButton: function () {
            var self = this;
            var homeDeliveryBtn = document.getElementById("home-delivery-btn");

            if (homeDeliveryBtn) {
                console.log("[HomeDelivery] Binding shop home delivery button");

                homeDeliveryBtn.addEventListener("click", function () {
                    var cart = self.getCart();
                    var isInCart = cart[self.deliveryProductId];

                    if (isInCart) {
                        // Remove delivery product
                        console.log("[HomeDelivery] Removing delivery product from shop cart");
                        self.removeDeliveryProduct();
                        homeDeliveryBtn.classList.remove("active", "btn-warning");
                        homeDeliveryBtn.classList.add("btn-outline-warning");
                    } else {
                        // Add delivery product
                        console.log("[HomeDelivery] Adding delivery product from shop cart");
                        self.addDeliveryProduct();
                        homeDeliveryBtn.classList.remove("btn-outline-warning");
                        homeDeliveryBtn.classList.add("active", "btn-warning");
                    }

                    // Trigger cart reload to update UI
                    if (typeof window.renderCheckoutSummary === "function") {
                        window.renderCheckoutSummary();
                    }
                });

                // Set initial button state
                var cart = self.getCart();
                if (cart[self.deliveryProductId]) {
                    homeDeliveryBtn.classList.add("active", "btn-warning");
                    homeDeliveryBtn.classList.remove("btn-outline-warning");
                } else {
                    homeDeliveryBtn.classList.add("btn-outline-warning");
                    homeDeliveryBtn.classList.remove("active", "btn-warning");
                }
            }
        },

        toggleHomeDeliverySection: function () {
            var homeDeliverySection = document.querySelector(
                '[id*="home-delivery"], [class*="home-delivery"]'
            );
            var checkbox = document.getElementById("home-delivery-checkbox");
            var homeDeliveryContainer = document.getElementById("home-delivery-container");

            if (this.homeDeliveryEnabled) {
                // Show home delivery option
                if (checkbox) {
                    checkbox.closest(".form-check").style.display = "block";
                }
                if (homeDeliveryContainer) {
                    homeDeliveryContainer.style.display = "block";
                }
                console.log("[HomeDelivery] Home delivery option shown");
            } else {
                // Hide home delivery option and delivery info alert
                if (checkbox) {
                    checkbox.closest(".form-check").style.display = "none";
                    checkbox.checked = false;
                }
                if (homeDeliveryContainer) {
                    homeDeliveryContainer.style.display = "none";
                }
                // Also hide the delivery info alert when home delivery is disabled
                this.hideDeliveryInfo();
                this.removeDeliveryProduct();
                console.log("[HomeDelivery] Home delivery option and delivery info hidden");
            }
        },

        checkDeliveryInCart: function () {
            if (!this.deliveryProductId) return;

            var cart = this.getCart();
            if (cart[this.deliveryProductId]) {
                var checkbox = document.getElementById("home-delivery-checkbox");
                if (checkbox) {
                    checkbox.checked = true;
                    this.showDeliveryInfo();
                }
            }
        },

        getCart: function () {
            if (!this.orderId) return {};
            var cartKey = "eskaera_" + this.orderId + "_cart";
            var cartStr = localStorage.getItem(cartKey);
            return cartStr ? JSON.parse(cartStr) : {};
        },

        saveCart: function (cart) {
            if (!this.orderId) return;
            var cartKey = "eskaera_" + this.orderId + "_cart";
            localStorage.setItem(cartKey, JSON.stringify(cart));

            // Mantener sincronizado el carrito en memoria (sidebar de tienda)
            if (window.groupOrderShop && window.groupOrderShop.cart !== undefined) {
                window.groupOrderShop.cart = cart;
                if (typeof window.groupOrderShop._updateCartDisplay === "function") {
                    window.groupOrderShop._updateCartDisplay();
                }
            }

            // Re-render checkout summary without reloading
            setTimeout(function () {
                // Use the global function from checkout_labels.js
                if (typeof window.renderCheckoutSummary === "function") {
                    window.renderCheckoutSummary();
                }
            }, 50);
        },

        renderCheckoutSummary: function () {
            // Stub - now handled by global window.renderCheckoutSummary
        },

        addDeliveryProduct: function () {
            if (!this.deliveryProductId) {
                console.warn("[HomeDelivery] Delivery product ID not found");
                return;
            }

            console.log(
                "[HomeDelivery] Adding delivery product - deliveryProductId:",
                this.deliveryProductId,
                "orderId:",
                this.orderId
            );
            var cart = this.getCart();
            console.log("[HomeDelivery] Current cart before adding:", cart);

            cart[this.deliveryProductId] = {
                id: this.deliveryProductId,
                name: this.deliveryProductName,
                price: this.deliveryProductPrice,
                qty: 1,
            };
            console.log("[HomeDelivery] Cart after adding delivery:", cart);
            this.saveCart(cart);
            console.log("[HomeDelivery] Delivery product added to localStorage");
        },

        removeDeliveryProduct: function () {
            if (!this.deliveryProductId) {
                console.warn("[HomeDelivery] Delivery product ID not found");
                return;
            }

            console.log(
                "[HomeDelivery] Removing delivery product - deliveryProductId:",
                this.deliveryProductId,
                "orderId:",
                this.orderId
            );
            var cart = this.getCart();
            console.log("[HomeDelivery] Current cart before removing:", cart);

            if (cart[this.deliveryProductId]) {
                delete cart[this.deliveryProductId];
                console.log("[HomeDelivery] Cart after removing delivery:", cart);
            }
            this.saveCart(cart);
            console.log("[HomeDelivery] Delivery product removed from localStorage");
        },

        showDeliveryInfo: function () {
            var alert = document.getElementById("delivery-info-alert");
            if (alert) {
                console.log("[HomeDelivery] Showing delivery info alert");
                alert.classList.remove("d-none");
                alert.style.display = "block";
            }
        },

        hideDeliveryInfo: function () {
            var alert = document.getElementById("delivery-info-alert");
            if (alert) {
                console.log("[HomeDelivery] Hiding delivery info alert");
                alert.classList.add("d-none");
                alert.style.display = "none";
            }
        },
    };

    // Initialize on DOM ready
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", function () {
            HomeDeliveryManager.init();
        });
    } else {
        HomeDeliveryManager.init();
    }

    // Export to global scope
    window.HomeDeliveryManager = HomeDeliveryManager;
})();
