(function () {
  'use strict';

  var GUIDE_ID = 'search-no-result-guide';
  var timer = null;
  var pollTimer = null;

  function getLang() {
    return (document.documentElement.lang || 'zh-CN').startsWith('en') ? 'en' : 'zh';
  }

  function createGuide() {
    var lang = getLang();
    var guide = document.createElement('div');
    guide.id = GUIDE_ID;
    guide.className = 'search-no-result-guide';

    if (lang === 'en') {
      guide.innerHTML =
        '<div class="sr-guide-title">Try these popular docs:</div>' +
        '<div class="sr-guide-chips">' +
          '<a class="sr-guide-chip" href="/DevOps引擎/引擎简介">DevOps Pipeline</a>' +
          '<a class="sr-guide-chip" href="/代码库管理/Webhook">Webhook</a>' +
          '<a class="sr-guide-chip" href="/合并请求/合并请求简介">Pull Request</a>' +
          '<a class="sr-guide-chip" href="/组织管理/组织简介">Organization</a>' +
        '</div>' +
        '<div class="sr-guide-footer">' +
          'Still can\'t find it? <a class="sr-guide-link" href="https://forum.gitlink.org.cn" target="_blank" rel="noopener">Ask on GitLink Forum</a>' +
        '</div>';
    } else {
      guide.innerHTML =
        '<div class="sr-guide-title">试试浏览这些热门文档：</div>' +
        '<div class="sr-guide-chips">' +
          '<a class="sr-guide-chip" href="/DevOps引擎/引擎简介">DevOps 流水线</a>' +
          '<a class="sr-guide-chip" href="/代码库管理/Webhook">Webhook 配置</a>' +
          '<a class="sr-guide-chip" href="/合并请求/合并请求简介">合并请求</a>' +
          '<a class="sr-guide-chip" href="/组织管理/组织简介">组织管理</a>' +
        '</div>' +
        '<div class="sr-guide-footer">' +
          '仍未找到？到 <a class="sr-guide-link" href="https://forum.gitlink.org.cn" target="_blank" rel="noopener">GitLink 论坛</a> 发帖提问' +
        '</div>';
    }

    return guide;
  }

  function removeGuide() {
    var guide = document.getElementById(GUIDE_ID);
    if (guide) guide.remove();
    if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  }

  function hasResults() {
    var listbox = document.querySelector('[role="listbox"]');
    if (!listbox) return false;

    // 检查是否有除了我们引导之外的子元素
    var hasOtherChildren = false;
    var children = listbox.children;
    for (var i = 0; i < children.length; i++) {
      if (children[i].id !== GUIDE_ID) { hasOtherChildren = true; break; }
    }
    if (!hasOtherChildren) return false;

    // 有子元素，但如果是无结果文字说明仍是无结果状态
    var text = (listbox.textContent || '').trim();
    if (text.includes('没有找到') || text.includes('没有结果') ||
        text.includes('No results') || text.includes('未找到')) {
      return false;
    }

    return true;
  }

  function showGuide() {
    if (document.getElementById(GUIDE_ID)) return;

    var listbox = document.querySelector('[role="listbox"]');
    if (!listbox) return;

    // 安全检查：如果此时已经有结果了，不要替换
    if (hasResults()) return;

    listbox.innerHTML = '';
    listbox.appendChild(createGuide());

    if (pollTimer) clearInterval(pollTimer);
    pollTimer = setInterval(function () {
      var input = document.querySelector('.navbar__search input');
      if (!input || input.value.trim().length === 0) { removeGuide(); return; }
      if (hasResults()) { removeGuide(); }
    }, 300);
  }

  function check() {
    removeGuide();
    clearTimeout(timer);

    timer = setTimeout(function () {
      var input = document.querySelector('.navbar__search input');
      if (!input || input.value.trim().length === 0) return;
      if (!hasResults()) {
        showGuide();
      }
    }, 800);
  }

  function onInput(e) {
    if (!e.target.closest('.navbar__search')) return;
    check();
  }

  // 搜索框已有文字时点击搜索框：反复检查，等插件渲染完再决定
  function onFocus(e) {
    if (!e.target.closest('.navbar__search input')) return;
    if (e.target.value.trim().length === 0) return;

    var attempts = 0;
    var maxAttempts = 6;

    function checkFocus() {
      if (hasResults()) return; // 结果出现了，不用引导
      var input = document.querySelector('.navbar__search input');
      if (!input || input.value.trim().length === 0) return;
      attempts++;
      if (attempts < maxAttempts) {
        setTimeout(checkFocus, 300);
      } else if (!hasResults()) {
        showGuide();
      }
    }

    setTimeout(checkFocus, 400);
  }

  function onClickOutside(e) {
    var guide = document.getElementById(GUIDE_ID);
    if (!guide) return;
    var searchEl = document.querySelector('.navbar__search');
    if (searchEl && !searchEl.contains(e.target)) { removeGuide(); }
  }

  function init() {
    document.addEventListener('input', onInput, true);
    document.addEventListener('focus', onFocus, true);
    document.addEventListener('click', onClickOutside, true);
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') removeGuide();
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
