// Desktop Search Enhancement
// Ensures search functionality works properly on PC screens

class DesktopSearchManager {
    constructor() {
        this.isSearchOpen = false;
        this.searchToggle = null;
        this.searchBar = null;
        this.searchInput = null;
        this.searchForm = null;
        this.searchSubmit = null;
        this.init();
    }

    init() {
        // Wait for DOM to be fully loaded
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setup());
        } else {
            this.setup();
        }
    }

    setup() {
        this.findElements();
        this.setupEventListeners();
        this.ensureSearchBarExists();
    }

    findElements() {
        this.searchToggle = document.querySelector('.search-toggle');
        this.searchBar = document.querySelector('.search-bar');
        this.searchInput = document.querySelector('.search-input');
        this.searchForm = document.querySelector('.search-form');
        this.searchSubmit = document.querySelector('.search-submit');
    }

    ensureSearchBarExists() {
        // If search bar doesn't exist, create it
        if (!this.searchBar) {
            this.createSearchBar();
        }
    }

    createSearchBar() {
        const header = document.querySelector('.enhanced-header');
        if (!header) return;

        const searchBarHTML = `
            <div class="search-bar">
                <div class="container">
                    <div class="search-container">
                        <form class="search-form">
                            <div class="search-input-group">
                                <input type="text" class="search-input" placeholder="Search for products, categories..." name="q" autocomplete="off">
                                <button type="submit" class="search-submit">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;

        header.insertAdjacentHTML('afterend', searchBarHTML);
        this.findElements();
    }

    setupEventListeners() {
        // Search toggle button
        if (this.searchToggle) {
            this.searchToggle.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.toggleSearch();
            });
        }

        // Search form submission
        if (this.searchForm) {
            this.searchForm.addEventListener('submit', (e) => {
                e.preventDefault();
                const query = this.searchInput?.value?.trim();
                if (query) {
                    this.handleSearch(query);
                }
            });
        }

        // Search submit button
        if (this.searchSubmit) {
            this.searchSubmit.addEventListener('click', (e) => {
                e.preventDefault();
                const query = this.searchInput?.value?.trim();
                if (query) {
                    this.handleSearch(query);
                }
            });
        }

        // Search input enter key
        if (this.searchInput) {
            this.searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const query = e.target.value.trim();
                    if (query) {
                        this.handleSearch(query);
                    }
                }
            });

            // Real-time search suggestions (optional)
            this.searchInput.addEventListener('input', (e) => {
                const query = e.target.value.trim();
                if (query.length > 2) {
                    // Could implement search suggestions here
                    console.log('Search query:', query);
                }
            });
        }

        // Close search with Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.isSearchOpen) {
                this.closeSearch();
            }
        });

        // Close search when clicking outside
        document.addEventListener('click', (e) => {
            if (this.isSearchOpen && 
                this.searchBar && !this.searchBar.contains(e.target) && 
                this.searchToggle && !this.searchToggle.contains(e.target)) {
                this.closeSearch();
            }
        });

        // Handle window resize
        window.addEventListener('resize', () => {
            if (this.isSearchOpen && window.innerWidth < 1200) {
                this.closeSearch();
            }
        });
    }

    toggleSearch() {
        if (this.isSearchOpen) {
            this.closeSearch();
        } else {
            this.openSearch();
        }
    }

    openSearch() {
        if (!this.searchBar) {
            console.warn('Search bar not found');
            return;
        }

        // Add active class to search bar
        this.searchBar.classList.add('active');
        
        // Add body classes for styling
        document.body.classList.add('search-active', 'search-open');
        
        // Set state
        this.isSearchOpen = true;

        // Update toggle button state
        if (this.searchToggle) {
            this.searchToggle.classList.add('active');
            this.searchToggle.setAttribute('aria-expanded', 'true');
        }

        // Focus and select input after animation
        setTimeout(() => {
            if (this.searchInput) {
                this.searchInput.focus();
                this.searchInput.select();
            }
        }, 400);

        // Announce to screen readers
        this.announceToScreenReader('Search opened');
    }

    closeSearch() {
        if (!this.searchBar) return;

        // Remove active class from search bar
        this.searchBar.classList.remove('active');
        
        // Remove body classes
        document.body.classList.remove('search-active', 'search-open');
        
        // Set state
        this.isSearchOpen = false;

        // Update toggle button state
        if (this.searchToggle) {
            this.searchToggle.classList.remove('active');
            this.searchToggle.setAttribute('aria-expanded', 'false');
        }

        // Blur input
        if (this.searchInput) {
            this.searchInput.blur();
        }

        // Announce to screen readers
        this.announceToScreenReader('Search closed');
    }

    handleSearch(query) {
        if (!query || !query.trim()) {
            console.warn('Empty search query');
            return;
        }

        const trimmedQuery = query.trim();
        
        // Close search if open
        if (this.isSearchOpen) {
            this.closeSearch();
        }

        // Add loading state
        this.showSearchLoading();

        // Navigate to search results
        try {
            const searchUrl = `/products?search=${encodeURIComponent(trimmedQuery)}`;
            window.location.href = searchUrl;
        } catch (error) {
            console.error('Search navigation error:', error);
            this.hideSearchLoading();
        }
    }

    showSearchLoading() {
        if (this.searchSubmit) {
            this.searchSubmit.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            this.searchSubmit.disabled = true;
        }
        
        if (this.searchInput) {
            this.searchInput.disabled = true;
        }
    }

    hideSearchLoading() {
        if (this.searchSubmit) {
            this.searchSubmit.innerHTML = '<i class="fas fa-search"></i>';
            this.searchSubmit.disabled = false;
        }
        
        if (this.searchInput) {
            this.searchInput.disabled = false;
        }
    }

    announceToScreenReader(message) {
        // Create temporary element for screen reader announcement
        const announcement = document.createElement('div');
        announcement.setAttribute('aria-live', 'polite');
        announcement.setAttribute('aria-atomic', 'true');
        announcement.className = 'sr-only';
        announcement.textContent = message;
        
        document.body.appendChild(announcement);
        
        setTimeout(() => {
            document.body.removeChild(announcement);
        }, 1000);
    }

    // Public method to programmatically open search
    openSearchProgrammatically() {
        this.openSearch();
    }

    // Public method to programmatically close search
    closeSearchProgrammatically() {
        this.closeSearch();
    }

    // Public method to check if search is open
    isSearchOpened() {
        return this.isSearchOpen;
    }
}

// Initialize desktop search when DOM is ready
let desktopSearchManager;

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        desktopSearchManager = new DesktopSearchManager();
    });
} else {
    desktopSearchManager = new DesktopSearchManager();
}

// Make available globally for debugging
window.desktopSearchManager = desktopSearchManager;

// Additional utility functions
function initializeDesktopSearch() {
    if (!desktopSearchManager) {
        desktopSearchManager = new DesktopSearchManager();
    }
}

function openDesktopSearch() {
    if (desktopSearchManager) {
        desktopSearchManager.openSearchProgrammatically();
    }
}

function closeDesktopSearch() {
    if (desktopSearchManager) {
        desktopSearchManager.closeSearchProgrammatically();
    }
}

// Export for module systems if needed
if (typeof module !== 'undefined' && module.exports) {
    module.exports = DesktopSearchManager;
}