/**
 * Modern Professional Category Filter
 * Enhanced JavaScript functionality for the category filter
 */

class ModernCategoryFilter {
    constructor(options = {}) {
        this.options = {
            containerSelector: options.containerSelector || '.category-filter-container',
            searchInputSelector: options.searchInputSelector || '#category-search',
            clearButtonSelector: options.clearButtonSelector || '#clear-filter',
            activeCategoryCountSelector: options.activeCategoryCountSelector || '#active-category-count',
            onCategoryChange: options.onCategoryChange || null,
            animationDuration: options.animationDuration || 300
        };

        this.activeCategory = null;
        this.searchTerm = '';
        this.isInitialized = false;

        this.init();
    }

    init() {
        if (this.isInitialized) return;

        this.containerEl = document.querySelector(this.options.containerSelector);
        this.searchInput = document.querySelector(this.options.searchInputSelector);
        this.clearButton = document.querySelector(this.options.clearButtonSelector);
        this.activeCategoryCount = document.querySelector(this.options.activeCategoryCountSelector);

        if (!this.containerEl) {
            console.warn('Modern Category Filter: Container not found');
            return;
        }

        this.attachEventListeners();
        this.setupAccessibility();
        this.updateActiveCategoryCount();
        this.isInitialized = true;

        // Setup debounced search
        this.debouncedSearch = this.debounceSearch(this.handleSearch.bind(this), 300);

        console.log('Modern Category Filter initialized successfully');
    }

