// 弹出页面的脚本

document.addEventListener('DOMContentLoaded', async () => {
  // 加载数据
  await loadData();

  // 打开书签管理应用
  document.getElementById('openAppBtn').addEventListener('click', () => {
    chrome.tabs.create({ url: chrome.runtime.getURL('app/index.html') });
  });

  // 打开测试页面
  document.getElementById('openTestBtn').addEventListener('click', () => {
    chrome.tabs.create({ url: chrome.runtime.getURL('app/test.html') });
  });

  // 刷新按钮点击事件
  document.getElementById('refreshBtn').addEventListener('click', async () => {
    await loadData();
    showMessage('已刷新！');
  });

  // 设置链接
  document.getElementById('settingsLink').addEventListener('click', (e) => {
    e.preventDefault();
    showMessage('设置功能开发中...');
  });
});

// 加载数据
async function loadData() {
  // 获取书签事件记录
  const result = await chrome.storage.local.get(['bookmarkEvents']);
  const events = result.bookmarkEvents || [];
  document.getElementById('eventCount').textContent = events.length;
  
  // 获取书签总数
  const bookmarkTree = await chrome.bookmarks.getTree();
  const totalBookmarks = countBookmarks(bookmarkTree);
  document.getElementById('bookmarkCount').textContent = totalBookmarks;
  
  // 渲染事件列表
  renderEventList(events);
}

// 计算书签总数
function countBookmarks(nodes) {
  let count = 0;
  for (const node of nodes) {
    if (node.url) {
      count++;
    }
    if (node.children) {
      count += countBookmarks(node.children);
    }
  }
  return count;
}

// 渲染事件列表
function renderEventList(events) {
  const listEl = document.getElementById('eventList');
  
  if (events.length === 0) {
    listEl.innerHTML = '<p class="empty-hint">暂无书签事件<br>尝试添加或删除一个书签</p>';
    return;
  }
  
  const eventIcons = {
    created: '📌',
    removed: '🗑️',
    changed: '✏️',
    moved: '📁'
  };
  
  const eventLabels = {
    created: '创建',
    removed: '删除',
    changed: '修改',
    moved: '移动'
  };
  
  listEl.innerHTML = events.slice(0, 10).map(event => {
    const icon = eventIcons[event.type] || '📄';
    const label = eventLabels[event.type] || event.type;
    const title = event.data?.title || event.data?.url || '未知';
    const time = formatTime(event.timestamp);
    
    return `
      <div class="event-item">
        <span class="event-icon">${icon}</span>
        <div class="event-content">
          <div class="event-title" title="${escapeHtml(title)}">${escapeHtml(title)}</div>
          <div class="event-meta">${label} · ${time}</div>
        </div>
      </div>
    `;
  }).join('');
}

// 格式化时间
function formatTime(timestamp) {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  
  return date.toLocaleDateString('zh-CN');
}

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

// 显示消息提示
function showMessage(text) {
  const messageEl = document.getElementById('message');
  messageEl.textContent = text;
  messageEl.classList.add('show');
  
  setTimeout(() => {
    messageEl.classList.remove('show');
  }, 2000);
}

