let selectedItemType = null;
let selectedItemTypeId = null;

document.addEventListener('DOMContentLoaded', function() {
    const optionSelects = document.querySelectorAll('.service-option');
    const quantityField = document.getElementById('quantity');
    
    optionSelects.forEach(select => {
        select.addEventListener('change', updateTotalPrice);
        
        if (select.dataset.optionType === 'fabric_type') {
            select.addEventListener('change', handleFabricTypeChange);
        }
    });
    
    if (quantityField) {
        quantityField.addEventListener('input', updateTotalPrice);
    }
    
    document.querySelectorAll('.item-type-btn').forEach(btn => {
        const imagePath = btn.getAttribute('data-image');
        if (imagePath) {
            btn.style.backgroundImage = `url('${imagePath}')`;
        }
    });
    
    updateTotalPrice();
});

function handleFabricTypeChange(event) {
    const select = event.target;
    const selectedOption = select.options[select.selectedIndex];
    const fabricValue = selectedOption.dataset.value || '';
    
    const genderGroup = document.querySelector('[data-option-type="gender"]')?.closest('.option-group');
    
    if (!genderGroup) return;
    
    const genderSelect = genderGroup.querySelector('select');
    
    const needsGenderSelection = fabricValue === 'jeans' || fabricValue === 'tshirt';
    
    if (needsGenderSelection) {
        genderGroup.style.display = 'block';
        genderSelect.setAttribute('required', 'required');
        genderSelect.value = '';
    } else {
        genderGroup.style.display = 'none';
        genderSelect.removeAttribute('required');
        
        if (fabricValue === 'abaya' || fabricValue === 'dress') {
            const womenOption = Array.from(genderSelect.options).find(opt => opt.dataset.value === 'women');
            if (womenOption) genderSelect.value = womenOption.value;
        } else if (fabricValue === 'shemagh' || fabricValue === 'thobe') {
            const menOption = Array.from(genderSelect.options).find(opt => opt.dataset.value === 'men');
            if (menOption) genderSelect.value = menOption.value;
        } else {
            genderSelect.value = '';
        }
    }
}

function changeQuantity(change) {
    const quantityField = document.getElementById('quantity');
    if (quantityField) {
        const currentValue = parseInt(quantityField.value) || 1;
        const step = parseInt(quantityField.step) || 1;
        const min = parseInt(quantityField.min) || 1;
        
        let newValue = currentValue + (change * step);
        if (newValue < min) newValue = min;
        
        quantityField.value = Math.round(newValue);
        updateTotalPrice();
    }
}

function calculateTieredPrice(serviceId, quantity) {
    const tieredServices = [1, 2];
    
    if (!tieredServices.includes(serviceId)) {
        return null;
    }
    
    if (quantity <= 4) {
        return { price: 20.00, total: 20.00 };
    }
    
    if (quantity >= 5 && quantity < 15) {
        return { price: 18.00, total: 18.00 };
    }
    
    if (quantity >= 15 && quantity < 20) {
        return { price: 17.00, total: 17.00 };
    }
    
    if (quantity == 20) {
        return { price: 16.00, total: 16.00 };
    }
    
    if (quantity > 20) {
        const baseTotal = 16.00;
        const extraQuantity = quantity - 20;
        const extraGroups = Math.ceil(extraQuantity / 5);
        const extraCost = extraGroups * 5;
        return { price: baseTotal + extraCost, total: baseTotal + extraCost };
    }
    
    return { price: 20.00, total: 20.00 };
}

