/**
 * Content Script
 * 在 X/Twitter 页面中运行，处理文本选择和显示侧边栏
 */

// 侧边栏元素
let sidebar = null;
let lastSelectedText = '';
let isProcessing = false;

// 当前语言
let currentLanguage = 'zh-CN';

/**
 * 初始化侧边栏
 */
async function initSidebar() {
  if (sidebar) return;

  // 获取用户语言设置
  const settings = await chrome.storage.sync.get({ nativeLanguage: 'en' });
  currentLanguage = settings.nativeLanguage;

  sidebar = document.createElement('div');
  sidebar.id = 'x-tweet-helper-sidebar';
  sidebar.className = 'x-tweet-helper-sidebar';
  
  updateSidebarContent();

  document.body.appendChild(sidebar);

  // 绑定最小化按钮
  const toggleBtn = sidebar.querySelector('.sidebar-toggle');
  toggleBtn.addEventListener('click', toggleSidebar);

  // 绑定头像和名称点击事件，打开设置页面
  const titleElement = sidebar.querySelector('.sidebar-title-clickable');
  if (titleElement) {
    titleElement.addEventListener('click', (e) => {
      e.stopPropagation();
      try {
        chrome.runtime.openOptionsPage();
      } catch (error) {
        // 备用方案：通过 background script 打开
        chrome.runtime.sendMessage({ action: 'openOptionsPage' });
      }
    });
  }

  // 阻止侧边栏内部的 mouseup 事件冒泡到 document
  // 避免触发文本选择处理
  sidebar.addEventListener('mouseup', (e) => {
    e.stopPropagation();
  });

  // 调整侧边栏位置和大小
  adjustSidebarLayout();
  window.addEventListener('resize', adjustSidebarLayout);

  // 监听语言设置变化
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'sync' && changes.nativeLanguage) {
      currentLanguage = changes.nativeLanguage.newValue;
      updateSidebarContent();
      // 如果侧边栏正在显示结果，重新绑定按钮
      rebindButtons();
    }
  });
}

/**
 * 更新侧边栏内容（使用当前语言）
 */
function updateSidebarContent() {
  if (!sidebar) return;
  
  sidebar.innerHTML = `
    <div class="sidebar-header">
      <div class="sidebar-title sidebar-title-clickable">
        <img src="${chrome.runtime.getURL('icons/touxiang.jpg')}" class="sidebar-avatar" alt="fluentx">
        <span>${getMessage('sidebarTitle', currentLanguage)} <span class="version-badge">v${chrome.runtime.getManifest().version}</span></span>
      </div>
      <button class="sidebar-toggle" title="${getMessage('minimize', currentLanguage)}">−</button>
    </div>
    <div class="sidebar-content">
      <!-- 核心功能区域：突出显示 -->
      <div class="main-feature-card">
        <div class="welcome-message">
          <p class="welcome-title-main">${getMessage('welcomeTitle', currentLanguage)}</p>
          <p class="welcome-text-main">${getMessage('welcomeText', currentLanguage)}</p>
        </div>
      </div>
      
      <!-- 分隔线 -->
      <div class="feature-divider">
        <span class="divider-text">${getMessage('dividerText', currentLanguage)}</span>
      </div>
      
      <!-- 辅助功能区域：快捷翻译（视觉上弱化） -->
      <div class="default-translation-section">
        <h3 class="section-title-secondary">${getMessage('quickTranslateTitle', currentLanguage)}</h3>
        <textarea 
          class="default-translation-input" 
          placeholder="${getMessage('customReplyPlaceholder', currentLanguage)}"
          rows="4"
        ></textarea>
        <div class="default-translation-buttons">
          <button class="default-translate-button">${getMessage('translateButton', currentLanguage)}</button>
        </div>
        <div class="default-translation-result" style="display: none;">
          <div class="default-translation-header">
            <span class="default-translation-label"></span>
            <button class="copy-button" data-text="">${getMessage('copyButton', currentLanguage)}</button>
          </div>
          <p class="default-translation-text"></p>
        </div>
      </div>
    </div>
  `;
  
  // 绑定默认翻译按钮
  bindDefaultTranslationButton();
}

/**
 * 计算并应用侧边栏起始位置（left）
 * 规则：取页面主内容区域（main 或 [role="main"]）的右边界作为 left，
 * 这样侧边栏会“填满主内容右侧的空白”，且不会遮挡页面内容/弹层
 */
function computeAndApplySidebarLeft() {
  try {
    const mainEl = document.querySelector('main, [role="main"]');
    if (!mainEl) {
      // 回退：如果未找到主内容元素，则使用视口右侧预留固定宽度
      const minWidth = 320;
      const leftPx = Math.max(0, window.innerWidth - minWidth) + 'px';
      document.documentElement.style.setProperty('--x-helper-left', leftPx);
      return;
    }
    const rect = mainEl.getBoundingClientRect();
    const viewport = window.innerWidth || document.documentElement.clientWidth;
    const minWidth = 320; // 确保至少留出可见宽度，避免“消失”
    let left = Math.round(rect.right);
    if (viewport - left < minWidth) {
      left = Math.max(0, viewport - minWidth);
    }
    const leftPx = `${left}px`;
    document.documentElement.style.setProperty('--x-helper-left', leftPx);
  } catch (e) {
  }
}

/**
 * 调整侧边栏布局
 * 固定在右侧，通过动态计算 left 来避免遮挡内容
 */
function adjustSidebarLayout() {
  if (!sidebar) return;
  
  computeAndApplySidebarLeft();
}

/**
 * 将元素提升到更高层级（带 !important）
 */
function setImportantZIndex(element, value) {
  try {
    const computed = window.getComputedStyle(element);
    if (computed.position === 'static') {
      element.style.setProperty('position', 'relative', 'important');
    }
    element.style.setProperty('z-index', String(value), 'important');
  } catch (_) {
    // ignore
  }
}

/**
 * 提升 Messages/抽屉/对话框等层级，保证高于侧边栏
 */
function boostMessagesLayer() {
  const selector = [
    '[data-testid="DMDrawer"]',
    '[data-testid*="DM"]',
    '[data-testid*="message" i]',
    '[role="dialog"]',
    '[aria-modal="true"]',
    '[data-testid*="Drawer"]',
    '[data-testid*="Modal"]'
  ].join(',');
  
  document.querySelectorAll(selector).forEach((el) => {
    setImportantZIndex(el, 1000);
  });
}

/**
 * 观察 DOM 变化，动态保证 Messages 在最上层
 */
function observeMessagesLayer() {
  boostMessagesLayer();
  
  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      for (const node of mutation.addedNodes) {
        if (node.nodeType !== 1) continue;
        const el = /** @type {Element} */ (node);
        // 若新增节点本身或其子孙包含目标元素，则提升层级
        if (
          el.matches?.('[data-testid="DMDrawer"], [data-testid*="DM"], [data-testid*="message" i], [role="dialog"], [aria-modal="true"], [data-testid*="Drawer"], [data-testid*="Modal"]') ||
          el.querySelector?.('[data-testid="DMDrawer"], [data-testid*="DM"], [data-testid*="message" i], [role="dialog"], [aria-modal="true"], [data-testid*="Drawer"], [data-testid*="Modal"]')
        ) {
          boostMessagesLayer();
        }
      }
    }
  });
  
  observer.observe(document.body, { childList: true, subtree: true });
  
  // 在窗口尺寸变化时也确保层级正确
  window.addEventListener('resize', boostMessagesLayer);
}

