---
//src/components/ToolFilters.astro
import { getToolsData } from '../utils/dataService.js';

const data = await getToolsData();
const domains = data.domains;
const phases = data.phases;

const skillLevels = [...new Set(data.tools.map(tool => tool.skillLevel))].filter(Boolean).sort();
const platforms = [...new Set(data.tools.flatMap(tool => tool.platforms || []))].filter(Boolean).sort();
const licenses = [...new Set(data.tools.map(tool => tool.license))].filter(Boolean).sort();
const toolTypes = [...new Set(data.tools.map(tool => tool.type))].filter(Boolean).sort();
const accessTypes = [...new Set(data.tools.map(tool => tool.accessType))].filter(Boolean).sort();

const tagFrequency = data.tools.reduce((acc: Record<string, number>, tool: any) => {
  tool.tags.forEach((tag: string) => {
    acc[tag] = (acc[tag] || 0) + 1;
  });
  return acc;
}, {});

const sortedTags = Object.entries(tagFrequency)
  .sort(([,a], [,b]) => (b as number) - (a as number))
  .map(([tag]) => tag);
---

<div class="filters-container">
  <!-- Search Section -->
    <div class="filter-section">
      <div class="filter-card-compact">
        <div class="filter-header-compact">
          <h3>🔍 Suche</h3>
        </div>
        <div class="search-row">
          <div class="search-wrapper">
            <div class="search-icon">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"/>
                <line x1="21" y1="21" x2="16.65" y2="16.65"/>
              </svg>
            </div>
            <input 
              type="text" 
              id="search-input" 
              placeholder="Software, Beschreibung oder Tags durchsuchen..."
              class="search-input"
            />
            <button id="clear-search" class="search-clear hidden" title="Suche löschen">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"/>
                <line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
            </button>
          </div>
          
          <!-- Semantic Search Toggle - Inline -->
          <div id="semantic-search-container" class="semantic-search-inline hidden">
            <label class="semantic-toggle-wrapper" title="Semantische Suche verwendet Embeddings. Dadurch kann mit natürlicher Sprache/Begriffen gesucht werden, die Ergebnisse richten sich nach der cosinus-Distanz.">
              <input type="checkbox" id="semantic-search-enabled" disabled/>
              <div class="semantic-checkbox-custom"></div>
              <span class="semantic-toggle-label">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M9 11H5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2h-4"/>
                  <path d="M9 11V7a3 3 0 0 1 6 0v4"/>
                </svg>
                Semantisch
              </span>
            </label>
          </div>
        </div>
        
        <!-- Status Display -->
        <div id="semantic-status" class="semantic-status hidden">
          <span class="semantic-results-count"></span>
        </div>
      </div>
    </div>

  <!-- Primary Filters Section - ONLY Domain and Phase -->
  <div class="filter-section">
    <div class="filter-card-compact">
      <div class="filter-header-compact">
        <h3>🎯 Primäre Filter</h3>
        <button class="filter-reset" id="reset-primary" title="Primäre Filter zurücksetzen">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="1 4 1 10 7 10"/>
            <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>
          </svg>
        </button>
      </div>
      
      <div class="filter-grid-compact">
        <div class="filter-group">
          <label class="filter-label">Forensische Domäne</label>
          <select id="domain-select" class="filter-select">
            <option value="">Alle Domänen</option>
            {domains.map((domain: any) => (
              <option value={domain.id}>{domain.name}</option>
            ))}
          </select>
        </div>

        <div class="filter-group">
          <label class="filter-label">Untersuchungsphase</label>
          <select id="phase-select" class="filter-select">
            <option value="">Alle Phasen</option>
            {phases.map((phase: any) => (
              <option value={phase.id}>{phase.name}</option>
            ))}
          </select>
        </div>
      </div>
    </div>
  </div>

  <!-- Advanced Filters Section - COLLAPSIBLE -->
  <div class="filter-section">
    <div class="filter-card-compact">
      <div class="filter-header-compact">
        <h3>⚙️ Erweiterte Filter</h3>
        <div class="filter-header-controls">
          <button class="filter-reset" id="reset-advanced" title="Erweiterte Filter zurücksetzen">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="1 4 1 10 7 10"/>
              <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>
            </svg>
          </button>
          <button class="collapse-toggle" id="toggle-advanced" data-collapsed="true" title="Erweiterte Filter ein/ausblenden">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </button>
        </div>
      </div>
      
      <div class="collapsible-content hidden" id="advanced-filters-content">
        <div class="advanced-filters-compact">
          <div class="filter-grid-compact">
            <div class="filter-group">
              <label class="filter-label">Tool-Typ</label>
              <select id="type-select" class="filter-select">
                <option value="">Alle Typen</option>
                {toolTypes.map((type: string) => (
                  <option value={type}>{type}</option>
                ))}
              </select>
            </div>

            <div class="filter-group">
              <label class="filter-label">Skill Level</label>
              <select id="skill-select" class="filter-select">
                <option value="">Alle Level</option>
                {skillLevels.map((level: string) => (
                  <option value={level}>{level}</option>
                ))}
              </select>
            </div>

            <div class="filter-group">
              <label class="filter-label">Plattform</label>
              <select id="platform-select" class="filter-select">
                <option value="">Alle Plattformen</option>
                {platforms.map((platform: string) => (
                  <option value={platform}>{platform}</option>
                ))}
              </select>
            </div>

            <div class="filter-group">
              <label class="filter-label">Lizenztyp</label>
              <select id="license-select" class="filter-select">
                <option value="">Alle Lizenzen</option>
                {licenses.map((license: string) => (
                  <option value={license}>{license}</option>
                ))}
              </select>
            </div>

            <div class="filter-group">
              <label class="filter-label">Zugangsart</label>
              <select id="access-select" class="filter-select">
                <option value="">Alle Zugangsarten</option>
                {accessTypes.map((access: string) => (
                  <option value={access}>{access}</option>
                ))}
              </select>
            </div>
          </div>

          <div class="filter-toggles-compact">
            <label class="toggle-wrapper">
              <input type="checkbox" id="hosted-only" />
              <span class="toggle-label">🟣 Nur CC24-Server Tools</span>
            </label>
            
            <label class="toggle-wrapper">
              <input type="checkbox" id="knowledgebase-only" />
              <span class="toggle-label">📖 Nur Tools mit Knowledgebase</span>
            </label>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Tag Filters Section - COLLAPSIBLE -->
  <div class="filter-section">
    <div class="filter-card-compact">
      <div class="filter-header-compact">
        <h3>🏷️ Tag-Filter</h3>
        <div class="filter-header-controls">
          <button class="filter-reset" id="reset-tags" title="Tags zurücksetzen">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="1 4 1 10 7 10"/>
              <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>
            </svg>
          </button>
          <button class="collapse-toggle" id="toggle-tags" data-collapsed="true" title="Tag-Filter ein/ausblenden">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </button>
        </div>
      </div>
      
      <div class="collapsible-content hidden" id="tag-filters-content">
        <div class="tag-section">
          <div class="selected-tags" id="selected-tags"></div>
          <div class="tag-controls">
            <button id="tag-cloud-toggle" class="tag-toggle" data-expanded="false">
              Mehr zeigen
            </button>
          </div>
          <div class="tag-cloud" id="tag-cloud">
            {sortedTags.map((tag, index) => (
              <button 
                class="tag-cloud-item" 
                data-tag={tag}
                data-frequency={tagFrequency[tag]}
                data-index={index}
              >
                {tag}
                <span class="tag-frequency">({tagFrequency[tag]})</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- View Controls Section -->
  <div class="filter-section">
    <div class="filter-card-compact">
      <div class="filter-header-compact">
        <h3>👁️ Ansicht</h3>
        <div class="results-count">
          <span id="results-counter">Alle Tools</span>
        </div>
      </div>
      
      <div class="view-controls-compact">
        <button class="view-toggle active" data-view="grid">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="7" height="7"/>
            <rect x="14" y="3" width="7" height="7"/>
            <rect x="14" y="14" width="7" height="7"/>
            <rect x="3" y="14" width="7" height="7"/>
          </svg>
          <span>Kacheln</span>
        </button>
        
        <button class="view-toggle" data-view="matrix">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="4" height="4"/>
            <rect x="10" y="3" width="4" height="4"/>
            <rect x="17" y="3" width="4" height="4"/>
            <rect x="3" y="10" width="4" height="4"/>
            <rect x="10" y="10" width="4" height="4"/>
            <rect x="17" y="10" width="4" height="4"/>
            <rect x="3" y="17" width="4" height="4"/>
            <rect x="10" y="17" width="4" height="4"/>
            <rect x="17" y="17" width="4" height="4"/>
          </svg>
          <span>Matrix</span>
        </button>
        
        <button id="ai-view-toggle" class="btn btn-accent view-toggle" data-view="ai" style="display: none;">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 11H5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2h-4"/>
            <path d="M9 11V7a3 3 0 0 1 6 0v4"/>
          </svg>
          <span>Forensic-AI</span>
        </button>

        <button class="filter-reset-all" id="reset-all-filters">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="1 4 1 10 7 10"/>
            <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>
          </svg>
          <span>Alle Filter zurücksetzen</span>
        </button>
      </div>
    </div>
  </div>
</div>

<script define:vars={{ toolsData: data.tools, tagFrequency, sortedTags }}>
  window.toolsData = toolsData;  
  document.addEventListener('DOMContentLoaded', () => {
    const elements = {
      searchInput: document.getElementById('search-input'),
      clearSearch: document.getElementById('clear-search'),
      semanticContainer: document.getElementById('semantic-search-container'),
      semanticCheckbox: document.getElementById('semantic-search-enabled'),
      semanticStatus: document.getElementById('semantic-status'),
      semanticResultsCount: document.querySelector('.semantic-results-count'),
      domainSelect: document.getElementById('domain-select'),
      phaseSelect: document.getElementById('phase-select'),
      typeSelect: document.getElementById('type-select'),
      skillSelect: document.getElementById('skill-select'),
      platformSelect: document.getElementById('platform-select'),
      licenseSelect: document.getElementById('license-select'),
      accessSelect: document.getElementById('access-select'),
      hostedOnly: document.getElementById('hosted-only'),
      knowledgebaseOnly: document.getElementById('knowledgebase-only'),
      tagCloudItems: document.querySelectorAll('.tag-cloud-item'),
      tagCloud: document.getElementById('tag-cloud'),
      tagCloudToggle: document.getElementById('tag-cloud-toggle'),
      selectedTags: document.getElementById('selected-tags'),
      viewToggles: document.querySelectorAll('.view-toggle'),
      resultsCounter: document.getElementById('results-counter'),
      resetButtons: {
        primary: document.getElementById('reset-primary'),
        advanced: document.getElementById('reset-advanced'),
        tags: document.getElementById('reset-tags'),
        all: document.getElementById('reset-all-filters')
      },
      toggleAdvanced: document.getElementById('toggle-advanced'),
      toggleTags: document.getElementById('toggle-tags'),
      advancedContent: document.getElementById('advanced-filters-content'),
      tagContent: document.getElementById('tag-filters-content')
    };
    
    if (!elements.searchInput || !elements.domainSelect) {
      console.error('Critical filter elements not found');
      return;
    }
    
    let selectedTags = new Set();
    let selectedPhase = '';
    let isTagCloudExpanded = false;
    let semanticSearchEnabled = false;
    let semanticSearchAvailable = false;
    let lastSemanticResults = null;
    
    async function checkEmbeddingsAvailability() {
      try {
        const res = await fetch('/api/ai/embeddings-status');
        const { embeddings } = await res.json();
        semanticSearchAvailable = embeddings?.initialized;

        if (semanticSearchAvailable) {
          elements.semanticContainer.classList.remove('hidden');
          elements.semanticCheckbox.disabled = false;
        }
      } catch (err) {
        console.error('[EMBEDDINGS] Status check failed:', err);
      }
    }
    
    async function performSemanticSearch(query) {
      if (!semanticSearchAvailable || !query.trim()) {
        return null;
      }
      
      try {
        const response = await fetch('/api/search/semantic', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ query: query.trim() })
        });
        
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }
        
        const data = await response.json();
        return data.results || [];
      } catch (error) {
        console.error('[SEMANTIC] Search failed:', error);
        return null;
      }
    }

    function isToolHosted(tool) {
      return tool.projectUrl !== undefined && 
            tool.projectUrl !== null && 
            tool.projectUrl !== "" && 
            tool.projectUrl.trim() !== "";
    }
    
    function toggleCollapsible(toggleBtn, content, storageKey) {
      const isCollapsed = toggleBtn.getAttribute('data-collapsed') === 'true';
      const newState = !isCollapsed;
      
      toggleBtn.setAttribute('data-collapsed', newState.toString());
      
      if (newState) {
        content.classList.add('hidden');
        toggleBtn.style.transform = 'rotate(0deg)';
      } else {
        content.classList.remove('hidden');
        toggleBtn.style.transform = 'rotate(180deg)';
      }
      
      sessionStorage.setItem(storageKey, newState.toString());
    }
    
    function initializeCollapsible() {
      const advancedCollapsed = sessionStorage.getItem('advanced-collapsed') !== 'false';
      elements.toggleAdvanced.setAttribute('data-collapsed', advancedCollapsed.toString());
      if (advancedCollapsed) {
        elements.advancedContent.classList.add('hidden');
        elements.toggleAdvanced.style.transform = 'rotate(0deg)';
      } else {
        elements.advancedContent.classList.remove('hidden');
        elements.toggleAdvanced.style.transform = 'rotate(180deg)';
      }
      
      const tagsCollapsed = sessionStorage.getItem('tags-collapsed') !== 'false';
      elements.toggleTags.setAttribute('data-collapsed', tagsCollapsed.toString());
      if (tagsCollapsed) {
        elements.tagContent.classList.add('hidden');
        elements.toggleTags.style.transform = 'rotate(0deg)';
      } else {
        elements.tagContent.classList.remove('hidden');
        elements.toggleTags.style.transform = 'rotate(180deg)';
      }
    }
    
    function initTagCloud() {
      const visibleCount = 20;
      elements.tagCloudItems.forEach((item, index) => {
        if (index >= visibleCount) {
          item.style.display = 'none';
        }
      });
    }
    
    function toggleTagCloud() {
      isTagCloudExpanded = !isTagCloudExpanded;
      const visibleCount = 20;
      
      if (isTagCloudExpanded) {
        elements.tagCloud.classList.add('expanded');
        elements.tagCloudToggle.textContent = 'Weniger zeigen';
        elements.tagCloudToggle.setAttribute('data-expanded', 'true');
        
        elements.tagCloudItems.forEach(item => {
          if (!item.classList.contains('hidden')) {
            item.style.display = 'inline-flex';
          }
        });
      } else {
        elements.tagCloud.classList.remove('expanded');
        elements.tagCloudToggle.textContent = 'Mehr zeigen';
        elements.tagCloudToggle.setAttribute('data-expanded', 'false');
        
        let visibleIndex = 0;
        elements.tagCloudItems.forEach(item => {
          if (!item.classList.contains('hidden')) {
            if (visibleIndex < visibleCount) {
              item.style.display = 'inline-flex';
              visibleIndex++;
            } else {
              item.style.display = 'none';
            }
          }
        });
      }
    }
    
    function filterTagCloud() {
      const searchTerm = elements.searchInput.value.toLowerCase();
      let visibleCount = 0;
      const maxVisibleWhenCollapsed = 20;
      
      elements.tagCloudItems.forEach(item => {
        const tagName = item.getAttribute('data-tag').toLowerCase();
        const shouldShow = tagName.includes(searchTerm);
        
        if (shouldShow) {
          item.classList.remove('hidden');
          if (isTagCloudExpanded || visibleCount < maxVisibleWhenCollapsed) {
            item.style.display = 'inline-flex';
            visibleCount++;
          } else {
            item.style.display = 'none';
          }
        } else {
          item.classList.add('hidden');
          item.style.display = 'none';
        }
      });
      
      const hasHiddenTags = Array.from(elements.tagCloudItems).some(item => 
        !item.classList.contains('hidden') && item.style.display === 'none'
      );
      elements.tagCloudToggle.style.display = hasHiddenTags ? 'block' : 'none';
    }
    
    function updateSelectedTags() {
      if (selectedTags.size === 0) {
        elements.selectedTags.style.display = 'none';
        return;
      }
      
      elements.selectedTags.style.display = 'block';
      elements.selectedTags.innerHTML = `
        <div class="selected-tags-header">Ausgewählte Tags:</div>
        <div class="selected-tags-list">
          ${Array.from(selectedTags).map(tag => `
            <span class="selected-tag">
              ${tag}
              <button class="remove-tag" data-tag="${tag}">×</button>
            </span>
          `).join('')}
        </div>
      `;
      
      elements.selectedTags.querySelectorAll('.remove-tag').forEach(btn => {
        btn.addEventListener('click', () => {
          const tag = btn.getAttribute('data-tag');
          removeTag(tag);
        });
      });
    }
    
    function addTag(tag) {
      selectedTags.add(tag);
      document.querySelectorAll(`[data-tag="${tag}"]`).forEach(element => {
        element.classList.add('active');
      });
      updateSelectedTags();
      filterTools();
    }
    
    function removeTag(tag) {
      selectedTags.delete(tag);
      document.querySelectorAll(`[data-tag="${tag}"]`).forEach(element => {
        element.classList.remove('active');
      });
      updateSelectedTags();
      filterTools();
    }
    
    function updateResultsCounter(count) {
      const total = window.toolsData.length;
      elements.resultsCounter.textContent = count === total 
        ? `${total} Tools` 
        : `${count} von ${total} Tools`;
    }
    
    function updateSemanticStatus(results) {
      if (!elements.semanticStatus || !elements.semanticResultsCount) return;
      
      if (semanticSearchEnabled && results?.length > 0) {
        elements.semanticStatus.classList.remove('hidden');
        elements.semanticResultsCount.textContent = `${results.length} semantische Treffer`;
      } else {
        elements.semanticStatus.classList.add('hidden');
      }
    }
    
    async function filterTools() {
      const searchTerm = elements.searchInput.value.trim().toLowerCase();
      const selectedDomain = elements.domainSelect.value;
      const selectedPhaseFromSelect = elements.phaseSelect.value;
      const selectedType = elements.typeSelect.value;
      const selectedSkill = elements.skillSelect.value;
      const selectedPlatform = elements.platformSelect.value;
      const selectedLicense = elements.licenseSelect.value;
      const selectedAccess = elements.accessSelect.value;
      const hostedOnly = elements.hostedOnly.checked;
      const knowledgebaseOnly = elements.knowledgebaseOnly.checked;
      
      const activePhase = selectedPhaseFromSelect || selectedPhase;
      
      let filteredTools = window.toolsData;
      let semanticResults = null;
      
      if (semanticSearchEnabled && semanticSearchAvailable && searchTerm) {
        semanticResults = await performSemanticSearch(searchTerm);
        lastSemanticResults = semanticResults;
        
        if (semanticResults?.length > 0) {
          filteredTools = [...semanticResults];
        }
      } else {
        lastSemanticResults = null;
        
        if (searchTerm) {
          filteredTools = window.toolsData.filter(tool =>
            tool.name.toLowerCase().includes(searchTerm) ||
            tool.description.toLowerCase().includes(searchTerm) ||
            (tool.tags || []).some(tag => tag.toLowerCase().includes(searchTerm))
          );
        }
      }
      
      filteredTools = filteredTools.filter(tool => {
        if (selectedDomain && !(tool.domains || []).includes(selectedDomain)) {
          return false;
        }
        
        if (activePhase && !(tool.phases || []).includes(activePhase)) {
          return false;
        }
        
        if (selectedType && tool.type !== selectedType) {
          return false;
        }
        
        if (selectedSkill && tool.skillLevel !== selectedSkill) {
          return false;
        }
        
        if (selectedPlatform && !(tool.platforms || []).includes(selectedPlatform)) {
          return false;
        }
        
        if (selectedLicense && tool.license !== selectedLicense) {
          return false;
        }
        
        if (selectedAccess && tool.accessType !== selectedAccess) {
          return false;
        }
        
        if (hostedOnly && !isToolHosted(tool)) {
          return false;
        }
        
        if (knowledgebaseOnly && !tool.knowledgebase) {
          return false;
        }
        
        if (selectedTags.size > 0 && !Array.from(selectedTags).every(tag => (tool.tags || []).includes(tag))) {
          return false;
        }
        
        return true;
      });
      
      if (semanticSearchEnabled && lastSemanticResults) {
        filteredTools.sort(
          (a, b) => (b._semanticSimilarity || 0) - (a._semanticSimilarity || 0)
        );
      }

      const finalResults = semanticSearchEnabled && lastSemanticResults
        ? filteredTools
        : (searchTerm && window.prioritizeSearchResults
            ? window.prioritizeSearchResults(filteredTools, searchTerm)
            : filteredTools);
      
      updateResultsCounter(finalResults.length);
      updateSemanticStatus(lastSemanticResults);
      
      window.dispatchEvent(
        new CustomEvent('toolsFiltered', {
          detail: {
            tools: finalResults,
            semanticSearch: semanticSearchEnabled && !!lastSemanticResults,
          },
        })
      );
    }
    
    function resetPrimaryFilters() {
      elements.domainSelect.value = '';
      elements.phaseSelect.value = '';
      selectedPhase = '';
      filterTools();
    }
    
    function resetAdvancedFilters() {
      elements.typeSelect.value = '';
      elements.skillSelect.value = '';
      elements.platformSelect.value = '';
      elements.licenseSelect.value = '';
      elements.accessSelect.value = '';
      elements.hostedOnly.checked = false;
      elements.knowledgebaseOnly.checked = false;
      filterTools();
    }
    
    function resetTags() {
      selectedTags.clear();
      document.querySelectorAll('.tag-cloud-item').forEach(item => {
        item.classList.remove('active');
      });
      updateSelectedTags();
      filterTools();
    }
    
    function resetAllFilters() {
      elements.searchInput.value = '';
      elements.clearSearch.classList.add('hidden');
      elements.semanticCheckbox.checked = false;
      semanticSearchEnabled = false;
      lastSemanticResults = null;
      updateSemanticStatus(null);
      resetPrimaryFilters();
      resetAdvancedFilters();
      resetTags();
      filterTagCloud();
    }
    
    elements.searchInput.addEventListener('input', (e) => {
      const hasValue = e.target.value.length > 0;
      elements.clearSearch.classList.toggle('hidden', !hasValue);
      filterTagCloud();
      filterTools();
    });
    
    elements.clearSearch.addEventListener('click', () => {
      elements.searchInput.value = '';
      elements.clearSearch.classList.add('hidden');
      filterTagCloud();
      filterTools();
    });
    
    if (elements.semanticCheckbox) {
      elements.semanticCheckbox.addEventListener('change', (e) => {
        semanticSearchEnabled = e.target.checked;
        filterTools();
      });
    }
    
    [elements.domainSelect, elements.phaseSelect, elements.typeSelect, elements.skillSelect, 
     elements.platformSelect, elements.licenseSelect, elements.accessSelect].forEach(select => {
      if (select) {
        select.addEventListener('change', filterTools);
      }
    });
    
    [elements.hostedOnly, elements.knowledgebaseOnly].forEach(checkbox => {
      if (checkbox) {
        checkbox.addEventListener('change', filterTools);
      }
    });
    
    if (elements.tagCloudToggle) {
      elements.tagCloudToggle.addEventListener('click', toggleTagCloud);
    }
    
    elements.tagCloudItems.forEach(item => {
      item.addEventListener('click', () => {
        const tag = item.getAttribute('data-tag');
        if (selectedTags.has(tag)) {
          removeTag(tag);
        } else {
          addTag(tag);
        }
      });
    });
    
    elements.viewToggles.forEach(btn => {
      btn.addEventListener('click', () => {
        const view = btn.getAttribute('data-view');
        
        elements.viewToggles.forEach(b => {
          b.classList.toggle('active', b.getAttribute('data-view') === view);
        });
        
        if (window.switchToView) {
          window.switchToView(view);
        } else {
          console.error('switchToView function not available');
        }
        
        window.dispatchEvent(new CustomEvent('viewChanged', { 
          detail: view,
          triggeredByButton: true 
        }));
        
        setTimeout(() => {
          if (view === 'matrix') {
            filterTools();
          } else if (view === 'grid') {
            filterTools();
          }
        }, 100); 
      });
    });
    
    elements.resetButtons.primary.addEventListener('click', resetPrimaryFilters);
    elements.resetButtons.advanced.addEventListener('click', resetAdvancedFilters);
    elements.resetButtons.tags.addEventListener('click', resetTags);
    elements.resetButtons.all.addEventListener('click', resetAllFilters);
    
    elements.toggleAdvanced.addEventListener('click', () => {
      toggleCollapsible(elements.toggleAdvanced, elements.advancedContent, 'advanced-collapsed');
    });
    
    elements.toggleTags.addEventListener('click', () => {
      toggleCollapsible(elements.toggleTags, elements.tagContent, 'tags-collapsed');
    });
    
    window.clearTagFilters = resetTags;
    window.clearAllFilters = resetAllFilters;
    
    checkEmbeddingsAvailability();
    initializeCollapsible();
    initTagCloud();
    filterTagCloud();
    updateSelectedTags();
    
    setTimeout(() => {
      filterTools();
    }, 100);
  });
</script>