    attachEventListeners() {
        // Search functionality
        if (this.searchInput) {
            this.searchInput.addEventListener('input', (e) => {
                this.debouncedSearch(e.target.value);
            });

            this.searchInput.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    this.clearSearch();
                }
            });
        }

        // Clear button
        if (this.clearButton) {
            this.clearButton.addEventListener('click', () => {
                this.clearFilters();
            });
        }

        // Category clicks
        this.containerEl.addEventListener('click', (e) => {
            const parentCategory = e.target.closest('.parent-category');
            const childCategory = e.target.closest('.child-category');

            if (parentCategory) {
                this.handleParentCategoryClick(parentCategory, e);
            } else if (childCategory) {
                this.handleChildCategoryClick(childCategory, e);
            }
        });

        // Keyboard navigation
        this.containerEl.addEventListener('keydown', (e) => {
            this.handleKeyboardNavigation(e);
        });
    }

    handleSearch(searchTerm) {
        this.searchTerm = searchTerm.toLowerCase().trim();
        this.filterCategories();
    }

    filterCategories() {
        const categoryItems = this.containerEl.querySelectorAll('.category-filter-item');
        const noResultsEl = this.containerEl.querySelector('.no-categories-found');
        let visibleCount = 0;

        categoryItems.forEach(item => {
            const categoryName = item.dataset.categoryName || '';
            const childCategories = item.querySelectorAll('.child-category');
            let hasVisibleChildren = false;

            // Check child categories
            childCategories.forEach(child => {
                const childName = child.dataset.categoryName || '';
                const isChildVisible = !this.searchTerm || childName.includes(this.searchTerm);

                if (isChildVisible) {
                    child.style.display = 'flex';
                    hasVisibleChildren = true;
                } else {
                    child.style.display = 'none';
                }
            });

            // Check parent category
            const isParentVisible = !this.searchTerm || categoryName.includes(this.searchTerm);
            const shouldShowItem = isParentVisible || hasVisibleChildren;

            if (shouldShowItem) {
                item.style.display = 'block';
                item.classList.add('category-item-enter');
                visibleCount++;

                // If search matches children, expand parent
                if (hasVisibleChildren && this.searchTerm) {
                    this.expandCategory(item.querySelector('.parent-category'), false);
                }
            } else {
                item.style.display = 'none';
                item.classList.remove('category-item-enter');
            }
        });

        // Show/hide no results message
        if (noResultsEl) {
            if (visibleCount === 0 && this.searchTerm) {
                noResultsEl.classList.remove('d-none');
            } else {
                noResultsEl.classList.add('d-none');
            }
        }
    }

    handleParentCategoryClick(parentCategory, event) {
        const categoryId = parentCategory.dataset.categoryId;
        const expandIcon = parentCategory.querySelector('.expand-icon');
        const childrenContainer = parentCategory.parentElement.querySelector('.children-container');

        // Check if clicking on expand icon, category meta, or category count
        const isExpandIconClick = event.target.closest('.expand-icon') || event.target.classList.contains('expand-icon');
        const isCategoryMetaClick = event.target.closest('.category-meta') || event.target.classList.contains('category-meta');
        const isCategoryCountClick = event.target.closest('.category-count') || event.target.classList.contains('category-count');
        const hasChildren = childrenContainer && childrenContainer.querySelector('.child-category');

        console.log('Parent category click:', {
            categoryId,
            isExpandIconClick,
            isCategoryMetaClick,
            isCategoryCountClick,
            hasChildren,
            targetElement: event.target.className
        });

        if ((isExpandIconClick || isCategoryMetaClick || isCategoryCountClick) && hasChildren) {
            // Just toggle expansion for icon/meta/count clicks
            event.preventDefault();
            event.stopPropagation();
            this.toggleCategoryExpansion(parentCategory);
        } else if (!isCategoryCountClick) {
            // Select category for content clicks (but not count clicks)
            this.selectCategory(categoryId, parentCategory, true);

            // Also expand if has children
            if (hasChildren && !parentCategory.classList.contains('expanded')) {
                this.expandCategory(parentCategory);
            }
        }
    }

    handleChildCategoryClick(childCategory, event) {
        const categoryId = childCategory.dataset.categoryId;

        console.log('Child category click:', {
            categoryId,
            element: childCategory,
            targetClass: event.target.className
        });

        // Check if clicking on category count
        const isCategoryCountClick = event.target.closest('.category-count') || event.target.classList.contains('category-count');

        if (!isCategoryCountClick) {
            this.selectCategory(categoryId, childCategory, false);
        }
    }

    toggleCategoryExpansion(parentCategory) {
        const childrenContainer = parentCategory.parentElement.querySelector('.children-container');
        const expandIcon = parentCategory.querySelector('.expand-icon');

        if (!childrenContainer) return;

        const isExpanded = !childrenContainer.classList.contains('hidden');

        if (isExpanded) {
            this.collapseCategory(parentCategory);
        } else {
            this.expandCategory(parentCategory);
        }
    }

    expandCategory(parentCategory, animate = true) {
        const childrenContainer = parentCategory.parentElement.querySelector('.children-container');
        const expandIcon = parentCategory.querySelector('.expand-icon');

        if (!childrenContainer) return;

        parentCategory.classList.add('expanded');
        childrenContainer.classList.remove('hidden');

        if (expandIcon) {
            expandIcon.style.transform = 'rotate(180deg)';
        }

        if (animate) {
            // Smooth animation
            childrenContainer.style.maxHeight = '0px';
            childrenContainer.style.opacity = '0';

            requestAnimationFrame(() => {
                childrenContainer.style.transition = `all ${this.options.animationDuration}ms cubic-bezier(0.4, 0, 0.2, 1)`;
                childrenContainer.style.maxHeight = childrenContainer.scrollHeight + 'px';
                childrenContainer.style.opacity = '1';
            });
        }
    }

    collapseCategory(parentCategory) {
        const childrenContainer = parentCategory.parentElement.querySelector('.children-container');
        const expandIcon = parentCategory.querySelector('.expand-icon');

        if (!childrenContainer) return;

        parentCategory.classList.remove('expanded');

        if (expandIcon) {
            expandIcon.style.transform = 'rotate(0deg)';
        }

        // Smooth animation
        childrenContainer.style.transition = `all ${this.options.animationDuration}ms cubic-bezier(0.4, 0, 0.2, 1)`;
        childrenContainer.style.maxHeight = '0px';
        childrenContainer.style.opacity = '0';

        setTimeout(() => {
            childrenContainer.classList.add('hidden');
            childrenContainer.style.transition = '';
            childrenContainer.style.maxHeight = '';
            childrenContainer.style.opacity = '';
        }, this.options.animationDuration);
    }

    selectCategory(categoryId, categoryElement, isParent) {
        console.log('Selecting category:', {
            categoryId,
            isParent,
            element: categoryElement,
            hasCallback: !!this.options.onCategoryChange
        });

        // Clear previous selection - this is important to prevent multiple categories being active
        this.clearActiveStates();

        // Set new active category
        this.activeCategory = categoryId;
        categoryElement.classList.add('active');

        // Update counter
        this.updateActiveCategoryCount();

        // Trigger callback
        if (this.options.onCategoryChange) {
            const options = {
                isParent: isParent,
                element: categoryElement,
                include_children: isParent, // Only include children for parent categories
                resetPrevious: false
            };

            console.log('Triggering onCategoryChange callback with options:', options);
            console.log('Category selection details:', {
                categoryId: categoryId,
                isParent: isParent,
                include_children: options.include_children
            });

            this.options.onCategoryChange(categoryId, options);
        } else {
            console.warn('No onCategoryChange callback defined!');
        }

        // Add visual feedback
        this.addSelectionFeedback(categoryElement);
    }

    clearActiveStates() {
        const activeElements = this.containerEl.querySelectorAll('.active');
        activeElements.forEach(el => {
            el.classList.remove('active');
        });
    }

    clearFilters() {
        this.activeCategory = null;
        this.clearActiveStates();
        this.clearSearch();
        this.collapseAllCategories();
        this.updateActiveCategoryCount();

        // Trigger callback
        if (this.options.onCategoryChange) {
            this.options.onCategoryChange(null, {
                include_children: true,
                resetPrevious: true
            });
        }
    }

    clearSearch() {
        if (this.searchInput) {
            this.searchInput.value = '';
        }
        this.searchTerm = '';
        this.filterCategories();
    }

    collapseAllCategories() {
        const parentCategories = this.containerEl.querySelectorAll('.parent-category.expanded');
        parentCategories.forEach(parent => {
            this.collapseCategory(parent);
        });
    }

    updateActiveCategoryCount() {
        const count = this.activeCategory ? 1 : 0;
        if (this.activeCategoryCount) {
            this.activeCategoryCount.textContent = count;

            // Add animation
            this.activeCategoryCount.style.transform = 'scale(1.2)';
            setTimeout(() => {
                this.activeCategoryCount.style.transform = 'scale(1)';
            }, 150);
        }
    }

    addSelectionFeedback(element) {
        // Add ripple effect
        const ripple = document.createElement('div');
        ripple.className = 'selection-ripple';
        ripple.style.cssText = `
            position: absolute;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.6);
            transform: scale(0);
            animation: ripple 0.6s linear;
            pointer-events: none;
        `;

        const rect = element.getBoundingClientRect();
        const size = Math.max(rect.width, rect.height);
        ripple.style.width = ripple.style.height = size + 'px';
        ripple.style.left = '50%';
        ripple.style.top = '50%';
        ripple.style.marginLeft = -size / 2 + 'px';
        ripple.style.marginTop = -size / 2 + 'px';

        element.style.position = 'relative';
        element.appendChild(ripple);

        setTimeout(() => {
            ripple.remove();
        }, 600);
    }

    handleKeyboardNavigation(event) {
        // Add keyboard navigation support
        const focusableElements = this.containerEl.querySelectorAll('.parent-category, .child-category');
        const currentIndex = Array.from(focusableElements).indexOf(document.activeElement);

        switch (event.key) {
            case 'ArrowDown':
                event.preventDefault();
                const nextIndex = Math.min(currentIndex + 1, focusableElements.length - 1);
                focusableElements[nextIndex]?.focus();
                break;
            case 'ArrowUp':
                event.preventDefault();
                const prevIndex = Math.max(currentIndex - 1, 0);
                focusableElements[prevIndex]?.focus();
                break;
            case 'Enter':
            case ' ':
                event.preventDefault();
                document.activeElement?.click();
                break;
        }
    }

    // Public methods
    getActiveCategory() {
        return this.activeCategory;
    }

    setActiveCategory(categoryId) {
        const categoryElement = this.containerEl.querySelector(`[data-category-id="${categoryId}"]`);
        if (categoryElement) {
            const isParent = categoryElement.classList.contains('parent-category');
            this.selectCategory(categoryId, categoryElement, isParent);
        }
    }

    updateCategoryCounts(counts) {
        if (!counts) return;

        Object.entries(counts).forEach(([categoryId, count]) => {
            const countElement = this.containerEl.querySelector(`[data-category-id="${categoryId}"] .category-count`);
            if (countElement) {
                const oldCount = parseInt(countElement.textContent) || 0;
                countElement.textContent = count;

                // Add appropriate styling based on count
                if (count === 0) {
                    countElement.classList.add('zero');
                } else {
                    countElement.classList.remove('zero');
                }

                // Add update animation if count changed
                if (oldCount !== count) {
                    countElement.classList.add('updated');
                    setTimeout(() => {
                        countElement.classList.remove('updated');
                    }, 400);
                }
            }
        });
    }

    // Enhanced search with highlighting
    highlightSearchTerm(text, searchTerm) {
        if (!searchTerm) return text;

        const regex = new RegExp(`(${searchTerm})`, 'gi');
        return text.replace(regex, '<span class="search-highlight">$1</span>');
    }

    // Add loading state
    setLoadingState(isLoading) {
        if (isLoading) {
            this.containerEl.classList.add('loading');
        } else {
            this.containerEl.classList.remove('loading');
        }
    }

    // Enhanced accessibility
    setupAccessibility() {
        // Add ARIA attributes
        const parentCategories = this.containerEl.querySelectorAll('.parent-category');
        parentCategories.forEach(parent => {
            const hasChildren = parent.parentElement.querySelector('.children-container');
            if (hasChildren) {
                parent.setAttribute('aria-expanded', 'false');
                parent.setAttribute('role', 'button');
                parent.setAttribute('tabindex', '0');
            }
        });

        // Add role to child categories
        const childCategories = this.containerEl.querySelectorAll('.child-category');
        childCategories.forEach(child => {
            child.setAttribute('role', 'button');
            child.setAttribute('tabindex', '0');
        });
    }

    // Performance optimization: debounced search
    debounceSearch(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
}

// Add CSS for ripple animation
const style = document.createElement('style');
style.textContent = `
    @keyframes ripple {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// Export for use
window.ModernCategoryFilter = ModernCategoryFilter;