/**
 * 切换侧边栏显示/隐藏
 * 点击折叠按钮时完全隐藏侧边栏
 */
function toggleSidebar(event) {
  if (!sidebar) return;

  // 阻止事件冒泡，避免触发文本选择处理
  if (event) {
    event.stopPropagation();
    event.preventDefault();
  }

  // 完全隐藏侧边栏
  sidebar.style.display = 'none';
  
  // 重置状态，允许下次选择文本时重新显示
  lastSelectedText = '';
  isProcessing = false;
  
}

/**
 * 显示加载状态
 */
function showLoading(message = null) {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  const loadingMessage = message || getMessage('loading', currentLanguage);
  content.innerHTML = `
    <div class="loading-container">
      <div class="loading-spinner"></div>
      <p>${loadingMessage}</p>
    </div>
  `;
}

/**
 * 只显示回复建议加载状态（不显示翻译，但显示文本框）
 */
function showRepliesLoadingOnly() {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  content.innerHTML = `
    <div class="result-container">
      <div class="custom-reply-section">
        <textarea 
          class="custom-reply-input" 
          placeholder="${getMessage('customReplyPlaceholder', currentLanguage)}"
          rows="4"
        ></textarea>
        <div class="custom-reply-buttons">
          <button class="translate-button">${getMessage('translateButton', currentLanguage)}</button>
          <button class="chat-button">${getMessage('chatButton', currentLanguage)}</button>
        </div>
        <div class="custom-reply-result" style="display: none;">
          <div class="custom-reply-header">
            <span>English:</span>
            <button class="copy-button" data-text="">${getMessage('copyButton', currentLanguage)}</button>
          </div>
          <p class="custom-reply-text"></p>
        </div>
      </div>

      <div class="loading-replies-section">
        <div class="loading-container">
          <div class="loading-spinner"></div>
          <p style="margin-bottom: 8px;">${getMessage('generatingReplies', currentLanguage)}</p>
          <p style="color: #9ca3af; font-size: 13px; margin-top: 0;">${getMessage('generatingRepliesHint', currentLanguage)}</p>
        </div>
      </div>
    </div>
  `;

  // 绑定自定义回复翻译按钮
  const translateBtn = content.querySelector('.translate-button');
  const chatBtn = content.querySelector('.chat-button');
  const customInput = content.querySelector('.custom-reply-input');
  
  if (translateBtn && customInput) {
    translateBtn.addEventListener('click', async () => {
      const text = customInput.value.trim();
      if (!text) {
        alert(getMessage('customReplyPlaceholder', currentLanguage));
        return;
      }
      await translateCustomReply(text);
    });
  }

  if (chatBtn && customInput) {
    chatBtn.addEventListener('click', async () => {
      const text = customInput.value.trim();
      if (!text) {
        alert(getMessage('customReplyPlaceholder', currentLanguage));
        return;
      }
      await chatWithAI(text);
    });
  }
}

/**
 * 显示错误信息
 */
function showError(message, showRetryButton = true) {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  
  // 使用更友好的错误提示
  const errorMsg = showRetryButton ? 
    getMessage('errorWithRetry', currentLanguage) : 
    getMessage('error', currentLanguage);
  
  content.innerHTML = `
    <div class="error-container">
      <div class="error-icon">⚠️</div>
      <p class="error-message">${errorMsg}</p>
      ${showRetryButton ? `<button class="retry-button" onclick="retryLastRequest()">${getMessage('retry', currentLanguage)}</button>` : ''}
    </div>
  `;
}

/**
 * 显示权限提示（无访问权限）
 */
function showNoAccessMessage() {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  content.innerHTML = `
    <div class="no-access-container" style="text-align: center; padding: 40px 20px;">
      <div class="no-access-icon" style="font-size: 64px; margin-bottom: 20px;">🔒</div>
      <h3 style="color: #dc2626; margin-bottom: 10px; font-size: 18px;">${getMessage('noAccessTitle', currentLanguage)}</h3>
      <p style="color: #6b7280; margin-bottom: 30px; line-height: 1.6;">${getMessage('noAccessMessage', currentLanguage)}</p>
      <button class="settings-button" style="
        background: #10b981;
        color: white;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        font-size: 14px;
        cursor: pointer;
        font-weight: 500;
        transition: background 0.2s;
      ">
        ${getMessage('goToSettings', currentLanguage)}
      </button>
    </div>
  `;

  // 绑定设置按钮
  const settingsBtn = content.querySelector('.settings-button');
  if (settingsBtn) {
    // 添加鼠标悬停效果
    settingsBtn.addEventListener('mouseenter', () => {
      settingsBtn.style.background = '#059669';
    });
    settingsBtn.addEventListener('mouseleave', () => {
      settingsBtn.style.background = '#10b981';
    });
    
    // 绑定点击事件
    settingsBtn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      try {
        chrome.runtime.openOptionsPage();
      } catch (error) {
        // 备用方案：通过 background script 打开
        chrome.runtime.sendMessage({ action: 'openOptionsPage' });
      }
    });
  }
}

/**
 * 只显示翻译部分（第一步）
 */
function showTranslationOnly(translationData) {
  if (!sidebar) return;

  // 兼容旧格式：如果传入的是字符串，转换为对象
  const data = typeof translationData === 'string' 
    ? { translation: translationData, summary: null }
    : translationData;

  const { translation, summary } = data;

  const content = sidebar.querySelector('.sidebar-content');
  
  // 构建摘要 HTML（如果存在）
  let summaryHtml = '';
  if (summary) {
    summaryHtml = `
      <div class="summary-section">
        <h3 class="section-title">${getMessage('summaryTitle', currentLanguage)}</h3>
        <div class="summary-content">
          <span class="summary-icon">${getMessage('summaryPrefix', currentLanguage)}</span>
          <span class="summary-text">${escapeHtml(summary)}</span>
        </div>
      </div>
    `;
  }

  content.innerHTML = `
    <div class="result-container">
      ${summaryHtml}
      <div class="translation-section">
        <h3 class="section-title">${getMessage('tweetTranslation', currentLanguage)}</h3>
        <div class="translation-content">
          ${escapeHtml(translation)}
        </div>
      </div>

      <div class="custom-reply-section">
        <textarea 
          class="custom-reply-input" 
          placeholder="${getMessage('customReplyPlaceholder', currentLanguage)}"
          rows="4"
        ></textarea>
        <div class="custom-reply-buttons">
          <button class="translate-button">${getMessage('translateButton', currentLanguage)}</button>
          <button class="chat-button">${getMessage('chatButton', currentLanguage)}</button>
        </div>
        <div class="custom-reply-result" style="display: none;">
          <div class="custom-reply-header">
            <span>English:</span>
            <button class="copy-button" data-text="">${getMessage('copyButton', currentLanguage)}</button>
          </div>
          <p class="custom-reply-text"></p>
        </div>
      </div>

      <div class="loading-replies-section">
        <div class="loading-container">
          <div class="loading-spinner"></div>
          <p style="margin-bottom: 8px;">${getMessage('generatingReplies', currentLanguage)}</p>
          <p style="color: #9ca3af; font-size: 13px; margin-top: 0;">${getMessage('generatingRepliesHint', currentLanguage)}</p>
        </div>
      </div>
    </div>
  `;

  // 绑定自定义回复翻译按钮
  const translateBtn = content.querySelector('.translate-button');
  const chatBtn = content.querySelector('.chat-button');
  const customInput = content.querySelector('.custom-reply-input');
  
  translateBtn.addEventListener('click', async () => {
    const text = customInput.value.trim();
    if (!text) {
      alert(getMessage('customReplyPlaceholder', currentLanguage));
      return;
    }
    await translateCustomReply(text);
  });

  chatBtn.addEventListener('click', async () => {
    const text = customInput.value.trim();
    if (!text) {
      alert(getMessage('customReplyPlaceholder', currentLanguage));
      return;
    }
    await chatWithAI(text);
  });
}

