<template>
  <div class="browser-tab-container">
    <!-- 工具栏 -->
    <div class="browser-toolbar">
      <div class="toolbar-left">
        <el-button-group size="small">
          <el-button :icon="ArrowLeft" :disabled="!canGoBack" @click="goBack" />
          <el-button :icon="ArrowRight" :disabled="!canGoForward" @click="goForward" />
          <el-button :icon="Refresh" :loading="isLoading" @click="reload" />
        </el-button-group>
        <div class="url-bar">
          <el-icon v-if="isLoading" class="loading-icon"><Loading /></el-icon>
          <el-icon v-else class="lock-icon"><Lock /></el-icon>
          <span class="url-text">{{ currentUrl }}</span>
        </div>
      </div>
      <div v-if="!isAdminMode" class="toolbar-right">
        <el-tag :type="statusType" size="small">
          {{ statusText }}
        </el-tag>
        <!-- AI 辅助状态 -->
        <el-tag v-if="aiAvailable && aiAnalyzing" type="warning" size="small" class="ai-analyzing-tag">
          <el-icon class="ai-icon"><Loading /></el-icon>
          <span>AI 分析中...</span>
        </el-tag>
        <el-button 
          v-if="loginStatus === 'success'"
          type="primary" 
          size="small"
          @click="handleSaveAccount"
          :loading="saving"
        >
          保存账号
        </el-button>
        <el-button 
          size="small"
          @click="handleCheckLogin"
          :loading="checking"
        >
          检测登录
        </el-button>
      </div>
    </div>
    
    <!-- AI 辅助提示面板 -->
    <div v-if="aiAvailable && showAIPanel && !isAdminMode" class="ai-panel">
      <div class="ai-panel-header">
        <span class="ai-panel-title">
          <el-icon><MagicStick /></el-icon>
          AI 智能助手
        </span>
        <div class="ai-panel-actions">
          <el-switch 
            v-model="autoOperationEnabled" 
            size="small"
            active-text="自动操作"
            inactive-text=""
          />
          <el-button 
            link
            size="small" 
            @click="showAIPanel = false"
            class="ai-panel-close"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      <div class="ai-panel-content">
        <!-- 正在执行操作提示 -->
        <div v-if="isExecutingOperation" class="ai-executing">
          <el-icon class="executing-icon"><Loading /></el-icon>
          <span>正在执行自动操作...</span>
        </div>
        
        <!-- 上一次操作信息 -->
        <div v-if="lastOperation?.hasAction && lastOperation.explanation" class="ai-last-operation">
          <div class="ai-status-label">上次操作</div>
          <div class="ai-status-value">{{ lastOperation.explanation }}</div>
        </div>
        
        <!-- 页面状态描述 -->
        <div v-if="aiAnalysis?.pageDescription" class="ai-status">
          <div class="ai-status-label">页面状态</div>
          <div class="ai-status-value">{{ aiAnalysis.pageDescription }}</div>
        </div>
        
        <!-- 验证码提示 -->
        <div v-if="aiAnalysis?.hasVerification" class="ai-verification">
          <el-alert 
            :title="getVerificationTitle(aiAnalysis.verificationType)" 
            type="warning" 
            :closable="false"
            show-icon
          >
            <template #default>
              <div v-if="aiAnalysis.verificationDescription">
                {{ aiAnalysis.verificationDescription }}
              </div>
              <div v-if="aiAnalysis.suggestedAction" class="ai-action">
                <strong>建议操作：</strong>{{ aiAnalysis.suggestedAction }}
              </div>
            </template>
          </el-alert>
        </div>
        
        <!-- 建议操作（非验证码情况） -->
        <div v-else-if="aiAnalysis?.suggestedAction && !aiAnalysis?.isLoggedIn" class="ai-suggestion">
          <el-alert 
            title="AI 建议" 
            type="info" 
            :closable="false"
            show-icon
          >
            <template #default>
              <div>{{ aiAnalysis.suggestedAction }}</div>
              <el-button 
                v-if="autoOperationEnabled"
                type="primary" 
                size="small" 
                @click="performAutoOperation(aiAnalysis?.suggestedAction || '完成登录')"
                :loading="isExecutingOperation"
                style="margin-top: 8px;"
              >
                执行此操作
              </el-button>
            </template>
          </el-alert>
        </div>
        
        <!-- 登录成功提示 -->
        <div v-else-if="aiAnalysis?.isLoggedIn" class="ai-success">
          <el-alert 
            title="AI 检测到登录成功" 
            type="success" 
            :closable="false"
            show-icon
          >
            <template #default>
              <div v-if="aiAnalysis.suggestedAction">{{ aiAnalysis.suggestedAction }}</div>
            </template>
          </el-alert>
        </div>
        
        <!-- 分析时间 -->
        <div v-if="lastAIAnalysisTime" class="ai-time">
          上次分析：{{ formatTime(lastAIAnalysisTime) }}
        </div>
      </div>
    </div>

    <!-- 内嵌浏览器 -->
    <div class="browser-content">
      <webview
        v-if="webviewReady"
        ref="webviewRef"
        :src="webviewSrc"
        :partition="webviewPartition"
        class="embedded-browser"
        allowpopups
        disablewebsecurity
        @did-start-loading="handleStartLoading"
        @did-stop-loading="handleStopLoading"
        @did-navigate="handleNavigate"
        @did-navigate-in-page="handleNavigateInPage"
        @page-title-updated="handleTitleUpdate"
        @dom-ready="handleDomReady"
      />
      
      <!-- 登录成功遮罩（管理模式下不显示） -->
      <div v-if="loginStatus === 'success' && !isAdminMode" class="success-overlay">
        <div class="success-content">
          <el-icon class="success-icon"><CircleCheck /></el-icon>
          <h3>登录成功！</h3>
          <!-- 正在获取账号信息 -->
          <div v-if="fetchingAccountInfo" class="account-fetching">
            <el-icon class="fetching-icon"><Loading /></el-icon>
            <span>正在获取账号信息...</span>
            <p class="fetching-hint">请稍候，正在获取头像、昵称、粉丝数、作品数等信息...</p>
            <el-button size="small" @click="cancelFetching" style="margin-top: 12px;">
              取消并关闭
            </el-button>
          </div>
          <!-- 已获取到账号信息，显示保存按钮 -->
          <template v-else>
            <div v-if="hasValidAccountInfo" class="account-preview">
              <div class="account-header">
                <el-avatar :size="56" :src="accountInfo?.avatarUrl || undefined">
                  {{ accountInfo?.accountName?.[0] }}
                </el-avatar>
                <div class="account-text">
                  <div class="account-preview-name">{{ accountInfo?.accountName }}</div>
                  <div class="account-preview-id">{{ accountInfo?.accountId }}</div>
                </div>
              </div>
              <div class="account-stats-grid">
                <div class="stat-item">
                  <span class="stat-value">{{ formatNumber(accountInfo?.fansCount || 0) }}</span>
                  <span class="stat-label">粉丝</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ formatNumber(accountInfo?.worksCount || 0) }}</span>
                  <span class="stat-label">作品</span>
                </div>
                <div v-if="accountInfo?.followingCount !== undefined" class="stat-item">
                  <span class="stat-value">{{ formatNumber(accountInfo.followingCount) }}</span>
                  <span class="stat-label">关注</span>
                </div>
                <div v-if="accountInfo?.likeCount !== undefined" class="stat-item">
                  <span class="stat-value">{{ formatNumber(accountInfo.likeCount) }}</span>
                  <span class="stat-label">获赞</span>
                </div>
              </div>
            </div>
            <p>点击"保存账号"完成添加</p>
            <el-button type="primary" @click="handleSaveAccount" :loading="saving">
              保存账号
            </el-button>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { ArrowLeft, ArrowRight, Refresh, Loading, Lock, CircleCheck, MagicStick, Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { accountsApi } from '@/api/accounts';
import { aiApi, type LoginStatusAnalysis, type PageOperationGuide } from '@/api/ai';
import { useTabsStore, type Tab } from '@/stores/tabs';
import { PLATFORMS } from '@media-manager/shared';
import type { PlatformType } from '@media-manager/shared';

const props = defineProps<{
  tab: Tab;
}>();

const emit = defineEmits<{
  (e: 'accountSaved'): void;
  (e: 'close'): void;
}>();

const tabsStore = useTabsStore();

// Refs
const webviewRef = ref<Electron.WebviewTag | null>(null);
const isLoading = ref(true);
const currentUrl = ref('');
const canGoBack = ref(false);
const canGoForward = ref(false);
const saving = ref(false);
const checking = ref(false);
const loginStatus = ref<'pending' | 'checking' | 'success' | 'failed'>('pending');
const webviewSrc = ref('about:blank'); // 初始为空白页，等 Cookie 设置完再导航
const webviewReady = ref(false); // 控制 webview 是否渲染
const accountInfo = ref<{
  accountId: string;
  accountName: string;
  avatarUrl: string;
  fansCount: number;
  worksCount: number;
  followingCount?: number;  // 关注数（抖音）
  likeCount?: number;       // 获赞数（抖音）
} | null>(null);
const cookieData = ref('');
const fetchingAccountInfo = ref(false); // 是否正在获取账号信息

// 计时器和标志位
let checkTimer: ReturnType<typeof setInterval> | null = null;
let isVerifying = false; // 防止重复验证
let hasShownSuccessMessage = false; // 防止重复显示成功消息

// API 拦截数据存储（用于从 webview 获取 API 响应）
const apiResponseData = ref<Record<string, any>>({});

// AI 辅助相关（前端不使用AI，登录检测使用URL检测）
const aiAvailable = ref(false);
const aiAnalyzing = ref(false);
const aiAnalysis = ref<LoginStatusAnalysis | null>(null);
const showAIPanel = ref(false);
const lastAIAnalysisTime = ref<Date | null>(null);
let aiCheckTimer: ReturnType<typeof setInterval> | null = null;
let isAIAnalyzing = false;
const AI_CHECK_INTERVAL = 5000;
const AI_INITIAL_DELAY = 3000;

// AI 自动操作相关（禁用）
const autoOperationEnabled = ref(false); // 禁用自动操作
const isExecutingOperation = ref(false);
const lastOperation = ref<PageOperationGuide | null>(null);

// 计算属性
const platform = computed(() => props.tab.browserData?.platform as PlatformType);

// 是否是管理后台模式（从后台按钮打开，不需要登录检测和保存账号）
const isAdminMode = computed(() => !!props.tab.browserData?.isAdminMode);

// 是否已获取到有效的账号信息（排除默认值）
const hasValidAccountInfo = computed(() => {
  if (!accountInfo.value) return false;
  const defaultNames = [
    '抖音账号', '小红书账号', '快手账号', '视频号账号', 'B站账号', 
    '头条账号', '百家号账号', '企鹅号账号', '大鱼号账号'
  ];
  return accountInfo.value.accountName && !defaultNames.includes(accountInfo.value.accountName);
});

const initialUrl = computed(() => {
  // 对于百家号管理模式且有预设 Cookie，先跳转到登录页面设置 Cookie
  if (platform.value === 'baijiahao' && 
      props.tab.browserData?.isAdminMode && 
      props.tab.browserData?.cookieData) {
    console.log('[BrowserTab] 百家号管理模式，先跳转到登录页面设置 Cookie');
    return PLATFORMS[platform.value]?.loginUrl || 'about:blank';
  }
  
  // 优先使用 browserData 中指定的 URL
  if (props.tab.browserData?.url) {
    return props.tab.browserData.url;
  }
  // 否则使用平台默认登录 URL
  const platformInfo = PLATFORMS[platform.value];
  return platformInfo?.loginUrl || 'about:blank';
});

// 每个标签页使用独立的 partition 来隔离 cookie
const webviewPartition = computed(() => `persist:browser-${props.tab.id}`);

const statusType = computed(() => {
  switch (loginStatus.value) {
    case 'success': return 'success';
    case 'failed': return 'danger';
    case 'checking': return 'warning';
    default: return 'info';
  }
});

const statusText = computed(() => {
  switch (loginStatus.value) {
    case 'success': return '已登录';
    case 'failed': return '未登录';
    case 'checking': return '检测中...';
    default: return '等待登录';
  }
});

// 方法

// 格式化数字（如 1234 显示为 1,234）
function formatNumber(num: number | undefined): string {
  if (num === undefined || num === null) return '0';
  if (num >= 10000) {
    return (num / 10000).toFixed(1).replace(/\.0$/, '') + '万';
  }
  return num.toLocaleString();
}

function goBack() {
  webviewRef.value?.goBack();
}

function goForward() {
  webviewRef.value?.goForward();
}

function reload() {
  webviewRef.value?.reload();
}

// ==================== AI 辅助功能 ====================

// 检查 AI 服务是否可用（前端 AI 功能已禁用，后端静默检测登录状态）
async function checkAIAvailability() {
  // 前端不再使用 AI 功能，后端会静默检测登录状态
  aiAvailable.value = false;
  console.log('[AI] 前端 AI 功能已禁用，后端静默检测登录状态');
}

// 截取 webview 截图并转为 Base64
async function captureWebviewScreenshot(): Promise<string | null> {
  const webview = webviewRef.value;
  if (!webview) return null;

  try {
    // 获取 webview 的 webContentsId，通过 IPC 调用主进程截图
    const webContentsId = webview.getWebContentsId?.();
    if (!webContentsId) {
      console.warn('[AI] Cannot get webContentsId');
      return null;
    }

    // 调用主进程的截图 API
    if (!window.electronAPI?.captureWebviewPage) {
      console.warn('[AI] captureWebviewPage API not available');
      return null;
    }

    const base64 = await window.electronAPI.captureWebviewPage(webContentsId);
    if (!base64) {
      console.warn('[AI] Captured empty image');
      return null;
    }
    return base64;
  } catch (error) {
    console.error('[AI] Failed to capture screenshot:', error);
    return null;
  }
}

// 执行 AI 分析（核心登录判断逻辑）
async function performAIAnalysis() {
  if (!aiAvailable.value || isAIAnalyzing || loginStatus.value === 'success') {
    return;
  }

  isAIAnalyzing = true;
  aiAnalyzing.value = true;

  try {
    const screenshot = await captureWebviewScreenshot();
    if (!screenshot) {
      console.warn('[AI] No screenshot available for analysis');
      return;
    }

    console.log('[AI] Starting login status analysis...');
    const result = await aiApi.analyzeLoginStatus(screenshot, platform.value);
    
    aiAnalysis.value = result;
    lastAIAnalysisTime.value = new Date();
    
    console.log('[AI] Analysis result:', {
      isLoggedIn: result.isLoggedIn,
      hasVerification: result.hasVerification,
      verificationType: result.verificationType,
      pageDescription: result.pageDescription?.substring(0, 50),
    });

    // 如果检测到验证码，显示提示（需要用户手动处理）
    if (result.hasVerification) {
      showAIPanel.value = true;
      // 验证码需要用户手动处理，不执行自动操作
      return;
    }

    // 如果 AI 检测到登录成功，开始提取账号信息
    if (result.isLoggedIn && loginStatus.value !== 'success') {
      console.log('[AI] Detected login success, starting account info extraction...');
      await handleAILoginSuccess(screenshot);
    } else if (!result.isLoggedIn && autoOperationEnabled.value && !isExecutingOperation.value) {
      // 未登录且启用了自动操作，尝试执行自动操作（如点击扫码登录）
      console.log('[AI] Not logged in, attempting auto operation...');
      // 延迟执行，避免频繁操作
      setTimeout(() => {
        performAutoOperation('完成登录（点击扫码登录或其他登录方式）');
      }, 1000);
    }
  } catch (error) {
    console.error('[AI] Analysis failed:', error);
  } finally {
    isAIAnalyzing = false;
    aiAnalyzing.value = false;
  }
}

// AI 检测到登录成功后，提取账号信息
async function handleAILoginSuccess(currentScreenshot: string) {
  if (loginStatus.value === 'success' || isVerifying) {
    return;
  }
  
  isVerifying = true;
  fetchingAccountInfo.value = true;
  accountInfo.value = null;
  
  console.log('[AI] Extracting account info...');
  
  // 多次尝试关闭可能的活动弹框（有些弹框可能需要多次点击）
  console.log('[AI] Trying to close popups...');
  for (let i = 0; i < 3; i++) {
    const closed = await closeActivityPopup();
    if (closed) {
      console.log(`[AI] Closed popup on attempt ${i + 1}`);
      await new Promise(resolve => setTimeout(resolve, 500));
    } else {
      break;
    }
  }
  
  // 对于视频号平台，需要导航到首页才能获取完整的账号信息（视频号ID、作品数、粉丝数）
  if (platform.value === 'weixin_video') {
    console.log('[AI] Weixin Video: navigating to home page for complete account info...');
    await navigateToWeixinVideoHomePage();
  }
  
  // 最多尝试 3 次提取账号信息
  const MAX_EXTRACT_RETRIES = 3;
  let extractedAccountInfo: {
    accountId: string;
    accountName: string;
    avatarUrl: string;
    fansCount: number;
    worksCount: number;
  } | null = null;
  
  // 优先从 HTML 中提取账号信息（不受遮罩/弹窗影响）
  console.log('[AI] Trying to extract account info from HTML first...');
  try {
    const htmlExtractResult = await extractAccountInfoFromPage();
    console.log('[AI] HTML extract result:', htmlExtractResult);
    
    if (htmlExtractResult && htmlExtractResult.accountName) {
      // 检查 accountId 是否有效（不是时间戳生成的，也不是空）
      const accountId = htmlExtractResult.accountId || '';
      const isValidAccountId = accountId && 
        !accountId.match(/_\d{13}$/) && // 不是时间戳结尾
        !accountId.match(/_\d{10}$/);   // 也不是 Unix 时间戳
      
      // 即使没有有效的 accountId，只要有用户名就可以先保存
      // 后台刷新会获取正确的 accountId
      extractedAccountInfo = {
        accountId: isValidAccountId ? accountId : `${platform.value}_${Date.now()}`,
        accountName: htmlExtractResult.accountName,
        avatarUrl: htmlExtractResult.avatarUrl || '',
        fansCount: htmlExtractResult.fansCount || 0,
        worksCount: htmlExtractResult.worksCount || 0,
      };
      
      if (isValidAccountId) {
        console.log('[AI] Successfully extracted complete account info from HTML:', extractedAccountInfo);
      } else {
        console.log('[AI] Extracted account name but ID is not valid, will refresh later:', extractedAccountInfo);
      }
    }
  } catch (htmlError) {
    console.warn('[AI] HTML extraction failed:', htmlError);
  }
  
  // 如果 HTML 提取失败，再用 AI 截图分析
  if (!extractedAccountInfo) {
    console.log('[AI] HTML extraction failed, falling back to screenshot AI...');
    
    for (let attempt = 1; attempt <= MAX_EXTRACT_RETRIES; attempt++) {
      console.log(`[AI] Extract attempt ${attempt}/${MAX_EXTRACT_RETRIES}...`);
      
      try {
        // 每次重试都重新截图
        const screenshot = attempt === 1 ? currentScreenshot : await captureWebviewScreenshot();
        if (!screenshot) {
          console.warn('[AI] No screenshot for extraction');
          continue;
        }
        
        // 调用 AI 提取账号信息
        const extractResult = await aiApi.extractAccountInfo(screenshot, platform.value);
        
        console.log('[AI] Extract result:', extractResult);
        
        if (extractResult.found && extractResult.accountName) {
          // AI 成功提取到账号信息
          // 注意：worksCount 设为 0，让后台刷新来获取准确数据（AI 提取的作品数常常不准确）
          extractedAccountInfo = {
            accountId: extractResult.accountId || `${platform.value}_${Date.now()}`,
            accountName: extractResult.accountName,
            avatarUrl: '', // AI 返回的是描述，不是 URL，头像需要从页面 JS 获取
            fansCount: parseInt(String(extractResult.fansCount || 0)) || 0,
            worksCount: 0, // 由后台刷新获取准确数据
          };
          
          // 尝试从页面获取头像 URL（补充 AI 无法获取的信息）
          try {
            const avatarUrl = await getAvatarUrlFromPage();
            if (avatarUrl) {
              extractedAccountInfo.avatarUrl = avatarUrl;
            }
          } catch (e) {
            console.warn('[AI] Failed to get avatar URL from page:', e);
          }
          
          console.log('[AI] Successfully extracted account info:', extractedAccountInfo);
          break;
        } else if (extractResult.navigationGuide) {
          // AI 提供了导航建议
          console.log('[AI] Navigation suggestion:', extractResult.navigationGuide);
          if (aiAnalysis.value) {
            aiAnalysis.value.suggestedAction = extractResult.navigationGuide || undefined;
          }
          
          // 如果启用了自动操作，尝试执行导航操作
          if (autoOperationEnabled.value && !isExecutingOperation.value) {
            console.log('[AI] Attempting auto navigation...');
            await performAutoOperation(`获取账号信息：${extractResult.navigationGuide}`);
            // 导航后等待页面加载
            await new Promise(resolve => setTimeout(resolve, 2000));
          } else {
            showAIPanel.value = true;
          }
        }
        
        // 等待后重试
        if (attempt < MAX_EXTRACT_RETRIES) {
          // 如果 AI 提到弹窗遮挡，多次尝试关闭
          const needClosePopup = extractResult?.navigationGuide?.includes('弹窗') || 
                                 extractResult?.navigationGuide?.includes('遮挡') ||
                                 extractResult?.navigationGuide?.includes('关闭');
          if (needClosePopup) {
            console.log('[AI] AI detected popup, trying to close...');
            for (let i = 0; i < 3; i++) {
              const closed = await closeActivityPopup();
              if (!closed) break;
              await new Promise(resolve => setTimeout(resolve, 500));
            }
          } else {
            await closeActivityPopup();
          }
          await new Promise(resolve => setTimeout(resolve, 2000));
        }
      } catch (error) {
        console.error(`[AI] Extract attempt ${attempt} failed:`, error);
      }
    }
  }
  
  // 检查是否成功提取到有效的账号信息（排除默认值）
  const defaultNames = [
    '抖音账号', '小红书账号', '快手账号', '视频号账号', 'B站账号', 
    '头条账号', '百家号账号', '企鹅号账号', '大鱼号账号', '未知账号'
  ];
  const isValidAccountInfo = extractedAccountInfo && 
    extractedAccountInfo.accountName && 
    !defaultNames.includes(extractedAccountInfo.accountName);
  
  if (isValidAccountInfo) {
    // 成功！保存 cookies 并设置登录成功状态
    const cookies = await getCookies();
    if (cookies && cookies.length > 0) {
      cookieData.value = formatCookies(cookies);
    }
    
    accountInfo.value = extractedAccountInfo;
    loginStatus.value = 'success';
    stopAutoCheck();
    stopAIAnalysis();
    
    if (!hasShownSuccessMessage) {
      hasShownSuccessMessage = true;
      ElMessage.success('登录成功！已获取账号信息');
    }
  } else {
    console.log('[AI] Account info is invalid or default, not triggering save prompt');
    // 提取失败，尝试导航到个人中心页面获取账号信息
    console.log('[AI] Failed to extract account info, trying to navigate to profile page...');
    
    if (autoOperationEnabled.value && !isExecutingOperation.value) {
      // 尝试自动导航到个人中心
      const navigated = await navigateToProfilePage();
      
      if (navigated) {
        // 导航成功，等待页面加载后重新提取
        await new Promise(resolve => setTimeout(resolve, 3000));
        
        // 再次尝试提取
        const retryScreenshot = await captureWebviewScreenshot();
        if (retryScreenshot) {
          const retryResult = await aiApi.extractAccountInfo(retryScreenshot, platform.value);
          console.log('[AI] Retry extract result after navigation:', retryResult);
          
          // 验证提取的账号信息是否有效
          const retryIsValid = retryResult.found && 
            retryResult.accountName && 
            !defaultNames.includes(retryResult.accountName);
          
          if (retryIsValid) {
            // 注意：worksCount 设为 0，让后台刷新来获取准确数据
            extractedAccountInfo = {
              accountId: retryResult.accountId || `${platform.value}_${Date.now()}`,
              accountName: retryResult.accountName,
              avatarUrl: '',
              fansCount: parseInt(String(retryResult.fansCount || 0)) || 0,
              worksCount: 0, // 由后台刷新获取准确数据
            };
            
            try {
              const avatarUrl = await getAvatarUrlFromPage();
              if (avatarUrl) extractedAccountInfo.avatarUrl = avatarUrl;
            } catch (e) { /* ignore */ }
            
            // 成功提取到账号信息
            const cookies = await getCookies();
            if (cookies && cookies.length > 0) {
              cookieData.value = formatCookies(cookies);
            }
            
            accountInfo.value = extractedAccountInfo;
            loginStatus.value = 'success';
            stopAutoCheck();
            stopAIAnalysis();
            
            if (!hasShownSuccessMessage) {
              hasShownSuccessMessage = true;
              ElMessage.success('登录成功！已获取账号信息');
            }
            
            fetchingAccountInfo.value = false;
            isVerifying = false;
            return;
          }
        }
      }
    }
    
    // AI 提取失败，尝试通过服务端 API 获取账号信息
    console.log('[AI] Trying to get account info via server API...');
    
    try {
      // 先获取 cookies
      const cookies = await getCookies();
      if (cookies && cookies.length > 0) {
        cookieData.value = formatCookies(cookies);
        
        // 调用服务端 API 验证 Cookie 并获取账号信息
        const verifyResult = await accountsApi.verifyLoginCookie(platform.value, cookieData.value);
        
        console.log('[AI] Server verify result:', verifyResult);
        
        // 检查服务端返回的账号信息是否有效
        if (verifyResult.success && verifyResult.accountInfo) {
          const serverAccountInfo = verifyResult.accountInfo;
          if (serverAccountInfo.accountName && !defaultNames.includes(serverAccountInfo.accountName)) {
            extractedAccountInfo = {
              accountId: serverAccountInfo.accountId || `${platform.value}_${Date.now()}`,
              accountName: serverAccountInfo.accountName,
              avatarUrl: serverAccountInfo.avatarUrl || '',
              fansCount: serverAccountInfo.fansCount || 0,
              worksCount: serverAccountInfo.worksCount || 0,
            };
            
            accountInfo.value = extractedAccountInfo;
            loginStatus.value = 'success';
            stopAutoCheck();
            stopAIAnalysis();
            
            if (!hasShownSuccessMessage) {
              hasShownSuccessMessage = true;
              ElMessage.success('登录成功！已获取账号信息');
            }
            
            fetchingAccountInfo.value = false;
            isVerifying = false;
            return;
          }
        }
      }
    } catch (serverError) {
      console.warn('[AI] Server API failed:', serverError);
    }
    
    // 仍然失败，显示提示
    if (aiAnalysis.value) {
      aiAnalysis.value.suggestedAction = '无法获取账号信息，请手动进入个人中心页面，或点击头像查看账号信息';
    }
    showAIPanel.value = true;
  }
  
  fetchingAccountInfo.value = false;
  isVerifying = false;
}

// 尝试导航到个人中心页面（用于获取账号信息）
async function navigateToProfilePage(): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  console.log('[AutoOp] Trying to navigate to profile page...');
  
  try {
    // 获取页面 HTML
    const html = await getPageHtml();
    if (!html) return false;
    
    // 使用 AI 分析 HTML，找到个人中心入口
    const guide = await aiApi.getHtmlOperationGuide(
      html, 
      platform.value, 
      '找到并点击"个人中心"、"账号管理"、"账号设置"、用户头像或用户名称等入口，进入可以查看账号信息的页面'
    );
    
    console.log('[AutoOp] Navigation guide:', guide);
    
    if (guide.hasAction && guide.targetSelector) {
      const success = await executeClick(guide);
      if (success) {
        console.log('[AutoOp] Successfully clicked profile entry');
        return true;
      }
    }
    
    // 如果 AI 分析失败，尝试直接查找常见的个人中心入口
    const fallbackClicked = await tryClickProfileEntryFallback();
    if (fallbackClicked) {
      console.log('[AutoOp] Clicked profile entry via fallback');
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('[AutoOp] Navigate to profile failed:', error);
    return false;
  }
}

// 尝试点击常见的个人中心入口（备用方案）
async function tryClickProfileEntryFallback(): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  const currentPlatform = platform.value;
  
  const script = `
    (function() {
      const platform = '${currentPlatform}';
      
      // 百家号特有的选择器和操作
      if (platform === 'baijiahao') {
        // 百家号侧边栏菜单
        const baijiahaoSelectors = [
          // 侧边栏菜单项
          'a[href*="/builder/rc/home"]',
          'a[href*="builder/rc/home"]',
          '.side-nav a[href*="home"]',
          '.menu-item[data-menu="home"]',
          // 个人中心入口
          '.header-user', '.header-avatar',
          '.user-dropdown', '.user-menu',
          // 账号设置
          'a[href*="account"]', 'a[href*="setting"]',
          // 侧边栏 - 首页（通常显示账号信息）
          '.sidebar a:first-child',
          '.side-nav li:first-child a',
          // 头像相关
          '.avatar-wrap', '.header-info',
          'img.avatar', '.user-avatar',
        ];
        
        for (const selector of baijiahaoSelectors) {
          try {
            const el = document.querySelector(selector);
            if (el && el.offsetParent !== null) {
              el.scrollIntoView({ behavior: 'instant', block: 'center' });
              el.click();
              console.log('[Baijiahao] Clicked:', selector);
              return { success: true, platform: 'baijiahao', selector };
            }
          } catch (e) {}
        }
        
        // 尝试查找百家号的菜单文本
        const baijiahaoTexts = ['首页', '个人中心', '账号信息', '账号设置', '我的主页'];
        const menuItems = document.querySelectorAll('.side-nav a, .menu-item, .nav-item, a[class*="menu"], a[class*="nav"]');
        for (const item of menuItems) {
          const text = item.textContent?.trim();
          if (text && baijiahaoTexts.some(t => text.includes(t))) {
            item.scrollIntoView({ behavior: 'instant', block: 'center' });
            item.click();
            console.log('[Baijiahao] Clicked menu text:', text);
            return { success: true, platform: 'baijiahao', text };
          }
        }
      }
      
      // 通用的个人中心入口选择器
      const profileSelectors = [
        // 头部用户区域
        '.header-user', '.header-avatar', '.user-dropdown',
        '[class*="header-user"]', '[class*="headerUser"]',
        '[class*="user-info"]', '[class*="userInfo"]',
        // 个人中心链接
        'a[href*="profile"]', 'a[href*="account"]', 
        'a[href*="personal"]', 'a[href*="center"]',
        'a[href*="setting"]', 'a[href*="home"]',
        // 通用选择器
        '[class*="profile"]', '[class*="Profile"]',
        '[class*="account"]', '[class*="Account"]',
        '[class*="personal"]', '[class*="Personal"]',
        '.user-center', '.user-info', '.user-name',
        '.author-info', '.author-name',
      ];
      
      const profileTexts = [
        '个人中心', '账号管理', '账号设置', '个人设置',
        '我的主页', '我的账号', '用户中心', '账户管理',
        '个人信息', '账号信息', '首页', '设置'
      ];
      
      // 尝试通过选择器点击
      for (const selector of profileSelectors) {
        try {
          const el = document.querySelector(selector);
          if (el && el.offsetParent !== null) {
            el.scrollIntoView({ behavior: 'instant', block: 'center' });
            el.click();
            console.log('[Fallback] Clicked:', selector);
            return { success: true, method: 'selector', selector };
          }
        } catch (e) {}
      }
      
      // 尝试通过文本点击
      const allElements = document.querySelectorAll('a, button, span, div, li');
      for (const el of allElements) {
        const text = el.textContent?.trim();
        if (text && text.length < 20 && profileTexts.some(t => text.includes(t))) {
          // 确保元素可见
          if (el.offsetParent !== null) {
            el.scrollIntoView({ behavior: 'instant', block: 'center' });
            el.click();
            console.log('[Fallback] Clicked by text:', text);
            return { success: true, method: 'text', text };
          }
        }
      }
      
      // 尝试点击头像图片（通常是进入个人中心的入口）
      const avatarImgs = document.querySelectorAll(
        '[class*="avatar"] img, [class*="Avatar"] img, img[class*="avatar"], ' +
        '.header img, .user img, img.avatar'
      );
      for (const img of avatarImgs) {
        if (img.offsetParent !== null) {
          const parent = img.closest('a') || img.parentElement;
          if (parent) {
            parent.scrollIntoView({ behavior: 'instant', block: 'center' });
            parent.click();
            console.log('[Fallback] Clicked avatar');
            return { success: true, method: 'avatar' };
          }
        }
      }
      
      return { success: false };
    })()
  `;
  
  try {
    const result = await webview.executeJavaScript(script);
    console.log('[Fallback] Click result:', result);
    return result?.success || false;
  } catch (e) {
    console.warn('[Fallback] Failed:', e);
    return false;
  }
}

