// 全局搜索浮层
let searchOverlay = null
let isSearchOpen = false

// 监听来自 background 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'toggleSearch') {
    toggleSearch()
  }
})

// 监听快捷键
document.addEventListener('keydown', (e) => {
  // Alt+K 打开搜索
  if (e.altKey && e.key === 'k') {
    e.preventDefault()
    toggleSearch()
  }

  // ESC 关闭搜索
  if (e.key === 'Escape' && isSearchOpen) {
    closeSearch()
  }
})

// 切换搜索
function toggleSearch() {
  if (isSearchOpen) {
    closeSearch()
  } else {
    openSearch()
  }
}

// 打开搜索
async function openSearch() {
  // 检查登录状态
  const { isLoggedIn } = await chrome.runtime.sendMessage({ action: 'getLoginStatus' })
  
  if (!isLoggedIn) {
    showToast('请先登录书签管理助手')
    return
  }

  if (searchOverlay) {
    searchOverlay.remove()
  }

  searchOverlay = createSearchOverlay()
  document.body.appendChild(searchOverlay)
  isSearchOpen = true

  // 聚焦输入框
  setTimeout(() => {
    const input = searchOverlay.querySelector('.bm-search-input')
    if (input) input.focus()
  }, 100)
}

// 关闭搜索
function closeSearch() {
  if (searchOverlay) {
    searchOverlay.classList.add('bm-fade-out')
    setTimeout(() => {
      searchOverlay?.remove()
      searchOverlay = null
    }, 200)
  }
  isSearchOpen = false
}

// 创建搜索浮层
function createSearchOverlay() {
  const overlay = document.createElement('div')
  overlay.className = 'bm-search-overlay'
  overlay.innerHTML = `
    <div class="bm-search-modal">
      <div class="bm-search-header">
        <svg class="bm-search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8"></circle>
          <path d="m21 21-4.35-4.35"></path>
        </svg>
        <input type="text" class="bm-search-input" placeholder="搜索书签..." />
        <kbd class="bm-search-kbd">ESC</kbd>
      </div>
      <div class="bm-search-body">
        <div class="bm-search-hint">输入关键词搜索书签</div>
      </div>
      <div class="bm-search-footer">
        <span><kbd>↑</kbd><kbd>↓</kbd> 导航</span>
        <span><kbd>Enter</kbd> 打开</span>
        <span><kbd>ESC</kbd> 关闭</span>
      </div>
    </div>
  `

  // 点击遮罩关闭
  overlay.addEventListener('click', (e) => {
    if (e.target === overlay) {
      closeSearch()
    }
  })

  // 搜索输入
  const input = overlay.querySelector('.bm-search-input')
  let searchTimeout = null

  input.addEventListener('input', () => {
    if (searchTimeout) clearTimeout(searchTimeout)
    searchTimeout = setTimeout(() => {
      performSearch(input.value)
    }, 300)
  })

  // 键盘导航
  input.addEventListener('keydown', (e) => {
    const items = overlay.querySelectorAll('.bm-search-item')
    const active = overlay.querySelector('.bm-search-item.active')
    let activeIndex = Array.from(items).indexOf(active)

    if (e.key === 'ArrowDown') {
      e.preventDefault()
      if (activeIndex < items.length - 1) {
        items[activeIndex]?.classList.remove('active')
        items[activeIndex + 1]?.classList.add('active')
      }
    } else if (e.key === 'ArrowUp') {
      e.preventDefault()
      if (activeIndex > 0) {
        items[activeIndex]?.classList.remove('active')
        items[activeIndex - 1]?.classList.add('active')
      }
    } else if (e.key === 'Enter') {
      e.preventDefault()
      const activeItem = overlay.querySelector('.bm-search-item.active')
      if (activeItem) {
        const url = activeItem.dataset.url
        const id = activeItem.dataset.id
        if (url) {
          chrome.runtime.sendMessage({ action: 'recordVisit', id })
          window.open(url, '_blank')
          closeSearch()
        }
      }
    }
  })

  return overlay
}

// 执行搜索
async function performSearch(keyword) {
  if (!keyword.trim()) {
    updateSearchResults([])
    return
  }

  const body = searchOverlay.querySelector('.bm-search-body')
  body.innerHTML = '<div class="bm-search-loading">搜索中...</div>'

  try {
    const result = await chrome.runtime.sendMessage({
      action: 'searchBookmarks',
      keyword
    })

    if (result.success && result.data) {
      updateSearchResults(result.data)
    } else {
      body.innerHTML = '<div class="bm-search-empty">搜索失败</div>'
    }
  } catch (error) {
    body.innerHTML = '<div class="bm-search-empty">搜索出错</div>'
  }
}

// 更新搜索结果
function updateSearchResults(results) {
  const body = searchOverlay.querySelector('.bm-search-body')

  if (results.length === 0) {
    body.innerHTML = '<div class="bm-search-empty">未找到相关书签</div>'
    return
  }

  body.innerHTML = results.map((item, index) => `
    <div class="bm-search-item ${index === 0 ? 'active' : ''}" data-id="${item.id}" data-url="${item.url}">
      ${item.icon ? `<img src="${item.icon}" class="bm-search-favicon" onerror="this.style.display='none'" />` : ''}
      <div class="bm-search-item-content">
        <div class="bm-search-item-title">${escapeHtml(item.title)}</div>
        <div class="bm-search-item-url">${escapeHtml(item.url)}</div>
      </div>
      ${item.tags.length > 0 ? `
        <div class="bm-search-item-tags">
          ${item.tags.slice(0, 2).map(tag => `<span class="bm-search-tag">${escapeHtml(tag)}</span>`).join('')}
        </div>
      ` : ''}
    </div>
  `).join('')

  // 添加点击事件
  body.querySelectorAll('.bm-search-item').forEach(item => {
    item.addEventListener('click', () => {
      const url = item.dataset.url
      const id = item.dataset.id
      if (url) {
        chrome.runtime.sendMessage({ action: 'recordVisit', id })
        window.open(url, '_blank')
        closeSearch()
      }
    })

    item.addEventListener('mouseenter', () => {
      body.querySelectorAll('.bm-search-item').forEach(i => i.classList.remove('active'))
      item.classList.add('active')
    })
  })
}

// 显示 Toast
function showToast(message) {
  const toast = document.createElement('div')
  toast.className = 'bm-toast'
  toast.textContent = message
  document.body.appendChild(toast)

  setTimeout(() => {
    toast.classList.add('bm-toast-hide')
    setTimeout(() => toast.remove(), 300)
  }, 2000)
}

// HTML 转义
function escapeHtml(text) {
  const div = document.createElement('div')
  div.textContent = text
  return div.innerHTML
}

console.log('Bookmark extension content script loaded')