/**
 * 初始化回复建议容器（替换加载区域）
 */
function initReplySuggestionsContainer() {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  if (!content) return;
  
  // 检查是否已经存在容器
  const existingContainer = content.querySelector('.suggestions-container');
  if (existingContainer) {
    return; // 容器已存在，不需要重新创建
  }
  
  const loadingSection = content.querySelector('.loading-replies-section');
  
  if (loadingSection) {
    // 如果有加载区域，替换为建议容器
    loadingSection.outerHTML = `
      <div class="suggestions-section">
        <div class="section-header-with-button">
          <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
          <button class="refresh-replies-button" id="refreshRepliesBtn">
            ${getMessage('refreshReplies', currentLanguage)}
          </button>
        </div>
        <div class="suggestions-container"></div>
      </div>
    `;
  } else {
    // 如果没有加载区域，直接在内容末尾添加建议容器
    const suggestionsSection = document.createElement('div');
    suggestionsSection.className = 'suggestions-section';
    suggestionsSection.innerHTML = `
      <div class="section-header-with-button">
        <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
        <button class="refresh-replies-button" id="refreshRepliesBtn">
          ${getMessage('refreshReplies', currentLanguage)}
        </button>
      </div>
      <div class="suggestions-container"></div>
    `;
    content.appendChild(suggestionsSection);
  }
  
  // 绑定"换一批"按钮事件
  const refreshBtn = content.querySelector('#refreshRepliesBtn');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', refreshReplySuggestions);
  }
}

/**
 * 添加单个回复建议（逐个显示）
 */
function appendSingleSuggestion(suggestion, index) {
  if (!sidebar) {
    console.warn('❌ [UI] sidebar 不存在');
    return;
  }

  const content = sidebar.querySelector('.sidebar-content');
  if (!content) {
    console.warn('❌ [UI] sidebar-content 不存在');
    return;
  }
  
  let container = content.querySelector('.suggestions-container');
  if (!container) {
    console.warn('⚠️ [UI] suggestions-container 不存在，尝试初始化...');
    initReplySuggestionsContainer();
    container = content.querySelector('.suggestions-container');
    if (!container) {
      console.error('❌ [UI] 无法创建 suggestions-container');
      return;
    }
  }
  
  console.log(`✅ [UI] 添加回复建议 ${index + 1}:`, suggestion.type);

  // 如果是第一个回复，清空容器（包括加载状态）
  if (index === 0) {
    container.innerHTML = '';
  }

  // 创建单个建议卡片
  const card = document.createElement('div');
  card.className = 'suggestion-card';
  card.style.animationDelay = `${index * 0.1}s`; // 错开动画时间
  card.innerHTML = `
    <div class="suggestion-header">
      <span class="suggestion-label">${suggestion.label}</span>
      <button class="copy-button" data-text="${escapeHtml(suggestion.original)}">${getMessage('copyButton', currentLanguage)}</button>
    </div>
    <div class="suggestion-content">
      <p class="suggestion-original">${escapeHtml(suggestion.original)}</p>
      <p class="suggestion-translation">${escapeHtml(suggestion.translation)}</p>
    </div>
  `;

  // 添加到容器
  container.appendChild(card);

  // 绑定复制按钮
  const copyBtn = card.querySelector('.copy-button');
  copyBtn.addEventListener('click', function() {
    const text = this.getAttribute('data-text');
    copyToClipboard(text);
    this.textContent = getMessage('copied', currentLanguage);
    setTimeout(() => {
      this.textContent = getMessage('copyButton', currentLanguage);
    }, 2000);
  });
}

/**
 * 逐个添加回复建议（带延迟动画）
 */
async function appendReplySuggestionsOneByOne(suggestions) {
  if (!suggestions || suggestions.length === 0) return;

  // 先初始化容器
  initReplySuggestionsContainer();

  // 逐个添加，每个间隔 300ms
  for (let i = 0; i < suggestions.length; i++) {
    await new Promise(resolve => setTimeout(resolve, i === 0 ? 0 : 300));
    appendSingleSuggestion(suggestions[i], i);
  }
}

/**
 * 添加回复建议到已有的内容（第二步）- 保留原函数作为快速版本
 */
function appendReplySuggestions(suggestions) {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  const loadingSection = content.querySelector('.loading-replies-section');
  
  if (!loadingSection) return;

  let suggestionsHTML = '';
  if (suggestions && suggestions.length > 0) {
    suggestionsHTML = `
      <div class="suggestions-section">
        <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
        ${suggestions.map((suggestion, index) => `
          <div class="suggestion-card" style="animation-delay: ${index * 0.1}s;">
            <div class="suggestion-header">
              <span class="suggestion-label">${suggestion.label}</span>
              <button class="copy-button" data-text="${escapeHtml(suggestion.original)}">${getMessage('copyButton', currentLanguage)}</button>
            </div>
            <div class="suggestion-content">
              <p class="suggestion-original">${escapeHtml(suggestion.original)}</p>
              <p class="suggestion-translation">${escapeHtml(suggestion.translation)}</p>
            </div>
          </div>
        `).join('')}
      </div>
    `;
  }

  // 替换加载区域为回复建议
  loadingSection.outerHTML = suggestionsHTML;

  // 绑定复制按钮
  content.querySelectorAll('.copy-button').forEach(btn => {
    btn.addEventListener('click', function() {
      const text = this.getAttribute('data-text');
      copyToClipboard(text);
      this.textContent = getMessage('copied', currentLanguage);
      setTimeout(() => {
        this.textContent = getMessage('copyButton', currentLanguage);
      }, 2000);
    });
  });
}

/**
 * 显示翻译和回复建议（完整版，保留兼容）
 */