// 从页面获取头像 URL
async function getAvatarUrlFromPage(): Promise<string | null> {
  const webview = webviewRef.value;
  if (!webview) return null;
  
  try {
    const script = `
      (function() {
        // 查找可能的头像图片
        const avatarSelectors = [
          // 通用头像选择器
          '[class*="avatar"] img',
          '[class*="Avatar"] img',
          'img[class*="avatar"]',
          '.user-avatar img',
          '.user-info img',
          '.ant-avatar img',
          '.header-user img',
          // 微信视频号特定选择器
          'img[src*="wx.qlogo"]',
          'img[src*="mmbiz.qpic"]',
          'img[src*="thirdwx"]',
          '.finder-avatar img',
          '.account-avatar img',
          // 顶部导航栏头像
          '.header img',
          'nav img',
          '.navbar img'
        ];
        
        for (const selector of avatarSelectors) {
          const imgs = document.querySelectorAll(selector);
          for (const img of imgs) {
            const src = img.src || '';
            if (src && src.startsWith('http') && !src.includes('logo') && !src.includes('icon') && !src.includes('banner')) {
              console.log('[getAvatarUrlFromPage] Found avatar:', src);
              return src;
            }
          }
        }
        
        // 备选：查找所有圆形或适当大小的图片
        const allImgs = document.querySelectorAll('img');
        for (const img of allImgs) {
          const src = img.src || '';
          if (!src || !src.startsWith('http')) continue;
          if (src.includes('logo') || src.includes('icon') || src.includes('banner')) continue;
          
          const style = window.getComputedStyle(img);
          const rect = img.getBoundingClientRect();
          const isRound = style.borderRadius && (style.borderRadius.includes('50%') || parseInt(style.borderRadius) > 10);
          const isAvatarSize = rect.width >= 24 && rect.width <= 100;
          const isInHeader = rect.top < 100;
          
          // 微信头像 URL 特征
          const isWeixinAvatar = src.includes('wx.qlogo') || src.includes('mmbiz') || src.includes('thirdwx');
          
          if ((isWeixinAvatar || (isRound && isAvatarSize) || (isInHeader && isAvatarSize))) {
            console.log('[getAvatarUrlFromPage] Found avatar via fallback:', src);
            return src;
          }
        }
        
        return null;
      })()
    `;
    return await webview.executeJavaScript(script);
  } catch (e) {
    return null;
  }
}

// ==================== AI 自动操作功能 ====================

// 获取页面 HTML 内容
async function getPageHtml(): Promise<string | null> {
  const webview = webviewRef.value;
  if (!webview) return null;
  
  try {
    const html = await webview.executeJavaScript('document.documentElement.outerHTML');
    return html;
  } catch (error) {
    console.error('[AutoOp] Failed to get page HTML:', error);
    return null;
  }
}

