import storage from '../shared/storage.js'
import api from '../shared/api.js'

// 监听书签创建事件
chrome.bookmarks.onCreated.addListener(async (id, bookmark) => {
  console.log('Bookmark created:', bookmark)

  const isLoggedIn = await storage.isLoggedIn()
  if (!isLoggedIn) {
    console.log('Not logged in, skipping sync')
    return
  }

  const settings = await storage.getSettings()
  if (!settings.autoSync) {
    console.log('Auto sync disabled')
    return
  }

  // 跳过文件夹
  if (!bookmark.url) {
    return
  }

  try {
    // 获取文件夹路径作为标签
    const tags = await getFolderPathAsTags(bookmark.parentId)

    // 检查 URL 是否已存在
    const checkResult = await api.checkUrl(bookmark.url)
    if (checkResult.success && checkResult.data) {
      console.log('URL already exists, skipping')
      return
    }

    // 同步到云端
    const result = await api.createBookmark({
      title: bookmark.title,
      url: bookmark.url,
      tags: tags
    })

    if (result.success) {
      console.log('Bookmark synced successfully')
      
      if (settings.showNotification) {
        showNotification('书签已同步', `"${bookmark.title}" 已同步到云端`)
      }

      // 更新扩展图标徽章
      chrome.action.setBadgeText({ text: '✓' })
      chrome.action.setBadgeBackgroundColor({ color: '#67c23a' })
      setTimeout(() => {
        chrome.action.setBadgeText({ text: '' })
      }, 2000)
    }
  } catch (error) {
    console.error('Sync failed:', error)
    
    chrome.action.setBadgeText({ text: '!' })
    chrome.action.setBadgeBackgroundColor({ color: '#f56c6c' })
    setTimeout(() => {
      chrome.action.setBadgeText({ text: '' })
    }, 3000)
  }
})

// 监听书签删除事件
chrome.bookmarks.onRemoved.addListener(async (id, removeInfo) => {
  const settings = await storage.getSettings()
  if (!settings.syncDelete) {
    return
  }
  // TODO: 实现删除同步
})

// 监听快捷键
chrome.commands.onCommand.addListener((command) => {
  if (command === 'toggle-search') {
    // 向当前标签页发送消息，打开搜索
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, { action: 'toggleSearch' })
      }
    })
  }
})

// 获取文件夹路径作为标签
async function getFolderPathAsTags(parentId) {
  const tags = []
  let currentId = parentId

  while (currentId) {
    try {
      const [folder] = await chrome.bookmarks.get(currentId)
      if (folder && folder.title && folder.title !== '书签栏' && folder.title !== '其他书签') {
        tags.unshift(folder.title)
      }
      currentId = folder?.parentId
    } catch {
      break
    }
  }

  return tags.slice(0, 3) // 最多取3级
}

// 显示通知
function showNotification(title, message) {
  chrome.notifications.create({
    type: 'basic',
    iconUrl: '../icons/icon128.png',
    title,
    message
  })
}

// 监听来自 popup 和 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getLoginStatus') {
    storage.isLoggedIn().then(isLoggedIn => {
      sendResponse({ isLoggedIn })
    })
    return true
  }

  if (request.action === 'login') {
    api.login(request.email, request.password, request.deviceInfo).then(result => {
      sendResponse(result)
    })
    return true
  }

  if (request.action === 'logout') {
    api.logout().then(() => {
      sendResponse({ success: true })
    })
    return true
  }

  if (request.action === 'searchBookmarks') {
    api.searchBookmarks(request.keyword).then(result => {
      sendResponse(result)
    })
    return true
  }

  if (request.action === 'createBookmark') {
    api.createBookmark(request.data).then(result => {
      sendResponse(result)
    })
    return true
  }

  if (request.action === 'recordVisit') {
    api.recordVisit(request.id).then(result => {
      sendResponse(result)
    })
    return true
  }
})

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