function showResults(data) {
  if (!sidebar) return;

  const { translation, suggestions } = data;
  
  let suggestionsHTML = '';
  if (suggestions && suggestions.length > 0) {
    suggestionsHTML = suggestions.map((suggestion, index) => `
      <div class="suggestion-card">
        <div class="suggestion-header">
          <span class="suggestion-label">${suggestion.label}</span>
          <button class="copy-button" data-text="${escapeHtml(suggestion.original)}">${getMessage('copyButton', currentLanguage)}</button>
        </div>
        <div class="suggestion-content">
          <p class="suggestion-original">${escapeHtml(suggestion.original)}</p>
          <p class="suggestion-translation">${escapeHtml(suggestion.translation)}</p>
        </div>
      </div>
    `).join('');
  }

  const content = sidebar.querySelector('.sidebar-content');
  content.innerHTML = `
    <div class="result-container">
      <div class="translation-section">
        <h3 class="section-title">${getMessage('tweetTranslation', currentLanguage)}</h3>
        <div class="translation-content">
          ${escapeHtml(translation)}
        </div>
      </div>

      <div class="custom-reply-section">
        <textarea 
          class="custom-reply-input" 
          placeholder="${getMessage('customReplyPlaceholder', currentLanguage)}"
          rows="4"
        ></textarea>
        <div class="custom-reply-buttons">
          <button class="translate-button">${getMessage('translateButton', currentLanguage)}</button>
          <button class="chat-button">${getMessage('chatButton', currentLanguage)}</button>
        </div>
        <div class="custom-reply-result" style="display: none;">
          <div class="custom-reply-header">
            <span>English:</span>
            <button class="copy-button" data-text="">${getMessage('copyButton', currentLanguage)}</button>
          </div>
          <p class="custom-reply-text"></p>
        </div>
      </div>

      ${suggestionsHTML ? `
        <div class="suggestions-section">
          <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
          ${suggestionsHTML}
        </div>
      ` : ''}
    </div>
  `;

  // 绑定复制按钮
  content.querySelectorAll('.copy-button').forEach(btn => {
    btn.addEventListener('click', function() {
      const text = this.getAttribute('data-text');
      copyToClipboard(text);
      this.textContent = getMessage('copied', currentLanguage);
      setTimeout(() => {
        this.textContent = getMessage('copyButton', currentLanguage);
      }, 2000);
    });
  });

  // 绑定自定义回复翻译按钮
  const translateBtn = content.querySelector('.translate-button');
  const chatBtn = content.querySelector('.chat-button');
  const customInput = content.querySelector('.custom-reply-input');
  
  translateBtn.addEventListener('click', async () => {
    const text = customInput.value.trim();
    if (!text) {
      alert(getMessage('customReplyPlaceholder', currentLanguage));
      return;
    }
    await translateCustomReply(text);
  });

  chatBtn.addEventListener('click', async () => {
    const text = customInput.value.trim();
    if (!text) {
      alert(getMessage('customReplyPlaceholder', currentLanguage));
      return;
    }
    await chatWithAI(text);
  });
}

/**
 * 绑定默认翻译按钮
 */
function bindDefaultTranslationButton() {
  const translateBtn = sidebar?.querySelector('.default-translate-button');
  const input = sidebar?.querySelector('.default-translation-input');
  
  if (!translateBtn || !input) return;
  
  translateBtn.addEventListener('click', async () => {
    const text = input.value.trim();
    if (!text) {
      alert(getMessage('customReplyPlaceholder', currentLanguage));
      return;
    }
    await translateDefaultText(text);
  });
  
  // 支持回车键翻译（Ctrl/Cmd + Enter）
  input.addEventListener('keydown', async (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
      e.preventDefault();
      const text = input.value.trim();
      if (text) {
        await translateDefaultText(text);
      }
    }
  });
}

/**
 * 翻译默认输入框的文本（自动检测语言并翻译到目标语言）
 */
async function translateDefaultText(text) {
  const resultDiv = sidebar?.querySelector('.default-translation-result');
  const resultText = sidebar?.querySelector('.default-translation-text');
  const resultLabel = sidebar?.querySelector('.default-translation-label');
  const copyBtn = resultDiv?.querySelector('.copy-button');
  const translateBtn = sidebar?.querySelector('.default-translate-button');
  const input = sidebar?.querySelector('.default-translation-input');

  if (!resultDiv || !resultText || !translateBtn) return;

  try {
    translateBtn.disabled = true;
    translateBtn.textContent = getMessage('translating', currentLanguage) || '翻译中...';
    resultDiv.style.display = 'none';

    // 🔐 检查用户状态和权限
    const userStatus = await apiClient.getUserStatus();
    if (!userStatus.hasAccess) {
      alert(getMessage('noAccessMessage', currentLanguage));
      translateBtn.disabled = false;
      translateBtn.textContent = getMessage('translateButton', currentLanguage);
      return;
    }

    // 获取用户设置的母语（目标语言）
    const settings = await chrome.storage.sync.get({ nativeLanguage: 'en' });
    const targetLanguage = settings.nativeLanguage;
    
    // 检测输入文本的语言（简单检测：如果包含中文字符，则认为是中文）
    const hasChinese = /[\u4e00-\u9fa5]/.test(text);
    const sourceLanguage = hasChinese ? 'zh-CN' : 'en';
    
    // 如果输入语言和目标语言相同，则翻译到另一种语言
    let finalTargetLanguage = targetLanguage;
    if (sourceLanguage === targetLanguage) {
      finalTargetLanguage = targetLanguage === 'zh-CN' ? 'en' : 'zh-CN';
    }
    
    // 执行翻译
    const translation = await apiClient.translate(text, finalTargetLanguage);
    
    // 显示结果
    const targetLangName = finalTargetLanguage === 'zh-CN' ? '中文' : 
                          finalTargetLanguage === 'en' ? 'English' : 
                          finalTargetLanguage;
    if (resultLabel) {
      resultLabel.textContent = `${targetLangName}:`;
    }
    resultText.textContent = translation;
    if (copyBtn) {
      copyBtn.setAttribute('data-text', translation);
      // 重新绑定复制按钮
      copyBtn.onclick = function() {
        copyToClipboard(translation);
        this.textContent = getMessage('copied', currentLanguage) || '已复制';
        setTimeout(() => {
          this.textContent = getMessage('copyButton', currentLanguage);
        }, 2000);
      };
    }
    resultDiv.style.display = 'block';
    
    // 滚动到结果区域
    resultDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    
  } catch (error) {
    console.error('❌ [Translation] 翻译失败:', error);
    alert(getMessage('error', currentLanguage) + ': ' + error.message);
  } finally {
    translateBtn.disabled = false;
    translateBtn.textContent = getMessage('translateButton', currentLanguage);
  }
}

/**
 * 翻译自定义回复（将用户母语翻译成英文）
 */
async function translateCustomReply(text) {
  const resultDiv = document.querySelector('.custom-reply-result');
  const resultText = document.querySelector('.custom-reply-text');
  const copyBtn = resultDiv.querySelector('.copy-button');
  const translateBtn = document.querySelector('.translate-button');

  try {
    translateBtn.disabled = true;
    translateBtn.textContent = getMessage('translating', currentLanguage);

    // 🔐 检查用户状态和权限
    const userStatus = await apiClient.getUserStatus();
    if (!userStatus.hasAccess) {
      alert(getMessage('noAccessMessage', currentLanguage));
      translateBtn.disabled = false;
      translateBtn.textContent = getMessage('translateButton', currentLanguage);
      return;
    }

    // 将用户的母语文本翻译成英文（用于回复推文）
    const translation = await apiClient.translate(text, 'en');

    resultText.textContent = translation;
    copyBtn.setAttribute('data-text', translation);
    resultDiv.style.display = 'block';

    // 重新绑定复制按钮
    copyBtn.onclick = function() {
      copyToClipboard(translation);
      this.textContent = getMessage('copied', currentLanguage);
      setTimeout(() => {
        this.textContent = getMessage('copyButton', currentLanguage);
      }, 2000);
    };
  } catch (error) {
    alert(getMessage('error', currentLanguage) + ': ' + error.message);
  } finally {
    translateBtn.disabled = false;
    translateBtn.textContent = getMessage('translateButton', currentLanguage);
  }
}