// 获取 AI 操作指导并执行（使用 HTML 分析）
async function performAutoOperation(goal: string = '完成登录并获取账号信息') {
  if (!aiAvailable.value || isExecutingOperation.value || loginStatus.value === 'success') {
    return;
  }
  
  const webview = webviewRef.value;
  if (!webview) return;
  
  isExecutingOperation.value = true;
  
  try {
    // 获取页面 HTML
    const html = await getPageHtml();
    if (!html) {
      console.warn('[AutoOp] No HTML available');
      return;
    }
    
    console.log('[AutoOp] Getting operation guide from AI (HTML analysis)...');
    console.log('[AutoOp] HTML length:', html.length);
    
    // 使用 HTML 分析获取操作指导
    const guide = await aiApi.getHtmlOperationGuide(html, platform.value, goal);
    lastOperation.value = guide;
    
    console.log('[AutoOp] AI guide:', guide);
    
    if (!guide.hasAction) {
      console.log('[AutoOp] No action needed:', guide.explanation);
      // 更新 AI 面板显示
      if (aiAnalysis.value) {
        aiAnalysis.value.suggestedAction = guide.explanation;
      }
      showAIPanel.value = true;
      return;
    }
    
    // 执行操作
    const success = await executeOperation(guide);
    
    if (success) {
      console.log('[AutoOp] Operation executed successfully');
      // 等待页面响应
      await new Promise(resolve => setTimeout(resolve, 2000));
      // 触发新一轮 AI 分析
      performAIAnalysis();
    } else {
      console.warn('[AutoOp] Operation execution failed');
      // 显示建议让用户手动操作
      if (aiAnalysis.value) {
        aiAnalysis.value.suggestedAction = `自动操作失败，请手动${guide.targetDescription || guide.explanation}`;
      }
      showAIPanel.value = true;
    }
  } catch (error) {
    console.error('[AutoOp] Error:', error);
    if (aiAnalysis.value) {
      aiAnalysis.value.suggestedAction = '自动操作失败，请手动操作';
    }
    showAIPanel.value = true;
  } finally {
    isExecutingOperation.value = false;
  }
}

// 执行具体操作
async function executeOperation(guide: PageOperationGuide): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  try {
    switch (guide.actionType) {
      case 'click':
        return await executeClick(guide);
      case 'input':
        return await executeInput(guide);
      case 'scroll':
        return await executeScroll(guide);
      case 'wait':
        await new Promise(resolve => setTimeout(resolve, 2000));
        return true;
      case 'navigate':
        // 导航操作需要特殊处理
        console.log('[AutoOp] Navigate action not implemented');
        return false;
      default:
        console.warn('[AutoOp] Unknown action type:', guide.actionType);
        return false;
    }
  } catch (error) {
    console.error('[AutoOp] Execute operation error:', error);
    return false;
  }
}

// 执行点击操作（优先使用 CSS 选择器 + JavaScript 点击）
async function executeClick(guide: PageOperationGuide): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  // 方法1: 使用 CSS 选择器直接点击（最可靠）
  if (guide.targetSelector) {
    console.log('[AutoOp] Trying to click by selector:', guide.targetSelector);
    
    // 尝试多种点击方式
    const clickScript = `
      (function() {
        const selector = '${guide.targetSelector.replace(/'/g, "\\'")}';
        const el = document.querySelector(selector);
        
        if (!el) {
          console.log('[AutoOp] Element not found:', selector);
          return { success: false, reason: 'not_found' };
        }
        
        // 滚动到元素可见
        el.scrollIntoView({ behavior: 'instant', block: 'center' });
        
        // 尝试多种点击方式
        try {
          // 方式1: 直接 click()
          el.click();
          console.log('[AutoOp] Clicked via click()');
          return { success: true, method: 'click' };
        } catch (e1) {
          try {
            // 方式2: 模拟鼠标事件
            const rect = el.getBoundingClientRect();
            const mouseDown = new MouseEvent('mousedown', {
              bubbles: true, cancelable: true, view: window,
              clientX: rect.left + rect.width / 2,
              clientY: rect.top + rect.height / 2
            });
            const mouseUp = new MouseEvent('mouseup', {
              bubbles: true, cancelable: true, view: window,
              clientX: rect.left + rect.width / 2,
              clientY: rect.top + rect.height / 2
            });
            const click = new MouseEvent('click', {
              bubbles: true, cancelable: true, view: window,
              clientX: rect.left + rect.width / 2,
              clientY: rect.top + rect.height / 2
            });
            el.dispatchEvent(mouseDown);
            el.dispatchEvent(mouseUp);
            el.dispatchEvent(click);
            console.log('[AutoOp] Clicked via MouseEvent');
            return { success: true, method: 'mouseEvent' };
          } catch (e2) {
            return { success: false, reason: 'click_failed', error: e2.message };
          }
        }
      })()
    `;
    
    try {
      const result = await webview.executeJavaScript(clickScript);
      console.log('[AutoOp] Click result:', result);
      if (result?.success) {
        return true;
      }
    } catch (e) {
      console.warn('[AutoOp] Failed to execute click script:', e);
    }
  }
  
  // 方法2: 通过文本内容查找并点击
  if (guide.targetDescription) {
    console.log('[AutoOp] Trying to click by text:', guide.targetDescription);
    
    const clickByTextScript = `
      (function() {
        const searchText = '${guide.targetDescription.replace(/'/g, "\\'")}';
        
        // 查找包含文本的可点击元素
        const clickables = document.querySelectorAll('a, button, [role="button"], input[type="submit"], input[type="button"], [onclick]');
        for (const el of clickables) {
          const text = el.textContent?.trim() || el.getAttribute('aria-label') || el.getAttribute('title') || '';
          if (text.includes(searchText)) {
            el.scrollIntoView({ behavior: 'instant', block: 'center' });
            el.click();
            console.log('[AutoOp] Clicked element with text:', text);
            return { success: true, text };
          }
        }
        
        // 查找所有元素
        const allElements = document.querySelectorAll('*');
        for (const el of allElements) {
          const text = el.innerText?.trim();
          if (text && text.length < 100 && text.includes(searchText)) {
            el.scrollIntoView({ behavior: 'instant', block: 'center' });
            el.click();
            console.log('[AutoOp] Clicked element:', el.tagName, text);
            return { success: true, text };
          }
        }
        
        return { success: false, reason: 'text_not_found' };
      })()
    `;
    
    try {
      const result = await webview.executeJavaScript(clickByTextScript);
      console.log('[AutoOp] Click by text result:', result);
      if (result?.success) {
        return true;
      }
    } catch (e) {
      console.warn('[AutoOp] Failed to click by text:', e);
    }
  }
  
  console.warn('[AutoOp] Could not find element to click');
  return false;
}

// 执行输入操作（使用 JavaScript 直接操作）
async function executeInput(guide: PageOperationGuide): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview || !guide.inputText) return false;
  
  const inputText = guide.inputText;
  const selector = guide.targetSelector;
  
  const inputScript = `
    (function() {
      const inputText = '${inputText.replace(/'/g, "\\'")}';
      const selector = '${selector?.replace(/'/g, "\\'") || ''}';
      
      let el = null;
      
      // 优先使用选择器
      if (selector) {
        el = document.querySelector(selector);
      }
      
      // 如果没找到，查找当前焦点元素
      if (!el) {
        el = document.activeElement;
        if (el?.tagName !== 'INPUT' && el?.tagName !== 'TEXTAREA') {
          el = null;
        }
      }
      
      // 如果还没找到，查找第一个可见输入框
      if (!el) {
        el = document.querySelector('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="checkbox"]):not([type="radio"]), textarea');
      }
      
      if (!el) {
        return { success: false, reason: 'no_input_found' };
      }
      
      // 滚动到元素可见
      el.scrollIntoView({ behavior: 'instant', block: 'center' });
      
      // 聚焦
      el.focus();
      
      // 清空并输入
      if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
        el.value = inputText;
      } else if (el.contentEditable === 'true') {
        el.textContent = inputText;
      }
      
      // 触发事件
      el.dispatchEvent(new Event('input', { bubbles: true }));
      el.dispatchEvent(new Event('change', { bubbles: true }));
      el.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true }));
      
      console.log('[AutoOp] Input completed:', el.tagName, inputText);
      return { success: true, element: el.tagName };
    })()
  `;
  
  try {
    const result = await webview.executeJavaScript(inputScript);
    console.log('[AutoOp] Input result:', result);
    return result?.success || false;
  } catch (e) {
    console.warn('[AutoOp] Failed to execute input script:', e);
    return false;
  }
}

// 执行滚动操作
async function executeScroll(_guide: PageOperationGuide): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  const scrollScript = `
    (function() {
      window.scrollBy({
        top: 300,
        behavior: 'smooth'
      });
      return true;
    })()
  `;
  
  await webview.executeJavaScript(scrollScript);
  console.log('[AutoOp] Scrolled down');
  return true;
}

// 启动 AI 分析
function startAIAnalysis() {
  if (!aiAvailable.value || isAdminMode.value) {
    return;
  }

  stopAIAnalysis();

  // 延迟首次分析，等待页面加载
  setTimeout(() => {
    performAIAnalysis();
  }, AI_INITIAL_DELAY);

  // 定期分析
  aiCheckTimer = setInterval(() => {
    if (loginStatus.value !== 'success') {
      performAIAnalysis();
    } else {
      stopAIAnalysis();
    }
  }, AI_CHECK_INTERVAL);
}

// 停止 AI 分析
function stopAIAnalysis() {
  if (aiCheckTimer) {
    clearInterval(aiCheckTimer);
    aiCheckTimer = null;
  }
}

// 获取验证类型标题
function getVerificationTitle(type?: string | null): string {
  const titles: Record<string, string> = {
    captcha: '需要输入图形验证码',
    sms: '需要输入短信验证码',
    qrcode: '需要扫码验证',
    face: '需要人脸识别验证',
    slider: '需要滑块验证',
    other: '需要完成验证',
  };
  return titles[type || 'other'] || '检测到验证码';
}

// 格式化时间
function formatTime(date: Date): string {
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

// ==================== 原有功能 ====================

function handleStartLoading() {
  isLoading.value = true;
}

function handleStopLoading() {
  isLoading.value = false;
  updateNavigation();
}

function handleNavigate(event: Electron.DidNavigateEvent) {
  currentUrl.value = event.url;
  updateNavigation();
  
  // 页面跳转后立即检测一次登录状态（加快响应）
  // 管理模式下跳过检测
  if (!isAdminMode.value && loginStatus.value !== 'success') {
    setTimeout(() => checkLoginSilently(), 500);
  }
}

function handleNavigateInPage(event: Electron.DidNavigateInPageEvent) {
  currentUrl.value = event.url;
  updateNavigation();
}

function handleTitleUpdate(event: Electron.PageTitleUpdatedEvent) {
  // 更新标签页标题
  const platformName = PLATFORMS[platform.value]?.name || platform.value;
  tabsStore.updateTab(props.tab.id, { 
    title: `${platformName} - ${event.title}` 
  });
}

function handleDomReady() {
  updateNavigation();
  currentUrl.value = webviewRef.value?.getURL() || '';
  
  // 对于百家号管理模式，在登录页面加载完成后跳转到后台
  if (isAdminMode.value && platform.value === 'baijiahao' && props.tab.browserData?.url) {
    const currentUrl = webviewRef.value?.getURL() || '';
    const targetUrl = props.tab.browserData.url;
    
    // 如果当前在登录页面，且目标是后台页面，则跳转
    if (currentUrl.includes('/builder/theme/bjh/login') && targetUrl.includes('/builder/rc/')) {
      console.log('[BrowserTab] 百家号登录页面加载完成，Cookie 已设置，跳转到后台:', targetUrl);
      setTimeout(() => {
        if (webviewRef.value) {
          webviewRef.value.loadURL(targetUrl);
        }
      }, 1000); // 等待 1 秒确保 Cookie 完全生效
      return; // 不执行后续逻辑
    }
  }
  
  // 拦截自定义协议链接（如 bitbrowser://）
  setupProtocolInterception();
  
  // 管理模式下不自动检测登录状态
  if (!isAdminMode.value) {
    // 优先使用 CDP 网络拦截（更底层更可靠）
    enableCDPNetworkIntercept();
    
    // 同时保留 JS 注入作为备用（某些情况下 CDP 可能不可用）
    injectApiInterceptScript();
    // 设置 console-message 监听器来接收 API 数据
    setupApiDataListener();
    // 启动自动登录检测
    startAutoCheck();
  }
}

// 注入 API 拦截脚本（监听 XHR/Fetch 响应）
function injectApiInterceptScript() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  // 根据平台获取需要监听的 API 列表
  const apiPatterns = getApiPatternsForPlatform();
  if (apiPatterns.length === 0) return;
  
  const script = `
    (function() {
      // 更新 API 模式列表（每次都更新，确保最新）
      window.__apiPatterns__ = ${JSON.stringify(apiPatterns)};
      
      // 如果已经安装过拦截器，只更新模式列表
      if (window.__apiInterceptorInstalled__) {
        console.log('API 拦截器已存在，更新模式列表，监听 ' + window.__apiPatterns__.length + ' 个 API');
        return;
      }
      window.__apiInterceptorInstalled__ = true;
      
      // 拦截 XMLHttpRequest
      const originalXHROpen = XMLHttpRequest.prototype.open;
      const originalXHRSend = XMLHttpRequest.prototype.send;
      
      XMLHttpRequest.prototype.open = function(method, url) {
        this._url = url;
        this._method = method;
        return originalXHROpen.apply(this, arguments);
      };
      
      XMLHttpRequest.prototype.send = function() {
        this.addEventListener('load', function() {
          try {
            const url = this._url || '';
            const patterns = window.__apiPatterns__ || [];
            for (const pattern of patterns) {
              if (url.includes(pattern.match)) {
                console.log('[XHR拦截] 匹配到 API:', pattern.key, url);
                const data = JSON.parse(this.responseText);
                console.log('__API_INTERCEPT__:' + JSON.stringify({
                  key: pattern.key,
                  url: url,
                  data: data
                }));
              }
            }
          } catch (e) {
            console.warn('[XHR拦截] 解析失败:', e);
          }
        });
        return originalXHRSend.apply(this, arguments);
      };
      
      // 拦截 Fetch
      const originalFetch = window.fetch;
      window.fetch = function(input, init) {
        return originalFetch.apply(this, arguments).then(async response => {
          try {
            const url = typeof input === 'string' ? input : input.url;
            const patterns = window.__apiPatterns__ || [];
            for (const pattern of patterns) {
              if (url.includes(pattern.match)) {
                console.log('[Fetch拦截] 匹配到 API:', pattern.key, url);
                const cloned = response.clone();
                const data = await cloned.json();
                console.log('__API_INTERCEPT__:' + JSON.stringify({
                  key: pattern.key,
                  url: url,
                  data: data
                }));
              }
            }
          } catch (e) {
            console.warn('[Fetch拦截] 解析失败:', e);
          }
          return response;
        });
      };
      
      console.log('API 拦截脚本已注入，监听 ' + window.__apiPatterns__.length + ' 个 API，模式:', JSON.stringify(window.__apiPatterns__));
    })();
  `;
  
  webview.executeJavaScript(script).catch(err => {
    console.warn('[ApiIntercept] 注入脚本失败:', err);
  });
}

// 获取各平台需要监听的 API 列表
function getApiPatternsForPlatform(): Array<{match: string, key: string}> {
  const patterns: Record<string, Array<{match: string, key: string}>> = {
    douyin: [
      { match: '/janus/douyin/creator/pc/work_list', key: 'workList' },
    ],
    xiaohongshu: [
      { match: '/api/galaxy/creator/home/personal_info', key: 'personalInfo' },
      { match: '/web_api/sns/v5/creator/note/user/posted', key: 'noteList' },
    ],
    weixin_video: [
      { match: '/cgi-bin/mmfinderassistant-bin/auth/auth_data', key: 'authData' },
    ],
    baijiahao: [
      { match: '/builder/app/appinfo', key: 'appInfo' },
      { match: '/cms-ui/rights/growth/get_info', key: 'growthInfo' },
      { match: '/pcui/article/lists', key: 'articleList' },
    ],
  };
  return patterns[platform.value] || [];
}

// 设置 console-message 监听器来接收 API 拦截数据（JS 注入方式的备用）
function setupApiDataListener() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  webview.addEventListener('console-message', (event: any) => {
    const message = event.message || '';
    if (message.startsWith('__API_INTERCEPT__:')) {
      try {
        const jsonStr = message.substring('__API_INTERCEPT__:'.length);
        const { key, data } = JSON.parse(jsonStr);
        console.log('[ApiIntercept] 收到数据:', key, data);
        apiResponseData.value[key] = data;
      } catch (e) {
        console.warn('[ApiIntercept] 解析数据失败:', e);
      }
    }
  });
}

// ========== CDP 网络拦截（更底层的方式）==========
let cdpInterceptEnabled = false;

// 启用 CDP 网络拦截
async function enableCDPNetworkIntercept() {
  const webview = webviewRef.value;
  if (!webview || cdpInterceptEnabled) return;
  
  try {
    const webContentsId = webview.getWebContentsId();
    if (!webContentsId) {
      console.warn('[CDP] 无法获取 webContentsId');
      return;
    }
    
    const patterns = getApiPatternsForPlatform();
    if (patterns.length === 0) {
      console.log('[CDP] 当前平台无需拦截的 API');
      return;
    }
    
    const result = await window.electronAPI?.enableNetworkIntercept(webContentsId, patterns);
    if (result) {
      cdpInterceptEnabled = true;
      console.log('[CDP] 网络拦截已启用，webContentsId:', webContentsId);
    }
  } catch (err) {
    console.error('[CDP] 启用网络拦截失败:', err);
  }
}

// 禁用 CDP 网络拦截
async function disableCDPNetworkIntercept() {
  const webview = webviewRef.value;
  if (!webview || !cdpInterceptEnabled) return;
  
  try {
    const webContentsId = webview.getWebContentsId();
    if (webContentsId) {
      await window.electronAPI?.disableNetworkIntercept(webContentsId);
    }
    cdpInterceptEnabled = false;
    console.log('[CDP] 网络拦截已禁用');
  } catch (err) {
    console.error('[CDP] 禁用网络拦截失败:', err);
  }
}

// 更新 CDP 拦截的 patterns
async function updateCDPPatterns() {
  const webview = webviewRef.value;
  if (!webview || !cdpInterceptEnabled) return;
  
  try {
    const webContentsId = webview.getWebContentsId();
    const patterns = getApiPatternsForPlatform();
    if (webContentsId && patterns.length > 0) {
      await window.electronAPI?.updateNetworkPatterns(webContentsId, patterns);
      console.log('[CDP] patterns 已更新');
    }
  } catch (err) {
    console.error('[CDP] 更新 patterns 失败:', err);
  }
}

