import ImageGenerator from '../lib/imageGenerator.js';

document.addEventListener('DOMContentLoaded', () => {
  const selectedTextElement = document.getElementById('selectedText');
  const previewCanvas = document.getElementById('previewCanvas');
  const copyBtn = document.getElementById('copyBtn');
  const saveBtn = document.getElementById('saveBtn');
  const templateButtons = document.querySelectorAll('.template-btn');
  
  // 样式控制元素
  const fontSizeRange = document.getElementById('fontSizeRange');
  const fontSizeValue = document.getElementById('fontSizeValue');
  const textColorPicker = document.getElementById('textColorPicker');
  const bgColorPicker = document.getElementById('bgColorPicker');
  
  const imageGenerator = new ImageGenerator();
  
  // 初始化样式设置
  textColorPicker.value = '#2c3e50';  // 默认文字颜色
  bgColorPicker.value = '#ffffff';    // 默认背景颜色
  
  // 监听字号变化
  fontSizeRange.addEventListener('input', (e) => {
    const size = e.target.value;
    fontSizeValue.textContent = `${size}px`;
    imageGenerator.setFontSize(size);
    updatePreview(selectedTextElement.textContent);
  });
  
  // 监听文字颜色变化
  textColorPicker.addEventListener('input', (e) => {
    imageGenerator.setTextColor(e.target.value);
    updatePreview(selectedTextElement.textContent);
  });
  
  // 监听背景颜色变化
  bgColorPicker.addEventListener('input', (e) => {
    imageGenerator.setBackgroundColor(e.target.value);
    updatePreview(selectedTextElement.textContent);
  });
  
  // 获取当前选中的文本
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {type: 'GET_SELECTED_TEXT'}, (response) => {
        if (chrome.runtime.lastError) {
          console.error('获取文本失败:', chrome.runtime.lastError);
          return;
        }
        
        if (response && response.text) {
          selectedTextElement.textContent = response.text;
          updatePreview(response.text);
        }
      });
    }
  });
  
  // 监听文本选择更新
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'TEXT_SELECTED' && message.data && message.data.text) {
      selectedTextElement.textContent = message.data.text;
      updatePreview(message.data.text);
    }
  });
  
  // 监听文本编辑
  selectedTextElement.addEventListener('input', () => {
    const text = selectedTextElement.textContent;
    updatePreview(text);
    
    chrome.storage.local.set({
      selectedText: text,
      timestamp: Date.now()
    });
  });

  // 更新预览
  async function updatePreview(text) {
    if (!text) return;
    
    imageGenerator.setText(text);
    await imageGenerator.render();
    
    // 将生成的图片显示在预览画布上
    const previewCtx = previewCanvas.getContext('2d');
    previewCanvas.width = imageGenerator.canvas.width;
    previewCanvas.height = imageGenerator.canvas.height;
    previewCtx.drawImage(imageGenerator.canvas, 0, 0);
  }

  // 复制按钮
  copyBtn.addEventListener('click', async () => {
    try {
      const blob = await imageGenerator.toBlob();
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': blob })
      ]);
      // 添加成功提示
      showToast('已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      showToast('复制失败，请重试');
    }
  });

  // 保存按钮
  saveBtn.addEventListener('click', async () => {
    try {
      const blob = await imageGenerator.toBlob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '金句卡片.png';
      a.click();
      URL.revokeObjectURL(url);
      // 添加成功提示
      showToast('已保存图片');
    } catch (error) {
      console.error('保存失败:', error);
      showToast('保存失败，请重试');
    }
  });

  // 添加提示函数
  function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    // 显示提示
    setTimeout(() => toast.classList.add('show'), 10);
    
    // 3秒后移除
    setTimeout(() => {
      toast.classList.remove('show');
      setTimeout(() => toast.remove(), 200);
    }, 3000);
  }

  templateButtons.forEach(btn => {
    btn.addEventListener('click', () => {
      // 更新按钮状态
      templateButtons.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      
      // 设置模板并更新预览
      const template = btn.dataset.template;
      imageGenerator.setTemplate(template);
      updatePreview(selectedTextElement.textContent);
    });
  });
}); 