/**
 * 基于用户指令与AI聊天，重新生成回复建议
 */
async function chatWithAI(userInstruction) {
  const chatBtn = document.querySelector('.chat-button');
  
  // 检查是否有当前选中的推文
  if (!lastSelectedText) {
    alert('请先选中一条推文');
    return;
  }

  try {
    chatBtn.disabled = true;
    chatBtn.textContent = getMessage('chatting', currentLanguage);

    // 先清空现有的回复建议，显示加载状态
    clearReplySuggestionsForChat();

    // 🔐 检查用户状态和权限
    const userStatus = await apiClient.getUserStatus();
    if (!userStatus.hasAccess) {
      alert(getMessage('noAccessMessage', currentLanguage));
      chatBtn.disabled = false;
      chatBtn.textContent = getMessage('chatButton', currentLanguage);
      return;
    }

    // 调用聊天API，传入原推文和用户指令
    console.log('💬 [Chat] 发送用户指令:', userInstruction);
    console.log('📝 [Chat] 原推文:', lastSelectedText);
    
    const result = await apiClient.chatReplySuggestions(
      lastSelectedText, 
      userInstruction, 
      currentLanguage
    );

    console.log('✅ [Chat] 收到新的回复建议:', result);

    // 更新回复建议区域（替换原有的建议）
    updateReplySuggestionsAfterChat(result);

    // 清空文本框
    const customInput = document.querySelector('.custom-reply-input');
    if (customInput) {
      customInput.value = '';
    }

  } catch (error) {
    console.error('❌ [Chat] 聊天失败:', error);
    alert(getMessage('error', currentLanguage));
  } finally {
    chatBtn.disabled = false;
    chatBtn.textContent = getMessage('chatButton', currentLanguage);
  }
}

/**
 * 聊天前清空回复建议，显示加载状态
 */
function clearReplySuggestionsForChat() {
  const suggestionsSection = document.querySelector('.suggestions-section');
  
  if (suggestionsSection) {
    // 显示加载状态
    suggestionsSection.innerHTML = `
      <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
      <div class="loading-container" style="padding: 40px 0; text-align: center;">
        <div class="loading-spinner" style="margin: 0 auto 12px;"></div>
        <p style="color: #6b7280; font-size: 14px;">${getMessage('chatting', currentLanguage)}</p>
      </div>
    `;
  }
}

/**
 * 聊天后更新回复建议
 */
function updateReplySuggestionsAfterChat(result) {
  const suggestionsSection = document.querySelector('.suggestions-section');
  
  if (!suggestionsSection) {
    // 如果没有建议区域，创建一个
    const content = sidebar.querySelector('.sidebar-content .result-container');
    const newSection = document.createElement('div');
    newSection.className = 'suggestions-section';
    newSection.innerHTML = `
      <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
    `;
    content.appendChild(newSection);
  }

  // 生成新的建议HTML
  const suggestionsHTML = result.suggestions.map(suggestion => `
    <div class="suggestion-card">
      <div class="suggestion-header">
        <span class="suggestion-label">${escapeHtml(suggestion.label)}</span>
        <button class="copy-button" data-text="${escapeHtml(suggestion.original)}">${getMessage('copyButton', currentLanguage)}</button>
      </div>
      <div class="suggestion-content">
        <p class="suggestion-original">${escapeHtml(suggestion.original)}</p>
        <p class="suggestion-translation">${escapeHtml(suggestion.translation)}</p>
      </div>
    </div>
  `).join('');

  // 更新建议区域
  const updatedSection = document.querySelector('.suggestions-section');
  updatedSection.innerHTML = `
    <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
    ${suggestionsHTML}
  `;

  // 重新绑定复制按钮
  updatedSection.querySelectorAll('.copy-button').forEach(btn => {
    btn.addEventListener('click', function() {
      const text = this.getAttribute('data-text');
      copyToClipboard(text);
      this.textContent = getMessage('copied', currentLanguage);
      setTimeout(() => {
        this.textContent = getMessage('copyButton', currentLanguage);
      }, 2000);
    });
  });
}

/**
 * 处理文本选择（分步展示版）
 */
async function handleTextSelection() {
  const selectedText = window.getSelection().toString().trim();
  
  // 如果没有选中文本或与上次相同，不处理
  if (!selectedText || selectedText === lastSelectedText || isProcessing) {
    return;
  }

  // 移除仅英文文本的限制，现在支持任何语言
  if (selectedText.length < 2) {
    return;
  }

  lastSelectedText = selectedText;
  isProcessing = true;
  

  try {
    // 显示侧边栏（如果之前被隐藏了）
    if (sidebar) {
      sidebar.style.display = 'flex';
    }

    // 🔐 检查用户状态和权限
    showLoading(getMessage('loading', currentLanguage));
    
    const userStatus = await apiClient.getUserStatus();
    
    if (!userStatus.hasAccess) {
      showNoAccessMessage();
      return;
    }
    

    // 获取用户设置的母语
    const settings = await chrome.storage.sync.get({ nativeLanguage: 'en' });
    const targetLanguage = settings.nativeLanguage;
    
    // 🔵 生成回复建议（使用SSE流式返回，逐步显示，包含翻译）
    showLoading(getMessage('generatingReplies', currentLanguage));
    let replyData = null;
    let retryCount = 0;
    const maxRetries = 2;
    
    // 初始化回复建议容器
    initReplySuggestionsContainer();
    
    while (retryCount <= maxRetries && !replyData) {
      try {
        let replyIndex = 0; // 用于跟踪已显示的回复数量
        
        replyData = await apiClient.getReplySuggestions(
          selectedText, 
          targetLanguage, 
          retryCount > 0,
          // onProgress 回调：逐步显示回复
          (type, data) => {
            if (type === 'translation') {
              // 显示翻译
              showTranslationOnly(data.translation);
              // 确保回复建议容器已初始化
              initReplySuggestionsContainer();
            } else if (type === 'reply') {
              // 确保容器存在
              let container = document.querySelector('.suggestions-container');
              if (!container) {
                initReplySuggestionsContainer();
                container = document.querySelector('.suggestions-container');
              }
              // 立即显示单个回复（哪个先完成就先显示哪个）
              if (container) {
                appendSingleSuggestion(data, replyIndex++);
              }
            } else if (type === 'error') {
              console.error('SSE错误:', data);
            }
          }
        );
        
        break;
        
      } catch (replyError) {
        retryCount++;
        console.warn(`回复生成失败 (尝试 ${retryCount}/${maxRetries + 1}):`, replyError);
        
        if (retryCount > maxRetries) {
          // 所有重试都失败了，显示错误
          throw replyError;
        }
        
        // 等待一小段时间后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
      }
    }
    
  } catch (error) {
    console.error('处理失败:', error);
    showError(error.message || '处理失败，请重试', true);
  } finally {
    isProcessing = false;
  }
}

/**
 * 重试上次请求
 */
async function retryLastRequest() {
  if (lastSelectedText) {
    const temp = lastSelectedText;
    lastSelectedText = '';
    
    // 模拟重新选择
    isProcessing = false;
    await handleTextSelection();
    lastSelectedText = temp;
  }
}

/**
 * 刷新回复建议（换一批）
 */