function updateTotalPrice() {
    if (typeof serviceData !== 'undefined' && serviceData.category === 'household') {
        updateHouseholdPrice();
        return;
    }
    
    const basePrice = parseFloat(serviceData.price);
    const quantity = parseInt(document.getElementById('quantity')?.value || 1);
    const serviceId = parseInt(serviceData.id);
    
    let optionsTotal = 0;
    document.querySelectorAll('.service-option').forEach(select => {
        const selectedOption = select.options[select.selectedIndex];
        if (selectedOption && selectedOption.dataset.price) {
            optionsTotal += parseFloat(selectedOption.dataset.price);
        }
    });

    let baseTotal;
    let optionsTotalForQuantity;
    const tieredServices = [1, 2];
    
    if (tieredServices.includes(serviceId)) {
        const tieredResult = calculateTieredPrice(serviceId, quantity);
        baseTotal = tieredResult.total;
        optionsTotalForQuantity = optionsTotal;
        
        updateTierDisplay(serviceId, quantity);
    } else {
        baseTotal = basePrice * quantity;
        optionsTotalForQuantity = optionsTotal * quantity;
    }
    
    const finalTotal = baseTotal + optionsTotalForQuantity;

    document.getElementById('base-total').textContent = 'SAR ' + baseTotal.toFixed(2);
    
    const optionsTotalElement = document.querySelector('.options-total');
    if (optionsTotalForQuantity > 0) {
        document.getElementById('options-total').textContent = 'SAR ' + optionsTotalForQuantity.toFixed(2);
        optionsTotalElement.style.display = 'flex';
    } else {
        optionsTotalElement.style.display = 'none';
    }

    document.getElementById('final-total').innerHTML = '<strong>SAR ' + finalTotal.toFixed(2) + '</strong>';
}

let lastTier = null;

function updateTierDisplay(serviceId, quantity) {
    const tieredServices = [1, 2];
    
    if (!tieredServices.includes(serviceId)) {
        return;
    }
    
    let tierInfo = '';
    let savings = 0;
    let currentTier = '';
    
    if (quantity <= 4) {
        currentTier = '1-4';
        tierInfo = `Current: SAR 20.00 total (Tier: 1-4 pieces)`;
        tierInfo += `<br><small style="color: #17a2b8;">💡 Order 5+ pieces for SAR 18.00 total!</small>`;
    } else if (quantity >= 5 && quantity < 15) {
        currentTier = '5-14';
        savings = 20.00 - 18.00;
        tierInfo = `Current: SAR 18.00 total (Tier: 5-14 pieces)`;
        tierInfo += `<br><small style="color: #28a745;">✅ You save SAR ${savings.toFixed(2)} vs regular price!</small>`;
        tierInfo += `<br><small style="color: #17a2b8;">💡 Order 15+ pieces for SAR 17.00 total!</small>`;
    } else if (quantity >= 15 && quantity < 20) {
        currentTier = '15-19';
        savings = 20.00 - 17.00;
        tierInfo = `Current: SAR 17.00 total (Tier: 15-19 pieces)`;
        tierInfo += `<br><small style="color: #28a745;">✅ You save SAR ${savings.toFixed(2)} vs regular price!</small>`;
        tierInfo += `<br><small style="color: #17a2b8;">💡 Order 20 pieces for SAR 16.00 total!</small>`;
    } else if (quantity == 20) {
        currentTier = '20';
        savings = 20.00 - 16.00;
        tierInfo = `Current: SAR 16.00 total (Tier: 20 pieces)`;
        tierInfo += `<br><small style="color: #28a745;">✅ You save SAR ${savings.toFixed(2)} vs regular price!</small>`;
        tierInfo += `<br><small style="color: #17a2b8;">💡 Order 25+ pieces: SAR 16.00 + SAR 5.00 per extra 5 pieces!</small>`;
    } else {
        currentTier = '20+';
        const baseTotal = 16.00;
        const extraQuantity = quantity - 20;
        const extraGroups = Math.ceil(extraQuantity / 5);
        const extraCost = extraGroups * 5;
        const actualTotal = baseTotal + extraCost;
        savings = 20.00 - actualTotal;
        
        tierInfo = `Current: SAR ${actualTotal.toFixed(2)} total (Tier: 20+ pieces)`;
        if (savings > 0) {
            tierInfo += `<br><small style="color: #28a745;">✅ You save SAR ${savings.toFixed(2)} vs regular price!</small>`;
        }
    }
    
    if (lastTier && lastTier !== currentTier) {
        showTierChangeNotification(currentTier, savings);
    }
    lastTier = currentTier;
    
    let tierDisplay = document.querySelector('.live-tier-info');
    if (!tierDisplay) {
        tierDisplay = document.createElement('div');
        tierDisplay.className = 'live-tier-info';
        
        const priceSection = document.querySelector('.total-price-section');
        if (priceSection) {
            priceSection.insertBefore(tierDisplay, priceSection.firstChild);
        }
    }
    
    tierDisplay.innerHTML = `<strong style="color: #00aaff;">Pricing:</strong><br>${tierInfo}`;
}