// 设置 CDP 数据监听器
function setupCDPDataListener() {
  window.electronAPI?.onNetworkInterceptData((data) => {
    const webview = webviewRef.value;
    if (!webview) return;
    
    const webContentsId = webview.getWebContentsId();
    if (data.webContentsId === webContentsId) {
      console.log('[CDP] 收到 API 数据:', data.key, data.url);
      apiResponseData.value[data.key] = data.data;
    }
  });
}

// 清理 CDP 监听器
function cleanupCDPListener() {
  window.electronAPI?.removeNetworkInterceptListener();
}

// 拦截自定义协议链接，防止弹出系统对话框
function setupProtocolInterception() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  // 拦截 will-navigate 事件
  webview.addEventListener('will-navigate', (event: any) => {
    const url = event.url || '';
    // 阻止非 http/https 协议的链接
    if (url && !url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('about:')) {
      console.log('[WebView] 阻止自定义协议链接:', url);
      event.preventDefault();
    }
  });
  
  // 拦截新窗口打开
  webview.addEventListener('new-window', (event: any) => {
    const url = event.url || '';
    // 阻止非 http/https 协议的链接
    if (url && !url.startsWith('http://') && !url.startsWith('https://')) {
      console.log('[WebView] 阻止打开自定义协议窗口:', url);
      event.preventDefault();
      return;
    }
    // 对于正常的 http/https 链接，在当前 webview 中打开
    if (url.startsWith('http://') || url.startsWith('https://')) {
      event.preventDefault();
      webview.loadURL(url);
    }
  });
}

function updateNavigation() {
  if (webviewRef.value) {
    canGoBack.value = webviewRef.value.canGoBack();
    canGoForward.value = webviewRef.value.canGoForward();
  }
}

// 开始自动检测登录状态
function startAutoCheck() {
  stopAutoCheck();
  
  // 立即执行一次检测
  checkLoginSilently();
  
  // 每 1.5 秒检测一次（加快检测速度）
  checkTimer = setInterval(() => {
    if (loginStatus.value !== 'success' && !isVerifying) {
      checkLoginSilently();
    } else if (loginStatus.value === 'success') {
      stopAutoCheck();
    }
  }, 1500);
}

function stopAutoCheck() {
  if (checkTimer) {
    clearInterval(checkTimer);
    checkTimer = null;
  }
}

// 取消获取并关闭遮罩
function cancelFetching() {
  fetchingAccountInfo.value = false;
  isVerifying = false;
  loginStatus.value = 'pending';
  accountInfo.value = null;
  hasShownSuccessMessage = false;
  ElMessage.info('已取消，请完成页面操作后再试');
}

/**
 * 检查当前 URL 是否表明已登录成功
 * 
 * 各平台登录成功判定（按用户要求）：
 * - 抖音：跳转到 https://creator.douyin.com/creator-micro/home
 * - 小红书：跳转到 https://creator.xiaohongshu.com/new/home
 * - 微信视频号：跳转到 https://channels.weixin.qq.com/platform
 * - 百家号：跳转到 https://baijiahao.baidu.com/builder/rc/home
 */
function isLoggedInByUrl(): boolean {
  const url = currentUrl.value;
  
  // 明确的登录页面（这些页面肯定不算已登录，包括根路径）
  const explicitLoginPatterns: Record<string, RegExp[]> = {
    douyin: [
      /creator\.douyin\.com\/?$/,           // 创作者中心首页（登录页）
      /creator\.douyin\.com\/login/,        // 登录页
      /passport\.douyin\.com/,              // 护照登录
    ],
    kuaishou: [
      /passport\.kuaishou/,
      /login\.kuaishou/,
      /cp\.kuaishou\.com\/?$/,              // 快手创作者根路径
    ],
    xiaohongshu: [
      /creator\.xiaohongshu\.com\/?$/,      // 小红书根路径（会重定向到登录页）
      /creator\.xiaohongshu\.com\/login/,   // 登录页
      /passport\.xiaohongshu/,
    ],
    weixin_video: [
      /channels\.weixin\.qq\.com\/?$/,      // 视频号根路径
      /channels\.weixin\.qq\.com\/login/,   // 登录页
    ],
    bilibili: [
      /passport\.bilibili/,
      /login\.bilibili/,
      /member\.bilibili\.com\/?$/,          // B站创作者根路径
    ],
    toutiao: [/passport\.toutiao/],
    baijiahao: [
      /baijiahao\.baidu\.com\/?$/,          // 百家号根路径
      /baijiahao\.baidu\.com\/builder\/theme\/bjh\/login/,  // 登录页
      /passport\.baidu/,
    ],
  };
  
  // 如果明确在登录页面，返回 false
  const loginPatterns = explicitLoginPatterns[platform.value] || [];
  if (loginPatterns.some(pattern => pattern.test(url))) {
    return false;
  }
  
  // 各平台登录成功后的页面特征（按用户要求）
  const loggedInPatterns: Record<string, RegExp[]> = {
    douyin: [
      /creator\.douyin\.com\/creator-micro\/home/,  // 主要判断条件
      /creator\.douyin\.com\/creator-micro/,        // creator-micro 下的其他页面也算
    ],
    kuaishou: [
      /cp\.kuaishou\.com\/article/,
      /cp\.kuaishou\.com\/profile/,
    ],
    xiaohongshu: [
      /creator\.xiaohongshu\.com\/new\/home/,       // 主要判断条件
      /creator\.xiaohongshu\.com\/new\//,           // /new/ 下的其他页面也算
    ],
    weixin_video: [
      /channels\.weixin\.qq\.com\/platform/,        // 主要判断条件
    ],
    bilibili: [
      /member\.bilibili\.com\/platform/,
      /space\.bilibili\.com\/\d+/,
    ],
    toutiao: [
      /mp\.toutiao\.com\/profile/,
    ],
    baijiahao: [
      /baijiahao\.baidu\.com\/builder\/rc\/home/,   // 主要判断条件
      /baijiahao\.baidu\.com\/builder\/rc/,         // /builder/rc 下的其他页面也算
    ],
  };
  
  const patterns = loggedInPatterns[platform.value] || [];
  if (patterns.some(pattern => pattern.test(url))) {
    return true;
  }
  
  // 平台相关域名（如果在这些域名下且不是登录页，也可能已登录）
  const relatedDomains: Record<string, RegExp[]> = {
    douyin: [
      /creator\.douyin\.com/,
      /douyin\.com/,
      /bytedance\.com/,        // 字节跳动相关域名（活动弹窗等）
    ],
    kuaishou: [/kuaishou\.com/],
    xiaohongshu: [
      /xiaohongshu\.com/,
      /xhslink\.com/,
    ],
    weixin_video: [/weixin\.qq\.com/, /qq\.com/],
    bilibili: [/bilibili\.com/],
    toutiao: [/toutiao\.com/],
    baijiahao: [/baidu\.com/, /baijiahao\.baidu\.com/],
  };
  
  // 如果在平台相关域名下（且不在明确的登录页），也认为可能已登录
  const domainPatterns = relatedDomains[platform.value] || [];
  return domainPatterns.some(pattern => pattern.test(url));
}

// 检查页面是否存在二次校验弹框（需要用户完成身份验证）
async function hasSecondaryVerification(): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;

  try {
    // 根据不同平台检测不同的二次校验弹框
    const checkScript = `
      (function() {
        try {
          // 获取整个页面的 HTML 和文本
          const bodyHtml = document.body.innerHTML || '';
          const bodyText = document.body.innerText || '';
          
          // 方法1: 直接检测页面文本中的关键词
          const hasVerifyTitle = bodyText.includes('身份验证');
          const hasSecurityHint = bodyText.includes('为保障账号安全') || bodyText.includes('确保为本人操作') || bodyText.includes('请先完成身份验证');
          const hasSmsOption = bodyText.includes('接收短信验证码');
          const hasFaceOption = bodyText.includes('手机刷脸验证') || bodyText.includes('刷脸验证');
          const hasSendSmsOption = bodyText.includes('发送短信验证');
          
          // 如果存在"身份验证"和任一验证选项，说明有二次校验弹框
          if (hasVerifyTitle && (hasSmsOption || hasFaceOption || hasSendSmsOption)) {
            console.log('[SecondaryVerification] Detected via text: 身份验证 + 验证选项');
            return true;
          }
          
          // 如果存在安全提示和任一验证选项
          if (hasSecurityHint && (hasSmsOption || hasFaceOption || hasSendSmsOption)) {
            console.log('[SecondaryVerification] Detected via text: 安全提示 + 验证选项');
            return true;
          }
          
          // 方法2: 检测 HTML 中是否包含这些文本（以防 innerText 没有正确获取）
          if (bodyHtml.includes('身份验证') && (bodyHtml.includes('接收短信验证码') || bodyHtml.includes('手机刷脸验证') || bodyHtml.includes('发送短信验证'))) {
            console.log('[SecondaryVerification] Detected via HTML content');
            return true;
          }
          
          // 方法3: 查找可能的弹框容器
          const possibleModals = document.querySelectorAll('[class*="modal"], [class*="dialog"], [class*="popup"], [class*="overlay"], [role="dialog"]');
          for (const modal of possibleModals) {
            const modalText = modal.innerText || '';
            const modalHtml = modal.innerHTML || '';
            
            // 检查弹框是否可见
            const style = window.getComputedStyle(modal);
            const isVisible = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
            
            if (isVisible) {
              if ((modalText.includes('身份验证') || modalText.includes('为保障账号安全')) && 
                  (modalText.includes('短信') || modalText.includes('刷脸'))) {
                console.log('[SecondaryVerification] Detected via modal element');
                return true;
              }
            }
          }
          
          // 方法4: 检查特定的抖音验证组件
          const douyinVerify = document.querySelector('[class*="uc-ui-verify"], [class*="verify-panel"], [class*="identity-verify"]');
          if (douyinVerify) {
            const style = window.getComputedStyle(douyinVerify);
            if (style.display !== 'none') {
              console.log('[SecondaryVerification] Detected via douyin verify component');
              return true;
            }
          }
          
          return false;
        } catch (e) {
          console.error('[SecondaryVerification] Error:', e);
          return false;
        }
      })()
    `;
    
    const result = await webview.executeJavaScript(checkScript);
    if (result) {
      console.log('[BrowserTab] Secondary verification detected!');
    }
    return result;
  } catch (error) {
    console.warn('[BrowserTab] Failed to check secondary verification:', error);
    return false;
  }
}

// 检查当前 URL 是否在登录页面
/**
 * 检查是否在登录页面
 * 各平台登录页（按用户要求）：
 * - 抖音：https://creator.douyin.com/
 * - 小红书：https://creator.xiaohongshu.com/login
 * - 微信视频号：https://channels.weixin.qq.com/login.html
 * - 百家号：https://baijiahao.baidu.com/builder/theme/bjh/login
 */
function isOnLoginPage(): boolean {
  const url = currentUrl.value;
  
  // 明确的登录页面 URL 特征（包括根路径，因为会重定向到登录页）
  const loginPagePatterns: Record<string, RegExp[]> = {
    douyin: [
      /creator\.douyin\.com\/?$/,           // 抖音创作者中心首页即登录页
      /creator\.douyin\.com\/login/,
      /passport\.douyin\.com/,
    ],
    kuaishou: [
      /passport\.kuaishou/,
      /login\.kuaishou/,
      /cp\.kuaishou\.com\/?$/,              // 快手创作者根路径
    ],
    xiaohongshu: [
      /creator\.xiaohongshu\.com\/?$/,      // 小红书创作者根路径（会重定向到登录页）
      /creator\.xiaohongshu\.com\/login/,   // 小红书登录页
      /passport\.xiaohongshu/,
    ],
    weixin_video: [
      /channels\.weixin\.qq\.com\/?$/,      // 视频号根路径
      /channels\.weixin\.qq\.com\/login/,   // 视频号登录页
    ],
    bilibili: [
      /passport\.bilibili/,
      /login\.bilibili/,
      /member\.bilibili\.com\/?$/,          // B站创作者根路径
    ],
    toutiao: [/passport\.toutiao/],
    baijiahao: [
      /baijiahao\.baidu\.com\/?$/,          // 百家号根路径
      /baijiahao\.baidu\.com\/builder\/theme\/bjh\/login/,  // 百家号登录页
      /passport\.baidu/,
    ],
  };
  
  // 只有明确匹配登录页面才返回 true，否则返回 false
  const patterns = loginPagePatterns[platform.value] || [];
  return patterns.some(pattern => pattern.test(url));
}

// 静默检测登录（使用 URL 检测，不依赖 AI）
async function checkLoginSilently() {
  // 如果已经登录成功、正在验证中、或正在获取账号信息，跳过
  if (loginStatus.value === 'success' || isVerifying || fetchingAccountInfo.value) {
    return;
  }
  
  // 如果 URL 还在登录页面，不触发验证
  if (isOnLoginPage()) {
    console.log('[checkLoginSilently] Still on login page, skipping...');
    return;
  }
  
  // 使用 URL 检测是否登录成功
  if (isLoggedInByUrl()) {
    console.log('[checkLoginSilently] URL detected login success, extracting account info...');
    await handleUrlLoginSuccess();
  }
}

/**
 * URL 检测到登录成功后，按步骤获取完整账号信息
 * 严格按照各平台的登录流程执行
 */
async function handleUrlLoginSuccess() {
  if (loginStatus.value === 'success' || isVerifying) {
    return;
  }
  
  isVerifying = true;
  fetchingAccountInfo.value = true;
  loginStatus.value = 'success'; // 先标记登录成功，显示"正在获取账号信息"
  accountInfo.value = null;
  apiResponseData.value = {}; // 清空 API 数据
  
  console.log(`[Login] 开始获取 ${platform.value} 账号信息...`);
  
  // 停止自动检测
  stopAutoCheck();
  
  // 重新注入 API 拦截脚本
  injectApiInterceptScript();
  
  // 设置超时（最多45秒）
  const timeout = new Promise<void>((_, reject) => {
    setTimeout(() => reject(new Error('获取账号信息超时')), 45000);
  });
  
  try {
    await Promise.race([
      collectAccountInfoByPlatform(),
      timeout
    ]);
    
  } catch (error) {
    console.error('[Login] 获取账号信息失败:', error);
    ElMessage.warning('获取账号信息超时或失败，可直接保存或刷新重试');
    // 即使失败也让用户保存
    if (!accountInfo.value) {
      accountInfo.value = {
        accountId: `${platform.value}_${Date.now()}`,
        accountName: '未知用户',
        avatarUrl: '',
        fansCount: 0,
        worksCount: 0,
      };
    }
    // 尝试获取 Cookie（用 try-catch 保护）
    try {
      await getCookieData();
    } catch (cookieError) {
      console.warn('[Login] 获取 Cookie 失败:', cookieError);
    }
  } finally {
    // 确保状态总是被重置
    fetchingAccountInfo.value = false;
    isVerifying = false;
  }
}

/**
 * 根据平台执行不同的账号信息收集流程
 */
async function collectAccountInfoByPlatform() {
  switch (platform.value) {
    case 'douyin':
      await collectDouyinAccountInfo();
      break;
    case 'xiaohongshu':
      await collectXiaohongshuAccountInfo();
      break;
    case 'weixin_video':
      await collectWeixinVideoAccountInfo();
      break;
    case 'baijiahao':
      await collectBaijiahaoAccountInfo();
      break;
    default:
      // 其他平台使用通用方式
      await collectGenericAccountInfo();
  }
}

/**
 * 抖音登录流程（按用户要求）：
 * 1. 从 HTML 提取：头像、昵称、抖音号、粉丝数、关注数、获赞数
 * 2. 跳转到作品管理页，监听 API 获取作品列表，取 items 数量
 * 3. 账号ID使用 dy_ 前缀
 */
async function collectDouyinAccountInfo() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  console.log('[抖音] 步骤1: 从 HTML 提取基本账号信息...');
  await sleep(2000); // 等待页面加载
  
  // 从 HTML 提取账号信息
  const basicInfo = await webview.executeJavaScript(`
    (function() {
      const result = {};
      const parseNum = (text) => {
        const match = text.match(/(\\d+(?:\\.\\d+)?)\\s*(万|亿|w)?/i);
        if (!match) return 0;
        let num = parseFloat(match[1]);
        if (match[2] === '万' || match[2]?.toLowerCase() === 'w') num *= 10000;
        if (match[2] === '亿') num *= 100000000;
        return Math.floor(num);
      };
      
      // 头像
      const avatarImg = document.querySelector('.avatar-XoPjK6 img, [class*="avatar"] img');
      if (avatarImg?.src) result.avatar = avatarImg.src;
      
      // 昵称
      const nameEl = document.querySelector('.name-_lSSDc, [class*="name-"]');
      if (nameEl) result.nickname = nameEl.textContent?.trim();
      
      // 抖音号
      const idEl = document.querySelector('.unique_id-EuH8eA, [class*="unique_id"]');
      if (idEl) {
        const text = idEl.textContent || '';
        const match = text.match(/抖音号[：:]\\s*(\\S+)/);
        if (match) result.douyinId = match[1];
      }
      
      // 关注数
      const followingEl = document.querySelector('#guide_home_following');
      if (followingEl) {
        const numEl = followingEl.querySelector('[class*="number"]');
        if (numEl) result.followingCount = parseNum(numEl.textContent || '0');
      }
      
      // 粉丝数
      const fansEl = document.querySelector('#guide_home_fans');
      if (fansEl) {
        const numEl = fansEl.querySelector('[class*="number"]');
        if (numEl) result.fansCount = parseNum(numEl.textContent || '0');
      }
      
      // 获赞数
      const statsItems = document.querySelectorAll('.statics-item-MDWoNA, [class*="statics-item"]');
      statsItems.forEach(item => {
        if (item.textContent?.includes('获赞')) {
          const numEl = item.querySelector('[class*="number"]');
          if (numEl) result.likeCount = parseNum(numEl.textContent || '0');
        }
      });
      
      return result;
    })()
  `);
  
  console.log('[抖音] 基本信息:', basicInfo);
  
  if (!basicInfo?.douyinId) {
    console.warn('[抖音] 未能提取到抖音号，重试...');
    await sleep(2000);
    return collectDouyinAccountInfo(); // 重试
  }
  
  // 步骤1.5: 先获取 Cookie
  console.log('[抖音] 获取 Cookie...');
  await getCookieData();
  
  console.log('[抖音] 步骤2: 跳转到作品管理页获取作品数...');
  const worksUrl = 'https://creator.douyin.com/creator-micro/content/manage';
  
  // 清空之前的 API 数据
  apiResponseData.value = {};
  
  // 跳转到作品页
  webview.loadURL(worksUrl);
  
  // 等待页面加载完成
  await waitForPageLoad(webview, 5000);
  
  // 重新注入 API 拦截脚本
  injectApiInterceptScript();
  
  // 等待 API 数据（最多15秒）
  const worksCount = await waitForApiData('workList', 15000).then(data => {
    const items = data?.items || data?.aweme_list || [];
    return items.length; // 使用 items 数量，不用 total
  }).catch(() => 0);
  
  console.log('[抖音] 作品数:', worksCount);
  
  // 组装账号信息
  accountInfo.value = {
    accountId: `dy_${basicInfo.douyinId}`,
    accountName: basicInfo.nickname || '抖音用户',
    avatarUrl: basicInfo.avatar || '',
    fansCount: basicInfo.fansCount || 0,
    worksCount,
    followingCount: basicInfo.followingCount,
    likeCount: basicInfo.likeCount,
  };
  
  console.log('[抖音] 完整账号信息:', accountInfo.value);
  await getCookieData();
  showSuccessMessage();
}