async function refreshReplySuggestions() {
  if (!sidebar || !lastSelectedText || isProcessing) return;
  
  try {
    isProcessing = true;
    
    const content = sidebar.querySelector('.sidebar-content');
    const refreshBtn = content.querySelector('#refreshRepliesBtn');
    const container = content.querySelector('.suggestions-container');
    
    if (!container) return;
    
    // 更新按钮状态
    if (refreshBtn) {
      refreshBtn.disabled = true;
      refreshBtn.textContent = getMessage('refreshing', currentLanguage);
    }
    
    // 清空现有建议
    container.innerHTML = '';
    
    // 获取用户设置的母语
    const settings = await chrome.storage.sync.get({ nativeLanguage: 'en' });
    const targetLanguage = settings.nativeLanguage;
    
    // 重新生成回复建议（带自动重试，不使用缓存）
    let replyData = null;
    // 清空现有回复建议，显示加载状态
    // 重要：保留 suggestions-section 的结构，只更新 container 的内容
    const suggestionsSection = content.querySelector('.suggestions-section');
    const existingContainer = content.querySelector('.suggestions-container');
    
    if (suggestionsSection && existingContainer) {
      // 清空容器并显示加载状态
      existingContainer.innerHTML = `
        <div class="loading-container" style="padding: 40px 0; text-align: center;">
          <div class="loading-spinner" style="margin: 0 auto 12px;"></div>
          <p style="color: #6b7280; font-size: 14px; margin-bottom: 8px;">${getMessage('generatingReplies', currentLanguage)}</p>
          <p style="color: #9ca3af; font-size: 13px; margin-top: 0;">${getMessage('generatingRepliesHint', currentLanguage)}</p>
        </div>
      `;
    } else if (suggestionsSection) {
      // 如果容器不存在，重新创建整个结构
      suggestionsSection.innerHTML = `
        <div class="section-header-with-button">
          <h3 class="section-title">${getMessage('replySuggestions', currentLanguage)}</h3>
          <button class="refresh-replies-button" id="refreshRepliesBtn">
            ${getMessage('refreshReplies', currentLanguage)}
          </button>
        </div>
        <div class="suggestions-container">
          <div class="loading-container" style="padding: 40px 0; text-align: center;">
            <div class="loading-spinner" style="margin: 0 auto 12px;"></div>
            <p style="color: #6b7280; font-size: 14px; margin-bottom: 8px;">${getMessage('generatingReplies', currentLanguage)}</p>
            <p style="color: #9ca3af; font-size: 13px; margin-top: 0;">${getMessage('generatingRepliesHint', currentLanguage)}</p>
          </div>
        </div>
      `;
      // 重新绑定按钮事件
      const refreshBtn = content.querySelector('#refreshRepliesBtn');
      if (refreshBtn) {
        refreshBtn.addEventListener('click', refreshReplySuggestions);
      }
    } else {
      // 如果 suggestions-section 都不存在，尝试初始化
      initReplySuggestionsContainer();
    }
    
    // 确保容器存在（在开始接收回复前）
    const finalContainer = content.querySelector('.suggestions-container');
    if (!finalContainer) {
      console.error('❌ [UI] 无法找到或创建 suggestions-container');
      if (refreshBtn) {
        refreshBtn.disabled = false;
        refreshBtn.textContent = getMessage('refreshReplies', currentLanguage);
      }
      return;
    }
    
    let retryCount = 0;
    const maxRetries = 2;
    
    while (retryCount <= maxRetries && !replyData) {
      try {
        let replyIndex = 0; // 用于跟踪已显示的回复数量
        
        replyData = await apiClient.getReplySuggestions(
          lastSelectedText, 
          targetLanguage, 
          true, // skipCache
          // onProgress 回调：逐步显示回复
          (type, data) => {
            if (type === 'translation') {
              // 更新翻译（如果需要）
              // 这里可以更新翻译显示，但换一批时通常不需要
            } else if (type === 'reply') {
              // 立即显示单个回复（哪个先完成就先显示哪个）
              appendSingleSuggestion(data, replyIndex++);
            } else if (type === 'error') {
              console.error('SSE错误:', data);
            }
          }
        );
        
        // 恢复按钮状态
        if (refreshBtn) {
          refreshBtn.disabled = false;
          refreshBtn.textContent = getMessage('refreshReplies', currentLanguage);
        }
        break;
        
      } catch (replyError) {
        retryCount++;
        console.warn(`换一批失败 (尝试 ${retryCount}/${maxRetries + 1}):`, replyError);
        
        if (retryCount > maxRetries) {
          // 所有重试都失败了
          if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.textContent = getMessage('refreshReplies', currentLanguage);
          }
          throw replyError;
        }
        
        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
      }
    }
    
  } catch (error) {
    console.error('刷新回复建议失败:', error);
    showError(error.message || '刷新失败，请重试', true);
  } finally {
    isProcessing = false;
  }
}

/**
 * 复制文本到剪贴板
 */
function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

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

/**
 * 重新绑定所有按钮（在语言切换后调用）
 */
function rebindButtons() {
  if (!sidebar) return;

  const content = sidebar.querySelector('.sidebar-content');
  if (!content) return;

  // 重新绑定复制按钮
  content.querySelectorAll('.copy-button').forEach(btn => {
    const oldBtn = btn.cloneNode(true);
    btn.parentNode.replaceChild(oldBtn, btn);
    
    oldBtn.addEventListener('click', function() {
      const text = this.getAttribute('data-text');
      copyToClipboard(text);
      this.textContent = getMessage('copied', currentLanguage);
      setTimeout(() => {
        this.textContent = getMessage('copyButton', currentLanguage);
      }, 2000);
    });
  });

  // 重新绑定翻译按钮
  const translateBtn = content.querySelector('.translate-button');
  if (translateBtn) {
    const oldTranslateBtn = translateBtn.cloneNode(true);
    translateBtn.parentNode.replaceChild(oldTranslateBtn, translateBtn);
    
    const customInput = content.querySelector('.custom-reply-input');
    oldTranslateBtn.addEventListener('click', async () => {
      const text = customInput.value.trim();
      if (!text) {
        alert(getMessage('customReplyPlaceholder', currentLanguage));
        return;
      }
      await translateCustomReply(text);
    });
  }
}

/**
 * 初始化
 */
function init() {
  // 创建侧边栏
  initSidebar();
  // 初始计算一次，并在滚动时也更新（X 的布局在滚动时可能会发生细微变化）
  computeAndApplySidebarLeft();
  window.addEventListener('scroll', computeAndApplySidebarLeft, { passive: true });
  // 确保侧边栏的层级恒为 1（高于主内容，低于弹窗）
  if (sidebar) {
    setImportantZIndex(sidebar, 1);
  }
  
  // 启动版本检查
  startVersionCheck();
  
  // 观察并提升 Messages/弹窗层级
  observeMessagesLayer();

  // 监听文本选择
  document.addEventListener('mouseup', () => {
    setTimeout(handleTextSelection, 100);
  });

  // 监听键盘选择（Shift + 方向键）
  document.addEventListener('keyup', (e) => {
    if (e.shiftKey) {
      setTimeout(handleTextSelection, 100);
    }
  });

  // 初始化推文翻译按钮功能（根据设置）
  initTweetTranslateFeature();

}

/**
 * 启动版本检查
 * 每1分钟检查一次是否有新版本
 */
