/**
 * Cart Manager - Manages shopping cart functionality
 * Uses backend for logged-in users, localStorage for guests
 */

class CartManager {
    constructor() {
        this.storageKey = 'granny_cart';
        this.isLoggedIn = this.checkLoginStatus();
        this.isReady = false;  // Flag to track when cart is initialized
        
        // Initialize immediately for guests, async for logged-in users
        if (this.isLoggedIn) {
            this.initCart();
        } else {
            // For guests, we can mark as ready immediately
            if (!this.getCart()) {
                this.saveCart([]);
            }
            this.isReady = true;
        }
        
        this.updateCartUI();
    }

    // Check if user is logged in
    checkLoginStatus() {
        const user = localStorage.getItem('user');
        return user ? true : false;
    }

    // Update login status (call this after user logs in)
    updateLoginStatus() {
        const wasLoggedIn = this.isLoggedIn;
        this.isLoggedIn = this.checkLoginStatus();
        console.log('Login status updated:', wasLoggedIn, '->', this.isLoggedIn);
        
        // If user just logged in, sync cart from backend
        if (!wasLoggedIn && this.isLoggedIn) {
            console.log('User just logged in, syncing cart from backend');
            this.initCart();
        }
        
        this.updateCartUI();
    }

    // Wait for cart to be ready
    async waitForReady(timeout = 5000) {
        const startTime = Date.now();
        while (!this.isReady && (Date.now() - startTime < timeout)) {
            await new Promise(resolve => setTimeout(resolve, 50));
        }
        return this.isReady;
    }

    // Initialize cart from backend (if logged in)
    initCart() {
        console.log('CartManager.initCart() called - isLoggedIn:', this.isLoggedIn);
        if (this.isLoggedIn) {
            this.syncCartFromBackend().then(() => {
                this.isReady = true;
                console.log('CartManager.initCart() completed - isReady:', this.isReady);
            }).catch((error) => {
                console.error('Error syncing cart from backend:', error);
                this.isReady = true;  // Mark as ready even if sync fails
            });
        }
    }

    // Sync cart from backend
    async syncCartFromBackend() {
        try {
            console.log('Syncing cart from backend...');
            const response = await fetch('backend/cart_api.php?action=get_cart', {
                credentials: 'include'
            });
            console.log('Backend response status:', response.status, response.ok);
            if (response.ok) {
                const data = await response.json();
                console.log('Backend cart data:', data);
                if (data.success) {
                    // Convert backend format to local format
                    const cart = data.data.map(item => ({
                        id: item.id,
                        item_id: item.item_id,
                        name: item.name,
                        price: item.price,
                        quantity: item.quantity,
                        image: item.image
                    }));
                    console.log('Saving synced cart to localStorage:', cart);
                    this.saveCart(cart);
                } else {
                    console.warn('Backend returned success:false -', data.message);
                }
            } else {
                console.error('Backend response not OK:', response.status);
            }
        } catch (error) {
            console.error('Error syncing cart from backend:', error);
        }
    }

    // Get cart from backend (if logged in) or localStorage
    getCart() {
        if (this.isLoggedIn) {
            // Cart is already synced in localStorage from syncCartFromBackend
            const cart = JSON.parse(localStorage.getItem(this.storageKey)) || [];
            console.log('getCart (logged in) - returning from localStorage:', cart);
            return cart;
        } else {
            const cart = localStorage.getItem(this.storageKey);
            const result = cart ? JSON.parse(cart) : [];
            console.log('getCart (guest) - returning from localStorage:', result);
            return result;
        }
    }

    // Save cart to localStorage and backend (if logged in)
    async saveCart(cart) {
        localStorage.setItem(this.storageKey, JSON.stringify(cart));
        // Backend is updated separately through addToCart, removeFromCart, etc.
    }