/**
 * 小红书登录流程（按用户要求）：
 * 1. 监听 API /api/galaxy/creator/home/personal_info 获取基本信息
 * 2. 跳转到笔记管理页，监听 API 获取笔记列表，取 notes 数量
 * 3. 账号ID使用 xhs_ 前缀
 */
async function collectXiaohongshuAccountInfo() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  // 步骤1: 先获取并保存 Cookie
  console.log('[小红书] 步骤0: 先获取 Cookie...');
  await getCookieData();
  
  console.log('[小红书] 步骤1: 等待个人信息 API...');
  await sleep(2000);
  
  // 等待 personal_info API 数据
  let personalInfo = await waitForApiData('personalInfo', 10000).catch(() => null);
  
  // 如果没获取到，先导航到首页再重试
  if (!personalInfo) {
    console.log('[小红书] 未收到个人信息 API，跳转到首页...');
    webview.loadURL('https://creator.xiaohongshu.com/new/home');
    await waitForPageLoad(webview, 5000);
    injectApiInterceptScript();
    await sleep(2000);
    personalInfo = await waitForApiData('personalInfo', 10000).catch(() => null);
  }
  
  // 尝试从页面 HTML 提取信息作为备选
  let info: any = personalInfo?.data || personalInfo || {};
  
  if (!info.red_num && !info.name) {
    console.log('[小红书] API 数据不完整，尝试从页面提取...');
    const pageInfo = await webview.executeJavaScript(`
      (function() {
        const result = {};
        // 尝试获取用户名
        const nameEl = document.querySelector('[class*="nick"], [class*="name"], .user-name');
        if (nameEl) result.name = nameEl.textContent?.trim();
        // 尝试获取小红书号
        const redNumEl = document.querySelector('[class*="red-id"], [class*="userId"]');
        if (redNumEl) {
          const match = redNumEl.textContent?.match(/小红书号[：:]?\\s*(\\S+)/);
          if (match) result.red_num = match[1];
        }
        // 尝试获取头像
        const avatarEl = document.querySelector('[class*="avatar"] img, .user-avatar img');
        if (avatarEl?.src) result.avatar = avatarEl.src;
        return result;
      })()
    `).catch(() => ({}));
    info = { ...info, ...pageInfo };
  }
  
  console.log('[小红书] 个人信息:', info);
  
  // 生成账号ID（如果没有 red_num，使用时间戳）
  const accountId = info.red_num ? `xhs_${info.red_num}` : `xhs_${Date.now()}`;
  
  // 获取作品数 - 小红书笔记管理页有额外权限验证，跳转会触发401
  // 直接从首页尝试获取，获取不到则使用0，后续通过后台刷新获取
  let worksCount = 0;
  
  console.log('[小红书] 步骤2: 尝试从首页获取作品数...');
  
  // 尝试从首页的数据面板获取作品数
  const pageWorksCount = await webview.executeJavaScript(`
    (function() {
      // 尝试从数据看板获取
      const dataItems = document.querySelectorAll('[class*="data-item"], [class*="dataItem"], [class*="stat"]');
      for (const item of dataItems) {
        const text = item.textContent || '';
        if (text.includes('笔记') || text.includes('作品')) {
          const match = text.match(/(\\d+)/);
          if (match) {
            console.log('[小红书] 从数据面板找到作品数:', match[1]);
            return parseInt(match[1]);
          }
        }
      }
      
      // 尝试从个人信息区域获取
      const infoArea = document.querySelector('[class*="user-info"], [class*="profile"], [class*="creator-info"]');
      if (infoArea) {
        const text = infoArea.textContent || '';
        const noteMatch = text.match(/笔记[：:]*\\s*(\\d+)/);
        if (noteMatch) return parseInt(noteMatch[1]);
        const workMatch = text.match(/作品[：:]*\\s*(\\d+)/);
        if (workMatch) return parseInt(workMatch[1]);
      }
      
      console.log('[小红书] 首页未找到作品数');
      return 0;
    })()
  `).catch(() => 0);
  
  worksCount = pageWorksCount;
  console.log('[小红书] 从首页获取的作品数:', worksCount);
  
  if (worksCount === 0) {
    console.log('[小红书] 首页无作品数，将通过后台刷新获取');
  }
  
  console.log('[小红书] 笔记数:', worksCount);
  
  // 组装账号信息
  accountInfo.value = {
    accountId,
    accountName: info.name || '小红书用户',
    avatarUrl: info.avatar || '',
    fansCount: info.fans_count || 0,
    worksCount,
  };
  
  console.log('[小红书] 完整账号信息:', accountInfo.value);
  await getCookieData();
  showSuccessMessage();
}

/**
 * 微信视频号登录流程（按用户要求）：
 * 1. 监听 API /cgi-bin/mmfinderassistant-bin/auth/auth_data 获取所有信息
 * 2. 账号ID使用 sph_ 前缀
 */
async function collectWeixinVideoAccountInfo() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  console.log('[视频号] 等待 auth_data API...');
  await sleep(2000);
  
  // 等待 auth_data API 数据
  let authData = await waitForApiData('authData', 10000).catch(() => null);
  
  if (!authData) {
    console.log('[视频号] 未收到 API 数据，刷新页面...');
    webview.reload();
    await sleep(3000);
    authData = await waitForApiData('authData', 10000).catch(() => null);
  }
  
  if (!authData) {
    throw new Error('无法获取视频号账号信息');
  }
  
  const user = authData.data?.finderUser || authData.finderUser || {};
  console.log('[视频号] 账号信息:', user);
  
  // 组装账号信息（视频号所有信息都在这个 API 里）
  accountInfo.value = {
    accountId: `sph_${user.uniqId}`,
    accountName: user.nickname || '视频号用户',
    avatarUrl: user.headImgUrl || '',
    fansCount: user.fansCount || 0,
    worksCount: user.feedsCount || 0,
  };
  
  console.log('[视频号] 完整账号信息:', accountInfo.value);
  await getCookieData();
  showSuccessMessage();
}

/**
 * 百家号登录流程：
 * 1. 监听 API /builder/app/appinfo 获取基本信息（头像、昵称、ID）
 * 2. 监听 API /cms-ui/rights/growth/get_info 获取粉丝数
 * 3. 跳转到作品管理页获取作品数
 * 4. 账号ID使用 bjh_ 前缀
 */
async function collectBaijiahaoAccountInfo() {
  const webview = webviewRef.value;
  if (!webview) return;
  
  // 先获取 Cookie
  console.log('[百家号] 步骤0: 获取 Cookie...');
  await getCookieData();
  
  console.log('[百家号] 步骤1: 获取账号基本信息 (appinfo API)...');
  
  // 先检查是否已有 appinfo 数据（可能由 CDP 拦截到）
  let appInfo = apiResponseData.value['appInfo'];
  
  if (!appInfo) {
    // 刷新首页以触发 appinfo API
    apiResponseData.value = {};
    webview.loadURL('https://baijiahao.baidu.com/builder/rc/home');
    await waitForPageLoad(webview, 5000);
    await sleep(1000);
    
    // 等待 appinfo API 数据
    appInfo = await waitForApiData('appInfo', 10000).catch(() => null);
  }
  
  console.log('[百家号] appInfo 数据:', appInfo);
  
  // 如果 API 获取失败，回退到页面提取
  let user: { name?: string; avatar?: string; app_id?: string } = {};
  
  if (appInfo?.data?.user) {
    user = appInfo.data.user;
    console.log('[百家号] 从 API 获取到用户信息:', user);
  } else {
    console.log('[百家号] API 获取失败，尝试从页面提取...');
    
    // 跳转到账号设置页面
    webview.loadURL('https://baijiahao.baidu.com/builder/rc/settings/accountSet');
    await waitForPageLoad(webview, 8000);
    await sleep(2000);
    
    const pageInfo = await webview.executeJavaScript(`
      (function() {
        const result = {};
        
        // 用户名
        const nameEl = document.querySelector('[class*="userName"]');
        if (nameEl) {
          const text = nameEl.childNodes[0]?.textContent?.trim();
          if (text) result.name = text;
        }
        
        // 头像
        const avatarEl = document.querySelector('[class*="userImg"]:not([class*="Mask"]):not([class*="Hover"]):not([class*="Box"])');
        if (avatarEl?.src) result.avatar = avatarEl.src;
        
        // ID
        const idEl = document.querySelector('[class*="idName"]');
        if (idEl) {
          const idText = idEl.textContent?.trim();
          if (idText && /^\\d+$/.test(idText)) {
            result.app_id = idText;
          }
        }
        
        if (!result.app_id) {
          const morInfoItems = document.querySelectorAll('[class*="morInfoItem"]');
          for (const item of morInfoItems) {
            const label = item.querySelector('[class*="morInfoLabel"]');
            const value = item.querySelector('[class*="morInfoValue"]');
            if (label?.textContent?.includes('ID') && value) {
              const match = value.textContent?.match(/(\\d{10,})/);
              if (match) result.app_id = match[1];
            }
          }
        }
        
        return result;
      })()
    `).catch(() => ({}));
    
    if (pageInfo && (pageInfo.name || pageInfo.app_id)) {
      user = pageInfo;
      console.log('[百家号] 从页面提取到用户信息:', user);
    }
  }
  
  if (!user.name && !user.app_id) {
    throw new Error('无法获取百家号账号信息');
  }
  
  console.log('[百家号] 基本信息:', user);
  
  // 步骤2: 获取粉丝数
  console.log('[百家号] 步骤2: 获取粉丝数...');
  
  // 检查是否已有 growthInfo 数据
  let growthInfo = apiResponseData.value['growthInfo'];
  
  if (!growthInfo) {
    // 确保在首页
    const currentUrl = webview.getURL();
    if (!currentUrl.includes('/builder/rc/home')) {
      apiResponseData.value = {};
      webview.loadURL('https://baijiahao.baidu.com/builder/rc/home');
      await waitForPageLoad(webview, 5000);
      await sleep(1000);
    }
    growthInfo = await waitForApiData('growthInfo', 8000).catch(() => null);
  }
  
  const fansCount = growthInfo?.data?.total_fans || growthInfo?.total_fans || 0;
  console.log('[百家号] 粉丝数:', fansCount);
  
  // 步骤3: 直接发起 API 请求获取作品数
  console.log('[百家号] 步骤3: 发起 API 请求获取作品数...');
  
  // 直接在 webview 中发起 API 请求（会自动携带 cookie）
  const worksCount = await webview.executeJavaScript(`
    (async function() {
      try {
        const apiUrl = 'https://baijiahao.baidu.com/pcui/article/lists?currentPage=1&pageSize=10&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0';
        console.log('[百家号] 发起 API 请求:', apiUrl);
        
        const response = await fetch(apiUrl, {
          method: 'GET',
          credentials: 'include', // 携带 cookie
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
          }
        });
        
        const data = await response.json();
        console.log('[百家号] API 响应:', JSON.stringify(data).substring(0, 200));
        
        if (data.errno === 0 && data.data) {
          const list = data.data.list || [];
          console.log('[百家号] 从 API 获取作品数:', list.length);
          return list.length;
        } else {
          console.log('[百家号] API 返回错误:', data.errno, data.errmsg);
          return 0;
        }
      } catch (err) {
        console.error('[百家号] API 请求失败:', err);
        return 0;
      }
    })()
  `).catch((err) => {
    console.error('[百家号] executeJavaScript 失败:', err);
    return 0;
  });
  
  console.log('[百家号] 作品数:', worksCount);
  
  // 处理头像 URL
  let avatar = user.avatar || '';
  if (avatar && !avatar.startsWith('http')) {
    avatar = 'https:' + avatar;
  }
  
  // 组装账号信息
  accountInfo.value = {
    accountId: `bjh_${user.app_id}`,
    accountName: user.name || '百家号用户',
    avatarUrl: avatar,
    fansCount,
    worksCount,
  };
  
  console.log('[百家号] 完整账号信息:', accountInfo.value);
  showSuccessMessage();
}

/**
 * 通用账号信息收集（用于未特别处理的平台）
 */
async function collectGenericAccountInfo() {
  const basicInfo = await extractAccountInfoFromPage();
  
  accountInfo.value = {
    accountId: basicInfo?.accountId || `${platform.value}_${Date.now()}`,
    accountName: basicInfo?.accountName || '未知用户',
    avatarUrl: basicInfo?.avatarUrl || '',
    fansCount: basicInfo?.fansCount || 0,
    worksCount: basicInfo?.worksCount || 0,
  };
  
  await getCookieData();
  showSuccessMessage();
}

/**
 * 等待 API 数据
 */
async function waitForApiData(key: string, timeout: number = 10000): Promise<any> {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    if (apiResponseData.value[key]) {
      return apiResponseData.value[key];
    }
    await sleep(500);
  }
  throw new Error(`等待 API ${key} 超时`);
}

/**
 * 睡眠函数
 */
function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 等待页面加载完成
 */
function waitForPageLoad(webview: any, timeout: number = 5000): Promise<void> {
  return new Promise((resolve) => {
    let resolved = false;
    
    const onStopLoading = () => {
      if (!resolved) {
        resolved = true;
        webview.removeEventListener('did-stop-loading', onStopLoading);
        // 额外等待 500ms 确保页面渲染完成
        setTimeout(resolve, 500);
      }
    };
    
    webview.addEventListener('did-stop-loading', onStopLoading);
    
    // 超时后也 resolve
    setTimeout(() => {
      if (!resolved) {
        resolved = true;
        webview.removeEventListener('did-stop-loading', onStopLoading);
        console.log('[waitForPageLoad] 超时，继续执行');
        resolve();
      }
    }, timeout);
  });
}

/**
 * 等待指定元素出现（用于 SPA 路由切换）
 */
async function waitForElement(webview: any, selector: string, timeout: number = 10000): Promise<boolean> {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    try {
      const found = await webview.executeJavaScript(`
        (function() {
          const selectors = '${selector}'.split(',').map(s => s.trim());
          for (const sel of selectors) {
            if (document.querySelector(sel)) return true;
          }
          return false;
        })()
      `);
      if (found) return true;
    } catch (e) {
      // 忽略错误，继续等待
    }
    await sleep(500);
  }
  return false;
}

/**
 * 获取并保存 Cookie 数据
 */
async function getCookieData() {
  try {
    const cookies = await getCookies();
    if (cookies && cookies.length > 0) {
      cookieData.value = formatCookies(cookies);
      console.log('[Login] Cookie 已获取:', cookies.length, '个');
    } else {
      console.warn('[Login] 未能获取到 Cookie');
    }
  } catch (error) {
    console.error('[Login] 获取 Cookie 失败:', error);
  }
}

/**
 * 显示成功消息
 */
function showSuccessMessage() {
  if (!hasShownSuccessMessage) {
    hasShownSuccessMessage = true;
    const name = accountInfo.value?.accountName || '用户';
    ElMessage.success(`登录成功！已获取 ${name} 的账号信息`);
  }
}

// 跳转到作品管理页并获取作品数
async function navigateAndGetWorksCount(): Promise<number | null> {
  const webview = webviewRef.value;
  if (!webview) return null;
  
  // 各平台作品管理页 URL
  const worksPageUrls: Record<string, string> = {
    douyin: 'https://creator.douyin.com/creator-micro/content/manage',
    xiaohongshu: 'https://creator.xiaohongshu.com/new/note-manager',
    weixin_video: '', // 视频号信息在首页就有
    baijiahao: 'https://baijiahao.baidu.com/builder/rc/content',
  };
  
  const worksUrl = worksPageUrls[platform.value];
  if (!worksUrl) {
    console.log('[Login] 该平台不需要跳转作品页');
    return null;
  }
  
  try {
    console.log('[Login] 跳转到作品管理页:', worksUrl);
    webview.loadURL(worksUrl);
    
    // 等待页面加载
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 从作品页提取作品数
    const extractScripts: Record<string, string> = {
      douyin: `
        (function() {
          // 尝试从页面元素获取
          const text = document.body.innerText;
          // 查找类似 "全部作品(12)" 或 "共12个作品" 的文本
          const match = text.match(/全部作品\\s*[（(](\\d+)[)）]/) ||
                        text.match(/共\\s*(\\d+)\\s*个?作品/) ||
                        text.match(/作品数[：:]?\\s*(\\d+)/);
          if (match) return parseInt(match[1], 10);
          
          // 直接数作品列表项
          const items = document.querySelectorAll('[class*="content-item"], [class*="work-item"], [class*="video-item"]');
          if (items.length > 0) return items.length;
          
          return 0;
        })()
      `,
      xiaohongshu: `
        (function() {
          const text = document.body.innerText;
          // 查找笔记数量
          const match = text.match(/共\\s*(\\d+)\\s*条?笔记/) ||
                        text.match(/笔记[（(](\\d+)[)）]/) ||
                        text.match(/全部[（(](\\d+)[)）]/);
          if (match) return parseInt(match[1], 10);
          
          // 数笔记列表项
          const items = document.querySelectorAll('[class*="note-item"], [class*="content-item"]');
          if (items.length > 0) return items.length;
          
          return 0;
        })()
      `,
      baijiahao: `
        (function() {
          const text = document.body.innerText;
          // 查找文章数
          const match = text.match(/共\\s*(\\d+)\\s*条?/) ||
                        text.match(/全部[（(](\\d+)[)）]/);
          if (match) return parseInt(match[1], 10);
          
          // 数文章列表项
          const items = document.querySelectorAll('[class*="article-item"], [class*="content-item"], tr[class*="ant-table-row"]');
          if (items.length > 0) return items.length;
          
          return 0;
        })()
      `,
    };
    
    const script = extractScripts[platform.value];
    if (!script) return null;
    
    // 多次尝试提取
    for (let i = 0; i < 3; i++) {
      try {
        const count = await webview.executeJavaScript(script);
        if (typeof count === 'number' && count >= 0) {
          console.log('[Login] 提取到作品数:', count);
          return count;
        }
      } catch (e) {
        console.warn('[Login] 提取作品数失败:', e);
      }
      await new Promise(resolve => setTimeout(resolve, 1500));
    }
    
    return null;
  } catch (error) {
    console.error('[Login] 获取作品数失败:', error);
    return null;
  }
}