function startVersionCheck() {
  const CHECK_INTERVAL = 1 * 60 * 1000; // 1分钟
  
  // 立即执行一次
  checkForUpdates();
  
  // 每10分钟检查一次
  setInterval(checkForUpdates, CHECK_INTERVAL);
}

/**
 * 检查更新
 */
async function checkForUpdates() {
  try {
    const versionInfo = await apiClient.checkVersion();
    
    if (!versionInfo) return;
    
    // 获取当前扩展版本
    const manifest = chrome.runtime.getManifest();
    const currentVersion = manifest.version;
    const latestVersion = versionInfo.latestVersion;
    
    console.log(`📦 [Version] 当前版本: ${currentVersion}, 最新版本: ${latestVersion}`);
    
    // 比较版本号
    if (isNewerVersion(latestVersion, currentVersion)) {
      console.log('🎉 [Version] 发现新版本！');
      showUpdateNotification(versionInfo);
    }
  } catch (error) {
    console.error('❌ [Version] 版本检查失败:', error);
  }
}

/**
 * 比较版本号
 * @param {string} latest - 最新版本
 * @param {string} current - 当前版本
 * @returns {boolean} - 是否有新版本
 */
function isNewerVersion(latest, current) {
  const latestParts = latest.split('.').map(Number);
  const currentParts = current.split('.').map(Number);
  
  for (let i = 0; i < Math.max(latestParts.length, currentParts.length); i++) {
    const l = latestParts[i] || 0;
    const c = currentParts[i] || 0;
    
    if (l > c) return true;
    if (l < c) return false;
  }
  
  return false;
}

/**
 * 显示更新通知
 * @param {Object} versionInfo - 版本信息
 */
function showUpdateNotification(versionInfo) {
  if (!sidebar) return;
  
  // 检查是否已经显示过通知
  if (document.querySelector('.update-notification')) return;
  
  const header = sidebar.querySelector('.sidebar-header');
  if (!header) return;
  
  // 创建更新通知
  const notification = document.createElement('div');
  notification.className = 'update-notification';
  notification.innerHTML = `
    <span class="update-text">🎉 新版本 ${versionInfo.latestVersion} 可用</span>
    <button class="update-link">立即更新</button>
  `;
  
  // 绑定点击事件：同时打开官网和扩展管理页面
  const updateButton = notification.querySelector('.update-link');
  updateButton.addEventListener('click', async () => {
    // 打开官网（下载页面）
    window.open(versionInfo.downloadUrl, '_blank');
    
    // 通过 background script 打开 chrome://extensions/ 页面
    try {
      chrome.runtime.sendMessage({ 
        action: 'openExtensionsPage' 
      }, (response) => {
        if (chrome.runtime.lastError) {
          console.error('❌ [Update] 消息发送失败:', chrome.runtime.lastError.message);
          // 备用方案：尝试直接打开（可能在某些情况下不工作）
          window.open('chrome://extensions/', '_blank');
        } else if (response && !response.success) {
          console.error('❌ [Update] 打开扩展管理页面失败:', response.error);
          // 备用方案：尝试直接打开
          window.open('chrome://extensions/', '_blank');
        } else {
          console.log('✅ [Update] 已请求打开扩展管理页面');
        }
      });
    } catch (error) {
      console.error('❌ [Update] 无法打开扩展管理页面:', error);
      // 备用方案：尝试直接打开（可能在某些情况下不工作）
      window.open('chrome://extensions/', '_blank');
    }
  });
  
  // 插入到header后面
  header.after(notification);
}

// 推文翻译功能观察器
let tweetTranslateObserver = null;

/**
 * 初始化推文翻译按钮功能（根据设置）
 */
async function initTweetTranslateFeature() {
  // 读取设置
  const settings = await chrome.storage.sync.get({ 
    tweetTranslateButtonEnabled: true // 默认开启
  });
  
  if (settings.tweetTranslateButtonEnabled) {
    enableTweetTranslateFeature();
  }
  
  // 监听设置变化
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'sync' && changes.tweetTranslateButtonEnabled) {
      const enabled = changes.tweetTranslateButtonEnabled.newValue;
      if (enabled) {
        enableTweetTranslateFeature();
      } else {
        disableTweetTranslateFeature();
      }
    }
  });
}

/**
 * 启用推文翻译功能
 */
function enableTweetTranslateFeature() {
  // 如果已经启用，不重复初始化
  if (tweetTranslateObserver) {
    return;
  }
  
  // 为现有推文添加翻译按钮
  addTranslateButtonsToAllTweets();
  
  // 监听 DOM 变化，为新加载的推文添加翻译按钮
  observeTweetsForTranslation();
}

/**
 * 禁用推文翻译功能
 */
function disableTweetTranslateFeature() {
  // 停止观察
  if (tweetTranslateObserver) {
    tweetTranslateObserver.disconnect();
    tweetTranslateObserver = null;
  }
  
  // 移除所有翻译按钮和翻译结果
  const buttons = document.querySelectorAll('.fluentx-translate-button');
  buttons.forEach(btn => {
    const container = btn.closest('div');
    if (container) {
      container.remove();
    }
  });
  
  const results = document.querySelectorAll('.fluentx-translation-result');
  results.forEach(result => result.remove());
}

/**
 * 监听 DOM 变化，为新加载的推文添加翻译按钮
 */
function observeTweetsForTranslation() {
  // 如果已有观察器，先断开
  if (tweetTranslateObserver) {
    tweetTranslateObserver.disconnect();
  }
  
  tweetTranslateObserver = new MutationObserver((mutations) => {
    // 延迟执行，避免频繁触发
    setTimeout(() => {
      addTranslateButtonsToAllTweets();
    }, 500);
  });

  // 开始观察整个文档的变化
  tweetTranslateObserver.observe(document.body, {
    childList: true,
    subtree: true
  });
}

/**
 * 为所有推文添加翻译按钮
 */
function addTranslateButtonsToAllTweets() {
  // 查找所有推文容器（X/Twitter 使用 article 标签）
  const tweets = document.querySelectorAll('article[data-testid="tweet"]');
  
  tweets.forEach((tweet) => {
    // 检查是否已经添加过翻译按钮
    if (tweet.querySelector('.fluentx-translate-button')) {
      return;
    }
    
    // 查找推文的互动按钮区域（通常在推文底部）
    const actionBar = tweet.querySelector('[role="group"]');
    if (!actionBar) return;
    
    // 添加翻译按钮
    addTranslateButtonToTweet(tweet, actionBar);
  });
}

/**
 * 为单个推文添加翻译按钮
 */
function addTranslateButtonToTweet(tweet, actionBar) {
  // 创建翻译按钮
  const translateButton = document.createElement('button');
  translateButton.className = 'fluentx-translate-button';
  translateButton.textContent = getMessage('translateTweetButton', currentLanguage);
  translateButton.setAttribute('data-tweet-id', tweet.getAttribute('data-testid') || Date.now());
  
  // 绑定点击事件
  translateButton.addEventListener('click', async (e) => {
    e.stopPropagation();
    e.preventDefault();
    await handleTweetTranslate(tweet, translateButton);
  });
  
  // 在互动按钮区域后添加翻译按钮
  const buttonContainer = document.createElement('div');
  buttonContainer.style.cssText = 'display: flex; align-items: center; margin-top: 8px;';
  buttonContainer.appendChild(translateButton);
  
  // 查找推文内容容器，在互动按钮区域后插入
  const tweetContent = tweet.querySelector('[data-testid="tweetText"]')?.closest('div');
  if (tweetContent) {
    // 检查是否已经有翻译结果显示区域
    const existingResult = tweet.querySelector('.fluentx-translation-result');
    if (existingResult) {
      existingResult.before(buttonContainer);
    } else {
      // 在推文内容后插入按钮容器
      const parent = actionBar.parentElement;
      if (parent) {
        parent.insertBefore(buttonContainer, actionBar.nextSibling);
      }
    }
  }
}