function showTierChangeNotification(newTier, savings) {
    const notification = document.createElement('div');
    notification.className = 'tier-notification';
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 4px 20px rgba(40, 167, 69, 0.3);
        z-index: 1000;
        max-width: 300px;
        animation: slideInRight 0.5s ease;
        font-size: 0.9rem;
    `;
    
    let message = '';
    switch(newTier) {
        case '5-14':
            message = '🎉 Great! You\'ve unlocked the 5-14 pieces tier!<br>Now paying SAR 15.00 total';
            break;
        case '15-19':
            message = '🎉 Excellent! You\'ve reached the 15-19 pieces tier!<br>Now paying SAR 17.00 total';
            break;
        case '20':
            message = '🎉 Perfect! You\'ve reached the 20 pieces tier!<br>Now paying SAR 18.00 total';
            break;
        case '20+':
            message = '🎉 Amazing! You\'ve reached the bulk pricing tier!<br>SAR 18.00 + extra fees';
            break;
    }
    
    if (savings > 0) {
        message += `<br><small style="opacity: 0.9;">You save SAR ${savings.toFixed(2)}!</small>`;
    }
    
    notification.innerHTML = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.5s ease';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 500);
    }, 4000);
}

const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

function addDetailedServiceToCart() {
    if (typeof serviceData !== 'undefined' && serviceData.category === 'household') {
        addHouseholdItemToCart();
        return;
    }
    
    const quantity = parseInt(document.getElementById('quantity')?.value || 1);
    const selectedOptions = {};
    
    const optionSelects = document.querySelectorAll('.service-option');
    let allOptionsSelected = true;
    
    optionSelects.forEach(select => {
        const isVisible = select.closest('.option-group').style.display !== 'none';
        const isRequired = select.hasAttribute('required');
        
        if (isVisible && isRequired && select.value === '') {
            allOptionsSelected = false;
            select.classList.add('error');
        } else {
            select.classList.remove('error');
            if (select.value !== '') {
                selectedOptions[select.dataset.optionType] = {
                    id: select.value,
                    name: select.options[select.selectedIndex].text,
                    price: parseFloat(select.options[select.selectedIndex].dataset.price || 0)
                };
            }
        }
    });

    if (!allOptionsSelected) {
        showNotification('Please select all required options', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('action', 'add_service');
    formData.append('service_id', serviceData.id);
    formData.append('quantity', quantity);
    formData.append('selected_options', JSON.stringify(selectedOptions));

    // ✅ Add pickup details
    const pickupOption = document.getElementById('pickup_option')?.value || '';
    const pickupAddress = document.getElementById('pickup_address')?.value || '';
    formData.append('pickup_option', pickupOption);
    formData.append('pickup_address', pickupAddress);
    
    fetch('php/cart_handler.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            return response.text().then(text => {
                console.error('Server returned non-JSON response:', text);
                throw new Error('Server error: Invalid response format');
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showNotification('Service added to cart successfully!', 'success');
            const cartCount = document.querySelector('.cart-count');
            
            if (cartCount) {
                if (data.cart_count && data.cart_count > 0) {
                    cartCount.textContent = data.cart_count;
                    cartCount.style.display = 'inline';
                    
                    cartCount.style.transform = 'scale(1.2)';
                    cartCount.style.color = '#28a745';
                    setTimeout(() => {
                        cartCount.style.transform = 'scale(1)';
                        cartCount.style.color = '';
                    }, 300);
                } else {
                    cartCount.style.display = 'none';
                }
            }
            
            setTimeout(() => {
                showCartNotification();
            }, 2000);
        } else {
            showNotification('Error occurred: ' + (data.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Connection error: ' + error.message, 'error');
    });
}

function showTab(tabName) {
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.remove('active');
    });
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });

    document.getElementById(tabName).classList.add('active');
    event.target.classList.add('active');
}

function showNotification(message, type = 'info') {
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    
    const icon = type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️';
    
    notification.innerHTML = `
        <span class="notification-icon">${icon}</span>
        <span class="notification-message">${message}</span>
        <button class="notification-close" onclick="this.parentElement.remove()">&times;</button>
    `;

    const container = document.querySelector('.service-details-container');
    container.insertBefore(notification, container.firstChild);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

function showCartNotification() {
    const existingNotifications = document.querySelectorAll('.cart-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'cart-notification';
    
    notification.innerHTML = `
        <div class="cart-notification-content">
            <div class="cart-notification-icon">🛒</div>
            <div class="cart-notification-text">
                <h4>Item Added Successfully!</h4>
                <p>Do you want to go to cart now?</p>
            </div>
            <div class="cart-notification-actions">
                <button class="cart-btn-yes" onclick="goToCart()">Yes, Go to Cart</button>
                <button class="cart-btn-no" onclick="closeCartNotification()">Continue Shopping</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 8000);
}