    // Add item to cart
    async addToCart(item) {
        console.log('addToCart called with item:', item);
        console.log('isLoggedIn:', this.isLoggedIn);
        
        if (this.isLoggedIn) {
            // Add to backend
            try {
                console.log('Adding to backend...');
                const response = await fetch('backend/cart_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    credentials: 'include',
                    body: `action=add_to_cart&item_id=${item.item_id}&quantity=${item.quantity || 1}`
                });
                const data = await response.json();
                console.log('Backend response:', data);
                if (data.success) {
                    // Sync cart from backend after adding
                    await this.syncCartFromBackend();
                    this.updateCartUI();
                    this.showAddedNotification(item.name);
                } else {
                    console.error('Failed to add item to backend cart:', data.message);
                    Swal.fire('Error', data.message, 'error');
                }
            } catch (error) {
                console.error('Error adding item to cart:', error);
                Swal.fire('Error', 'Failed to add item to cart', 'error');
            }
        } else {
            // Add to localStorage for guests
            console.log('Adding to localStorage as guest...');
            const cart = this.getCart();
            console.log('Current cart:', cart);
            
            // Check if item already exists in cart (by item_id for consistency with backend)
            const existingItem = cart.find(cartItem => cartItem.item_id === item.item_id);
            
            if (existingItem) {
                existingItem.quantity += (item.quantity || 1);
                console.log('Updated existing item quantity');
            } else {
                cart.push({
                    item_id: item.item_id,
                    name: item.name,
                    price: item.price,
                    quantity: item.quantity || 1,
                    image: item.image || ''
                });
                console.log('Added new item to cart');
            }
            
            console.log('Cart before save:', cart);
            this.saveCart(cart);
            console.log('Cart after save - localStorage:', localStorage.getItem(this.storageKey));
            this.updateCartUI();
            this.showAddedNotification(item.name);
        }
    }

    // Remove item from cart
    async removeFromCart(itemId) {
        if (this.isLoggedIn) {
            // Remove from backend
            try {
                const response = await fetch('backend/cart_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    credentials: 'include',
                    body: `action=remove_from_cart&item_id=${itemId}`
                });
                const data = await response.json();
                if (data.success) {
                    // Sync cart from backend after removing
                    await this.syncCartFromBackend();
                    this.updateCartUI();
                } else {
                    console.error('Failed to remove item from backend cart:', data.message);
                }
            } catch (error) {
                console.error('Error removing item from cart:', error);
            }
        } else {
            // Remove from localStorage for guests
            const cart = this.getCart();
            const index = cart.findIndex(item => item.item_id === itemId);
            if (index > -1) {
                cart.splice(index, 1);
                this.saveCart(cart);
                this.updateCartUI();
            }
        }
    }

    // Update item quantity
    async updateQuantity(itemId, quantity) {
        if (quantity <= 0) {
            return this.removeFromCart(itemId);
        }

        if (this.isLoggedIn) {
            // Update in backend
            try {
                const response = await fetch('backend/cart_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },                    credentials: 'include',                    body: `action=update_quantity&item_id=${itemId}&quantity=${quantity}`
                });
                const data = await response.json();
                if (data.success) {
                    // Sync cart from backend after updating
                    await this.syncCartFromBackend();
                    this.updateCartUI();
                } else {
                    console.error('Failed to update quantity in backend:', data.message);
                }
            } catch (error) {
                console.error('Error updating quantity:', error);
            }
        } else {
            // Update in localStorage for guests
            const cart = this.getCart();
            const item = cart.find(cartItem => cartItem.item_id === itemId);
            if (item) {
                item.quantity = quantity;
                this.saveCart(cart);
                this.updateCartUI();
            }
        }
    }

    // Get cart item count
    getCartCount() {
        const cart = this.getCart();
        return cart.reduce((count, item) => count + item.quantity, 0);
    }

    // Update cart UI (cart counter in navbar)
    updateCartUI() {
        const cartCount = this.getCartCount();
        const cartCountElements = document.querySelectorAll('.header-cart-count');
        cartCountElements.forEach(element => {
            element.textContent = cartCount;
            
            // Show badge when count is greater than 0
            if (cartCount > 0) {
                element.style.opacity = '1';
                element.style.transform = 'scale(1)';
                
                // Trigger pop animation
                element.style.animation = 'none';
                setTimeout(() => {
                    element.style.animation = 'badgePop 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)';
                }, 10);
            } else {
                // Hide badge when count is 0 or less
                element.style.opacity = '0';
                element.style.transform = 'scale(0)';
                element.style.animation = 'none';
            }
        });
    }

    // Show notification when item is added
    showAddedNotification(dishName) {
        // Remove any existing notification
        const existing = document.querySelector('.cart-notification');
        if (existing) {
            existing.remove();
        }

        // Create notification
        const notification = document.createElement('div');
        notification.className = 'cart-notification';
        notification.innerHTML = `<i class="fas fa-check-circle"></i> ${dishName} added to cart!`;
        document.body.appendChild(notification);

        // Remove notification after 3 seconds
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    // Clear cart
    async clearCart() {
        if (this.isLoggedIn) {
            // Clear from backend
            try {
                const response = await fetch('backend/cart_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },                    credentials: 'include',                    body: 'action=clear_cart'
                });
                const data = await response.json();
                if (data.success) {
                    this.saveCart([]);
                    this.updateCartUI();
                } else {
                    console.error('Failed to clear backend cart:', data.message);
                }
            } catch (error) {
                console.error('Error clearing cart:', error);
            }
        } else {
            // Clear from localStorage for guests
            this.saveCart([]);
            this.updateCartUI();
        }
    }

    // Check if user logged in changed
    handleLoginStatusChange() {
        const user = localStorage.getItem('user');
        const newLoginStatus = user ? true : false;
        
        if (newLoginStatus !== this.isLoggedIn) {
            this.isLoggedIn = newLoginStatus;
            
            if (this.isLoggedIn) {
                // User just logged in - sync backend cart and clear localStorage
                // Backend cart should already have their items
                this.syncCartFromBackend().then(() => {
                    this.updateCartUI();
                });
            } else {
                // User just logged out - keep localStorage cart as is
                this.updateCartUI();
            }
        }
    }
}

// Initialize cart manager immediately (don't wait for DOM)
console.log('Creating CartManager instance...');
window.cartManager = new CartManager();
console.log('CartManager instance created:', window.cartManager);
console.log('Initial isReady:', window.cartManager.isReady);

// Re-update UI after DOM is fully ready
document.addEventListener('DOMContentLoaded', function() {
    if (window.cartManager) {
        window.cartManager.updateCartUI();
    }
    
    // Listen for login/logout changes
    window.addEventListener('storage', function(e) {
        if (e.key === 'user') {
            window.cartManager.handleLoginStatusChange();
        }
    });
});