/**
 * 处理推文翻译按钮点击
 */
async function handleTweetTranslate(tweet, button) {
  // 检查是否已经有翻译结果
  const existingResult = tweet.querySelector('.fluentx-translation-result');
  if (existingResult && !existingResult.classList.contains('loading')) {
    // 如果已有翻译结果，切换显示/隐藏
    existingResult.style.display = existingResult.style.display === 'none' ? 'block' : 'none';
    return;
  }
  
  try {
    // 禁用按钮
    button.disabled = true;
    button.textContent = getMessage('translating', currentLanguage);
    
    // 提取推文文本
    const tweetText = extractTweetText(tweet);
    if (!tweetText || tweetText.trim().length < 2) {
      throw new Error('无法提取推文文本');
    }
    
    // 检查用户权限
    const userStatus = await apiClient.getUserStatus();
    if (!userStatus.hasAccess) {
      showTweetTranslationError(tweet, getMessage('noAccessMessage', currentLanguage));
      return;
    }
    
    // 获取用户设置的母语
    const settings = await chrome.storage.sync.get({ nativeLanguage: 'en' });
    const targetLanguage = settings.nativeLanguage;
    
    // 显示加载状态（在推文下方）
    showTweetTranslationLoading(tweet);
    
    // 显示侧边栏（如果之前被隐藏了）
    if (sidebar) {
      sidebar.style.display = 'flex';
    }
    
    // 显示侧边栏加载状态（只显示回复建议，不显示翻译）
    showRepliesLoadingOnly();
    
    // 使用 getReplySuggestions API（SSE流式返回，包含翻译和回复建议）
    let replyData = null;
    let retryCount = 0;
    const maxRetries = 2;
    let translationText = null; // 保存翻译文本，用于在推文下方显示
    
    while (retryCount <= maxRetries && !replyData) {
      try {
        let replyIndex = 0; // 用于跟踪已显示的回复数量
        
        replyData = await apiClient.getReplySuggestions(
          tweetText, 
          targetLanguage, 
          retryCount > 0,
          // onProgress 回调：逐步显示回复
          (type, data) => {
            if (type === 'translation') {
              // 保存翻译文本
              translationText = data.translation;
              
              // 只在推文下方显示翻译，不在侧边栏显示
              showTweetTranslation(tweet, translationText);
              
              // 确保回复建议容器已初始化（不显示翻译内容）
              initReplySuggestionsContainer();
            } else if (type === 'reply') {
              // 确保容器存在
              let container = document.querySelector('.suggestions-container');
              if (!container) {
                initReplySuggestionsContainer();
                container = document.querySelector('.suggestions-container');
              }
              // 立即显示单个回复（哪个先完成就先显示哪个）
              if (container) {
                appendSingleSuggestion(data, replyIndex++);
              }
            } else if (type === 'error') {
              console.error('SSE错误:', data);
            }
          }
        );
        
        break;
        
      } catch (replyError) {
        retryCount++;
        console.warn(`回复生成失败 (尝试 ${retryCount}/${maxRetries + 1}):`, replyError);
        
        if (retryCount > maxRetries) {
          throw replyError;
        }
        
        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
    
    // 如果翻译文本还未显示（可能SSE没有返回translation事件），使用翻译API作为备用
    if (!translationText) {
      try {
        const translationData = await apiClient.translateTweet(tweetText, targetLanguage);
        translationText = translationData.translation;
        showTweetTranslation(tweet, translationText);
      } catch (translateError) {
        console.warn('备用翻译API失败:', translateError);
      }
    }
    
  } catch (error) {
    console.error('❌ [Tweet Translate] 翻译失败:', error);
    showTweetTranslationError(tweet, getMessage('error', currentLanguage));
  } finally {
    // 恢复按钮状态
    button.disabled = false;
    button.textContent = getMessage('translateTweetButton', currentLanguage);
  }
}

/**
 * 提取推文文本内容
 */
function extractTweetText(tweet) {
  // 查找推文文本元素
  const tweetTextElement = tweet.querySelector('[data-testid="tweetText"]');
  if (!tweetTextElement) return null;
  
  // 提取文本内容，排除互动数据
  let text = tweetTextElement.innerText || tweetTextElement.textContent || '';
  
  // 清理文本：移除可能的互动数据（如 "1.6K"、"9.7K" 等）
  // 这些通常出现在文本末尾
  text = text.trim();
  
  // 移除末尾的数字模式（如 "1.6K"、"150万" 等）
  text = text.replace(/\s*\d+[\.\d]*(K|M|万|k|m)\s*$/, '').trim();
  
  return text;
}

/**
 * 显示翻译加载状态
 */
function showTweetTranslationLoading(tweet) {
  // 移除现有的翻译结果
  const existingResult = tweet.querySelector('.fluentx-translation-result');
  if (existingResult) {
    existingResult.remove();
  }
  
  // 创建加载状态元素
  const loadingDiv = document.createElement('div');
  loadingDiv.className = 'fluentx-translation-result loading';
  loadingDiv.textContent = getMessage('translating', currentLanguage);
  
  // 插入到推文内容后
  const actionBar = tweet.querySelector('[role="group"]');
  if (actionBar && actionBar.parentElement) {
    actionBar.parentElement.insertBefore(loadingDiv, actionBar.nextSibling);
  }
}

/**
 * 显示翻译结果
 */
function showTweetTranslation(tweet, translation) {
  // 移除加载状态
  const loadingDiv = tweet.querySelector('.fluentx-translation-result.loading');
  if (loadingDiv) {
    loadingDiv.remove();
  }
  
  // 移除现有的翻译结果
  const existingResult = tweet.querySelector('.fluentx-translation-result:not(.loading)');
  if (existingResult) {
    existingResult.remove();
  }
  
  // 创建翻译结果显示元素
  const resultDiv = document.createElement('div');
  resultDiv.className = 'fluentx-translation-result';
  resultDiv.textContent = translation;
  
  // 插入到推文内容后
  const actionBar = tweet.querySelector('[role="group"]');
  if (actionBar && actionBar.parentElement) {
    actionBar.parentElement.insertBefore(resultDiv, actionBar.nextSibling);
  }
}

/**
 * 显示翻译错误
 */
function showTweetTranslationError(tweet, errorMessage) {
  // 移除加载状态
  const loadingDiv = tweet.querySelector('.fluentx-translation-result.loading');
  if (loadingDiv) {
    loadingDiv.remove();
  }
  
  // 创建错误显示元素
  const errorDiv = document.createElement('div');
  errorDiv.className = 'fluentx-translation-result error';
  errorDiv.textContent = errorMessage;
  
  // 插入到推文内容后
  const actionBar = tweet.querySelector('[role="group"]');
  if (actionBar && actionBar.parentElement) {
    actionBar.parentElement.insertBefore(errorDiv, actionBar.nextSibling);
  }
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}

