import BaseComponent from './BaseComponent.js';

/**
 * CartHandler component
 * Handles add to cart and buy now functionality using Shopify web components
 */
class CartHandler extends BaseComponent {
    constructor() {
        super('body'); // No specific container needed
        this.quantity = 1;
        this.cart = null;
        this.store = null;
    }

    /**
     * Initialize cart handler
     */
    init() {
        // Wait for Shopify web components to load
        if (window.customElements && window.customElements.get('shopify-cart')) {
            this.initializeComponents();
        } else {
            // Wait for components to be defined
            if (window.customElements) {
                window.customElements.whenDefined('shopify-cart').then(() => {
                    this.initializeComponents();
                });
            }
        }

        // Bind quantity controls
        this.bindQuantityControls();

        // Make functions globally accessible for onclick handlers
        window.shopyPressAddToCart = this.addToCart.bind(this);
        window.shopyPressBuyNow = this.buyNow.bind(this);
        window.increaseQuantity = this.increaseQuantity.bind(this);
        window.decreaseQuantity = this.decreaseQuantity.bind(this);
    }

    /**
     * Initialize Shopify components
     */
    initializeComponents() {
        this.cart = document.getElementById('shopypress-cart');
        this.store = document.querySelector('shopify-store');

        if (this.cart) {
            console.log('ShopyPress: Cart component ready');
        }
        if (this.store) {
            console.log('ShopyPress: Store component ready');
        }
    }

    /**
     * Bind quantity control events
     */
    bindQuantityControls() {
        // Listen for variant changes to enable/disable buttons
        if (window.ShopyPressEventBus) {
            window.ShopyPressEventBus.on('variant:changed', (data) => {
                this.updateButtonState(data.variant);
            });
        }
    }

    /**
     * Add to cart
     */
    addToCart(event) {
        if (!this.cart) {
            console.error('ShopyPress: Cart component not found');
            return;
        }

        // Set quantity on the event
        if (event) {
            event.quantity = this.quantity;
        }

        try {
            // Add to cart using Shopify's method
            this.cart.addLine(event);

            // Show cart modal
            this.cart.showModal();

            console.log('ShopyPress: Added to cart, quantity:', this.quantity);

            // Reset quantity to 1
            this.quantity = 1;
            this.updateQuantityDisplay();

        } catch (error) {
            console.error('ShopyPress: Error adding to cart', error);
        }
    }

    /**
     * Buy now (direct to checkout)
     */
    buyNow(event) {
        if (!this.store) {
            console.error('ShopyPress: Store component not found');
            return;
        }

        // Set quantity on the event
        if (event) {
            event.quantity = this.quantity;
        }

        try {
            // Redirect to checkout with this product
            this.store.buyNow(event);

            console.log('ShopyPress: Buy now, quantity:', this.quantity);

        } catch (error) {
            console.error('ShopyPress: Error with buy now', error);
        }
    }

    /**
     * Increase quantity
     */
    increaseQuantity() {
        this.quantity++;
        this.updateQuantityDisplay();
    }

    /**
     * Decrease quantity
     */
    decreaseQuantity() {
        if (this.quantity > 1) {
            this.quantity--;
            this.updateQuantityDisplay();
        }
    }

    /**
     * Update quantity display
     */
    updateQuantityDisplay() {
        const display = document.getElementById('shopypress-quantity');
        if (display) {
            display.textContent = this.quantity;
        }
    }

    /**
     * Update button state based on variant availability
     */
    updateButtonState(variant) {
        const addToCartBtn = document.getElementById('shopypress-add-to-cart');
        const buyNowBtn = document.getElementById('shopypress-buy-now');

        if (!variant || !variant.available) {
            // Disable buttons
            if (addToCartBtn) {
                addToCartBtn.disabled = true;
                addToCartBtn.textContent = 'Out of Stock';
            }
            if (buyNowBtn) {
                buyNowBtn.disabled = true;
            }
        } else {
            // Enable buttons
            if (addToCartBtn) {
                addToCartBtn.disabled = false;
                addToCartBtn.textContent = 'Add to Cart';
            }
            if (buyNowBtn) {
                buyNowBtn.disabled = false;
            }
        }
    }
}

export default CartHandler;
