// A1Tabs 内容脚本
// 在网页中注入功能，支持快速添加链接等操作

// 监听来自background script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.action) {
    case 'getPageInfo':
      sendResponse(getPageInfo());
      break;
      
    case 'highlightElement':
      highlightElement(message.selector);
      sendResponse({ success: true });
      break;
      
    default:
      sendResponse({ error: 'Unknown action' });
  }
});

// 获取页面信息
function getPageInfo() {
  return {
    title: document.title,
    url: window.location.href,
    description: getMetaDescription(),
    favicon: getFaviconUrl(),
    selectedText: window.getSelection().toString().trim()
  };
}

// 获取页面描述
function getMetaDescription() {
  const metaDescription = document.querySelector('meta[name="description"]');
  return metaDescription ? metaDescription.getAttribute('content') : '';
}

// 获取网站图标URL
function getFaviconUrl() {
  const faviconLink = document.querySelector('link[rel*="icon"]');
  if (faviconLink) {
    return new URL(faviconLink.href, window.location.href).href;
  }
  
  // 尝试默认的favicon.ico
  return new URL('/favicon.ico', window.location.href).href;
}

// 高亮元素（用于调试或演示）
function highlightElement(selector) {
  const element = document.querySelector(selector);
  if (element) {
    const originalBorder = element.style.border;
    element.style.border = '3px solid #4285f4';
    
    setTimeout(() => {
      element.style.border = originalBorder;
    }, 2000);
  }
}

// 创建快速添加按钮（可选功能）
function createQuickAddButton() {
  // 检查是否已经存在按钮
  if (document.getElementById('a1tabs-quick-add')) {
    return;
  }
  
  const button = document.createElement('div');
  button.id = 'a1tabs-quick-add';
  button.innerHTML = `
    <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
      <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
    </svg>
  `;
  
  button.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    background: #4285f4;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 10000;
    transition: all 0.3s ease;
    opacity: 0.8;
  `;
  
  // 添加悬停效果
  button.addEventListener('mouseenter', () => {
    button.style.opacity = '1';
    button.style.transform = 'scale(1.1)';
  });
  
  button.addEventListener('mouseleave', () => {
    button.style.opacity = '0.8';
    button.style.transform = 'scale(1)';
  });
  
  // 点击事件
  button.addEventListener('click', async () => {
    const pageInfo = getPageInfo();
    
    // 发送消息给background script添加链接
    chrome.runtime.sendMessage({
      action: 'addCurrentPage',
      pageInfo: pageInfo
    });
    
    // 显示添加成功的临时提示
    showTempNotification('已添加到 A1Tabs!');
  });
  
  document.body.appendChild(button);
  
  // 3秒后自动隐藏
  setTimeout(() => {
    if (button.parentNode) {
      button.parentNode.removeChild(button);
    }
  }, 3000);
}

// 显示临时通知
function showTempNotification(message) {
  const notification = document.createElement('div');
  notification.textContent = message;
  notification.style.cssText = `
    position: fixed;
    top: 80px;
    right: 20px;
    background: #4285f4;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
    font-size: 14px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 10001;
    animation: slideInRight 0.3s ease;
  `;
  
  document.body.appendChild(notification);
  
  setTimeout(() => {
    notification.style.animation = 'slideOutRight 0.3s ease';
    setTimeout(() => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    }, 300);
  }, 2000);
}

// 添加CSS动画
if (!document.getElementById('a1tabs-animations')) {
  const style = document.createElement('style');
  style.id = 'a1tabs-animations';
  style.textContent = `
    @keyframes slideInRight {
      from {
        transform: translateX(100%);
        opacity: 0;
      }
      to {
        transform: translateX(0);
        opacity: 1;
      }
    }
    
    @keyframes slideOutRight {
      from {
        transform: translateX(0);
        opacity: 1;
      }
      to {
        transform: translateX(100%);
        opacity: 0;
      }
    }
  `;
  
  document.head.appendChild(style);
}

// 监听双击Ctrl键显示快速添加按钮
let ctrlKeyCount = 0;
let ctrlKeyTimer = null;

document.addEventListener('keydown', (event) => {
  if (event.key === 'Control') {
    ctrlKeyCount++;
    
    if (ctrlKeyCount === 1) {
      ctrlKeyTimer = setTimeout(() => {
        ctrlKeyCount = 0;
      }, 500);
    } else if (ctrlKeyCount === 2) {
      clearTimeout(ctrlKeyTimer);
      ctrlKeyCount = 0;
      createQuickAddButton();
    }
  }
});

document.addEventListener('keyup', (event) => {
  if (event.key === 'Control' && ctrlKeyTimer) {
    // 重置计时器
    clearTimeout(ctrlKeyTimer);
    ctrlKeyTimer = setTimeout(() => {
      ctrlKeyCount = 0;
    }, 500);
  }
});