function goToCart() {
    window.location.href = 'cart.php';
}

function closeCartNotification() {
    const notification = document.querySelector('.cart-notification');
    if (notification) {
        notification.remove();
    }
}


function selectHouseholdItem(itemType, itemTypeId) {
    selectedItemType = itemType;
    selectedItemTypeId = itemTypeId;
    
    const clickedBtn = event.target.closest('.item-type-btn');
    
    document.querySelectorAll('.item-type-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    clickedBtn.classList.add('active');
    
    const imagePath = clickedBtn.getAttribute('data-image');
    if (imagePath) {
        const mainImage = document.getElementById('main-service-image');
        if (mainImage) {
            mainImage.src = imagePath;
            mainImage.style.transition = 'opacity 0.3s ease';
            mainImage.style.opacity = '0';
            setTimeout(() => {
                mainImage.style.opacity = '1';
            }, 50);
        }
    }
    
    document.getElementById('household-quantity').style.display = 'block';
    
    const labels = {
        'pillows': 'Pillows',
        'blankets': 'Blankets',
        'curtains': 'Curtains',
        'carpets': 'Carpets'
    };
    document.getElementById('item-label').textContent = labels[itemType] || 'Items';
    
    loadItemOptions(itemType);
    
    document.getElementById('pickup-time-section').style.display = 'block';
    document.getElementById('delivery-speed-section').style.display = 'block';
    document.getElementById('special-instructions-section').style.display = 'block';
    
    document.getElementById('dynamic-household-options').style.display = 'block';
    
    updateTotalPrice();
}

function loadItemOptions(itemType) {
    const container = document.getElementById('dynamic-household-options');
    container.innerHTML = '';
    
    const optionTypeMap = {
        'pillows': 'pillow_type',
        'blankets': 'blanket_type',
        'curtains': 'curtain_type',
        'carpets': 'carpet_type'
    };
    
    const typeKey = optionTypeMap[itemType];
    
    if (householdOptionsData[typeKey]) {
        const typeGroup = createOptionGroup(
            `Type of ${itemType.charAt(0).toUpperCase() + itemType.slice(1)}:`,
            householdOptionsData[typeKey],
            typeKey,
            true
        );
        container.appendChild(typeGroup);
    }
    
    if (householdOptionsData['garment_size']) {
        const sizeGroup = createOptionGroup(
            'Item Size (Length):',
            householdOptionsData['garment_size'],
            'garment_size',
            true
        );
        container.appendChild(sizeGroup);
    }
    
    const cleaningOptions = getCleaningOptionsForItem(itemType);
    if (cleaningOptions.length > 0) {
        const cleaningGroup = createOptionGroup(
            'Cleaning Preference:',
            cleaningOptions,
            'cleaning_preference',
            true
        );
        container.appendChild(cleaningGroup);
    }
    
    const addonOptions = getAddonOptionsForItem(itemType);
    if (addonOptions.length > 0) {
        const addonGroup = createCheckboxGroup(
            'Optional Add-ons:',
            addonOptions,
            'optional_addon'
        );
        container.appendChild(addonGroup);
    }
}

function getCleaningOptionsForItem(itemType) {
    if (!householdOptionsData['cleaning_preference']) return [];
    
    return householdOptionsData['cleaning_preference'].filter(option => {
        const optionName = option.option_name.toLowerCase();
        return optionName.includes(itemType) || 
               (!optionName.includes('pillows') && 
                !optionName.includes('blankets') && 
                !optionName.includes('curtains') && 
                !optionName.includes('carpets'));
    });
}

function getAddonOptionsForItem(itemType) {
    if (!householdOptionsData['optional_addon']) return [];
    
    return householdOptionsData['optional_addon'].filter(option => {
        const optionName = option.option_name.toLowerCase();
        const optionValue = option.option_value.toLowerCase();
        
        if (itemType === 'pillows') {
            return optionValue.includes('restuffing') || optionValue.includes('reshaping');
        } else if (itemType === 'blankets') {
            return optionValue.includes('steam_blankets') || optionValue.includes('deodorizing_blankets');
        } else if (itemType === 'carpets') {
            return optionValue.includes('antibacterial') || optionValue.includes('deodorizing_carpets') || optionValue.includes('moth_protection');
        }
        
        return false;
    });
}

function createOptionGroup(label, options, optionType, required = false) {
    const div = document.createElement('div');
    div.className = 'option-group';
    
    const labelEl = document.createElement('label');
    labelEl.className = 'option-label';
    labelEl.textContent = label;
    div.appendChild(labelEl);
    
    const select = document.createElement('select');
    select.className = 'service-option';
    select.setAttribute('data-option-type', optionType);
    if (required) select.setAttribute('required', 'required');
    
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = 'Choose...';
    select.appendChild(defaultOption);
    
    options.forEach(option => {
        const opt = document.createElement('option');
        opt.value = option.id;
        opt.setAttribute('data-price', option.price_modifier);
        opt.textContent = option.option_name;
        
        if (option.price_modifier != 0) {
            opt.textContent += ` (+SAR ${parseFloat(option.price_modifier).toFixed(2)})`;
        }
        
        select.appendChild(opt);
    });
    
    select.addEventListener('change', updateTotalPrice);
    div.appendChild(select);
    
    return div;
}

function createCheckboxGroup(label, options, optionType) {
    const div = document.createElement('div');
    div.className = 'option-group';
    
    const labelEl = document.createElement('label');
    labelEl.className = 'option-label';
    labelEl.textContent = label;
    div.appendChild(labelEl);
    
    const checkboxContainer = document.createElement('div');
    checkboxContainer.className = 'checkbox-group';
    
    options.forEach(option => {
        const checkboxDiv = document.createElement('div');
        checkboxDiv.className = 'checkbox-option';
        
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'addon-checkbox';
        checkbox.value = option.id;
        checkbox.setAttribute('data-price', option.price_modifier);
        checkbox.setAttribute('data-option-type', optionType);
        checkbox.id = `addon-${option.id}`;
        
        const checkboxLabel = document.createElement('label');
        checkboxLabel.setAttribute('for', `addon-${option.id}`);
        checkboxLabel.textContent = option.option_name;
        
        if (option.price_modifier != 0) {
            checkboxLabel.textContent += ` (+SAR ${parseFloat(option.price_modifier).toFixed(2)})`;
        }
        
        checkbox.addEventListener('change', updateTotalPrice);
        
        checkboxDiv.appendChild(checkbox);
        checkboxDiv.appendChild(checkboxLabel);
        checkboxContainer.appendChild(checkboxDiv);
    });
    
    div.appendChild(checkboxContainer);
    return div;
}

function updateHouseholdPrice() {
    if (!selectedItemType) {
        document.getElementById('base-total').textContent = 'SAR 0.00';
        document.getElementById('final-total').innerHTML = '<strong>SAR 0.00</strong>';
        return;
    }
    
    const quantity = parseInt(document.getElementById('quantity')?.value || 1);
    let totalPrice = 0;
    let optionsPrice = 0;
    
    document.querySelectorAll('.service-option').forEach(select => {
        const selectedOption = select.options[select.selectedIndex];
        if (selectedOption && selectedOption.value) {
            const price = parseFloat(selectedOption.getAttribute('data-price') || 0);
            optionsPrice += price;
        }
    });
    
    document.querySelectorAll('.addon-checkbox:checked').forEach(checkbox => {
        const price = parseFloat(checkbox.getAttribute('data-price') || 0);
        optionsPrice += price;
    });
    
    totalPrice = optionsPrice * quantity;
    
    document.getElementById('base-total').textContent = 'SAR ' + (optionsPrice * quantity).toFixed(2);
    
    const optionsTotalElement = document.querySelector('.options-total');
    if (optionsPrice > 0) {
        document.getElementById('options-total').textContent = 'SAR ' + (optionsPrice * quantity).toFixed(2);
        optionsTotalElement.style.display = 'flex';
    } else {
        optionsTotalElement.style.display = 'none';
    }
    
    document.getElementById('final-total').innerHTML = '<strong>SAR ' + totalPrice.toFixed(2) + '</strong>';
}

function addHouseholdItemToCart() {
    if (!selectedItemType) {
        showNotification('Please select an item type first', 'error');
        return;
    }
    
    const quantity = parseInt(document.getElementById('quantity')?.value || 1);
    const selectedOptions = {
        item_type: {
            id: selectedItemTypeId,
            name: selectedItemType,
            price: 0
        }
    };
    
    document.querySelectorAll('.service-option').forEach(select => {
        if (select.value) {
            const selectedOption = select.options[select.selectedIndex];
            const optionType = select.getAttribute('data-option-type');
            selectedOptions[optionType] = {
                id: select.value,
                name: selectedOption.textContent.split('(')[0].trim(),
                price: parseFloat(selectedOption.getAttribute('data-price') || 0)
            };
        }
    });
        
    const addons = [];
    document.querySelectorAll('.addon-checkbox:checked').forEach(checkbox => {
        addons.push({
            id: checkbox.value,
            name: checkbox.nextElementSibling.textContent.split('(')[0].trim(),
            price: parseFloat(checkbox.getAttribute('data-price') || 0)
        });
    });
    
    if (addons.length > 0) {
        selectedOptions.addons = addons;
    }
    
    const specialInstructions = document.getElementById('special-instructions')?.value || '';
    
    const requiredSelects = document.querySelectorAll('.service-option[required]');
    let allValid = true;
    
    requiredSelects.forEach(select => {
        if (!select.value) {
            allValid = false;
            select.classList.add('error');
        } else {
            select.classList.remove('error');
        }
    });
    
    if (!allValid) {
        showNotification('Please fill all required fields', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'add_service');
    formData.append('service_id', serviceData.id);
    formData.append('quantity', quantity);
    formData.append('selected_options', JSON.stringify(selectedOptions));
    if (specialInstructions) {
        formData.append('special_instructions', specialInstructions);
    }
    
    fetch('php/cart_handler.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            return response.text().then(text => {
                console.error('Server returned non-JSON response:', text);
                throw new Error('Server error: Invalid response format');
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showNotification('Item added to cart successfully!', 'success');
            
            const cartCount = document.querySelector('.cart-count');
            if (cartCount && data.cart_count) {
                cartCount.textContent = data.cart_count;
                cartCount.style.display = 'inline';
                
                cartCount.style.transform = 'scale(1.2)';
                cartCount.style.color = '#28a745';
                setTimeout(() => {
                    cartCount.style.transform = 'scale(1)';
                    cartCount.style.color = '';
                }, 300);
            }
            
            setTimeout(() => {
                showCartNotification();
            }, 2000);
        } else {
            showNotification('Error: ' + (data.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Connection error: ' + error.message, 'error');
    });
}
