
  (() => {
    const allData = JSON.parse(document.getElementById('tools-data')?.textContent || '{}');
    const input = document.getElementById('topbar-search-input');
    const dropdown = document.getElementById('topbar-search-dropdown');
    const resultsList = document.getElementById('topbar-search-results');
    if (!input || !dropdown || !resultsList) return;

    const normalizeLocale = (value) => {
      const lower = String(value || '').toLowerCase();
      if (lower === 'zh-tw' || lower === 'zh-hk') return 'zh-TW';
      if (lower.startsWith('zh-')) return 'zh-CN';
      if (lower.startsWith('en')) return 'en';
      return ['fr', 'de', 'ru', 'th'].includes(lower) ? lower : 'zh-CN';
    };
    let locale = normalizeLocale(document.documentElement.lang);
    let active = -1;
    let items = [];
    const data = () => allData[locale] || allData['zh-CN'] || [];
    const text = {
      empty: {
        'zh-CN': '没有匹配的工具',
        'zh-TW': '沒有匹配的工具',
        en: 'No matching tools',
        fr: 'Aucun outil correspondant',
        de: 'Keine passenden Tools',
        ru: 'Нет подходящих инструментов',
        th: 'ไม่พบเครื่องมือที่ตรงกัน',
      },
    };

    function match(query) {
      const q = query.toLowerCase().trim();
      const list = data();
      if (!q) return list.slice(0, 8);
      return list.filter((t) =>
        t.t.toLowerCase().includes(q) ||
        t.d.toLowerCase().includes(q) ||
        t.k.toLowerCase().includes(q) ||
        t.c.toLowerCase().includes(q)
      ).slice(0, 8);
    }

    function render(results) {
      items = results;
      active = -1;
      if (!results.length) {
        resultsList.innerHTML = `<li class="topbar-search-empty">${text.empty[locale]}</li>`;
        return;
      }
      resultsList.innerHTML = results.map((t, i) =>
        `<li class="topbar-search-item" role="option" data-idx="${i}" data-href="${t.h}">
          <span class="topbar-search-item-cat">${t.c}</span>
          <strong>${t.t}</strong>
          <span class="topbar-search-item-desc">${t.d}</span>
        </li>`
      ).join('');
    }

    function show() {
      dropdown.hidden = false;
      input.setAttribute('aria-expanded', 'true');
    }

    function hide() {
      dropdown.hidden = true;
      input.setAttribute('aria-expanded', 'false');
      active = -1;
    }

    function highlight(idx) {
      const els = resultsList.querySelectorAll('.topbar-search-item');
      els.forEach((el, i) => el.classList.toggle('is-active', i === idx));
      active = idx;
    }

    function navigate(href) {
      if (href) window.location.href = href;
    }

    input.addEventListener('focus', () => {
      render(match(input.value));
      show();
    });

    input.addEventListener('input', () => {
      render(match(input.value));
      show();
    });

    input.addEventListener('keydown', (e) => {
      if (!dropdown.hidden) {
        if (e.key === 'ArrowDown') {
          e.preventDefault();
          highlight(Math.min(active + 1, items.length - 1));
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          highlight(Math.max(active - 1, 0));
        } else if (e.key === 'Enter') {
          e.preventDefault();
          if (active >= 0 && items[active]) {
            navigate(items[active].h);
          }
        } else if (e.key === 'Escape') {
          e.preventDefault();
          hide();
          input.blur();
        }
      }
    });

    resultsList.addEventListener('click', (e) => {
      const li = e.target.closest('.topbar-search-item');
      if (li) navigate(li.dataset.href);
    });

    document.addEventListener('click', (e) => {
      if (!e.target.closest('#topbar-search')) hide();
    });

    document.addEventListener('keydown', (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        input.focus();
        input.select();
      }
    });

    document.getElementById('topbar-search-form')?.addEventListener('submit', (e) => {
      e.preventDefault();
      if (active >= 0 && items[active]) {
        navigate(items[active].h);
      } else if (items.length) {
        navigate(items[0].h);
      }
    });

    window.addEventListener('taitan:locale-change', (event) => {
      locale = normalizeLocale(event.detail?.locale);
      if (!dropdown.hidden) render(match(input.value));
    });
  })();