// 从页面直接提取账号信息
async function extractAccountInfoFromPage(): Promise<{
  accountId: string;
  accountName: string;
  avatarUrl: string;
  fansCount: number;
  worksCount: number;
} | null> {
  const webview = webviewRef.value;
  if (!webview) {
    console.warn('[extractAccountInfoFromPage] webviewRef is null');
    return null;
  }

  try {
    // 根据不同平台使用不同的提取脚本
    const extractScripts: Record<string, string> = {
      douyin: `
        (function() {
          const result = { accountId: '', accountName: '', avatarUrl: '', fansCount: 0, worksCount: 0 };
          
          try {
            // 抖音创作服务平台页面（summon.bytedance.com）
            // 1. 查找头像 - 通常是较大的圆形图片
            const imgs = Array.from(document.querySelectorAll('img'));
            for (const img of imgs) {
              const src = img.src || '';
              const style = window.getComputedStyle(img);
              const isRound = style.borderRadius && (style.borderRadius.includes('50%') || parseInt(style.borderRadius) > 20);
              const isAvatarSize = img.width >= 40 && img.width <= 150;
              const isAvatarUrl = src.includes('avatar') || src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance');
              
              if ((isRound || isAvatarUrl) && isAvatarSize && src.startsWith('http')) {
                result.avatarUrl = src;
                break;
              }
            }
            
            // 2. 查找抖音号 - 格式通常是 "抖音号：xxx"
            const bodyText = document.body.innerText;
            const douyinIdMatch = bodyText.match(/抖音号[：:]\s*([a-zA-Z0-9_]+)/);
            if (douyinIdMatch) {
              result.accountId = 'douyin_' + douyinIdMatch[1];
            }
            
            // 3. 查找昵称 - 通常在抖音号附近，或者在用户信息区域
            // 先找到抖音号所在的元素，然后向上找用户名
            const allElements = document.querySelectorAll('*');
            let userInfoContainer = null;
            
            for (const el of allElements) {
              const text = el.innerText || '';
              if (text.includes('抖音号') && text.length < 200) {
                userInfoContainer = el.parentElement || el;
                break;
              }
            }
            
            if (userInfoContainer) {
              // 在用户信息容器中查找昵称（通常是第一个非空的短文本）
              const children = userInfoContainer.querySelectorAll('span, div, p, a');
              for (const child of children) {
                const text = child.innerText?.trim() || '';
                // 昵称特征：2-20字符，不是纯数字，不包含特殊词
                if (text.length >= 2 && text.length <= 20 && 
                    !/^[0-9]+$/.test(text) &&
                    !text.includes('抖音号') && !text.includes('粉丝') && 
                    !text.includes('关注') && !text.includes('获赞') &&
                    !text.includes('家人') && !text.includes('@')) {
                  result.accountName = text;
                  break;
                }
              }
            }
            
            // 4. 备选：遍历页面查找看起来像用户名的文本
            if (!result.accountName) {
              const candidates = [];
              document.querySelectorAll('span, div').forEach(el => {
                const text = el.innerText?.trim() || '';
                const rect = el.getBoundingClientRect();
                // 筛选条件：可见、长度适中、包含中文或字母
                if (rect.width > 0 && text.length >= 2 && text.length <= 25 &&
                    /[\u4e00-\u9fa5a-zA-Z]/.test(text) &&
                    !/粉丝|关注|获赞|作品|发布|数据|登录|注册/.test(text)) {
                  candidates.push({ text, top: rect.top, left: rect.left });
                }
              });
              // 优先选择靠上方、靠左侧的（通常是用户名位置）
              candidates.sort((a, b) => (a.top + a.left) - (b.top + b.left));
              if (candidates.length > 0) {
                result.accountName = candidates[0].text;
              }
            }
            
            // 5. 从 Cookie 获取 UID 作为备选
            if (!result.accountId) {
              const uidMatch = document.cookie.match(/passport_uid=([^;]+)/) || 
                              document.cookie.match(/uid_tt=([^;]+)/) ||
                              document.cookie.match(/ttwid=1%7C([^%|]+)/);
              if (uidMatch) {
                result.accountId = 'douyin_' + uidMatch[1];
              } else {
                result.accountId = 'douyin_' + Date.now();
              }
            }
            
          } catch (e) {
            console.error('[Douyin Extract] Error:', e);
          }
          
          console.log('[Douyin Extract] Result:', result);
          return result;
        })()
      `,
      xiaohongshu: `
        (function() {
          const result = { accountId: '', accountName: '', avatarUrl: '', fansCount: 0, worksCount: 0 };
          
          try {
            console.log('[Xiaohongshu Extract] Starting extraction...');
            console.log('[Xiaohongshu Extract] Current URL:', window.location.href);
            
            // 1. 查找用户名 - 小红书创作平台用户名通常在右上角或侧边栏
            const nameSelectors = [
              // 创作平台顶部用户名（常见位置）
              '.creator-header [class*="name"]',
              '.user-info [class*="name"]',
              // 右上角下拉菜单中的用户名
              '[class*="dropdown"] [class*="name"]',
              '[class*="user"] [class*="name"]',
              // 通用选择器
              '[class*="userName"]',
              '[class*="UserName"]',
              '[class*="user-name"]',
              '[class*="nickname"]',
              '[class*="NickName"]',
              '[class*="nick-name"]',
              // Ant Design 或其他UI库的组件
              '.ant-dropdown-trigger [class*="name"]'
            ];
            
            for (const selector of nameSelectors) {
              const els = document.querySelectorAll(selector);
              for (const el of els) {
                const text = el.textContent?.trim() || '';
                console.log('[Xiaohongshu Extract] Checking selector:', selector, 'text:', text);
                if (text.length >= 2 && text.length <= 30 && 
                    !/登录|注册|小红书|创作|发布|数据|内容|消息|设置|帮助|退出|首页|笔记|灵感|学院|活动/.test(text) &&
                    /[\u4e00-\u9fa5a-zA-Z0-9]/.test(text)) {
                  result.accountName = text;
                  console.log('[Xiaohongshu Extract] Found name via selector:', text);
                  break;
                }
              }
              if (result.accountName) break;
            }
            
            // 2. 备选方案：在整个页面中查找可能是用户名的文本
            if (!result.accountName) {
              console.log('[Xiaohongshu Extract] Trying fallback method for name...');
              // 查找页面右上角区域的文本（通常是用户名所在位置）
              const allElements = document.querySelectorAll('span, div, p, a');
              const candidates = [];
              
              for (const el of allElements) {
                const rect = el.getBoundingClientRect();
                // 只查找右上角区域（通常用户信息在这里）
                if (rect.right < window.innerWidth * 0.5 || rect.top > 200) continue;
                
                // 获取直接文本内容
                const directText = Array.from(el.childNodes)
                  .filter(node => node.nodeType === Node.TEXT_NODE)
                  .map(node => node.textContent?.trim())
                  .join('')
                  .trim();
                
                if (!directText) continue;
                
                if (directText.length >= 2 && directText.length <= 20 &&
                    /[\u4e00-\u9fa5]/.test(directText) &&
                    !/登录|注册|小红书|创作|发布|数据|内容|消息|设置|帮助|退出|首页|笔记|灵感|学院|活动|图文|视频|直播|百科/.test(directText)) {
                  candidates.push({ text: directText, right: rect.right, top: rect.top });
                }
              }
              
              // 按右上角位置排序
              candidates.sort((a, b) => (b.right - a.right) + (a.top - b.top));
              console.log('[Xiaohongshu Extract] Candidates:', candidates.slice(0, 5));
              
              if (candidates.length > 0) {
                result.accountName = candidates[0].text;
                console.log('[Xiaohongshu Extract] Using fallback name:', result.accountName);
              }
            }
            
            // 3. 查找头像
            const avatarSelectors = [
              // 创作平台头像
              '.creator-header img',
              '.user-info img',
              '[class*="avatar"] img',
              '[class*="Avatar"] img',
              'img[class*="avatar"]',
              'img[class*="Avatar"]',
              // 右上角用户头像
              '.ant-avatar img',
              '.ant-avatar-image'
            ];
            
            for (const selector of avatarSelectors) {
              const els = document.querySelectorAll(selector);
              for (const el of els) {
                const src = el.src || el.style?.backgroundImage?.match(/url\\(["']?([^"')]+)["']?\\)/)?.[1];
                if (src && src.startsWith('http') && !src.includes('logo') && !src.includes('icon')) {
                  result.avatarUrl = src;
                  console.log('[Xiaohongshu Extract] Found avatar:', src);
                  break;
                }
              }
              if (result.avatarUrl) break;
            }
            
            // 4. 备选：查找所有图片，找到可能是头像的（圆形、适当大小）
            if (!result.avatarUrl) {
              const imgs = Array.from(document.querySelectorAll('img'));
              for (const img of imgs) {
                const src = img.src || '';
                const style = window.getComputedStyle(img);
                const isRound = style.borderRadius && (style.borderRadius.includes('50%') || parseInt(style.borderRadius) > 15);
                const isAvatarSize = img.width >= 24 && img.width <= 100;
                const rect = img.getBoundingClientRect();
                const isInTopArea = rect.top < 150;
                
                if ((isRound || isInTopArea) && isAvatarSize && src.startsWith('http') && 
                    !src.includes('logo') && !src.includes('icon') && !src.includes('banner')) {
                  result.avatarUrl = src;
                  console.log('[Xiaohongshu Extract] Found avatar via fallback:', src);
                  break;
                }
              }
            }
            
            // 5. 查找粉丝数
            const bodyText = document.body.innerText;
            const fansMatch = bodyText.match(/粉丝[\\s:：]*([0-9,\\.]+[万亿]?)/);
            if (fansMatch) {
              let fansStr = fansMatch[1].replace(/,/g, '');
              if (fansStr.includes('万')) {
                result.fansCount = Math.round(parseFloat(fansStr) * 10000);
              } else if (fansStr.includes('亿')) {
                result.fansCount = Math.round(parseFloat(fansStr) * 100000000);
              } else {
                result.fansCount = parseInt(fansStr) || 0;
              }
              console.log('[Xiaohongshu Extract] Found fans:', result.fansCount);
            }
            
            // 6. 优先从页面获取小红书号作为 account_id
            // 小红书号格式：通常是 "小红书号：xxxxxxx" 或 "小红书号:xxxxxxx"
            const xhsIdMatch = bodyText.match(/小红书号[：:]\s*([a-zA-Z0-9_]+)/) ||
                              bodyText.match(/红书号[：:]\s*([a-zA-Z0-9_]+)/);
            if (xhsIdMatch) {
              result.accountId = 'xiaohongshu_' + xhsIdMatch[1];
              console.log('[Xiaohongshu Extract] Found 小红书号 from page:', result.accountId);
            }
            
            // 7. 备选：尝试从页面元素中查找小红书号
            if (!result.accountId) {
              // 查找可能包含小红书号的元素
              const idSelectors = [
                '[class*="redId"]',
                '[class*="red-id"]',
                '[class*="userId"]',
                '[class*="user-id"]'
              ];
              for (const selector of idSelectors) {
                const el = document.querySelector(selector);
                const text = el?.textContent?.trim();
                if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 6 && text.length <= 30) {
                  result.accountId = 'xiaohongshu_' + text;
                  console.log('[Xiaohongshu Extract] Found ID from selector:', result.accountId);
                  break;
                }
              }
            }
            
            // 8. 备选：从 URL 中查找用户 ID
            if (!result.accountId) {
              const urlIdMatch = window.location.href.match(/user\\/([a-f0-9]+)/);
              if (urlIdMatch) {
                result.accountId = 'xiaohongshu_' + urlIdMatch[1];
                console.log('[Xiaohongshu Extract] Found ID from URL:', result.accountId);
              }
            }
            
            // 9. 最后备选：从 Cookie 获取
            if (!result.accountId) {
              const uidMatch = document.cookie.match(/customerClientId=([^;]+)/) || 
                              document.cookie.match(/customer-client-id=([^;]+)/) ||
                              document.cookie.match(/web_session=([^;]+)/);
              if (uidMatch) {
                result.accountId = 'xiaohongshu_' + uidMatch[1].slice(0, 20);
                console.log('[Xiaohongshu Extract] Found ID from cookie:', result.accountId);
              } else {
                result.accountId = 'xiaohongshu_' + Date.now();
                console.log('[Xiaohongshu Extract] Using timestamp as fallback ID');
              }
            }
            
          } catch (e) {
            console.error('[Xiaohongshu Extract] Error:', e);
          }
          
          console.log('[Xiaohongshu Extract] Final result:', result);
          return result;
        })()
      `,
      kuaishou: `
        (function() {
          const result = { accountId: '', accountName: '', avatarUrl: '', fansCount: 0, worksCount: 0 };
          
          const avatarEl = document.querySelector('.user-avatar img, [class*="avatar"] img');
          if (avatarEl) result.avatarUrl = avatarEl.src || '';
          
          const nameEl = document.querySelector('.user-name, [class*="userName"], [class*="nickname"]');
          if (nameEl) result.accountName = nameEl.textContent?.trim() || '';
          
          const uidMatch = document.cookie.match(/userId=([^;]+)/);
          if (uidMatch) result.accountId = 'kuaishou_' + uidMatch[1];
          
          return result;
        })()
      `,
      baijiahao: `
        (function() {
          const result = { accountId: '', accountName: '', avatarUrl: '', fansCount: 0, worksCount: 0 };
          
          try {
            console.log('[Baijiahao Extract] Starting extraction...');
            console.log('[Baijiahao Extract] Current URL:', window.location.href);
            
            // 1. 查找头像 - 百家号创作中心的各种可能的头像位置
            const avatarSelectors = [
              // 侧边栏用户头像
              '.cheetah-sidebar img',
              '.sidebar-user img',
              '.user-center img',
              // 通用头像选择器
              '[class*="avatar"] img',
              '[class*="Avatar"] img',
              'img[class*="avatar"]',
              'img[class*="Avatar"]',
              // 可能的用户信息区域
              '.user-info img',
              '.author-info img',
              '.header-user img',
              // Ant Design 头像
              '.ant-avatar img',
              '.ant-avatar-image'
            ];
            
            for (const selector of avatarSelectors) {
              const els = document.querySelectorAll(selector);
              for (const el of els) {
                const src = el.src || el.style?.backgroundImage?.match(/url\\(["']?([^"')]+)["']?\\)/)?.[1];
                if (src && src.startsWith('http') && !src.includes('logo') && !src.includes('icon')) {
                  result.avatarUrl = src;
                  console.log('[Baijiahao Extract] Found avatar:', src);
                  break;
                }
              }
              if (result.avatarUrl) break;
            }
            
            // 2. 查找用户名 - 更全面的选择器
            const nameSelectors = [
              // 百家号特定选择器
              '.cheetah-sidebar [class*="name"]',
              '.sidebar-user [class*="name"]',
              '.user-center [class*="name"]',
              // 通用选择器
              '[class*="userName"]',
              '[class*="UserName"]',
              '[class*="user-name"]',
              '[class*="nickname"]',
              '[class*="NickName"]',
              '[class*="authorName"]',
              // 可能的标签
              '.author-name',
              '.user-name',
              '.nick-name'
            ];
            
            for (const selector of nameSelectors) {
              const els = document.querySelectorAll(selector);
              for (const el of els) {
                const text = el.textContent?.trim() || '';
                console.log('[Baijiahao Extract] Checking selector:', selector, 'text:', text);
                if (text.length >= 2 && text.length <= 30 && 
                    !/登录|注册|百家号|创作中心|发布|数据|内容|消息|设置|帮助|退出/.test(text) &&
                    /[\u4e00-\u9fa5a-zA-Z0-9]/.test(text)) {
                  result.accountName = text;
                  console.log('[Baijiahao Extract] Found name via selector:', text);
                  break;
                }
              }
              if (result.accountName) break;
            }
            
            // 3. 备选方案：查找页面中所有可能是用户名的元素
            if (!result.accountName) {
              console.log('[Baijiahao Extract] Trying fallback method...');
              // 查找所有文本节点，找到可能的用户名
              const allElements = document.querySelectorAll('span, div, p, a, h1, h2, h3, h4');
              const candidates = [];
              
              for (const el of allElements) {
                // 只获取直接文本内容
                const directText = Array.from(el.childNodes)
                  .filter(node => node.nodeType === Node.TEXT_NODE)
                  .map(node => node.textContent?.trim())
                  .join('')
                  .trim();
                
                if (!directText) continue;
                
                const rect = el.getBoundingClientRect();
                // 在可见区域内，且文本长度合适
                if (rect.width > 0 && rect.height > 0 && 
                    rect.top < window.innerHeight && rect.left < window.innerWidth &&
                    directText.length >= 2 && directText.length <= 20 &&
                    /[\u4e00-\u9fa5]/.test(directText) &&
                    !/登录|注册|百家号|创作|发布|数据|内容|消息|设置|帮助|退出|首页|文章|视频|图集|动态|评论|私信|粉丝|关注|订阅/.test(directText)) {
                  // 检查是否在头部或侧边栏区域
                  const isInUserArea = rect.top < 200 || rect.left < 300;
                  candidates.push({ text: directText, score: isInUserArea ? 100 : 50, top: rect.top, left: rect.left });
                }
              }
              
              // 按分数和位置排序，优先选择头部/侧边栏的
              candidates.sort((a, b) => b.score - a.score || a.top - b.top || a.left - b.left);
              console.log('[Baijiahao Extract] Candidates:', candidates.slice(0, 5));
              
              if (candidates.length > 0) {
                result.accountName = candidates[0].text;
                console.log('[Baijiahao Extract] Using fallback name:', result.accountName);
              }
            }
            
            // 4. 从 cookie 获取用户 ID
            const bdussMatch = document.cookie.match(/BDUSS=([^;]+)/);
            const stokenMatch = document.cookie.match(/STOKEN=([^;]+)/);
            const baiduidMatch = document.cookie.match(/BAIDUID=([^:;]+)/);
            
            if (bdussMatch) {
              result.accountId = 'baijiahao_' + bdussMatch[1].slice(0, 16);
            } else if (stokenMatch) {
              result.accountId = 'baijiahao_' + stokenMatch[1].slice(0, 16);
            } else if (baiduidMatch) {
              result.accountId = 'baijiahao_' + baiduidMatch[1];
            } else {
              result.accountId = 'baijiahao_' + Date.now();
            }
            
          } catch (e) {
            console.error('[Baijiahao Extract] Error:', e);
          }
          
          console.log('[Baijiahao Extract] Final result:', result);
          return result;
        })()
      `,
      bilibili: `
        (function() {
          const result = { accountId: '', accountName: '', avatarUrl: '', fansCount: 0, worksCount: 0 };
          
          const avatarEl = document.querySelector('.user-avatar img, [class*="avatar"] img');
          if (avatarEl) result.avatarUrl = avatarEl.src || '';
          
          const nameEl = document.querySelector('.user-name, [class*="userName"], [class*="nickname"]');
          if (nameEl) result.accountName = nameEl.textContent?.trim() || '';
          
          const uidMatch = document.cookie.match(/DedeUserID=([^;]+)/);
          if (uidMatch) result.accountId = 'bilibili_' + uidMatch[1];
          
          return result;
        })()
      `,
      weixin_video: `
        (function() {
          const result = { accountId: '', accountName: '', avatarUrl: '', fansCount: 0, worksCount: 0 };
          
          try {
            console.log('[Weixin Extract] Starting extraction...');
            console.log('[Weixin Extract] Current URL:', window.location.href);
            
            // 1. 查找头像 - 视频号创作者平台头像（优先微信特有域名）
            // 先查找微信头像 URL 特征的图片
            const allImgs = Array.from(document.querySelectorAll('img'));
            for (const img of allImgs) {
              const src = img.src || '';
              // 微信头像通常包含这些域名
              if (src.includes('wx.qlogo') || src.includes('mmbiz.qpic') || src.includes('thirdwx.qlogo')) {
                result.avatarUrl = src;
                console.log('[Weixin Extract] Found avatar by URL pattern:', src);
                break;
              }
            }
            
            // 2. 如果没找到，尝试通过选择器查找
            if (!result.avatarUrl) {
              const avatarSelectors = [
                '.finder-avatar img',
                '.account-avatar img',
                '.user-avatar img',
                '[class*="avatar"] img',
                '[class*="Avatar"] img',
                'img[class*="avatar"]',
                '.header-user img',
                '.header img',
                'nav img',
                '.navbar img'
              ];
              
              for (const selector of avatarSelectors) {
                const el = document.querySelector(selector);
                if (el && el.src && el.src.startsWith('http')) {
                  const src = el.src;
                  if (!src.includes('logo') && !src.includes('icon') && !src.includes('banner')) {
                    result.avatarUrl = src;
                    console.log('[Weixin Extract] Found avatar by selector:', selector, src);
                    break;
                  }
                }
              }
            }
            
            // 3. 备选：查找所有圆形或适当大小且在页面顶部的图片
            if (!result.avatarUrl) {
              for (const img of allImgs) {
                const src = img.src || '';
                if (!src || !src.startsWith('http')) continue;
                if (src.includes('logo') || src.includes('icon') || src.includes('banner')) continue;
                
                const style = window.getComputedStyle(img);
                const rect = img.getBoundingClientRect();
                const isRound = style.borderRadius && (style.borderRadius.includes('50%') || parseInt(style.borderRadius) > 10);
                const isAvatarSize = rect.width >= 24 && rect.width <= 80;
                const isInHeader = rect.top < 120;
                
                if ((isRound && isAvatarSize) || (isInHeader && isAvatarSize)) {
                  result.avatarUrl = src;
                  console.log('[Weixin Extract] Found avatar by fallback:', src);
                  break;
                }
              }
            }
            
            // 4. 优先查找视频号ID - 格式通常是 "视频号ID：xxx" 或 "视频号ID:xxx"
            const bodyText = document.body.innerText;
            // 匹配多种格式：视频号ID:xxx、视频号ID：xxx、视频号ID xxx
            const finderIdMatch = bodyText.match(/视频号ID[：:\s]*([a-zA-Z0-9_]+)/) ||
                                 bodyText.match(/视频号[：:\s]*ID[：:\s]*([a-zA-Z0-9_]+)/);
            if (finderIdMatch) {
              result.accountId = 'weixin_video_' + finderIdMatch[1];
              console.log('[Weixin Extract] Found 视频号ID from page text:', result.accountId);
            }
            
            // 4.1 备选：从页面元素中查找视频号ID
            if (!result.accountId) {
              // 查找可能包含视频号ID的元素
              const idSelectors = [
                '[class*="finder-id"]',
                '[class*="finderId"]',
                '[class*="channel-id"]',
                '[class*="channelId"]'
              ];
              for (const selector of idSelectors) {
                const el = document.querySelector(selector);
                const text = el?.textContent?.trim();
                if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10 && text.length <= 30) {
                  result.accountId = 'weixin_video_' + text;
                  console.log('[Weixin Extract] Found ID from selector:', result.accountId);
                  break;
                }
              }
            }
            
            // 5. 查找昵称 - 在用户信息区域
            const nameSelectors = [
              '.finder-nickname',
              '.account-name',
              '.user-name',
              '[class*="nickname"]',
              '[class*="userName"]',
              '[class*="user-name"]',
              '.header-user-name',
              'h2.name',
              '.name-text'
            ];
            
            for (const selector of nameSelectors) {
              const el = document.querySelector(selector);
              const text = el?.textContent?.trim();
              if (text && text.length >= 2 && text.length <= 30) {
                result.accountName = text;
                console.log('[Weixin Extract] Found name by selector:', selector, text);
                break;
              }
            }
            
            // 6. 备选：遍历页面查找看起来像用户名的文本
            if (!result.accountName) {
              const candidates = [];
              document.querySelectorAll('span, div, h2, h3').forEach(el => {
                const rect = el.getBoundingClientRect();
                // 只在页面顶部区域查找
                if (rect.top > 200 || rect.width === 0) return;
                
                // 获取直接文本内容
                const directText = Array.from(el.childNodes)
                  .filter(node => node.nodeType === Node.TEXT_NODE)
                  .map(node => node.textContent?.trim())
                  .join('')
                  .trim();
                
                if (directText && directText.length >= 2 && directText.length <= 20 &&
                    /[\u4e00-\u9fa5a-zA-Z]/.test(directText) &&
                    !/粉丝|关注|获赞|作品|发布|数据|登录|注册|视频号|首页|创作|评论|消息|设置/.test(directText)) {
                  candidates.push({ text: directText, top: rect.top, left: rect.left });
                }
              });
              // 优先选择靠上方的
              candidates.sort((a, b) => a.top - b.top);
              console.log('[Weixin Extract] Name candidates:', candidates.slice(0, 5));
              if (candidates.length > 0) {
                result.accountName = candidates[0].text;
              }
            }
            
            // 7. 查找粉丝数（视频号使用"关注者"表示粉丝）
            const fansMatch = bodyText.match(/关注者[\\s:：]*([0-9,\\.]+[万亿]?)/) ||
                             bodyText.match(/粉丝[\\s:：]*([0-9,\\.]+[万亿]?)/);
            if (fansMatch) {
              let fansStr = fansMatch[1].replace(/,/g, '');
              if (fansStr.includes('万')) {
                result.fansCount = Math.round(parseFloat(fansStr) * 10000);
              } else if (fansStr.includes('亿')) {
                result.fansCount = Math.round(parseFloat(fansStr) * 100000000);
              } else {
                result.fansCount = parseInt(fansStr) || 0;
              }
              console.log('[Weixin Extract] Found fans (关注者):', result.fansCount);
            }
            
            // 7.1 查找作品数（视频号显示为"视频 X"）
            const worksMatch = bodyText.match(/视频[\\s:：]*([0-9]+)/) ||
                              bodyText.match(/作品[\\s:：]*([0-9]+)/);
            if (worksMatch) {
              result.worksCount = parseInt(worksMatch[1]) || 0;
              console.log('[Weixin Extract] Found works (视频):', result.worksCount);
            }
            
            // 8. 不再从 Cookie 获取 ID，只有真正的视频号ID才有效
            // 如果没有找到视频号ID，返回空字符串，让后续流程处理
            if (!result.accountId) {
              console.log('[Weixin Extract] No valid 视频号ID found, will use fallback');
              // 不设置默认值，让后续流程判断是否需要重新获取
            }
            
          } catch (e) {
            console.error('[Weixin Extract] Error:', e);
          }
          
          console.log('[Weixin Extract] Final result:', result);
          return result;
        })()
      `,
    };

    const script = extractScripts[platform.value];
    if (!script) return null;

    const info = await webview.executeJavaScript(script);
    console.log(`[${platform.value}] Extracted account info from page:`, info);
    
    // 验证提取结果
    if (info && (info.accountName || info.accountId)) {
      return {
        accountId: info.accountId || `${platform.value}_${Date.now()}`,
        accountName: info.accountName || `${PLATFORMS[platform.value]?.name || platform.value}账号`,
        avatarUrl: info.avatarUrl || '',
        fansCount: info.fansCount || 0,
        worksCount: info.worksCount || 0,
      };
    }
    
    return null;
  } catch (error) {
    console.error('Failed to extract account info from page:', error);
    return null;
  }
}

