    let currentPage = 1;
    const itemsPerPage = 50;
    let allSiteElements = []; // Store all site elements once rendered by Jekyll
    let filteredSiteElements = [];
    let currentFilter = 'all';

    function initializeSites() {
      // Delay execution slightly to ensure all DOM elements are parsed
      setTimeout(() => {
        allSiteElements = Array.from(document.querySelectorAll('#sites-container .site-item'));
        console.log('Initialized allSiteElements (after delay):', allSiteElements.length, 'elements found.'); // Debug log
        
        // Make sure all elements are visible initially before filtering
        allSiteElements.forEach(el => el.style.display = 'flex'); 
        applyFilter('all');
      }, 0); // A 0ms timeout defers execution until after current script block and DOM updates
    }

    function renderSites() {
      const container = document.getElementById('sites-container');
      const statusElement = document.getElementById('sites-status');
      const startIndex = (currentPage - 1) * itemsPerPage;
      const endIndex = startIndex + itemsPerPage;

      allSiteElements.forEach(el => el.style.display = 'none'); // Hide all initially

      let visibleCount = 0;
      for (let i = 0; i < filteredSiteElements.length; i++) {
        if (i >= startIndex && i < endIndex) {
          filteredSiteElements[i].style.display = 'flex'; // Show only current page items
          visibleCount++;
        }
      }

      // Update screen reader status
      const totalSites = filteredSiteElements.length;
      const currentFilterName = getCurrentFilterName();
      const statusMessage = `Showing ${visibleCount} of ${totalSites} ${currentFilterName} sites on page ${currentPage}`;
      statusElement.textContent = statusMessage;

      updatePagination();
      
      // Announce filter change to screen readers
      if (window.lastFilterAnnouncement !== statusMessage) {
        setTimeout(() => {
          statusElement.textContent = statusMessage;
        }, 100);
        window.lastFilterAnnouncement = statusMessage;
      }
    }

    function getCurrentFilterName() {
      const filterNames = {
        'all': 'All',
        'popular': 'Popular',
        'social': 'Social Media',
        'professional': 'Professional',
        'nsfw': 'Adult Content',
        'other': 'Other'
      };
      return filterNames[currentFilter] || 'Filtered';
    }

    function updateFilterIndicator() {
      const indicator = document.getElementById('filter-indicator');
      const indicatorText = document.getElementById('filter-indicator-text');
      const searchInput = document.getElementById('search-input');
      const searchQuery = searchInput.value.trim();
      
      // Check if we have an active filter or search
      const hasActiveFilter = currentFilter !== 'all';
      const hasActiveSearch = searchQuery !== '';
      
      if (hasActiveFilter || hasActiveSearch) {
        let text = '';
        
        if (hasActiveSearch) {
          text = `Search: "${searchQuery}"`;
          if (hasActiveFilter) {
            text += ` in ${getCurrentFilterName()} sites`;
          }
        } else if (hasActiveFilter) {
          text = `Filter: ${getCurrentFilterName()} sites`;
        }
        
        indicatorText.textContent = text;
        indicator.classList.remove('hidden');
        indicator.setAttribute('aria-hidden', 'false');
      } else {
        indicator.classList.add('hidden');
        indicator.setAttribute('aria-hidden', 'true');
      }
    }

    function clearFilter() {
      // Clear search input
      document.getElementById('search-input').value = '';
      
      // Reset to "All Sites" filter
      document.querySelectorAll('.filter-btn').forEach(b => {
        b.classList.remove('active');
        b.setAttribute('aria-pressed', 'false');
      });
      
      const allButton = document.querySelector('[data-filter="all"]');
      allButton.classList.add('active');
      allButton.setAttribute('aria-pressed', 'true');
      
      // Apply filter
      currentFilter = 'all';
      applyFilter('all');
      
      // Announce to screen readers
      announceToScreenReader('Filters and search cleared, showing all sites');
      
      // Focus the search input for better UX
      document.getElementById('search-input').focus();
    }

    function updatePagination() {
      const totalPages = Math.ceil(filteredSiteElements.length / itemsPerPage);
      document.getElementById('page-info').textContent = `Page ${currentPage} of ${totalPages}`;
      document.getElementById('prev-page').disabled = currentPage === 1;
      document.getElementById('next-page').disabled = currentPage === totalPages;
    }

    function applyFilter(filter) {
      currentFilter = filter;
      currentPage = 1;
      
      filteredSiteElements = allSiteElements.filter(siteElement => {
        const isNSFW = siteElement.dataset.isNsfw === 'true';
        const category = siteElement.dataset.category;
        const isPopular = siteElement.dataset.isPopular === 'true';

        if (filter === 'popular') {
          return isPopular;
        } else if (filter === 'nsfw') {
          return isNSFW;
        } else if (filter !== 'all') {
          return category === filter;
        }
        return true; // 'all' filter
      });

      // Sort alphabetically
      filteredSiteElements.sort((a, b) => a.dataset.siteName.localeCompare(b.dataset.siteName));

      renderSites();
      updateFilterIndicator();
    }

    function searchSites(query) {
      const lowerCaseQuery = query.toLowerCase();
      filteredSiteElements = allSiteElements.filter(siteElement => 
        siteElement.dataset.siteName.toLowerCase().includes(lowerCaseQuery)
      );

      // Sort alphabetically
      filteredSiteElements.sort((a, b) => a.dataset.siteName.localeCompare(b.dataset.siteName));

      currentPage = 1;
      renderSites();
      updateFilterIndicator();
    }

    function toggleMobileMenu() {
      const menu = document.getElementById('mobile-menu');
      const button = document.querySelector('[aria-controls="mobile-menu"]');
      const isExpanded = button.getAttribute('aria-expanded') === 'true';

      if (isExpanded) {
        menu.style.display = 'none';
        button.setAttribute('aria-expanded', 'false');
      } else {
        menu.style.display = 'block';
        button.setAttribute('aria-expanded', 'true');
      }
    }

    function toggleMobileSubMenu(subMenuId) {
      const subMenu = document.getElementById(subMenuId);
      const isExpanded = subMenu.style.display === 'block';
      subMenu.style.display = isExpanded ? 'none' : 'block';
    }

    // Event listeners
    document.addEventListener('DOMContentLoaded', () => {
      initializeSites();
      updateFilterIndicator();

      document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
          handleFilterChange(e.target);
        });
        
        btn.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handleFilterChange(e.target);
          }
          // Arrow key navigation for filter buttons
          if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
            e.preventDefault();
            navigateFilters(e.target, e.key === 'ArrowRight');
          }
        });
      });

      function handleFilterChange(button) {
        // Update visual state
        document.querySelectorAll('.filter-btn').forEach(b => {
          b.classList.remove('active');
          b.setAttribute('aria-pressed', 'false');
        });
        button.classList.add('active');
        button.setAttribute('aria-pressed', 'true');
        
        // Apply filter
        applyFilter(button.dataset.filter);
        
        // Announce to screen readers
        const filterName = getCurrentFilterName();
        announceToScreenReader(`Filter changed to ${filterName}`);
      }

      function navigateFilters(currentButton, moveRight) {
        const buttons = Array.from(document.querySelectorAll('.filter-btn'));
        const currentIndex = buttons.indexOf(currentButton);
        let nextIndex;
        
        if (moveRight) {
          nextIndex = (currentIndex + 1) % buttons.length;
        } else {
          nextIndex = (currentIndex - 1 + buttons.length) % buttons.length;
        }
        
        buttons[nextIndex].focus();
      }

      function announceToScreenReader(message) {
        const statusElement = document.getElementById('sites-status');
        const originalText = statusElement.textContent;
        statusElement.textContent = message;
        setTimeout(() => {
          statusElement.textContent = originalText;
        }, 1000);
      }

      document.getElementById('prev-page').addEventListener('click', () => {
        if (currentPage > 1) {
          currentPage--;
          renderSites();
          announceToScreenReader(`Moved to page ${currentPage}`);
          // Focus the first site item for screen reader navigation
          setTimeout(() => {
            const firstSite = document.querySelector('.site-item');
            if (firstSite) firstSite.focus();
          }, 100);
        }
      });

      document.getElementById('next-page').addEventListener('click', () => {
        const totalPages = Math.ceil(filteredSiteElements.length / itemsPerPage);
        if (currentPage < totalPages) {
          currentPage++;
          renderSites();
          announceToScreenReader(`Moved to page ${currentPage}`);
          // Focus the first site item for screen reader navigation
          setTimeout(() => {
            const firstSite = document.querySelector('.site-item');
            if (firstSite) firstSite.focus();
          }, 100);
        }
      });

      // Keyboard navigation for pagination
      document.getElementById('prev-page').addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          e.target.click();
        }
      });

      document.getElementById('next-page').addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          e.target.click();
        }
      });

      // Enhanced search with debouncing and accessibility
      let searchTimeout;
      document.getElementById('search-input').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
          const query = e.target.value.trim();
          if (query === '') {
            applyFilter(currentFilter);
            announceToScreenReader(`Showing all ${getCurrentFilterName()} sites`);
          } else {
            searchSites(query);
            announceToScreenReader(`Search results for "${query}": ${filteredSiteElements.length} sites found`);
          }
        }, 300);
      });

      // Clear filter button event listener
      document.getElementById('clear-filter').addEventListener('click', clearFilter);
      
      document.getElementById('clear-filter').addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          clearFilter();
        }
      });

      document.getElementById("year").textContent = new Date().getFullYear();

      // Close mobile menu when clicking outside
      document.addEventListener("click", function(event) {
        const menu = document.getElementById("mobile-menu");
        const button = event.target.closest("button[aria-label=\"Open navigation menu\"]");
        
        if (!menu.contains(event.target) && !button) {
          menu.style.display = 'none';
        }
      });

      // Add keyboard navigation for site items
      document.addEventListener('keydown', function(event) {
        const focusedElement = document.activeElement;
        
        // Navigate through site items with arrow keys
        if (focusedElement && focusedElement.classList.contains('site-item')) {
          const siteItems = Array.from(document.querySelectorAll('.site-item'));
          const currentIndex = siteItems.indexOf(focusedElement);
          let nextIndex;
          
          switch(event.key) {
            case 'ArrowDown':
            case 'ArrowRight':
              event.preventDefault();
              nextIndex = (currentIndex + 1) % siteItems.length;
              siteItems[nextIndex].focus();
              break;
            case 'ArrowUp':
            case 'ArrowLeft':
              event.preventDefault();
              nextIndex = (currentIndex - 1 + siteItems.length) % siteItems.length;
              siteItems[nextIndex].focus();
              break;
            case 'Home':
              event.preventDefault();
              siteItems[0].focus();
              break;
            case 'End':
              event.preventDefault();
              siteItems[siteItems.length - 1].focus();
              break;
          }
        }
        
        // Close mobile menu with Escape key
        if (event.key === 'Escape') {
          const menu = document.getElementById('mobile-menu');
          if (menu.style.display === 'block') {
            menu.style.display = 'none';
          }
        }
      });
      
      // Close menu when clicking on menu items
      document.querySelectorAll('#mobile-menu a').forEach(link => {
        link.addEventListener('click', function() {
          const menu = document.getElementById('mobile-menu');
          menu.style.display = 'none';
        });
      });
    });
