document.addEventListener('DOMContentLoaded', function() {
    
    updateSelectedCategories();
    
    
    const defaultFromDate = document.getElementById('orders-from-date').value;
    document.getElementById('orders_sync_from_date').value = defaultFromDate;
    
    
    const syncForm = document.querySelector('.finalpos-sync-form');
    const syncButton = document.getElementById('finalpos-sync-button');
    
    if (syncForm && syncButton) {
        syncForm.addEventListener('submit', function() {
            syncButton.textContent = 'One moment...';
            syncButton.disabled = true;
        });
    }
    
    
    document.getElementById('orders-from-date').addEventListener('change', function() {
        
        document.getElementById('orders_sync_from_date').value = this.value;
    });
    
    
    const ordersDescElem = document.querySelector('.finalpos-sync-category[data-sync-type="orders"] .finalpos-text-small');
    if (defaultFromDate) {
        
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
        const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().split('T')[0];
        
        if (defaultFromDate === thirtyDaysAgoStr) {
            ordersDescElem.textContent = 'Syncing orders from the last 30 days.';
        } else {
            ordersDescElem.textContent = `Syncing orders from ${defaultFromDate}.`;
        }
    } else {
        ordersDescElem.textContent = 'Syncing all orders.';
    }
    
    
    const syncLinks = document.querySelectorAll('.finalpos-sync-terms');
    const closeButtons = document.querySelectorAll('.finalpos-modal-close, .modal-cancel');
    const saveButtons = document.querySelectorAll('.modal-save');
    const toggles = document.querySelectorAll('.sync-toggle');
    
    
    const categorySearch = document.getElementById('category-search');
    if (categorySearch) {
        categorySearch.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const categoryItems = document.querySelectorAll('.finalpos-categories-list .finalpos-category-item');
            
            categoryItems.forEach(item => {
                const categoryName = item.querySelector('.category-name').textContent.toLowerCase();
                if (categoryName.includes(searchTerm)) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    }
    
    
    syncLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const syncType = this.getAttribute('data-sync-type');
            const modal = document.getElementById(`${syncType}-sync-modal`);
            modal.style.display = 'block';
            
            
            if (syncType === 'products' && categorySearch) {
                categorySearch.value = '';
                
                document.querySelectorAll('.finalpos-categories-list .finalpos-category-item').forEach(item => {
                    item.style.display = 'block';
                });
            }
        });
    });
    
    
    closeButtons.forEach(button => {
        button.addEventListener('click', function() {
            const modalId = this.getAttribute('data-modal-id');
            const modal = document.getElementById(modalId);
            modal.style.display = 'none';
        });
    });
    
    
    toggles.forEach(toggle => {
        toggle.addEventListener('change', function() {
            const syncType = this.getAttribute('data-sync-type');
            const enabled = this.checked ? 1 : 0;
            document.getElementById(`${syncType}_sync_enabled`).value = enabled;
            
            
            const descriptionElem = this.closest('.finalpos-sync-category').querySelector('.finalpos-text-small');
            if (!this.checked) {
                descriptionElem.textContent = `${syncType.charAt(0).toUpperCase() + syncType.slice(1)} sync disabled.`;
            } else {
                if (syncType === 'products') {
                    descriptionElem.textContent = 'Syncing all product categories.';
                } else if (syncType === 'orders') {
                    const fromDate = document.getElementById('orders_sync_from_date').value;
                    if (fromDate) {
                        descriptionElem.textContent = `Syncing orders from ${fromDate}.`;
                    } else {
                        descriptionElem.textContent = 'Syncing all orders.';
                    }
                } else if (syncType === 'customers') {
                    descriptionElem.textContent = 'Syncing all registered customers.';
                }
            }
        });
    });
    
    const categoryCheckboxes = document.querySelectorAll('.category-checkbox');
    const selectAllCheckbox = document.getElementById('select-all-categories');
    
    function updateSelectedCategories() {
        const selectedCategories = [];
        document.querySelectorAll('.category-checkbox:checked').forEach(checkbox => {
            selectedCategories.push(checkbox.value);
        });
        document.getElementById('products_sync_categories').value = JSON.stringify(selectedCategories);
    }

    function checkAllChildren(categoryId, checked) {
        const childCheckboxes = document.querySelectorAll(`.category-checkbox[data-parent-id="${categoryId}"]`);
        childCheckboxes.forEach(childCheckbox => {
            childCheckbox.checked = checked;
            checkAllChildren(childCheckbox.value, checked);
        });
    }
    
    function uncheckAllParents(categoryCheckbox) {
        const parentId = categoryCheckbox.getAttribute('data-parent-id');
        if (parentId && parentId !== '0') {
            const parentCheckbox = document.querySelector(`.category-checkbox[value="${parentId}"]`);
            if (parentCheckbox) {
                parentCheckbox.checked = false;
                uncheckAllParents(parentCheckbox);
            }
        }
    }
    
    categoryCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const checked = this.checked;
            const categoryId = this.value;
            
            const categoryItem = this.closest('.finalpos-category-item');
            categoryItem.classList.add('highlight');
            setTimeout(() => {
                categoryItem.classList.remove('highlight');
            }, 500);
            
            if (checked) {
                
                checkAllChildren(categoryId, true);
            } else {
                
                checkAllChildren(categoryId, false);
                uncheckAllParents(this);
            }
            
            
            updateSelectAllStatus();
            
            
            updateSelectedCategories();
        });
    });
    
    
    selectAllCheckbox.addEventListener('change', function() {
        const checked = this.checked;
        
        
        categoryCheckboxes.forEach(checkbox => {
            checkbox.checked = checked;
        });
        
        
        updateSelectedCategories();
    });
    
    
    function updateSelectAllStatus() {
        const totalCategories = categoryCheckboxes.length;
        const checkedCategories = document.querySelectorAll('.category-checkbox:checked').length;
        
        selectAllCheckbox.checked = (checkedCategories === totalCategories);
    }
    
    
    saveButtons.forEach(button => {
        button.addEventListener('click', function() {
            const modalId = this.getAttribute('data-modal-id');
            const syncType = this.getAttribute('data-sync-type');
            const modal = document.getElementById(modalId);
            
            if (syncType === 'products') {
                
                
                
                const descriptionElem = document.querySelector('.finalpos-sync-category[data-sync-type="products"] .finalpos-text-small');
                const selectedCount = document.querySelectorAll('.category-checkbox:checked').length;
                const totalCount = document.querySelectorAll('.category-checkbox').length;
                
                if (selectedCount === 0) {
                    descriptionElem.textContent = 'No product categories selected for sync.';
                } else if (selectedCount === totalCount) {
                    descriptionElem.textContent = 'Syncing all product categories.';
                } else {
                    descriptionElem.textContent = `Syncing ${selectedCount} product categories.`;
                }
            } else if (syncType === 'orders') {
                const fromDate = document.getElementById('orders-from-date').value;
                document.getElementById('orders_sync_from_date').value = fromDate;
                
                
                const descriptionElem = document.querySelector('.finalpos-sync-category[data-sync-type="orders"] .finalpos-text-small');
                if (fromDate) {
                    
                    const thirtyDaysAgo = new Date();
                    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
                    const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().split('T')[0];
                    
                    if (fromDate === thirtyDaysAgoStr) {
                        descriptionElem.textContent = 'Syncing orders from the last 30 days.';
                    } else {
                        descriptionElem.textContent = `Syncing orders from ${fromDate}.`;
                    }
                } else {
                    descriptionElem.textContent = 'Syncing all orders.';
                }
            }
            
            
            modal.style.display = 'none';
        });
    });
    
    
    window.addEventListener('click', function(event) {
        document.querySelectorAll('.finalpos-modal').forEach(modal => {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        });
    });
    
    
    updateSelectAllStatus();
});