// 关闭平台活动弹框/遮罩
async function closeActivityPopup(): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  try {
    const closeScript = `
      (function() {
        let closed = false;
        
        // 通用关闭按钮选择器
        const closeSelectors = [
          // 通用关闭按钮
          '.dialog-close, .modal-close, .popup-close',
          '[class*="close-btn"], [class*="closeBtn"], [class*="close-icon"], [class*="closeIcon"]',
          '.ant-modal-close, .el-dialog__close, .el-message-box__close',
          '[class*="dialog"] [class*="close"], [class*="modal"] [class*="close"]',
          '[class*="popup"] [class*="close"], [class*="toast"] [class*="close"]',
          'button[aria-label="Close"], button[aria-label="关闭"]',
          '.mask-close, [class*="mask"] [class*="close"]',
          // 小红书特定选择器
          '[class*="guide"] [class*="close"]',
          '[class*="tip"] [class*="close"]',
          '[class*="notice"] [class*="close"]',
          '[class*="banner"] [class*="close"]',
          '[class*="float"] [class*="close"]',
          '.close, .icon-close, .btn-close',
          // X 按钮（通常是 SVG 或特殊字符）
          'button svg[class*="close"]',
          '[role="button"][class*="close"]',
          // 确认/知道了/我知道了 按钮（用于关闭提示）
          'button:contains("知道了")', 'button:contains("我知道了")',
          'button:contains("确定")', 'button:contains("关闭")',
          '[class*="confirm"], [class*="ok-btn"]'
        ];
        
        // 尝试所有关闭按钮
        for (const selector of closeSelectors) {
          try {
            const elements = document.querySelectorAll(selector);
            for (const btn of elements) {
              if (btn && btn.offsetParent !== null) {
                const rect = btn.getBoundingClientRect();
                // 确保按钮可见且在视口内
                if (rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.left >= 0) {
                  btn.click();
                  closed = true;
                  console.log('[closeActivityPopup] Clicked:', selector);
                }
              }
            }
          } catch (e) {
            // 忽略无效选择器
          }
        }
        
        // 特殊处理：查找包含"关闭"、"知道了"、"确定"文字的按钮
        const allButtons = document.querySelectorAll('button, [role="button"], a[class*="btn"]');
        for (const btn of allButtons) {
          const text = btn.textContent?.trim() || '';
          if (['关闭', '知道了', '我知道了', '确定', '取消', '跳过', '暂不', '稍后再说'].some(t => text.includes(t))) {
            if (btn.offsetParent !== null) {
              const rect = btn.getBoundingClientRect();
              if (rect.width > 0 && rect.height > 0) {
                btn.click();
                closed = true;
                console.log('[closeActivityPopup] Clicked button with text:', text);
              }
            }
          }
        }
        
        // 尝试点击遮罩层外部关闭
        const masks = document.querySelectorAll(
          '.ant-modal-mask, .el-overlay, [class*="mask"], [class*="overlay"], [class*="backdrop"]'
        );
        for (const mask of masks) {
          const style = window.getComputedStyle(mask);
          if (style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0') {
            // 查找是否有可点击关闭的按钮
            const closeInMask = mask.querySelector('[class*="close"], .close, button');
            if (closeInMask && closeInMask.offsetParent !== null) {
              closeInMask.click();
              closed = true;
              console.log('[closeActivityPopup] Clicked close in mask');
            }
          }
        }
        
        // 按 ESC 键尝试关闭
        document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true }));
        document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true }));
        
        return closed;
      })()
    `;
    
    const result = await webview.executeJavaScript(closeScript);
    if (result) {
      console.log('[closeActivityPopup] Successfully closed popup');
      // 等待弹框关闭动画
      await new Promise(resolve => setTimeout(resolve, 800));
    }
    return result;
  } catch (error) {
    console.warn('[closeActivityPopup] Failed:', error);
    return false;
  }
}

// 旧的 quickLoginSuccess 函数已被 handleAILoginSuccess 替代

// 视频号：导航到首页获取完整账号信息
async function navigateToWeixinVideoHomePage(): Promise<boolean> {
  const webview = webviewRef.value;
  if (!webview) return false;
  
  try {
    // 获取当前 URL
    const currentUrl = webview.getURL ? webview.getURL() : (webview.src || '');
    console.log('[WeixinVideo] Current URL:', currentUrl);
    
    // 如果已经在首页，不需要导航
    if (currentUrl.includes('/platform/home') || currentUrl.includes('/platform/post/list')) {
      console.log('[WeixinVideo] Already on home page');
      return true;
    }
    
    // 使用 webview 的 src 属性直接导航（避免 iframe 跨域问题）
    console.log('[WeixinVideo] Navigating to home page via webview.src...');
    const targetUrl = 'https://channels.weixin.qq.com/platform/home';
    
    // 设置 src 并等待加载完成
    return new Promise((resolve) => {
      const onDidFinishLoad = () => {
        console.log('[WeixinVideo] Page loaded');
        webview.removeEventListener('did-finish-load', onDidFinishLoad);
        // 页面加载完成后，等待一段时间让内容渲染
        setTimeout(async () => {
          // 再次尝试关闭可能出现的弹窗
          for (let i = 0; i < 3; i++) {
            const closed = await closeActivityPopup();
            if (!closed) break;
            await new Promise(r => setTimeout(r, 500));
          }
          console.log('[WeixinVideo] Navigation complete');
          resolve(true);
        }, 2000);
      };
      
      const onDidFailLoad = () => {
        console.error('[WeixinVideo] Page load failed');
        webview.removeEventListener('did-fail-load', onDidFailLoad);
        resolve(false);
      };
      
      webview.addEventListener('did-finish-load', onDidFinishLoad);
      webview.addEventListener('did-fail-load', onDidFailLoad);
      
      // 设置超时
      setTimeout(() => {
        webview.removeEventListener('did-finish-load', onDidFinishLoad);
        webview.removeEventListener('did-fail-load', onDidFailLoad);
        console.log('[WeixinVideo] Navigation timeout, continuing anyway...');
        resolve(true);
      }, 10000);
      
      // 执行导航
      webview.src = targetUrl;
    });
  } catch (error) {
    console.error('[WeixinVideo] Navigation failed:', error);
    return false;
  }
}

// 检查是否有登录 cookie
function checkHasLoginCookie(cookies: Electron.Cookie[]): boolean {
  // 根据不同平台检查特定的 cookie
  // 注意：只检查真正表示已登录的 cookie，不要包含通用 cookie
  const platformCookieNames: Record<string, string[]> = {
    douyin: ['sessionid', 'passport_csrf_token', 'sid_guard'],
    kuaishou: ['passToken', 'userId'],
    xiaohongshu: ['web_session', 'xsecappid'],
    weixin_video: ['wxuin', 'pass_ticket'],
    bilibili: ['SESSDATA', 'bili_jct'],
    toutiao: ['sessionid', 'sso_uid'],
    baijiahao: ['BDUSS', 'STOKEN'],  // BAIDUID 是通用 Cookie，不能用于判断登录
    qie: ['uin', 'skey'],
    dayuhao: ['cna', 'login_aliyunid'],
  };
  
  const targetCookies = platformCookieNames[platform.value] || [];
  const cookieNames = cookies.map(c => c.name);
  
  return targetCookies.some(name => cookieNames.includes(name));
}

// 获取 webview 的 cookies
async function getCookies(): Promise<Electron.Cookie[]> {
  if (!window.electronAPI?.getWebviewCookies) {
    console.warn('electronAPI.getWebviewCookies 不可用');
    return [];
  }
  
  const platformInfo = PLATFORMS[platform.value];
  if (!platformInfo) return [];
  
  // 获取登录域名的 cookies
  const url = platformInfo.loginUrl;
  return await window.electronAPI.getWebviewCookies(webviewPartition.value, url);
}

