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

// DOM 元素
const loginView = document.getElementById('login-view')
const mainView = document.getElementById('main-view')
const loginForm = document.getElementById('login-form')
const loginError = document.getElementById('login-error')
const logoutBtn = document.getElementById('logout-btn')
const userName = document.getElementById('user-name')
const deviceName = document.getElementById('device-name')
const bookmarkTitle = document.getElementById('bookmark-title')
const bookmarkUrl = document.getElementById('bookmark-url')
const bookmarkTags = document.getElementById('bookmark-tags')
const saveBtn = document.getElementById('save-btn')
const saveResult = document.getElementById('save-result')
const autoSyncCheckbox = document.getElementById('auto-sync')
const showNotificationCheckbox = document.getElementById('show-notification')

// 初始化
async function init() {
  const isLoggedIn = await storage.isLoggedIn()
  
  if (isLoggedIn) {
    showMainView()
    await loadUserInfo()
    await loadCurrentTab()
    await loadSettings()
  } else {
    showLoginView()
  }
}

// 显示登录视图
function showLoginView() {
  loginView.style.display = 'block'
  mainView.style.display = 'none'
}

// 显示主视图
function showMainView() {
  loginView.style.display = 'none'
  mainView.style.display = 'block'
}

// 加载用户信息
async function loadUserInfo() {
  const user = await storage.getUserInfo()
  const device = await storage.getDeviceInfo()
  
  if (user) {
    userName.textContent = user.userName
  }
  
  if (device) {
    deviceName.textContent = device.isAdmin ? '管理员设备' : device.deviceName
  }
}

// 加载当前标签页信息
async function loadCurrentTab() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
    if (tab) {
      bookmarkTitle.value = tab.title || ''
      bookmarkUrl.value = tab.url || ''
    }
  } catch (e) {
    console.error('Failed to get current tab:', e)
  }
}

// 加载设置
async function loadSettings() {
  const settings = await storage.getSettings()
  autoSyncCheckbox.checked = settings.autoSync
  showNotificationCheckbox.checked = settings.showNotification
}

// 保存设置
async function saveSettings() {
  await storage.setSettings({
    autoSync: autoSyncCheckbox.checked,
    syncDelete: false,
    showNotification: showNotificationCheckbox.checked
  })
}

// 登录
loginForm.addEventListener('submit', async (e) => {
  e.preventDefault()
  
  const email = document.getElementById('email').value
  const password = document.getElementById('password').value
  
  loginError.textContent = ''
  
  try {
    const result = await chrome.runtime.sendMessage({
      action: 'login',
      email,
      password,
      deviceInfo: {
        name: 'Chrome Extension',
        type: 'Chrome Extension',
        fingerprint: await generateFingerprint()
      }
    })
    
    if (result.success) {
      showMainView()
      await loadUserInfo()
      await loadCurrentTab()
      await loadSettings()
    } else {
      loginError.textContent = result.message || '登录失败'
    }
  } catch (error) {
    loginError.textContent = '登录失败，请稍后重试'
  }
})

// 登出
logoutBtn.addEventListener('click', async () => {
  await chrome.runtime.sendMessage({ action: 'logout' })
  showLoginView()
})

// 保存书签
saveBtn.addEventListener('click', async () => {
  const title = bookmarkTitle.value.trim()
  const url = bookmarkUrl.value.trim()
  const tags = bookmarkTags.value.split(',').map(t => t.trim()).filter(Boolean)
  
  if (!title || !url) {
    showSaveResult('请填写标题和URL', false)
    return
  }
  
  try {
    const result = await chrome.runtime.sendMessage({
      action: 'createBookmark',
      data: { title, url, tags }
    })
    
    if (result.success) {
      showSaveResult('收藏成功！', true)
      bookmarkTags.value = ''
    } else {
      showSaveResult(result.message || '收藏失败', false)
    }
  } catch (error) {
    showSaveResult('收藏失败，请稍后重试', false)
  }
})

// 显示保存结果
function showSaveResult(message, success) {
  saveResult.textContent = message
  saveResult.className = success ? 'success' : 'error'
  
  setTimeout(() => {
    saveResult.textContent = ''
    saveResult.className = ''
  }, 3000)
}

// 设置变更
autoSyncCheckbox.addEventListener('change', saveSettings)
showNotificationCheckbox.addEventListener('change', saveSettings)

// 生成设备指纹
async function generateFingerprint() {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  ctx.textBaseline = 'top'
  ctx.font = '14px Arial'
  ctx.fillText('fingerprint', 2, 2)
  
  const data = `${canvas.toDataURL()}-${screen.width}x${screen.height}-${navigator.language}`
  
  let hash = 0
  for (let i = 0; i < data.length; i++) {
    hash = ((hash << 5) - hash) + data.charCodeAt(i)
    hash = hash & hash
  }
  return Math.abs(hash).toString(16)
}

// 初始化
init()

