document.addEventListener('DOMContentLoaded', () => {
    // Inquiry Form Handling
    const inquiryForm = document.getElementById('inquiryForm');
    if (inquiryForm) {
        inquiryForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(inquiryForm);
            const submitBtn = inquiryForm.querySelector('button[type="submit"]');
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Sending...';

            try {
                const response = await fetch('/api/inquiry.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();

                if (result.success) {
                    inquiryForm.innerHTML = `<div class="text-center py-4">
                        <div class="h1 text-gold mb-3"><i class="bi bi-check-circle"></i></div>
                        <h6>Thank you, ${formData.get('name')}!</h6>
                        <p class="small text-muted mb-0">We have received your inquiry and will contact you shortly.</p>
                    </div>`;
                } else {
                    alert('Something went wrong. Please try again.');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = 'Send Inquiry';
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Connection error. Please try again later.');
                submitBtn.disabled = false;
                submitBtn.innerHTML = 'Send Inquiry';
            }
        });
    }

    // Initialize cart count
    updateCartCount();
});

function addToCart(id, name, price, image) {
    const formData = new FormData();
    formData.append('id', id);
    formData.append('name', name);
    formData.append('price', price);
    formData.append('image', image);

    fetch('/api/cart.php?action=add', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(data => {
        if (data.success) {
            updateCartCount(data.cart_count);
            showToast(`<i class="bi bi-cart-check-fill me-2"></i> ${name} added to cart!`);
        } else {
            console.error('API Error:', data.error);
        }
    })
    .catch(error => {
        console.error('Error adding to cart:', error);
        alert('Could not add item to cart. Please try again.');
    });
}

function updateCartCount(count = null) {
    if (count !== null) {
        renderCartCount(count);
        return;
    }

    fetch('/api/cart.php?action=get')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderCartCount(data.cart_count);
        }
    })
    .catch(error => console.error('Error fetching cart count:', error));
}

function renderCartCount(count) {
    const cartCountElement = document.getElementById('cart-count');
    if (cartCountElement) {
        cartCountElement.innerText = count;
        if (count > 0) {
            cartCountElement.classList.remove('d-none');
        } else {
            cartCountElement.classList.add('d-none');
        }
    }
}

function showToast(message) {
    const toastContainer = document.getElementById('toast-container') || createToastContainer();
    const toast = document.createElement('div');
    toast.className = 'toast align-items-center text-white bg-charcoal border-0 show mb-2 shadow-lg';
    toast.role = 'alert';
    toast.ariaLive = 'assertive';
    toast.ariaAtomic = 'true';
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body py-3">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
    toastContainer.appendChild(toast);
    
    // Auto-remove after 4 seconds
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 500);
    }, 4000);
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toast-container';
    container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
    container.style.zIndex = '1100';
    document.body.appendChild(container);
    return container;
}