// 格式化 cookies 为字符串
function formatCookies(cookies: Electron.Cookie[]): string {
  return cookies.map(c => `${c.name}=${c.value}`).join('; ');
}

// 手动检测登录（使用 URL 检测）
async function handleCheckLogin() {
  checking.value = true;
  loginStatus.value = 'checking';
  
  try {
    // 检查是否还在登录页面
    if (isOnLoginPage()) {
      loginStatus.value = 'pending';
      ElMessage.info('请先完成扫码登录');
      return;
    }
    
    // 使用 URL 检测是否登录成功
    if (isLoggedInByUrl()) {
      ElMessage.info('检测到已登录，正在获取账号信息...');
      await handleUrlLoginSuccess();
    } else {
      // 检查是否有二次验证
      const hasVerify = await hasSecondaryVerification();
      if (hasVerify) {
        loginStatus.value = 'pending';
        ElMessage.warning('请完成页面上的身份验证');
      } else {
        loginStatus.value = 'pending';
        ElMessage.info('未检测到登录状态，请确认已完成登录');
      }
    }
  } catch (error) {
    loginStatus.value = 'pending';
    ElMessage.error('检测登录状态失败');
    console.error('[handleCheckLogin] Error:', error);
  } finally {
    checking.value = false;
  }
}

// 旧的 verifyLoginWithServer 函数已被 AI 驱动的登录流程替代

// 保存账号
async function handleSaveAccount() {
  if (!cookieData.value) {
    ElMessage.warning('请先完成登录');
    return;
  }
  
  saving.value = true;
  try {
    // 构建账号信息，包含获取到的用户数据
    const accountData: {
      platform: string;
      cookieData: string;
      groupId?: number;
      accountInfo?: {
        accountId?: string;
        accountName?: string;
        avatarUrl?: string;
        fansCount?: number;
        worksCount?: number;
      };
    } = {
      platform: platform.value,
      cookieData: cookieData.value,
      groupId: props.tab.browserData?.groupId,
    };
    
    // 如果有获取到的账号信息，一并传递
    if (accountInfo.value) {
      accountData.accountInfo = {
        accountId: accountInfo.value.accountId,
        accountName: accountInfo.value.accountName,
        avatarUrl: accountInfo.value.avatarUrl,
        fansCount: accountInfo.value.fansCount,
        worksCount: accountInfo.value.worksCount,
      };
    }
    
    await accountsApi.addAccount(accountData);
    
    ElMessage.success('账号添加成功');
    emit('accountSaved');
    
    // 清除 webview cookies
    if (window.electronAPI?.clearWebviewCookies) {
      await window.electronAPI.clearWebviewCookies(webviewPartition.value);
    }
    
    // 关闭标签页
    tabsStore.closeTab(props.tab.id);
  } catch (error) {
    // 错误已处理
  } finally {
    saving.value = false;
  }
}

// 生命周期
onMounted(async () => {
  // 调试：输出 browserData 信息
  console.log('[BrowserTab] onMounted, browserData:', JSON.stringify(props.tab.browserData, null, 2));
  console.log('[BrowserTab] isAdminMode:', isAdminMode.value);
  console.log('[BrowserTab] initialUrl:', initialUrl.value);
  
  // 设置 CDP 网络拦截数据监听器
  setupCDPDataListener();
  
  // 检查 AI 服务可用性（非管理模式）
  if (!isAdminMode.value) {
    await checkAIAvailability();
  }
  
  const targetUrl = initialUrl.value;
  currentUrl.value = targetUrl;
  
  // 如果有预设的 Cookie，先设置到 session 中，然后再加载页面
  if (props.tab.browserData?.cookieData) {
    console.log('[BrowserTab] 检测到预设 Cookie，先设置再加载页面');
    await setPresetCookies(props.tab.browserData.cookieData);
    
    // 对于百家号，需要更长的等待时间确保 Cookie 生效
    if (platform.value === 'baijiahao') {
      console.log('[BrowserTab] 百家号平台，等待 Cookie 生效...');
      await new Promise(resolve => setTimeout(resolve, 500));
    } else {
      // 等待一小段时间确保 Cookie 设置完成
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
  
  // 设置目标 URL 并渲染 webview
  webviewSrc.value = targetUrl;
  webviewReady.value = true;
  console.log('[BrowserTab] webview 准备就绪，加载页面:', targetUrl);
});

// 设置预设的 Cookies
async function setPresetCookies(cookieDataStr: string) {
  if (!window.electronAPI?.setWebviewCookies) {
    console.warn('[BrowserTab] electronAPI.setWebviewCookies 不可用');
    ElMessage.error('浏览器功能不可用，请重启应用');
    return;
  }
  
  try {
    // 尝试解析 JSON 格式的 cookie
    let cookieList: Array<{ name: string; value: string; domain?: string; path?: string; expires?: number }>;
    
    try {
      cookieList = JSON.parse(cookieDataStr);
      console.log('[BrowserTab] 成功解析 JSON 格式的 Cookie');
    } catch {
      // 如果不是 JSON，尝试解析 "name=value; name2=value2" 格式
      console.log('[BrowserTab] JSON 解析失败，尝试解析字符串格式');
      cookieList = parseCookieString(cookieDataStr);
    }
    
    if (cookieList.length === 0) {
      console.warn('[BrowserTab] 没有有效的 Cookie 数据');
      ElMessage.warning('账号 Cookie 数据为空，可能需要重新登录');
      return;
    }
    
    // 获取目标 URL（优先使用 browserData 中的 url）
    const targetUrl = props.tab.browserData?.url || PLATFORMS[platform.value]?.loginUrl || '';
    
    // 获取平台的根域名
    const platformDomainMap: Record<string, string> = {
      douyin: '.douyin.com',
      xiaohongshu: '.xiaohongshu.com',
      kuaishou: '.kuaishou.com',
      weixin_video: '.qq.com',
      bilibili: '.bilibili.com',
      baijiahao: '.baidu.com',
      toutiao: '.toutiao.com',
    };
    const rootDomain = platformDomainMap[platform.value] || '';
    
    // 对于百家号，使用百度主站 URL 来设置 Cookie
    const cookieUrl = platform.value === 'baijiahao' 
      ? 'https://www.baidu.com' 
      : targetUrl;
    
    console.log(`[BrowserTab] 设置 Cookie, platform=${platform.value}, targetUrl=${targetUrl}, cookieUrl=${cookieUrl}, domain=${rootDomain}`);
    console.log(`[BrowserTab] Cookie 列表:`, cookieList.slice(0, 3).map(c => ({ name: c.name, domain: c.domain })));
    
    // 过滤掉已过期的 Cookie
    const now = Date.now() / 1000;
    const validCookies = cookieList.filter(cookie => {
      if (cookie.expires && cookie.expires < now) {
        console.warn(`[BrowserTab] Cookie ${cookie.name} 已过期，跳过`);
        return false;
      }
      return true;
    });
    
    if (validCookies.length === 0) {
      console.error('[BrowserTab] 所有 Cookie 都已过期');
      ElMessage.error('账号登录已过期，请重新登录');
      return;
    }
    
    if (validCookies.length < cookieList.length) {
      console.warn(`[BrowserTab] 过滤掉 ${cookieList.length - validCookies.length} 个过期的 Cookie`);
    }
    
    // 转换为 Electron 需要的格式，保留原始 Cookie 的所有属性
    const cookiesForElectron = validCookies.map(cookie => {
      // 优先使用 Cookie 自带的 domain，否则使用平台根域名
      let cookieDomain = cookie.domain;
      if (!cookieDomain || cookieDomain === '') {
        cookieDomain = rootDomain;
      }
      // 确保域名以点开头（用于子域名匹配）
      if (cookieDomain && !cookieDomain.startsWith('.') && !cookieDomain.includes('localhost')) {
        cookieDomain = '.' + cookieDomain;
      }
      
      const electronCookie: any = {
        url: cookieUrl, // 使用正确的 URL
        name: cookie.name,
        value: cookie.value,
        domain: cookieDomain,
        path: cookie.path || '/',
      };
      
      // 添加可选字段
      if (cookie.expires) {
        electronCookie.expirationDate = cookie.expires;
      }
      if ((cookie as any).httpOnly !== undefined) {
        electronCookie.httpOnly = (cookie as any).httpOnly;
      }
      if ((cookie as any).secure !== undefined) {
        electronCookie.secure = (cookie as any).secure;
      }
      if ((cookie as any).sameSite) {
        // 转换 sameSite 值
        const sameSite = (cookie as any).sameSite;
        if (sameSite === 'None') {
          electronCookie.sameSite = 'no_restriction';
        } else if (sameSite === 'Lax' || sameSite === 'lax') {
          electronCookie.sameSite = 'lax';
        } else if (sameSite === 'Strict' || sameSite === 'strict') {
          electronCookie.sameSite = 'strict';
        }
      }
      
      return electronCookie;
    });
    
    console.log(`[BrowserTab] 准备设置 ${cookiesForElectron.length} 个 Cookies`);
    console.log(`[BrowserTab] 示例 Cookie:`, cookiesForElectron.slice(0, 2));
    
    // 设置 cookies
    const success = await window.electronAPI.setWebviewCookies(
      webviewPartition.value,
      cookiesForElectron
    );
    
    if (success) {
      console.log(`[BrowserTab] 预设 ${validCookies.length} 个 Cookies 成功`);
      // 标记已有登录 cookie
      loginStatus.value = 'checking';
    } else {
      console.warn('[BrowserTab] 设置 Cookies 失败');
      ElMessage.warning('设置登录信息失败，可能需要重新登录');
    }
  } catch (error) {
    console.error('[BrowserTab] 设置预设 Cookies 失败:', error);
    ElMessage.error('设置登录信息时出错');
  }
}

// 解析 "name=value; name2=value2" 格式的 cookie 字符串
function parseCookieString(cookieString: string): Array<{ name: string; value: string }> {
  const cookies: Array<{ name: string; value: string }> = [];
  
  const pairs = cookieString.split(';');
  for (const pair of pairs) {
    const trimmed = pair.trim();
    if (!trimmed) continue;
    
    const eqIndex = trimmed.indexOf('=');
    if (eqIndex === -1) continue;
    
    const name = trimmed.substring(0, eqIndex).trim();
    const value = trimmed.substring(eqIndex + 1).trim();
    
    if (name && value) {
      cookies.push({ name, value });
    }
  }
  
  return cookies;
}

onUnmounted(() => {
  stopAutoCheck();
  stopAIAnalysis();
  
  // 清理 CDP 网络拦截
  disableCDPNetworkIntercept();
  cleanupCDPListener();
  
  // 清理 webview session
  if (window.electronAPI?.clearWebviewCookies) {
    window.electronAPI.clearWebviewCookies(webviewPartition.value);
  }
});

// 监听标签页变化
watch(() => props.tab.id, () => {
  stopAutoCheck();
  stopAIAnalysis();
});
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.browser-tab-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  margin: -20px;
  border-radius: $radius-lg;
  overflow: hidden;
}

.browser-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background: linear-gradient(180deg, #fafbfc 0%, #f3f4f6 100%);
  border-bottom: 1px solid $border-light;
  gap: 16px;
  
  .toolbar-left {
    display: flex;
    align-items: center;
    gap: 14px;
    flex: 1;
    min-width: 0;
    
    :deep(.el-button-group) {
      .el-button {
        border-radius: $radius-base;
        background: #fff;
        border-color: $border-light;
        
        &:hover:not(:disabled) {
          background: $primary-color-light;
          border-color: $primary-color;
          color: $primary-color;
        }
        
        &:first-child {
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
        
        &:last-child {
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
        }
        
        &:not(:first-child):not(:last-child) {
          border-radius: 0;
        }
      }
    }
  }
  
  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
    
    .el-button {
      border-radius: $radius-base;
      font-weight: 500;
    }
    
    .el-tag {
      border-radius: 12px;
      font-weight: 500;
      
      &.ai-analyzing-tag {
        display: inline-flex !important;
        flex-direction: row !important;
        flex-wrap: nowrap !important;
        align-items: center !important;
        gap: 4px !important;
        padding: 0 10px !important;
        height: 24px !important;
        min-width: max-content !important;
        white-space: nowrap !important;
        
        :deep(.el-tag__content) {
          display: inline-flex !important;
          flex-direction: row !important;
          flex-wrap: nowrap !important;
          align-items: center !important;
          gap: 4px !important;
          white-space: nowrap !important;
        }
        
        .el-icon.ai-icon {
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          margin: 0 !important;
          font-size: 12px !important;
          width: 12px !important;
          height: 12px !important;
          flex-shrink: 0 !important;
          animation: spin 1s linear infinite;
        }
        
        > span {
          white-space: nowrap !important;
          flex-shrink: 0 !important;
        }
      }
    }
  }
}

.url-bar {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 16px;
  background: #fff;
  border: 1px solid $border-light;
  border-radius: 24px;
  min-width: 0;
  box-shadow: $shadow-sm;
  transition: all 0.2s;
  
  &:hover {
    border-color: $primary-color;
  }
  
  .loading-icon {
    color: $primary-color;
    animation: spin 1s linear infinite;
    font-size: 15px;
  }
  
  .lock-icon {
    color: $success-color;
    font-size: 15px;
  }
  
  .url-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 13px;
    color: $text-regular;
  }
}

.browser-content {
  flex: 1;
  position: relative;
  overflow: hidden;
  background: #fff;
}

.embedded-browser {
  width: 100%;
  height: 100%;
  border: none;
}

.success-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  backdrop-filter: blur(3px);
}

.success-content {
  text-align: center;
  padding: 48px;
  max-width: 400px;
  
  .success-icon {
    font-size: 72px;
    color: $success-color;
    margin-bottom: 20px;
    filter: drop-shadow(0 4px 12px rgba(82, 196, 26, 0.3));
  }
  
  h3 {
    margin: 0 0 24px;
    font-size: 22px;
    font-weight: 600;
    color: $text-primary;
  }
  
  p {
    margin: 20px 0;
    color: $text-secondary;
    font-size: 14px;
  }
  
  .el-button {
    min-width: 140px;
    height: 40px;
    font-size: 15px;
    font-weight: 500;
    border-radius: $radius-base;
  }
}

.account-fetching {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 24px 32px;
  background: $primary-color-light;
  border-radius: $radius-lg;
  margin: 24px 0;
  border: 1px solid $border-light;
  color: $text-secondary;
  font-size: 14px;
  
  > span {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .fetching-icon {
    font-size: 18px;
    color: $primary-color;
    animation: spin 1s linear infinite;
  }
  
  .fetching-hint {
    font-size: 12px;
    color: $text-regular;
    margin: 0;
  }
}

.account-preview {
  display: flex;
  flex-direction: column;
  padding: 20px 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: $radius-lg;
  margin: 20px 0;
  border: 1px solid $border-light;
  
  .account-header {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 16px;
    
    :deep(.el-avatar) {
      border: 2px solid #fff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      background: linear-gradient(135deg, $primary-color-light, #fff);
      color: $primary-color;
      font-weight: 600;
      flex-shrink: 0;
    }
    
    .account-text {
      flex: 1;
      min-width: 0;
      
      .account-preview-name {
        font-weight: 600;
        font-size: 16px;
        color: $text-primary;
        line-height: 1.4;
      }
      
      .account-preview-id {
        font-size: 12px;
        color: $text-secondary;
        margin-top: 2px;
      }
    }
  }
  
  .account-stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    padding-top: 12px;
    border-top: 1px solid rgba(0, 0, 0, 0.06);
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 8px 4px;
      
      .stat-value {
        font-size: 18px;
        font-weight: 700;
        color: $text-primary;
        line-height: 1.2;
      }
      
      .stat-label {
        font-size: 12px;
        color: $text-secondary;
        margin-top: 4px;
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// AI 辅助面板样式
.ai-panel {
  background: linear-gradient(135deg, #f0f7ff 0%, #e8f4fd 100%);
  border-bottom: 1px solid #d0e3f5;
  padding: 12px 16px;
  
  .ai-panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    
    .ai-panel-title {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 13px;
      font-weight: 600;
      color: $primary-color;
      
      .el-icon {
        font-size: 16px;
      }
    }
    
    .ai-panel-actions {
      display: flex;
      align-items: center;
      gap: 10px;
      
      :deep(.el-switch) {
        --el-switch-on-color: $primary-color;
        
        .el-switch__label {
          font-size: 11px;
          color: $text-secondary;
        }
      }
    }
    
    .ai-panel-close {
      padding: 4px;
      min-height: auto;
      color: $text-secondary;
      
      &:hover {
        color: $text-primary;
      }
    }
  }
  
  .ai-panel-content {
    .ai-executing {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 14px;
      background: #e6f7ff;
      border-radius: 6px;
      margin-bottom: 10px;
      font-size: 13px;
      color: $primary-color;
      
      .executing-icon {
        animation: spin 1s linear infinite;
      }
    }
    
    .ai-last-operation {
      display: flex;
      gap: 8px;
      margin-bottom: 10px;
      font-size: 12px;
      padding: 8px 10px;
      background: rgba(0, 0, 0, 0.03);
      border-radius: 4px;
      
      .ai-status-label {
        color: $text-secondary;
        flex-shrink: 0;
      }
      
      .ai-status-value {
        color: $text-regular;
      }
    }
    
    .ai-status {
      display: flex;
      gap: 8px;
      margin-bottom: 10px;
      font-size: 13px;
      
      .ai-status-label {
        color: $text-secondary;
        flex-shrink: 0;
      }
      
      .ai-status-value {
        color: $text-primary;
      }
    }
    
    .ai-verification,
    .ai-success,
    .ai-suggestion {
      margin-bottom: 8px;
      
      :deep(.el-alert) {
        padding: 10px 14px;
        
        .el-alert__title {
          font-size: 13px;
        }
        
        .el-alert__description {
          font-size: 12px;
          margin-top: 6px;
        }
      }
      
      .ai-action {
        margin-top: 6px;
        padding-top: 6px;
        border-top: 1px dashed rgba(0, 0, 0, 0.1);
      }
    }
    
    .ai-time {
      font-size: 11px;
      color: $text-secondary;
      text-align: right;
      margin-top: 6px;
    }
  }
}

</style>
