---
import { getToolsData } from '../utils/dataService.js';

const data = await getToolsData();
const scenarios = data.scenarios || [];

// Configuration
const maxDisplayed = 9;
const displayedScenarios = scenarios.slice(0, maxDisplayed);
---

<section id="targeted-section" class="targeted-section">
  <div class="targeted-header">
    <h3>Gezielte Tool-Suche</h3>
    <p class="targeted-subtitle">
      Finden Sie schnell das passende Werkzeug für Ihre spezifische Anforderung
    </p>
  </div>

  <div class="search-interface">
    <div class="search-box">
      <div class="search-icon">
        <svg width="20" height="20" 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" 
        class="targeted-search-input" 
        placeholder="z.B. 'Windows Registry analysieren' oder 'PCAP-Dateien auswerten'..."
        id="targeted-search-input"
      />
    </div>

    {scenarios.length > 0 && (
      <div class="search-suggestions" id="scenario-suggestions">
        {displayedScenarios.map((scenario) => (
          <div 
            class="suggestion-chip" 
            data-scenario-id={scenario.id}
            onclick={`applyScenarioSearch('${scenario.id}')`}
          >
            <span class="scenario-emoji">{scenario.icon}</span>
            <span class="scenario-text">{scenario.friendly_name}</span>
          </div>
        ))}
      </div>
    )}

    {scenarios.length > maxDisplayed && (
      <div class="more-scenarios">
        <button class="btn-more-scenarios" onclick="toggleAllScenarios()" id="more-scenarios-btn">
          + {scenarios.length - maxDisplayed} weitere Szenarien
        </button>
      </div>
    )}
  </div>

  <div class="targeted-tip">
    <p>
      <strong>Tipp:</strong> Die Szenarien durchsuchen automatisch nach passenden Tags und Beschreibungen.
      Für KI-gestützte Empfehlungen nutzen Sie den entsprechenden Modus.
    </p>
  </div>
</section>

<script define:vars={{ allScenarios: scenarios, maxDisplay: maxDisplayed }}>
  let showingAllScenarios = false;


  window.applyScenarioSearch = function(scenarioId) {
    console.log(`Applying scenario search: ${scenarioId}`);
    
    const clickedChip = document.querySelector(`[data-scenario-id="${scenarioId}"]`);
    const mainSearchInput = document.getElementById('search-input');
    
    if (!mainSearchInput) return;
    
    if (clickedChip && clickedChip.classList.contains('active')) {
      mainSearchInput.value = '';
      document.querySelectorAll('.suggestion-chip').forEach(chip => {
        chip.classList.remove('active');
      });
      
      const targetedInput = document.getElementById('targeted-search-input');
      if (targetedInput) {
        targetedInput.value = '';
      }
      
      const inputEvent = new Event('input', { bubbles: true });
      mainSearchInput.dispatchEvent(inputEvent);
      
      return;
    }
    
    mainSearchInput.value = scenarioId;
    
    const inputEvent = new Event('input', { bubbles: true });
    mainSearchInput.dispatchEvent(inputEvent);
    
    const gridToggle = document.querySelector('.view-toggle[data-view="grid"]');
    if (gridToggle && !gridToggle.classList.contains('active')) {
      gridToggle.click();
    }
    
    document.querySelectorAll('.suggestion-chip').forEach(chip => {
      chip.classList.remove('active');
    });
    if (clickedChip) {
      clickedChip.classList.add('active');
    }
    
    window.scrollToElementById('tools-grid');
  };

  window.toggleAllScenarios = function() {
    const suggestionsContainer = document.getElementById('scenario-suggestions');
    const moreBtn = document.getElementById('more-scenarios-btn');
    
    if (!showingAllScenarios) {
      const additionalScenarios = allScenarios.slice(maxDisplay);
      additionalScenarios.forEach(scenario => {
        const chip = document.createElement('div');
        chip.className = 'suggestion-chip additional-scenario';
        chip.setAttribute('data-scenario-id', scenario.id);
        chip.onclick = () => applyScenarioSearch(scenario.id);
        chip.innerHTML = `
          <span class="scenario-emoji">${scenario.icon}</span>
          <span class="scenario-text">${scenario.friendly_name}</span>
        `;
        suggestionsContainer.appendChild(chip);
      });
      
      moreBtn.textContent = 'Weniger anzeigen';
      showingAllScenarios = true;
    } else {
      document.querySelectorAll('.additional-scenario').forEach(chip => chip.remove());
      moreBtn.textContent = `+ ${allScenarios.length - maxDisplay} weitere Szenarien`;
      showingAllScenarios = false;
    }
  };

  document.addEventListener('DOMContentLoaded', () => {
    const targetedInput = document.getElementById('targeted-search-input');
    if (targetedInput) {
      targetedInput.addEventListener('input', (e) => {
        const mainSearchInput = document.getElementById('search-input');
        if (mainSearchInput && e.target.value.length > 2) {
          mainSearchInput.value = e.target.value;
          const inputEvent = new Event('input', { bubbles: true });
          mainSearchInput.dispatchEvent(inputEvent);
        }
      });
      
      targetedInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            const gridToggle = document.querySelector('.view-toggle[data-view="grid"]');
            if (gridToggle) {
            gridToggle.click();
            setTimeout(() => window.scrollToElementById('tools-grid'), 200);
            }
        }
      });
    }
  });
</script>