/**
 * Axure上传助手 - 内容脚本 v2.1.1
 * 修复版：中文文件名解码 + 目录结构保持 + 自动收集
 */

// 全局变量
let collectedFiles = [];
let collectedUrls = new Set();
let extractedHtmlFiles = [];
let currentProjectId = '';
let currentProjectName = '';
let isCollecting = false;

let fileCollectionPromise = null;

// 立即检查页面是否为Axure生成的页面
checkAxurePage();

// 检查是否为Axure生成的页面
function checkAxurePage() {
    console.log('🔍 检查是否为Axure生成的页面');
    
    // 检查URL是否包含127.0.0.1
    if (window.location.href.includes('127.0.0.1')) {
        console.log('✅ 检测到Axure生成的页面');
        
        // 等待页面完全加载
        if (document.readyState === 'complete') {
            injectUploadButton();
        } else {
            window.addEventListener('load', injectUploadButton);
        }
    } else {
        console.log('❌ 不是Axure生成的页面');
    }
}

// 注入上传按钮
function injectUploadButton() {
    console.log('🔧 注入上传按钮');
    
    // 注入样式
    injectStyles();
    
    // 查找目标按钮
    const targetBtn = document.getElementById('pageNotesHostBtn');
    
    if (targetBtn) {
        console.log('✅ 找到目标按钮，在其左侧添加上传按钮');
        
        // 创建上传按钮
        const uploadBtn = createUploadButton();
        
        // 在目标按钮左侧添加
        targetBtn.parentNode.insertBefore(uploadBtn, targetBtn);
        
        console.log('✅ 上传按钮已添加到页面');
        
        // 添加点击事件，先验证登录状态
        uploadBtn.addEventListener('click', async () => {
            console.log('🔍 点击上传按钮，开始验证登录状态');
            
            // 先检查登录状态
            const isLoggedIn = await checkLoginStatus();
            
            console.log('✅ 登录状态检查完成，结果:', isLoggedIn);
            showMainModal();
        });
    } else {
        console.warn('⚠️ 未找到目标按钮，使用备用位置');
        
        // 使用备用位置 - 页面右下角
        const uploadBtn = createUploadButton();
        document.body.appendChild(uploadBtn);
        uploadBtn.style.position = 'fixed';
        uploadBtn.style.bottom = '20px';
        uploadBtn.style.right = '20px';
        uploadBtn.style.zIndex = '9999999';
        
        // 添加点击事件，先验证登录状态
        uploadBtn.addEventListener('click', async () => {
            console.log('🔍 点击备用上传按钮，开始验证登录状态');
            
            // 先检查登录状态
            const isLoggedIn = await checkLoginStatus();
            
            console.log('✅ 登录状态检查完成，结果:', isLoggedIn);
            
            // 无论登录状态如何，都调用showMainModal，由它内部处理登录状态检查
            showMainModal();
        });
    }
}

// 注入样式
function injectStyles() {
    const style = document.createElement('style');
    style.textContent = `
    /* 上传按钮样式 */
    #axureUploadBtn {
        background: linear-gradient(135deg, #002eff, #b267ff) !important;
        color: white !important;
        border: none !important;
        border-radius: 6px !important;
        padding: 4px 8px !important;
        cursor: pointer !important;
        font-size: 12px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        margin: 2px 8px !important;
        width: 32px !important;
        height: 32px !important;
      
        transition: all 0.3s ease !important;
    }
    

    
    #axureUploadBtn svg {
        width: 20px !important;
        height: 20px !important;
        stroke: white !important;
        stroke-width: 2 !important;
    }
    
    /* 模态窗口样式 */
    .axure-modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.6);
        backdrop-filter: blur(5px);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999998;
        display: none;
        animation: fadeIn 0.3s ease;
    }
    
    .axure-modal-dialog {
        background: white;
        border-radius: 6px;
        width: 90%;
        max-width: 520px;
    
        overflow-y: auto;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
        animation: slideUp 0.3s ease;
    }
    
    .axure-modal-header {
        padding: 10px 14px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
         background:linear-gradient(126deg, #002fffff, #7d44ff);
    }
    
    .axure-modal-title {
        margin: 0;
        font-size: 20px;
        font-weight: 700;
        color: #1a202c;
        background:#fff;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .axure-modal-close {
        background: none;
        border: none;
        cursor: pointer;
        color: #fff;
        font-size: 20px;
        width: 32px;
        height: 32px;
        padding: 4px;
        border-radius: 8px;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    

    .axure-modal-close svg {
        width: 24px;
        height: 24px;
        stroke: currentColor;
        stroke-width: 2;
        fill: none;
    }
    
    /* 动画效果 */
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    @keyframes slideUp {
        from { 
            opacity: 0;
            transform: translateY(20px);
        }
        to { 
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .axure-modal-body {
        padding: 24px;
    }
    
    .axure-form-group {
        margin-bottom: 20px;
    }
    
    .axure-form-label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #2d3748;
        font-size: 14px;
    }
    
    .axure-form-input,
    .axure-form-select,
    .axure-form-password {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid #e2e8f0;
        border-radius: 10px;
        font-size: 14px;
        color: #2d3748;
        background: white;
        transition: all 0.2s ease;
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
    }
    
    .axure-form-input:focus,
    .axure-form-select:focus,
    .axure-form-password:focus {
        outline: none;
        border-color: #002eff;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    .axure-form-select {
        cursor: pointer;
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 16px center;
        padding-right: 40px;
    }
    
    .axure-modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        margin-top: 24px;
      
    }
    
    .axure-btn-primary,
    .axure-btn-secondary,
    .axure-btn-danger {
        padding: 12px 20px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.3s ease;
    
    }
    
    .axure-btn-primary {
        background:linear-gradient(126deg, #002fffff, #7d44ff);
        color: white;
    }
    
    .axure-btn-primary:hover {
        background: linear-gradient(135deg,#002fffff, #4900f2);
        box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        
    }
    
    .axure-btn-secondary {
        background: #f7fafc;
        color: #4a5568;
        border: 1px solid #e2e8f0;
    }
    
    .axure-btn-secondary:hover {
        background: #edf2f7;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }
    
    .axure-btn-danger {
        background: linear-gradient(135deg, #f56565, #c53030);
        color: white;
    }
    
    .axure-btn-danger:hover {
        background: linear-gradient(135deg, #e53e3e, #9b2c2c);
        box-shadow: 0 6px 16px rgba(245, 101, 101, 0.4);
        transform: translateY(-2px);
    }
    
    /* 文件列表样式 */
    .axure-file-list {
        margin: 20px 0;
        padding: 16px;
        background: #f8fafc;
        border-radius: 12px;
        max-height: 250px;
        overflow-y: auto;
        border: 1px solid #e2e8f0;
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
    }
    
    .axure-file-item {
        padding: 6px 0;
        border-bottom: 1px solid #f1f5f9;
        font-size: 13px;
        color: #64748b;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .axure-file-item:last-child {
        border-bottom: none;
    }
    
    .axure-file-item::before {
        content: '📄';
        font-size: 16px;
    }
    
    .axure-file-item-html {
        color: #15803d;
        font-weight: 600;
    }
    
    .axure-file-item-html::before {
        content: '📄';
    }
    
    .axure-file-item-js {
        color: #dc2626;
    }
    
    .axure-file-item-js::before {
        content: '📜';
    }
    
    .axure-file-item-css {
        color: #1d4ed8;
    }
    
    .axure-file-item-css::before {
        content: '🎨';
    }
    
    .axure-file-item-image {
        color: #b45309;
    }
    
    .axure-file-item-image::before {
        content: '🖼️';
    }
    
    .axure-file-item-font {
        color: #7e22ce;
    }
    
    .axure-file-item-font::before {
        content: '🔤';
    }
    
    /* 项目列表样式 */
    .axure-project-list {
        margin: 20px 0;
        padding: 16px;
        background: #f8fafc;
        border-radius: 12px;
        max-height: 250px;
        overflow-y: auto;
        border: 1px solid #e2e8f0;
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
    }
    
    .axure-project-item {
        padding: 12px 16px;
        border-bottom: 1px solid #f1f5f9;
        cursor: pointer;
        border-radius: 8px;
        transition: all 0.2s ease;
        margin-bottom: 4px;
    }
    
    .axure-project-item:last-child {
        border-bottom: none;
        margin-bottom: 0;
    }
    
    .axure-project-item:hover {
        background: #e0f2fe;
        transform: translateX(4px);
    }
    
    .axure-project-name {
        font-weight: 600;
        color: #1e293b;
        font-size: 14px;
        margin-bottom: 4px;
    }
    
    .axure-project-code {
        font-size: 12px;
        color: #64748b;
        font-family: 'Courier New', monospace;
    }
    
    /* 上传进度样式 */
    .axure-upload-progress {
        margin: 20px 0;
        padding: 16px;
        background: #f8fafc;
        border-radius: 12px;
        border: 1px solid #e2e8f0;
    }
    
    .axure-progress-bar {
        height: 12px;
        background: #e2e8f0;
        border-radius: 6px;
        overflow: hidden;
        margin: 12px 0;
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
    }
    
    .axure-progress-fill {
        height: 100%;
        background: linear-gradient(37deg, #113cff, #7800f4);
        width: 0%;
        transition: width 0.3s ease;
        border-radius: 6px;
        box-shadow: 0 0 10px rgba(102, 126, 234, 0.4);
    }
    
    .axure-progress-text {
        font-size: 13px;
        color: #64748b;
        display: flex;
        justify-content: space-between;
        font-weight: 500;
    }
    
    /* 状态信息样式 */
    .axure-upload-status {
        margin: 6px 0;
        padding: 6px 10px;
        border-radius: 10px;
        font-size: 13px;
        display: flex;
        align-items: flex-start;
        gap: 8px;
        border-left: 4px solid transparent;
    }
    
    .axure-upload-status::before {
        font-size: 16px;
        margin-top: -2px;
    }
    
    .axure-status-info {
        background: #dbeafe;
        color: #1e40af;
        border-left-color: #3b82f6;
    }
    
    .axure-status-info::before {
        content: 'ℹ️';
    }
    
    .axure-status-success {
        background: #dcfce7;
        color: #166534;
        border-left-color: #10b981;
    }
    
    .axure-status-success::before {
        content: '✅';
    }
    
    .axure-status-error {
        background: #fee2e2;
        color: #991b1b;
        border-left-color: #ef4444;
    }
    
    .axure-status-error::before {
        content: '❌';
    }
    
    .axure-status-warning {
        background: #fef3c7;
        color: #92400e;
        border-left-color: #f59e0b;
    }
    
    .axure-status-warning::before {
        content: '⚠️';
    }
    
    .axure-status-note {
        background: #f0f9ff;
        color: #0284c7;
        border-left-color: #06b6d4;
    }
    
    .axure-status-note::before {
        content: '📝';
    }
    
    /* 收集进度样式 */
    .axure-collection-progress {
        margin: 12px 0;
        font-size: 13px;
        color: #64748b;
        padding: 8px 12px;
        background: #f8fafc;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
    }
    
    /* 分享链接样式 */
    .axure-share-link {
        margin: 20px 0;
        padding: 16px;
        background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
        border-radius: 12px;
        display: flex;
        align-items: center;
        gap: 12px;
        border: 1px solid #bae6fd;
    }
    
    .axure-share-url {
        flex: 1;
        font-size: 13px;
        color: #1e40af;
        word-break: break-all;
        font-family: 'Courier New', monospace;
        background: white;
        padding: 8px 12px;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
    }
    
    .axure-share-copy {
        background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        font-weight: 600;
        transition: all 0.2s ease;
    }
    
    .axure-share-copy:hover {
        background: linear-gradient(135deg, #2563eb, #1e40af);
        transform: translateY(-1px);
        box-shadow: 0 0px 12px rgba(59, 130, 246, 0.4);
    }
    
    /* 登录表单样式 */
    .axure-login-form {
        max-width: 350px;
        margin: 0 auto;
        padding: 24px;
        background: #f8fafc;
        border-radius: 16px;
        border: 1px solid #e2e8f0;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    }
    
    .axure-login-title {
        text-align: center;
        margin-bottom: 24px;
        color: #1e293b;
        font-size: 20px;
        font-weight: 700;
        background: linear-gradient(135deg, #002eff, #764ba2);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .axure-login-footer {
        text-align: center;
        margin-top: 20px;
        font-size: 13px;
        color: #64748b;
    }
    
    .axure-login-help {
        text-align: center;
        margin-top: 12px;
        font-size: 12px;
        color: #92400e;
        background: #fef3c7;
        padding: 10px;
        border-radius: 8px;
        border-left: 4px solid #f59e0b;
    }
    
    /* 步骤指示器 */
    .axure-steps {
        display: flex;
        justify-content: space-between;
        margin: 24px 0;
        padding: 0;
        list-style: none;
        position: relative;
    }
    
    .axure-steps::before {
        content: '';
        position: absolute;
        top: 18px;
        left: 0;
        width: 100%;
        height: 3px;
        background: #e2e8f0;
        z-index: 1;
    }
    
    .axure-step {
        flex: 1;
        text-align: center;
        position: relative;
        z-index: 2;
    }
    
    .axure-step-number {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #f1f5f9;
        color: #64748b;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 10px;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
    
    .axure-step.active .axure-step-number {
        background: linear-gradient(135deg, #002eff, #764ba2);
        color: white;
        transform: scale(1.1);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
    
    .axure-step.completed .axure-step-number {
        background: linear-gradient(135deg, #10b981, #059669);
        color: white;
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
    }
    
    .axure-step.completed .axure-step-number::after {
        content: '✓';
        font-size: 16px;
    }
    
    .axure-step-label {
        font-size: 13px;
        color: #64748b;
        font-weight: 500;
    }
    
    .axure-step.active .axure-step-label {
        color: #002eff;
        font-weight: 600;
    }
    
    .axure-step.completed .axure-step-label {
        color: #10b981;
    }
    
    /* 项目列表刷新按钮 */
    .axure-refresh-button {
        background: linear-gradient(135deg, #002eff, #764ba2);
        color: white;
        border: none;
        padding: 4px 8px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        margin-left: 8px;
    }
    
    .axure-project-selection-container {
        display: flex;
        align-items: center;
    }
    
    .axure-project-select-wrapper {
        flex: 1;
    }
    
    /* 单选按钮组样式 */
    .axure-radio-group {
        display: flex;
        gap: 24px;
        margin-top: 8px;
    }
    
    .axure-radio-option {
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        color: #4a5568;
        transition: all 0.2s ease;
    }
    
    .axure-radio-option:hover {
        color: #002eff;
    }
    
    .axure-radio-option input[type="radio"] {
        width: 18px;
        height: 18px;
        accent-color: #002eff;
        cursor: pointer;
    }
    
    .axure-radio-text {
        user-select: none;
    }
    
    /* 收集统计信息 */
    .axure-collection-stats {
        display: flex;
        justify-content: space-between;
        margin-top: 8px;
        font-size: 12px;
        color: #666;
    }
    
    /* 文件目录树样式 */
    .axure-file-tree {
        margin: 16px 0;
        padding: 12px;
        background: #f9f9f9;
        border-radius: 4px;
        max-height: 300px;
        overflow-y: auto;
        font-family: monospace;
    }
    
    .axure-tree-node {
        padding: 2px 0;
        font-size: 12px;
    }
    
    .axure-tree-folder {
        color: #3B82F6;
        font-weight: bold;
    }
    
    .axure-tree-file {
        color: #666;
        padding-left: 16px;
    }
    
    .axure-tree-indent {
        display: inline-block;
        width: 16px;
    }
    
    .axure-tree-icon {
        display: inline-block;
        width: 16px;
        text-align: center;
    }
    
    .axure-tree-html {
        color: #166534;
    }
    
    .axure-tree-js {
        color: #991b1b;
    }
    
    .axure-tree-css {
        color: #1e40af;
    }
    
    .axure-tree-image {
        color: #854d0e;
    }
    
    .axure-tree-font {
        color: #7e22ce;
    }
    
    .axure-tree-other {
        color: #666;
    }
    
    /* 自动收集提示 */
    .axure-auto-collect-hint {
        background: #f0f9ff;
        color: #0284c7;
        padding: 8px;
        border-radius: 4px;
        margin-bottom: 16px;
        font-size: 12px;
    }
    `;
    
    document.head.appendChild(style);
}

// 创建上传按钮
function createUploadButton() {
    const btn = document.createElement('button');
    btn.id = 'axureUploadBtn';
    btn.title = '上传Axure原型';
    
    btn.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
    </svg>
    `;
    
    return btn;
}

// 显示主模态窗口
function showMainModal() {
    console.log('🗂️  显示主模态窗口');
    
    // 重置所有全局收集变量和状态
    resetCollectionVariables();
    
    // 强制移除所有可能存在的登录成功监听器，避免重复监听
    chrome.runtime.onMessage.removeListener((message) => message.action === 'loginSuccess');
    
    // 检查是否已经有模态窗口
    let modal = document.getElementById('axureMainModal');
    if (modal) {
        modal.style.display = 'flex';
        
        // 强制重置界面状态 - 添加null检查
        const loginForm = document.getElementById('loginForm');
        const mainInterface = document.getElementById('mainInterface');
        if (loginForm) loginForm.style.display = 'none';
        if (mainInterface) mainInterface.style.display = 'none';
        
        // 确保文件收集的UI元素保持隐藏
        const fileCollectionDiv = document.getElementById('fileCollection');
        if (fileCollectionDiv) {
            fileCollectionDiv.style.display = 'none';
        }
        
        // 重新添加事件监听器
        addEventListeners();
        
        // 重新检查登录状态
        (async () => {
            const isLoggedIn = await checkLoginStatus();
            if (isLoggedIn) {
                console.log('✅ 已登录，显示主界面');
                showMainInterface();
            } else {
                console.log('❌ 未登录，显示登录表单');
                showLoginForm();
            }
        })();
        return;
    }
    
    // 创建主模态窗口
    modal = document.createElement('div');
    modal.id = 'axureMainModal';
    modal.className = 'axure-modal-overlay';
    
    modal.innerHTML = `
    <div class="axure-modal-dialog">
        <div class="axure-modal-header">
            <h3 class="axure-modal-title">Axure上传助手</h3>
            <button class="axure-modal-close" id="closeButton">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>
        
        <!-- 登录表单 -->
        <div id="loginForm" class="axure-modal-body">
            <div class="axure-login-form" style="background: transparent; border: none; box-shadow: none;">
                <h4 class="axure-login-title">请登录</h4>
                <div class="axure-form-group">
                    <label class="axure-form-label">手机号</label>
                    <input type="tel" id="loginPhone" class="axure-form-input" placeholder="请输入手机号">
                </div>
                <div class="axure-form-group">
                    <label class="axure-form-label">密码</label>
                    <input type="password" id="loginPassword" class="axure-form-password" placeholder="请输入密码">
                </div>
                <div class="axure-modal-footer">
                    <button id="loginButton" class="axure-btn-primary">登录</button>
                </div>
                <div id="loginError" class="axure-upload-status axure-status-error" style="display: none;"></div>
                <div id="loginNote" class="axure-upload-status axure-status-note" style="display: none;"></div>
            </div>
        </div>
        
        <!-- 主界面 -->
        <div id="mainInterface" class="axure-modal-body" style="display: none;">
            <!-- 步骤指示器 -->
            <ul class="axure-steps" style="display: none;">
                <li class="axure-step active" id="step1">
                    <div class="axure-step-number">1</div>
                    <div class="axure-step-label">选择项目</div>
                </li>
                <li class="axure-step" id="step2">
                    <div class="axure-step-number">2</div>
                    <div class="axure-step-label">自动收集</div>
                </li>
                <li class="axure-step" id="step3">
                    <div class="axure-step-number">3</div>
                    <div class="axure-step-label">上传完成</div>
                </li>
            </ul>
            
            <!-- 自动收集提示 -->
            <div class="axure-auto-collect-hint" id="autoCollectHint" style="display: none;">
                <strong>自动收集中...</strong> 系统正在扫描页面并收集所有相关文件，请稍候。
            </div>
            
            <!-- 项目操作选择 - 单选按钮版 -->
            <div class="axure-project-operation-container">
                <label class="axure-form-label">项目操作</label>
                <div class="axure-radio-group">
                    <label class="axure-radio-option">
                        <input type="radio" name="projectOperation" value="update" id="updateProject" checked>
                        <span class="axure-radio-text">更新项目</span>
                    </label>
                    <label class="axure-radio-option">
                        <input type="radio" name="projectOperation" value="new" id="newProject">
                        <span class="axure-radio-text">新建项目</span>
                    </label>
                </div>
            </div>
            
            <!-- 项目列表 - 更新项目时显示 -->
            <div id="projectListContainer" class="axure-form-group">
                <label class="axure-form-label">选择项目</label>
                <div class="axure-project-selection-container">
                    <div class="axure-project-select-wrapper">
                        <select id="projectSelect" class="axure-form-select">
                            <option value="">请选择项目...</option>
                        </select>
                    </div>
                    <button id="refreshProjectList" class="axure-refresh-button" style="display: none;">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                    </button>
                </div>

                <div id="projectListError" class="axure-upload-status axure-status-error" style="display: none;"></div>
                <div id="projectListNote" class="axure-upload-status axure-status-note" style="display: none;"></div>
            </div>
            
            <!-- 新建项目 -->
            <div id="newProjectForm" class="axure-form-group" style="display: none;">
                <label class="axure-form-label">项目名称</label>
                <input type="text" id="newProjectName" class="axure-form-input" placeholder="请输入项目名称">
                <div id="projectNameError" class="axure-form-error" style="display: none; color: red; font-size: 12px; margin-top: 5px;"></div>
            </div>
            
            <!-- 文件收集 - 改进版：目录树显示 -->
            <div id="fileCollection" class="axure-form-group" style="display: none;">
                <label class="axure-form-label">已收集文件 (目录结构)</label>
                <div id="fileTree" class="axure-file-tree">
                    <div class="axure-status-info">等待开始收集...</div>
                </div>
                <div id="collectionProgress" class="axure-collection-progress"></div>
                <div class="axure-collection-stats">
                    <div id="collectionStats">文件: 0 | 大小: 0 KB</div>
                    <div id="collectionStatus">等待收集...</div>
                </div>
            </div>
            
            <!-- 上传进度 -->
            <div id="uploadProgress" class="axure-upload-progress" style="display: none;">
                <div class="axure-progress-bar">
                    <div class="axure-progress-fill"></div>
                </div>
                <div class="axure-progress-text">
                    <span>0% 完成</span>
                    <span>0/0 文件</span>
                </div>
                <div id="uploadStatus" class="axure-upload-status axure-status-info">
                    等待上传...
                </div>
            </div>
            
            <!-- 分享链接 -->
            <div id="shareLink" class="axure-share-link" style="display: none;">
                <div class="axure-share-url" id="shareUrl"></div>
                <button class="axure-share-copy" id="copyLinkButton">复制链接</button>
            </div>
            
            <div class="axure-modal-footer">
                <button id="logoutButton" class="axure-btn-secondary" style="display: none;">退出登录</button>
                <button id="cancelButton" class="axure-btn-secondary">取消</button>
                <button id="nextButton" class="axure-btn-primary" style="display: none;">下一步</button>
                <button id="uploadButton" class="axure-btn-primary" style="display: none;">上传</button>
                <button id="updateButton" class="axure-btn-primary" style="display: none;">更新</button>
                <button id="finishButton" class="axure-btn-primary" style="display: none;">完成</button>
            </div>
        </div>
    </div>
    `;
    
    document.body.appendChild(modal);
    modal.style.display = 'flex';
    
    // 添加事件监听器
    addEventListeners();
    
    // 检查登录状态并根据结果显示相应界面
    (async () => {
        const isLoggedIn = await checkLoginStatus();
        
        if (isLoggedIn) {
            console.log('✅ 已登录，显示主界面');
            showMainInterface();
        } else {
            console.log('❌ 未登录，显示登录表单');
            showLoginForm();
        }
    })();
}

// 检查登录状态 - 返回Promise但不自动显示界面，让调用者决定如何处理
function checkLoginStatus() {
    console.log('🔍 检查登录状态');
    
    return new Promise((resolve) => {
        try {
            chrome.runtime.sendMessage({ action: 'checkLoginStatus' }, (response) => {
                // 检查是否有错误发生
                if (chrome.runtime.lastError) {
                    console.error('❌ 检查登录状态时发生错误:', chrome.runtime.lastError);
                    resolve(false);
                    return;
                }
                
                const isLoggedIn = response && response.success && response.isLoggedIn;
                console.log('📊 登录状态检查结果:', isLoggedIn);
                resolve(isLoggedIn);
            });
        } catch (error) {
            console.error('❌ 检查登录状态时发生异常:', error);
            resolve(false);
        }
    });
}

// 显示登录表单
function showLoginForm() {
    console.log('🔐 显示登录表单');
    
    const loginForm = document.getElementById('loginForm');
    const mainInterface = document.getElementById('mainInterface');
    
    if (loginForm) loginForm.style.display = 'block';
    if (mainInterface) mainInterface.style.display = 'none';
}

// 显示主界面
async function showMainInterface() {
    console.log('✅ 显示主界面');
    
    const loginForm = document.getElementById('loginForm');
    const mainInterface = document.getElementById('mainInterface');
    const autoCollectHint = document.getElementById('autoCollectHint');
    
    if (loginForm) loginForm.style.display = 'none';
    if (mainInterface) mainInterface.style.display = 'block';
    
    // 隐藏自动收集提示，实现静默收集
    if (autoCollectHint) autoCollectHint.style.display = 'none';
    
    // 显示步骤2，让用户可以看到更新/上传按钮，同时后台收集文件
    updateStepButtons(2);
    
    // 确保文件收集的UI元素保持隐藏
    const fileCollectionDiv = document.getElementById('fileCollection');
    if (fileCollectionDiv) {
        fileCollectionDiv.style.display = 'none';
    }
    
    // 检查登录状态后再加载项目列表
    console.log('🔍 在showMainInterface中检查登录状态');
    const isLoggedIn = await checkLoginStatus();
    
    if (isLoggedIn) {
        console.log('✅ 已登录，开始加载项目列表');
        loadProjectList(null, 'showMainInterface');
    } else {
        console.log('❌ 未登录，显示登录表单');
        showLoginForm();
    }
    
    
    
    // 调用handleProjectOperationChange确保按钮正确显示
    handleProjectOperationChange();
}

// 加载项目列表 - 修复版：改进错误处理和用户体验
async function loadProjectList(callback, caller = 'unknown') {
    console.log('📋 加载项目列表（增强调试版） - 调用者:', caller);
    
    // 首先检查登录状态 - 严格验证，确保未登录时不执行任何网络请求
    console.log('🔍 检查登录状态');
    const isLoggedIn = await checkLoginStatus();
    
    // 如果未登录，显示登录表单并返回，不执行任何后续操作
    if (!isLoggedIn) {
        console.log('⚠️ 未登录，显示登录表单并终止加载');
        
        // 显示登录表单
        showLoginForm();
        
        // 不添加任何监听器，让用户通过登录按钮登录
        return;
    }
    
    // 已登录，继续获取项目列表
    console.log('✅ 已登录，开始获取项目列表');
    
    const projectSelect = document.getElementById('projectSelect');
    const errorIndicator = document.getElementById('projectListError');
    const noteIndicator = document.getElementById('projectListNote');
    
    // 隐藏错误和提示信息
    errorIndicator.style.display = 'none';
    noteIndicator.style.display = 'none';
    
    // 移除事件监听器，防止innerHTML重置时触发
    projectSelect.removeEventListener('change', handleProjectSelect);
    
    console.log('📤 发送获取项目列表请求到后台脚本');
    
    // 检查扩展上下文是否有效
    if (!chrome.runtime || !chrome.runtime.sendMessage) {
        console.error('❌ 扩展上下文失效，无法发送消息');
        errorIndicator.textContent = '无法连接到扩展，请刷新页面重试';
        errorIndicator.style.display = 'block';
        noteIndicator.style.display = 'none';
        
        // 重新添加事件监听器
        projectSelect.addEventListener('change', handleProjectSelect);
        
        // 调用回调函数
        if (typeof callback === 'function') {
            callback();
        }
        return;
    }
    
    // 尝试发送消息并处理可能的错误
    try {
        chrome.runtime.sendMessage({ action: 'getProjectList' }, (response) => {
            // 检查是否有错误发生
            if (chrome.runtime.lastError) {
                console.error('❌ 获取项目列表时发生错误:', chrome.runtime.lastError);
                errorIndicator.textContent = '无法连接到扩展，请刷新页面重试';
                errorIndicator.style.display = 'block';
                noteIndicator.style.display = 'none';
                return;
            }
            
            console.log('📥 收到项目列表响应:', JSON.stringify(response, null, 2));
        
        if (response && response.success) {
            projectSelect.innerHTML = '<option value="">请选择项目...</option>';
            
            // 验证projects是否为数组
            const projects = Array.isArray(response.projects) ? response.projects : [];
            
            console.log('🔍 项目列表数据:', JSON.stringify(projects, null, 2));
            console.log('📊 项目数量:', projects.length);
            
            if (projects.length > 0) {
                // 添加已有项目
                console.log('🔧 开始填充项目列表');
                
                projects.forEach((project, index) => {
                    console.log(`📝 添加项目 ${index + 1}:`, project);
                    
                    const option = document.createElement('option');
                    option.value = project.random_code || '';
                    if (project.id) {
                        option.dataset.id = project.id;
                        console.log(`🔑 项目ID: ${project.id}`);
                    }
                    
                    option.textContent = project.project_name || `项目${index + 1}`;
                    
                    if (project.create_time) {
                        const createDate = new Date(project.create_time);
                        option.title = `创建时间: ${createDate.toLocaleString()}\n随机码: ${project.random_code || '未知'}\nID: ${project.id || '未知'}`;
                    }
                    
                    projectSelect.appendChild(option);
                });
                
                // 默认选中最新项目
                if (projectSelect.options.length > 1) {
                    projectSelect.selectedIndex = 1;
                    const selectedOption = projectSelect.options[1];
                    currentProjectId = selectedOption.dataset.id || selectedOption.value;
                    currentProjectName = selectedOption.text;
                    console.log('🎯 默认选择项目:', currentProjectName, 'ID:', currentProjectId);
                }
                



                
            } else {
                console.warn('⚠️ 项目列表为空');
                noteIndicator.textContent = '暂无项目数据';
                noteIndicator.style.display = 'block';
                noteIndicator.className = 'axure-message info';
                currentProjectId = '';
                currentProjectName = '';
            }
            
        } else {
            console.error('❌ 获取项目列表失败:', response ? response.error : '未知错误');
            
            // 显示具体的错误信息，而不是直接跳转到登录页面
            let errorMessage = response ? response.error || '获取项目列表失败' : '获取项目列表失败';
            console.log('⚠️ 获取列表失败原因:', errorMessage);
            
            // 显示调用者和配置信息以方便定位原因
            const callerInfo = `\n调用者: ${caller}`;
            errorMessage += callerInfo;
            
            if (response && response.config) {
                console.log('🔧 使用的配置信息:', JSON.stringify(response.config, null, 2));
                const configInfo = `\n配置信息: API地址=${response.config.apiUrl}, 超时时间=${response.config.timeout}ms`;
                errorMessage += configInfo;
            }
            
            // 显示错误信息
            errorIndicator.textContent = errorMessage;
            errorIndicator.style.display = 'block';
            noteIndicator.style.display = 'none';
            
            // 重置当前项目选择
            currentProjectId = '';
            currentProjectName = '';
        }
        
        // 重新添加事件监听器
        projectSelect.addEventListener('change', handleProjectSelect);
        
        // 调用回调函数
        if (typeof callback === 'function') {
            callback();
        }
    });
    } catch (error) {
        console.error('❌ 发送项目列表请求时出错:', error);
        errorIndicator.textContent = '获取项目列表失败，请检查网络连接';
        errorIndicator.style.display = 'block';
        noteIndicator.style.display = 'none';
        
        // 重新添加事件监听器
        projectSelect.addEventListener('change', handleProjectSelect);
        
        // 调用回调函数
        if (typeof callback === 'function') {
            callback();
        }
    }
}

// 更新步骤按钮
function updateStepButtons(step) {
    console.log('🔄 更新步骤按钮，当前步骤:', step);
    
    // 隐藏所有按钮，但保持取消按钮在步骤1和步骤2中可见
    const buttons = ['nextButton', 'uploadButton', 'updateButton', 'finishButton'];
    buttons.forEach(id => {
        document.getElementById(id).style.display = 'none';
    });
    
    // 更新步骤指示器
    for (let i = 1; i <= 3; i++) {
        const stepElement = document.getElementById(`step${i}`);
        stepElement.className = 'axure-step';
        
        if (i < step) {
            stepElement.className = 'axure-step completed';
        } else if (i === step) {
            stepElement.className = 'axure-step active';
        }
    }
    
    // 根据当前步骤显示相应按钮
    switch (step) {
        case 1:
            document.getElementById('nextButton').style.display = 'inline-block';
            document.getElementById('cancelButton').style.display = 'inline-block';
            break;
            
        case 2:
            // 第二步是自动收集，同时显示更新/上传按钮
            document.getElementById('cancelButton').style.display = 'inline-block';
            
            // 根据当前操作类型显示相应按钮
            const updateRadio = document.getElementById('updateProject');
            const newRadio = document.getElementById('newProject');
            
            // 确保按钮始终显示，无论单选按钮状态如何
            if (updateRadio && updateRadio.checked) {
                document.getElementById('updateButton').style.display = 'inline-block';
            } else if (newRadio && newRadio.checked) {
                document.getElementById('uploadButton').style.display = 'inline-block';
            } else {
                // 如果单选按钮状态异常，默认显示更新按钮
                console.warn('⚠️ 单选按钮状态异常，默认显示更新按钮');
                document.getElementById('updateButton').style.display = 'inline-block';
            }
            break;
            
        case 3:
            // 第三步（上传阶段）隐藏所有按钮，包括取消按钮
            document.getElementById('cancelButton').style.display = 'none';
            break;
            
        case 4:
            // 上传完成/更新完成时不显示完成按钮
            break;
    }
}

// 添加事件监听器
function addEventListeners() {
    console.log('🔧 添加事件监听器');
    
    // 登录按钮
    document.getElementById('loginButton').removeEventListener('click', handleLogin);
    document.getElementById('loginButton').addEventListener('click', handleLogin);
    
    // 项目选择变化
    document.getElementById('projectSelect').removeEventListener('change', handleProjectSelect);
    document.getElementById('projectSelect').addEventListener('change', handleProjectSelect);
    
    // 刷新项目列表按钮
    const refreshButtonHandler = () => loadProjectList(null, 'refreshButton');
    document.getElementById('refreshProjectList').removeEventListener('click', refreshButtonHandler);
    document.getElementById('refreshProjectList').addEventListener('click', refreshButtonHandler);
    
    // 单选按钮事件监听
    document.getElementById('updateProject').removeEventListener('change', handleProjectOperationChange);
    document.getElementById('updateProject').addEventListener('change', handleProjectOperationChange);
    document.getElementById('newProject').removeEventListener('change', handleProjectOperationChange);
    document.getElementById('newProject').addEventListener('change', handleProjectOperationChange);
    
    // 下一步按钮
    document.getElementById('nextButton').removeEventListener('click', handleNext);
    document.getElementById('nextButton').addEventListener('click', handleNext);
    
    // 上传按钮
    document.getElementById('uploadButton').removeEventListener('click', handleUpload);
    document.getElementById('uploadButton').addEventListener('click', handleUpload);
    
    // 更新按钮
    document.getElementById('updateButton').removeEventListener('click', handleUpdate);
    document.getElementById('updateButton').addEventListener('click', handleUpdate);
    
    // 完成按钮
    document.getElementById('finishButton').removeEventListener('click', handleFinish);
    document.getElementById('finishButton').addEventListener('click', handleFinish);
    
    // 退出登录按钮
    document.getElementById('logoutButton').removeEventListener('click', handleLogout);
    document.getElementById('logoutButton').addEventListener('click', handleLogout);
    
    // 取消按钮
    document.getElementById('cancelButton').removeEventListener('click', handleCancel);
    document.getElementById('cancelButton').addEventListener('click', handleCancel);
    
    // 复制链接按钮
    document.getElementById('copyLinkButton').removeEventListener('click', handleCopyLink);
    document.getElementById('copyLinkButton').addEventListener('click', handleCopyLink);
        
    // 关闭按钮
    document.getElementById('closeButton').removeEventListener('click', handleClose);
    document.getElementById('closeButton').addEventListener('click', handleClose);
    }

// 上传进度模拟定时器
let uploadProgressTimer = null;
let currentProgress = 0;
let totalFilesToUpload = 0;

// 开始模拟上传进度更新
function startUploadProgressSimulation(totalFiles) {
    // 清除之前的定时器
    if (uploadProgressTimer) {
        clearInterval(uploadProgressTimer);
    }
    
    // 重置进度
    currentProgress = 0;
    totalFilesToUpload = totalFiles;
    
    // 更新初始进度
    updateUploadProgressUI(0, 0, totalFiles);
    
    // 每500ms更新一次进度，直到90%（上传完成后会设置为100%）
    uploadProgressTimer = setInterval(() => {
        if (currentProgress < 90) {
            // 随机增加1-5%的进度
            currentProgress += Math.floor(Math.random() * 5) + 1;
            if (currentProgress > 90) {
                currentProgress = 90;
            }
            
            // 计算当前上传的文件数量（模拟）
            const uploadedFiles = Math.floor((currentProgress / 100) * totalFilesToUpload);
            
            // 更新进度UI
            updateUploadProgressUI(currentProgress, uploadedFiles, totalFilesToUpload);
        }
    }, 500);
}

// 停止模拟上传进度更新
function stopUploadProgressSimulation() {
    if (uploadProgressTimer) {
        clearInterval(uploadProgressTimer);
        uploadProgressTimer = null;
    }
}

// 更新上传进度UI
function updateUploadProgressUI(progress, uploadedFiles, totalFiles) {
    const progressBar = document.querySelector('.axure-progress-fill');
    const progressText = document.querySelector('.axure-progress-text');
    const uploadStatus = document.getElementById('uploadStatus');
    
    if (progressBar) {
        progressBar.style.width = progress + '%';
    }
    
    if (progressText) {
        progressText.innerHTML = `<span>${progress}% 完成</span><span>${uploadedFiles}/${totalFiles} 文件</span>`;
    }
    
    if (uploadStatus) {
        uploadStatus.textContent = `正在上传 ${uploadedFiles}/${totalFiles} 文件...`;
    }
}

// 监听来自后台的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('📥 收到后台消息:', message.action);
    
    if (message.action === 'loginSuccess') {
        console.log('✅ 登录成功');
        document.getElementById('loginPassword').value = '';
        showMainInterface();
    } else if (message.action === 'loginError') {

        document.getElementById('loginError').textContent = message.error;
        document.getElementById('loginError').style.display = 'block';
    } else if (message.action === 'uploadProgress') {
        // 更新上传进度UI
        console.log('📊 上传进度更新:', message.progress);
        updateUploadProgressUI(message.progress, message.uploadedFiles, message.totalFiles);
    } else if (message.action === 'loginExpired') {
        // 处理登录过期
        console.log('🔐 登录已过期');
        showLoginForm();
        
        // 显示登录过期提示
        const errorElement = document.getElementById('loginError');
        if (errorElement) {
            errorElement.textContent = '登录已过期，请重新登录';
            errorElement.style.display = 'block';
        }
    }
});

// 处理登录
function handleLogin() {
    console.log('🔐 处理登录');
    
    const phone = document.getElementById('loginPhone').value.trim();
    const password = document.getElementById('loginPassword').value.trim();
    const errorElement = document.getElementById('loginError');
    const noteElement = document.getElementById('loginNote');
    
    if (!phone) {
        errorElement.textContent = '请输入手机号';
        errorElement.style.display = 'block';
        noteElement.style.display = 'none';
        return;
    }
    
    if (!password) {
        errorElement.textContent = '请输入密码';
        errorElement.style.display = 'block';
        noteElement.style.display = 'none';
        return;
    }
    
    errorElement.style.display = 'none';
    noteElement.style.display = 'none';
    
    try {
        chrome.runtime.sendMessage({ action: 'login', phone: phone, password: password }, (response) => {
            // 检查扩展上下文错误
            if (chrome.runtime.lastError) {
                console.error('❌ 登录时发生错误:', chrome.runtime.lastError);
                errorElement.textContent = '无法连接到扩展，请刷新页面重试';
                errorElement.style.display = 'block';
                return;
            }
            
            if (response && response.success) {
                showMainInterface();
                
                // 显示登录提示
                if (response.note) {
                    noteElement.textContent = response.note;
                    noteElement.style.display = 'block';
                    setTimeout(() => {
                        noteElement.style.display = 'none';
                    }, 5000);
                }
                
                // 发送登录成功消息，用于处理上传流程的恢复
                try {
                    chrome.runtime.sendMessage({ action: 'loginSuccess' });
                } catch (error) {
                    console.error('❌ 发送登录成功消息时发生错误:', error);
                }
                
            } else {
                let errorMessage = response ? response.error : '登录失败';
                let helpMessage = '';
                
                // 提供更友好的错误提示
                if (errorMessage.includes('无法获取配置信息') || errorMessage.includes('网络') || errorMessage.includes('连接')) {
                    helpMessage = '\n💡 提示：请检查网络连接';
                } else if (errorMessage.includes('密码错误')) {
                    helpMessage = '';
                }
                
                errorElement.textContent = errorMessage + helpMessage;
                errorElement.style.display = 'block';
            }
        });
    } catch (error) {
        console.error('❌ 发送登录请求时发生异常:', error);
        errorElement.textContent = '无法连接到扩展，请刷新页面重试';
        errorElement.style.display = 'block';
    }
}

// 处理项目操作类型切换
function handleProjectOperationChange() {
    console.log('🔄 处理项目操作类型切换');
    
    const updateProjectRadio = document.getElementById('updateProject');
    const projectListContainer = document.getElementById('projectListContainer');
    const newProjectForm = document.getElementById('newProjectForm');
    const updateButton = document.getElementById('updateButton');
    const uploadButton = document.getElementById('uploadButton');
    
    if (updateProjectRadio.checked) {
        // 选择更新项目
        projectListContainer.style.display = 'block';
        newProjectForm.style.display = 'none';
        // 加载项目列表前先检查登录状态
        (async () => {
            const isLoggedIn = await checkLoginStatus();
            
            if (isLoggedIn) {
                // 已登录，加载项目列表
                loadProjectList(null, 'handleProjectOperationChange');
            } else {
                // 未登录，显示登录表单
                showLoginForm();
            }
        })();
        // 将按钮文本改为"更新"
        if (updateButton) {
            updateButton.textContent = "更新";
        }
        // 根据文件收集状态决定是否显示按钮
        if (isCollecting) {
            // 文件收集过程中隐藏所有按钮
            if (uploadButton) {
                uploadButton.style.display = 'none';
            }
            if (updateButton) {
                updateButton.style.display = 'none';
            }
        } else {
            // 文件收集前显示更新按钮，隐藏上传按钮
            if (uploadButton) {
                uploadButton.style.display = 'none';
            }
            if (updateButton) {
                updateButton.style.display = 'inline-block';
            }
        }
    } else {
        // 选择新建项目
        projectListContainer.style.display = 'none';
        newProjectForm.style.display = 'block';
        currentProjectId = '';
        currentProjectName = '';
        // 将按钮文本改为"提交"
        if (updateButton) {
            updateButton.textContent = "提交";
        }
        // 根据文件收集状态决定是否显示按钮
        if (isCollecting) {
            // 文件收集过程中隐藏所有按钮
            if (updateButton) {
                updateButton.style.display = 'none';
            }
            if (uploadButton) {
                uploadButton.style.display = 'none';
            }
        } else {
            // 文件收集前显示上传按钮，隐藏更新按钮
            if (updateButton) {
                updateButton.style.display = 'none';
            }
            if (uploadButton) {
                uploadButton.style.display = 'inline-block';
            }
        }
    }
}

// 处理项目选择
function handleProjectSelect() {
    console.log('📋 处理项目选择');
    
    const projectSelect = document.getElementById('projectSelect');
    const selectedOption = projectSelect.options[projectSelect.selectedIndex];
    
    // 获取项目ID（优先从dataset.id获取，其次使用value）
    currentProjectId = selectedOption.dataset.id || selectedOption.value;
    
    if (currentProjectId) {
        // 已有项目
        currentProjectName = selectedOption.text;
        console.log('🎯 选择项目:', currentProjectName, 'ID:', currentProjectId, 'Random Code:', selectedOption.value);
    } else {
        // 未选择
        currentProjectName = '';
        currentProjectId = '';
        console.log('❌ 未选择项目');
    }
}

// 处理下一步
function handleNext() {
    console.log('➡️ 处理下一步');
    
    const updateProjectRadio = document.getElementById('updateProject');
    const projectSelect = document.getElementById('projectSelect');
    const newProjectName = document.getElementById('newProjectName').value.trim();
    
    // 根据选择的操作类型进行验证
    if (updateProjectRadio.checked) {
        // 更新项目：检查是否选择了有效的项目
        if (!currentProjectId || currentProjectId === '') {
            // 显示内联错误提示
            const projectSelectError = document.createElement('div');
            projectSelectError.id = 'projectSelectError';
            projectSelectError.textContent = '请选择要更新的项目';
            projectSelectError.style.color = 'red';
            projectSelectError.style.fontSize = '12px';
            projectSelectError.style.marginTop = '5px';
            
            const existingError = document.getElementById('projectSelectError');
            if (existingError) {
                existingError.remove();
            }
            projectSelect.parentNode.appendChild(projectSelectError);
            return;
        }
    } else {
        // 新建项目：检查是否输入了项目名称
        if (!newProjectName) {
            // 显示内联错误提示
            const errorElement = document.getElementById('projectNameError');
            errorElement.textContent = '请输入项目名称';
            errorElement.style.display = 'block';
            return;
        } else {
            // 清除可能存在的错误提示
            const errorElement = document.getElementById('projectNameError');
            errorElement.style.display = 'none';
        }
        
        // 更新全局变量
        currentProjectId = '';
        currentProjectName = newProjectName;
    }
    
    // 隐藏自动收集提示，实现静默收集
    document.getElementById('autoCollectHint').style.display = 'none';
    
    // 更新步骤
    updateStepButtons(2);
    
    // 自动开始收集文件
    setTimeout(() => {
        autoCollectFiles();
    }, 1000);
}

// 自动收集文件 - 新增功能
async function autoCollectFiles(showUI = true) {
    console.log('🔍 自动开始收集文件...');
    
    // 只有在需要显示UI时才获取UI元素
    const fileTree = showUI ? document.getElementById('fileTree') : null;
    const progress = showUI ? document.getElementById('collectionProgress') : null;
    const statsElement = showUI ? document.getElementById('collectionStats') : null;
    const statusElement = showUI ? document.getElementById('collectionStatus') : null;
    
    // 只有在需要显示UI时才更新UI
    if (showUI) {
        fileTree.innerHTML = '<div class="axure-status-info">正在初始化自动收集...</div>';
        progress.textContent = '进度: 0%';
        statsElement.textContent = '文件: 0 | 大小: 0 KB';
        statusElement.textContent = '初始化中...';
    }
    
    // 重置收集状态，但保留项目选择
    collectedFiles = [];
    collectedUrls = new Set();
    extractedHtmlFiles = [];
    isCollecting = true;
    
    // 更新按钮显示状态：文件收集开始，隐藏上传/更新按钮
    handleProjectOperationChange();
    
    // 创建收集Promise
    fileCollectionPromise = new Promise(async (resolve, reject) => {
    
    // 更新统计信息
    function updateCollectionStats() {
        if (showUI) {
            const fileCount = collectedFiles.length;
            const totalSize = collectedFiles.reduce((sum, file) => sum + file.size, 0);
            const sizeKB = (totalSize / 1024).toFixed(2);
            
            statsElement.textContent = `文件: ${fileCount} | 大小: ${sizeKB} KB`;
        }
    }
    
    try {
        // 第一阶段：收集已渲染的HTML及引用的所有文件
        if (showUI) {
            fileTree.innerHTML = '<div class="axure-status-info">第一阶段：收集已渲染的HTML及引用的所有文件...</div>';
            progress.textContent = '进度: 10%';
            statusElement.textContent = '收集已渲染内容';
        }
        
        // 收集当前页面HTML
        await collectCurrentPage();
        
        // 收集主页面资源（CSS、JS、图片等）
        await collectMainPageResources();
        
        // 收集iframe中的资源
        await collectIframeResources();
        
        // 显示当前收集的文件树
        if (showUI) {
            showFileTree();
            updateCollectionStats();
        }
        
        // 第二阶段：读取document.js中的文件及固定文件
        if (showUI) {
            fileTree.innerHTML = '<div class="axure-status-info">第二阶段：读取document.js中的文件及固定文件...</div>';
            progress.textContent = '进度: 40%';
            statusElement.textContent = '处理配置文件';
        }
        
        // 从document.js提取HTML文件
        await extractHtmlFromDocumentJs();
        
        // 收集特定URL文件
        await collectSpecificUrls();
        
        // 显示更新后的文件树
        if (showUI) {
            showFileTree();
            updateCollectionStats();
        }
        
        // 第三阶段：递归读取所有已收集文件引用的文件
        if (showUI) {
            fileTree.innerHTML = '<div class="axure-status-info">第三阶段：递归读取所有已收集文件引用的文件...</div>';
            progress.textContent = '进度: 70%';
            statusElement.textContent = '递归收集依赖';
        }
        
        // 递归收集所有文件引用的资源
        await recursivelyCollectDependencies(showUI);
        
        // 显示最终文件树
        if (showUI) {
            showFileTree();
            updateCollectionStats();
            
            // 收集完成
            fileTree.innerHTML = '<div class="axure-status-success">✅ 自动收集完成！</div>';
            progress.textContent = '进度: 100% - 收集完成';
            statusElement.textContent = '收集完成';
        }
        
        // 隐藏自动收集提示
        document.getElementById('autoCollectHint').style.display = 'none';
        
        // 更新步骤到第三阶段（只在后台收集时更新，避免与初始UI冲突）
        if (!showUI) {
            updateStepButtons(3);
        }
        
    } catch (error) {

        if (showUI) {
            fileTree.innerHTML = `<div class="axure-status-error">❌ 收集过程出错: ${error.message}</div>`;
            statusElement.textContent = '收集失败';
        }
    } finally {
            isCollecting = false;
            
            // 不再自动触发上传，让用户手动点击按钮触发
            // 保持上传进度模拟，提供更好的用户体验
            if (collectedFiles.length > 0) {
                // 开始上传进度模拟
                startUploadProgressSimulation(collectedFiles.length);
                console.log('✅ 文件收集完成，等待用户手动触发上传/更新');
            }
            
            resolve(collectedFiles);
            fileCollectionPromise = null;
            
            // 不再自动显示上传/更新按钮，仅在需要时手动控制
        }
    });
    
    return fileCollectionPromise;
}

// 递归收集所有文件的依赖
async function recursivelyCollectDependencies(showUI = true) {
    console.log('🔄 递归收集文件依赖...');
    
    let filesToProcess = [...collectedFiles];
    let processedCount = 0;
    const totalFiles = filesToProcess.length;
    
    while (filesToProcess.length > 0 && processedCount < 1000) { // 防止无限循环
        const file = filesToProcess.shift();
        processedCount++;
        
        try {
            // 更新进度（仅在需要显示UI时）
            if (showUI) {
                const progress = Math.min(70 + (processedCount / totalFiles) * 25, 95);
                const progressElement = document.getElementById('collectionProgress');
                if (progressElement) {
                    progressElement.textContent = `进度: ${progress.toFixed(0)}%`;
                }
            }
            
            // 根据文件类型处理
            if (file.name.endsWith('.html') || file.name.endsWith('.htm')) {
                // 处理HTML文件中的资源引用
                await processHtmlDependencies(file);
                
            } else if (file.name.endsWith('.css')) {
                // 处理CSS文件中的资源引用
                await processCssDependencies(file);
                
            } else if (file.name.endsWith('.js')) {
                // 处理JS文件中的资源引用（简单处理）
                await processJsDependencies(file);
            }
            
        } catch (error) {
            // 简单忽略错误，继续处理其他文件
        }
    }
    
    console.log('✅ 递归收集依赖完成，处理了', processedCount, '个文件');
}

// 处理HTML文件中的依赖
async function processHtmlDependencies(htmlFile) {
    console.log('🔍 处理HTML文件依赖:', htmlFile.path);
    
    try {
        // 创建临时DOM解析HTML
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlFile.content, 'text/html');
        
        // 使用文件自身的URL作为baseURL，如果没有则使用window.location.href
        const baseUrl = htmlFile.url || window.location.href;
        
        // 收集CSS链接
        const cssLinks = doc.querySelectorAll('link[rel="stylesheet"]');
        for (const link of cssLinks) {
            const href = link.getAttribute('href');
            if (href) {
                const absoluteUrl = new URL(href, baseUrl).href;
                if (!collectedUrls.has(absoluteUrl)) {
                    await collectResourceFile(href, 'css', baseUrl);
                } else {
                    console.log('⏭️ iframe中跳过已收集的CSS资源:', absoluteUrl, '（已收集资源总数:', collectedUrls.size, '）');
                }
            }
        }
        
        // 收集JS脚本
        const jsScripts = doc.querySelectorAll('script[src]');
        for (const script of jsScripts) {
            const src = script.getAttribute('src');
            if (src) {
                const absoluteUrl = new URL(src, baseUrl).href;
                if (!collectedUrls.has(absoluteUrl)) {
                    await collectResourceFile(src, 'js', baseUrl);
                } else {
                    console.log('⏭️ iframe中跳过已收集的JS资源:', absoluteUrl, '（已收集资源总数:', collectedUrls.size, '）');
                }
            }
        }
        
        // 收集图片
        const images = doc.querySelectorAll('img[src]');
        for (const img of images) {
            const src = img.getAttribute('src');
            if (src) {
                const absoluteUrl = new URL(src, baseUrl).href;
                if (!collectedUrls.has(absoluteUrl)) {
                    await collectResourceFile(src, 'image', baseUrl);
                } else {
                    console.log('⏭️ iframe中跳过已收集的图片资源:', absoluteUrl, '（已收集资源总数:', collectedUrls.size, '）');
                }
            }
        }
        
        // 收集favicon
        const favicons = doc.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]');
        for (const favicon of favicons) {
            const href = favicon.getAttribute('href');
            if (href) {
                const absoluteUrl = new URL(href, baseUrl).href;
                if (!collectedUrls.has(absoluteUrl)) {
                    await collectResourceFile(href, 'image', baseUrl);
                } else {
                    console.log('⏭️ iframe中跳过已收集的favicon资源:', absoluteUrl, '（已收集资源总数:', collectedUrls.size, '）');
                }
            }
        }
        
        // 收集iframe
        const iframes = doc.querySelectorAll('iframe[src]');
        for (const iframe of iframes) {
            const src = iframe.getAttribute('src');
            if (src) {
                const absoluteUrl = new URL(src, baseUrl).href;
                if (!collectedUrls.has(absoluteUrl)) {
                    // 对于iframe，我们只收集HTML文件
                    try {
                        // 跳过about:blank的iframe，避免fetch错误
                        if (absoluteUrl.startsWith('about:')) {
                            continue;
                        }
                        
                        // 使用no-cache确保每次都获取最新资源
                        // 添加更严格的缓存控制头，确保完全避免缓存问题
                        const response = await fetch(absoluteUrl, {
                            cache: 'no-cache',
                            headers: {
                                'Cache-Control': 'no-cache, no-store, must-revalidate',
                                'Pragma': 'no-cache',
                                'Expires': '0'
                            }
                        });
                        const html = await response.text();
                        
                        // 解析URL获取路径信息
                        const parsedUrl = new URL(absoluteUrl);
                        const pathParts = decodeURIComponent(parsedUrl.pathname).split('/');
                        const fileName = pathParts.pop() || 'iframe.html';
                        const folderPath = pathParts.join('/').replace(/^\//, '');
                        
                        // 添加到收集的文件
                        addFile(folderPath, fileName, html, false, absoluteUrl);
                        
                        // 标记为已收集
                        collectedUrls.add(absoluteUrl);
                        
                    } catch (error) {

                    }
                }
            }
        }
        
    } catch (error) {
        console.log('❌ 收集资源时出错:', absoluteUrl, '错误:', error.message);
        collectedUrls.delete(absoluteUrl); // 从已收集列表中移除
    }
}

// 处理CSS文件中的依赖
async function processCssDependencies(cssFile) {
    console.log('🔍 处理CSS文件依赖:', cssFile.path);
    
    try {
        // 提取CSS中的资源引用
        const resources = extractResourcesFromCss(cssFile.content, cssFile.path);
        
        if (resources.length > 0) {
            console.log('📋 从', cssFile.path, '中找到', resources.length, '个资源引用');
            
            for (const resource of resources) {
                try {
                    // 构建完整URL
                    const baseUrl = cssFile.url || new URL(cssFile.path, window.location.href);
                    const resourceUrl = new URL(resource.url, baseUrl).href;
                    
                    if (!collectedUrls.has(resourceUrl)) {
                        console.log('� 新资源准备收集:', resourceUrl, '（资源总数:', collectedUrls.size, '）');
                        console.log('�� 收集CSS依赖:', resourceUrl);
                        await collectResourceFile(resource.url, resource.type, baseUrl);
                    }
                    
                } catch (error) {

                }
            }
        }
        
    } catch (error) {

    }
}

// 处理JS文件中的依赖（简单处理）
async function processJsDependencies(jsFile) {
    console.log('🔍 处理JS文件依赖:', jsFile.path);
    
    try {
        // 使用文件自身的URL作为baseURL，如果没有则使用window.location.href
        const baseUrl = jsFile.url || window.location.href;
        
        // 增强：提取完整URL和相对路径的资源引用，包括图片文件
        // 更严格的匹配：只匹配出现在引号中的路径或完整URL
        const urlPattern = /https?:\/\/[^\s"'(){}]+|['"]([^\s"'(){}]+\.(?:js|json|txt|png|jpg|jpeg|gif|svg|ico|bmp))['"]/g;
        const matches = [];
        let match;
        while ((match = urlPattern.exec(jsFile.content)) !== null) {
            matches.push(match[1] || match[0]);
        }
        
        if (matches) {
            for (const url of matches) {
                try {
                    const absoluteUrl = new URL(url, baseUrl).href;
                    if (!collectedUrls.has(absoluteUrl)) {
                        // 根据文件扩展名确定资源类型
                        if (url.match(/\.(js|json|txt)$/i)) {
                            await collectResourceFile(url, 'js', baseUrl);
                        } else if (url.match(/\.(png|jpg|jpeg|gif|svg|ico|bmp)$/i)) {
                            await collectResourceFile(url, 'image', baseUrl);
                        }
                    }
                } catch (error) {
                    // 忽略无效URL
                }
            }
        }
        
        // 增强：专门处理Axure data目录下的核心JS文件引用
        if (jsFile.path.includes('data/')) {
            const dataFilePattern = /"([^"]+\.(js|json|png|jpg|jpeg|gif|svg|ico|bmp))"|'([^']+\.(js|json|png|jpg|jpeg|gif|svg|ico|bmp))'/g;
            let match;
            while ((match = dataFilePattern.exec(jsFile.content)) !== null) {
                const relativePath = match[1] || match[3];
                if (relativePath) {
                    try {
                        const absoluteUrl = new URL(relativePath, baseUrl).href;
                        if (!collectedUrls.has(absoluteUrl)) {
                            // 根据文件扩展名确定资源类型
                            if (relativePath.match(/\.(js|json)$/i)) {
                                await collectResourceFile(relativePath, 'js', baseUrl);
                            } else if (relativePath.match(/\.(png|jpg|jpeg|gif|svg|ico|bmp)$/i)) {
                                await collectResourceFile(relativePath, 'image', baseUrl);
                            }
                        }
                    } catch (error) {
                        // 忽略无效路径
                    }
                }
            }
        }
        
    } catch (error) {

    }
}

// 处理上传
async function handleUpload() {
    console.log('🚀 处理上传');
    
    // 首先检查登录状态
    const isLoggedIn = await checkLoginStatus();
    
    // 如果未登录，显示登录表单并等待登录完成
    if (!isLoggedIn) {
        // 保存当前状态，用于登录后恢复
        const originalUploadButton = document.getElementById('uploadButton');
        const originalUpdateButton = document.getElementById('updateButton');
        const originalCancelButton = document.getElementById('cancelButton');
        
        // 显示登录表单
        showLoginForm();
        
        // 添加一次性登录成功监听器
        const loginSuccessListener = (message) => {
            if (message.action === 'loginSuccess') {
                // 登录成功后移除监听器
                chrome.runtime.onMessage.removeListener(loginSuccessListener);
                
                // 显示主界面
                showMainInterface();
                
                // 重新调用上传函数
                handleUpload();
            }
        };
        
        chrome.runtime.onMessage.addListener(loginSuccessListener);
        
        return;
    }
    
    // 获取按钮元素
    const uploadButton = document.getElementById('uploadButton');
    const updateButton = document.getElementById('updateButton');
    const cancelButton = document.getElementById('cancelButton');
    
    // 隐藏上传、更新和取消按钮
    uploadButton.style.display = 'none';
    updateButton.style.display = 'none';
    cancelButton.style.display = 'none';
    
    try {
        // 显示上传进度
        document.getElementById('uploadProgress').style.display = 'block';
        document.getElementById('uploadStatus').textContent = '正在后台收集文件...';
    
    // 首先确保获取最新的项目信息
    let projectName = currentProjectName;
    
    // 如果是新建项目，直接从输入框获取名称
    const updateProjectRadio = document.getElementById('updateProject');
    if (!updateProjectRadio.checked) {
        const inputProjectName = document.getElementById('newProjectName').value.trim();
        if (!inputProjectName) {
            // 显示内联错误提示
            const errorElement = document.getElementById('projectNameError');
            errorElement.textContent = '请输入项目名称';
            errorElement.style.display = 'block';
            
            // 恢复按钮显示
            uploadButton.style.display = 'inline-block';
            cancelButton.style.display = 'inline-block';
            
            // 隐藏上传进度
            document.getElementById('uploadProgress').style.display = 'none';
            return;
        } else {
            // 清除可能存在的错误提示
            const errorElement = document.getElementById('projectNameError');
            errorElement.style.display = 'none';
        }
        projectName = inputProjectName;
        currentProjectName = projectName;
    } else {
        // 更新项目时，确保有有效的项目ID
        if (!currentProjectId || currentProjectId === 'new') {
            alert('请选择要更新的项目');
            return;
        }
    }
    
    // 如果还没开始收集，在后台开始收集（不显示UI）
    if (!isCollecting && collectedFiles.length === 0) {
        // 等待文件收集完成后再继续
        await autoCollectFiles(false);
    } else if (isCollecting && fileCollectionPromise) {
        // 如果正在收集，等待收集完成
        await fileCollectionPromise;
    }
    
    // 准备上传数据
    const uploadData = {
        projectName: projectName,
        files: collectedFiles
    };
    
    // 将chrome.runtime.sendMessage转换为Promise
    const response = await new Promise((resolve) => {
        chrome.runtime.sendMessage({ action: 'uploadProject', data: uploadData }, (response) => {
            // 停止进度模拟
            stopUploadProgressSimulation();
            resolve(response);
        });
    });
    
    // 处理响应
    if (response && response.success) {
        // 上传成功
        document.querySelector('.axure-progress-fill').style.width = '100%';
        document.querySelector('.axure-progress-text').innerHTML = '<span>100% 完成</span><span>' + collectedFiles.length + '/' + collectedFiles.length + ' 文件</span>';
        document.getElementById('uploadStatus').className = 'axure-upload-status axure-status-success';
        document.getElementById('uploadStatus').textContent = '上传成功！';
        
        // 显示分享链接，并使其可点击
        const shareUrlElement = document.getElementById('shareUrl');
        shareUrlElement.innerHTML = `<a href="${response.url}" target="_blank" style="color: #007bff; text-decoration: underline;">${response.url}</a>`;
        document.getElementById('shareLink').style.display = 'flex';
        
        // 自动在新窗口打开演示链接
        window.open(response.url, '_blank');
        
        // 更新步骤
        updateStepButtons(4);
        
    } else {
        // 上传失败
        document.getElementById('uploadStatus').className = 'axure-upload-status axure-status-error';
        document.getElementById('uploadStatus').textContent = '上传失败: ' + (response ? response.error : '未知错误');
    }
    } finally {
        // 恢复按钮的显示，根据当前操作类型决定显示哪个按钮
        const updateButton = document.getElementById('updateButton');
        const uploadButton = document.getElementById('uploadButton');
        const cancelButton = document.getElementById('cancelButton');
        const updateProjectRadio = document.getElementById('updateProject');
        
        // 根据当前选择的操作类型恢复对应按钮
        if (updateProjectRadio.checked) {
            // 更新项目时，只恢复更新按钮
            updateButton.style.display = 'inline-block';
            uploadButton.style.display = 'none';
        } else {
            // 新建项目时，只恢复上传按钮
            uploadButton.style.display = 'inline-block';
            updateButton.style.display = 'none';
        }
        cancelButton.style.display = 'inline-block';
        updateButton.disabled = false;
        uploadButton.disabled = false;
    }
}

// 处理更新或提交
async function handleUpdate() {
    console.log('🔄 处理更新/提交');
    
    // 获取按钮元素
    const updateButton = document.getElementById('updateButton');
    const uploadButton = document.getElementById('uploadButton');
    const cancelButton = document.getElementById('cancelButton');
    
    // 隐藏更新、上传和取消按钮
    updateButton.style.display = 'none';
    uploadButton.style.display = 'none';
    cancelButton.style.display = 'none';
    
    try {
        // 显示上传进度
        document.getElementById('uploadProgress').style.display = 'block';
        document.getElementById('uploadStatus').textContent = '正在后台收集文件...';
    
    // 检查选择的是更新项目还是新建项目
    const updateProjectRadio = document.getElementById('updateProject');
    let projectName = currentProjectName;
    
    // 如果还没开始收集，在后台开始收集（不显示UI）
    if (!isCollecting && collectedFiles.length === 0) {
        // 等待文件收集完成后再继续
        await autoCollectFiles(false);
    } else if (isCollecting && fileCollectionPromise) {
        // 如果正在收集，等待收集完成
        await fileCollectionPromise;
    }
    
    if (!updateProjectRadio.checked) {
        // 新建项目逻辑
        projectName = document.getElementById('newProjectName').value.trim();
        if (!projectName) {
            // 显示内联错误提示
            const errorElement = document.getElementById('projectNameError');
            errorElement.textContent = '请输入项目名称';
            errorElement.style.display = 'block';
            
            // 恢复按钮显示
            updateButton.style.display = 'none';
            uploadButton.style.display = 'inline-block';
            cancelButton.style.display = 'inline-block';
            
            // 隐藏上传进度
            document.getElementById('uploadProgress').style.display = 'none';
            return;
        } else {
            // 清除可能存在的错误提示
            const errorElement = document.getElementById('projectNameError');
            errorElement.style.display = 'none';
        }
        
        // 准备新建项目数据
        const uploadData = {
            projectName: projectName,
            files: collectedFiles
        };
        
        console.log('📋 新建项目数据:', JSON.stringify(uploadData, null, 2));
        
        // 将chrome.runtime.sendMessage转换为Promise
        const response = await new Promise((resolve) => {
            chrome.runtime.sendMessage({ action: 'uploadProject', data: uploadData }, (response) => {
                // 停止进度模拟
                stopUploadProgressSimulation();
                resolve(response);
            });
        });
        
        // 处理响应
        if (response && response.success) {
            // 新建成功
            document.querySelector('.axure-progress-fill').style.width = '100%';
            document.querySelector('.axure-progress-text').innerHTML = '<span>100% 完成</span><span>' + collectedFiles.length + '/' + collectedFiles.length + ' 文件</span>';
            document.getElementById('uploadStatus').className = 'axure-upload-status axure-status-success';
            document.getElementById('uploadStatus').textContent = '提交成功！';
            
            // 显示分享链接，并使其可点击
            const shareUrlElement = document.getElementById('shareUrl');
            shareUrlElement.innerHTML = `<a href="${response.url}" target="_blank" style="color: #007bff; text-decoration: underline;">${response.url}</a>`;
            document.getElementById('shareLink').style.display = 'flex';
            
            // 自动在新窗口打开演示链接
            window.open(response.url, '_blank');
            
            // 更新步骤
            updateStepButtons(4);
            
        } else {
            // 新建失败
            document.getElementById('uploadStatus').className = 'axure-upload-status axure-status-error';
            document.getElementById('uploadStatus').textContent = response ? response.error : '提交失败: 未知错误';
        }
    } else {
        // 更新项目逻辑
        if (!currentProjectId) {
            // 显示内联错误提示
            const projectSelectError = document.createElement('div');
            projectSelectError.id = 'projectSelectError';
            projectSelectError.textContent = '请选择要更新的项目';
            projectSelectError.style.color = 'red';
            projectSelectError.style.fontSize = '12px';
            projectSelectError.style.marginTop = '5px';
            
            const projectSelect = document.getElementById('projectSelect');
            const existingError = document.getElementById('projectSelectError');
            if (existingError) {
                existingError.remove();
            }
            projectSelect.parentNode.appendChild(projectSelectError);
            
            // 恢复按钮显示
            updateButton.style.display = 'inline-block';
            cancelButton.style.display = 'inline-block';
            
            // 隐藏上传进度
            document.getElementById('uploadProgress').style.display = 'none';
            return;
        }
        
        // 准备更新数据
        const projectSelect = document.getElementById('projectSelect');
        const selectedOption = projectSelect.options[projectSelect.selectedIndex];
        const randomCode = selectedOption.value; // 存储random_code用于构建分享链接
        
        const updateData = {
            projectId: currentProjectId,
            randomCode: randomCode,
            files: collectedFiles
        };
        
        console.log('📋 更新数据:', JSON.stringify(updateData, null, 2));
        
        // 将chrome.runtime.sendMessage转换为Promise
        const response = await new Promise((resolve) => {
            chrome.runtime.sendMessage({ action: 'updateProject', data: updateData }, (response) => {
                // 停止进度模拟
                stopUploadProgressSimulation();
                resolve(response);
            });
        });
        
        // 处理响应
        if (response && response.success) {
            // 更新成功
            document.querySelector('.axure-progress-fill').style.width = '100%';
            document.querySelector('.axure-progress-text').innerHTML = '<span>100% 完成</span><span>' + collectedFiles.length + '/' + collectedFiles.length + ' 文件</span>';
            document.getElementById('uploadStatus').className = 'axure-upload-status axure-status-success';
            document.getElementById('uploadStatus').textContent = '更新成功！';
            
            // 显示分享链接，并使其可点击
            const shareUrlElement = document.getElementById('shareUrl');
            shareUrlElement.innerHTML = `<a href="${response.url}" target="_blank" style="color: #007bff; text-decoration: underline;">${response.url}</a>`;
            document.getElementById('shareLink').style.display = 'flex';
            
            // 自动在新窗口打开演示链接
            window.open(response.url, '_blank');
            
            // 更新步骤
            updateStepButtons(4);
            
        } else {
            // 更新失败
            document.getElementById('uploadStatus').className = 'axure-upload-status axure-status-error';
            document.getElementById('uploadStatus').textContent = response ? response.error : '更新失败: 未知错误';
        }
    }
    } finally {
        // 恢复按钮的显示，根据当前操作类型决定显示哪个按钮
        const updateButton = document.getElementById('updateButton');
        const uploadButton = document.getElementById('uploadButton');
        const cancelButton = document.getElementById('cancelButton');
        const updateProjectRadio = document.getElementById('updateProject');
        
        // 根据当前选择的操作类型恢复对应按钮
        if (updateProjectRadio.checked) {
            // 更新项目时，只恢复更新按钮
            updateButton.style.display = 'inline-block';
            uploadButton.style.display = 'none';
        } else {
            // 新建项目时，只恢复上传按钮
            uploadButton.style.display = 'inline-block';
            updateButton.style.display = 'none';
        }
        cancelButton.style.display = 'inline-block';
        updateButton.disabled = false;
        uploadButton.disabled = false;
    }
}

// 重置收集变量的辅助函数
function resetCollectionVariables() {
    console.log('🔄 重置收集变量...');
    collectedFiles = [];
    collectedUrls = new Set();
    extractedHtmlFiles = [];
    currentProjectId = '';
    currentProjectName = '';
    isCollecting = false;
}

// 处理完成
function handleFinish() {
    console.log('✅ 处理完成');
    // 使用handleReset完全重置弹窗状态
    handleReset();
}

// 处理退出登录
function handleLogout() {
    console.log('🚪 处理退出登录');
    // 重置收集变量
    resetCollectionVariables();
    
    chrome.runtime.sendMessage({ action: 'logout' }, (response) => {
        if (response && response.success) {
            showLoginForm();
        }
    });
}

// 处理关闭按钮
function handleClose() {
    console.log('❌ 处理关闭按钮');
    handleReset();
}

// 处理取消
function handleCancel() {
    console.log('❌ 处理取消');
    handleReset();
}

// 重置弹窗到初始状态
function handleReset() {
    // 如果正在收集，停止收集
    if (isCollecting) {
        isCollecting = false;
    }
    // 重置收集变量
    resetCollectionVariables();
    
    // 恢复到初始界面状态
    document.getElementById('updateProject').checked = true;
    document.getElementById('newProjectForm').style.display = 'none';
    document.getElementById('projectListContainer').style.display = 'block';
    
    // 重置界面元素
    document.getElementById('autoCollectHint').style.display = 'none';
    document.getElementById('uploadProgress').style.display = 'none';
    document.getElementById('shareLink').style.display = 'none';
    
    // 显示第一步按钮
    updateStepButtons(1);
    
    // 隐藏弹窗，确保完全关闭
    const modal = document.getElementById('axureMainModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 处理复制链接
function handleCopyLink() {
    console.log('📋 处理复制链接');
    
    const url = document.getElementById('shareUrl').textContent;
    
    navigator.clipboard.writeText(url).then(() => {
        alert('链接已复制到剪贴板');
    }).catch(err => {

        alert('复制失败，请手动复制链接');
    });
}

// 从document.js提取HTML文件
async function extractHtmlFromDocumentJs() {
    try {
        console.log('🔍 从document.js提取HTML文件...');
        
        // 构建document.js的URL
        const baseUrl = new URL(window.location.href);
        const documentJsUrl = new URL('data/document.js', baseUrl).href;
        
        console.log('📌 document.js URL:', documentJsUrl);
        
        // 获取document.js内容
        // 使用no-cache选项，确保每次都获取最新资源，避免缓存导致的跨项目资源收集问题
        // 添加更严格的缓存控制头，确保完全避免缓存问题
        const response = await fetch(documentJsUrl, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            }
        });
        const jsContent = await response.text();
        
        console.log('✅ document.js获取成功，大小:', jsContent.length, '字节');
        
        // 提取HTML文件 - 匹配格式：="选择生成方式.html" 或 ="选择生成方式.html?id=1"
        const regex = /=\s*['"]([^'"]+\.html(\?[^'"]*)?)['"]/g;
        const matches = [];
        let match;
        
        while ((match = regex.exec(jsContent)) !== null) {
            const fileName = match[1];
            matches.push(fileName);
            console.log('✅ 找到HTML文件:', fileName);
        }
        
        console.log('📋 从document.js提取到', matches.length, '个HTML文件');
        
        // 去重处理
        const uniqueFiles = [...new Set(matches)];
        console.log('📋 去重后HTML文件数:', uniqueFiles.length);
        
        // 收集这些HTML文件
        for (const fileName of uniqueFiles) {
            try {
                const htmlUrl = new URL(fileName, baseUrl).href;
                
                // 项目隔离检查：确保资源与当前页面属于同一个项目（相同端口）
                const currentUrl = new URL(window.location.href);
                const resourceUrl = new URL(htmlUrl);
                
                if (!isSameProject(currentUrl, resourceUrl)) {
                    console.log('❌ 跳过跨项目资源（不同端口）:', htmlUrl);
                    continue;
                } else {
                    console.log('✅ 同一项目资源（相同端口）:', htmlUrl);
                }
                
                console.log('🔍 收集HTML文件:', htmlUrl);
                
                // 使用no-cache选项，确保每次都获取最新资源，避免缓存导致的跨项目资源收集问题
                // 添加更严格的缓存控制头，确保完全避免缓存问题
                const response = await fetch(htmlUrl, {
                    cache: 'no-cache',
                    headers: {
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    }
                });
                
                // 检查文件是否存在（状态码不是2xx）
                if (!response.ok) {
                    console.log('❌ 跳过不存在的HTML文件:', fileName, '（状态码:', response.status, '）');
                    continue;
                }
                
                const html = await response.text();
                
                // 解析URL获取路径信息
                const parsedUrl = new URL(htmlUrl);
                const pathParts = decodeURIComponent(parsedUrl.pathname).split('/');
                const actualFileName = pathParts.pop() || fileName;
                const folderPath = pathParts.join('/').replace(/^\//, '');
                
                // 添加到收集的文件，并保存完整URL
                addFile(folderPath, actualFileName, html, false, htmlUrl);
                extractedHtmlFiles.push(fileName);
                
            } catch (error) {

            }
        }
        
        console.log('✅ 从document.js提取HTML文件完成');
        
    } catch (error) {
        console.warn('⚠️ document.js分析失败:', error.message);
        // 不抛出错误，继续收集其他文件
    }
}

// 收集当前页面
async function collectCurrentPage() {
    try {
        console.log('📄 收集当前页面:', window.location.href);
        
        // 使用no-cache选项，确保每次都获取最新资源，避免缓存导致的跨项目资源收集问题
        // 添加更严格的缓存控制头，确保完全避免缓存问题
        const response = await fetch(window.location.href, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            }
        });
        const html = await response.text();
        
        // 解析URL获取路径信息
        const parsedUrl = new URL(window.location.href);
        const pathParts = decodeURIComponent(parsedUrl.pathname).split('/');
        const fileName = pathParts.pop() || 'index.html';
        const folderPath = pathParts.join('/').replace(/^\//, '');
        
        // 添加当前页面到收集的文件，并保存完整URL
        addFile(folderPath, fileName, html, false, window.location.href);
        
        console.log('✅ 当前页面收集成功，路径:', folderPath + '/' + fileName);
        
    } catch (error) {

    }
}

// 收集特定URL文件
async function collectSpecificUrls() {
    try {
        console.log('🔍 收集特定URL文件...');
        
        const baseUrl = new URL(window.location.href);
        const specificUrls = [
            'index.html',
            'start.html',
            'start_c_1.html',
            'start_with_pages.html'
        ];
        
        // 增强：收集Axure data目录下的核心文件
        const dataCoreFiles = [
            'data/document.js',
            'data/main.js',
            'data/menu.js',
            'data/styles.css',
            'data/axurerp.css',
            'data/icons.css'
        ];
        
        // 合并所有需要收集的URL
        const allUrls = [...specificUrls, ...dataCoreFiles];
        
        for (const urlPath of allUrls) {
            try {
                const fullUrl = new URL(urlPath, baseUrl).href;
                
                // 跳过已经收集过的URL
                if (collectedUrls.has(fullUrl)) {
                    console.log('⏭️ 跳过已收集的文件:', urlPath, '（完整URL:', fullUrl, '，已收集资源总数:', collectedUrls.size, '）');
                    continue;
                }
                
                // 对于HTML文件，跳过已经从document.js提取的
                if (urlPath.endsWith('.html') && extractedHtmlFiles.includes(urlPath)) {
                    console.log('⏭️ 跳过已从document.js提取的文件:', urlPath);
                    continue;
                }
                
                // 项目隔离检查：确保资源与当前页面属于同一个项目（相同端口）
                const currentUrl = new URL(window.location.href);
                const resourceUrl = new URL(fullUrl);
                
                if (!isSameProject(currentUrl, resourceUrl)) {
                    console.log('❌ 跳过跨项目资源（不同端口）:', fullUrl);
                    continue;
                } else {
                    console.log('✅ 同一项目资源（相同端口）:', fullUrl);
                }
                
                console.log('🔍 收集特定URL:', fullUrl);
                
                // 使用no-cache选项，确保每次都获取最新资源，避免缓存导致的跨项目资源收集问题
                // 添加更严格的缓存控制头，确保完全避免缓存问题
                const response = await fetch(fullUrl, {
                    cache: 'no-cache',
                    headers: {
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    }
                });
                
                // 检查文件是否存在（状态码不是2xx）
                if (!response.ok) {
                    console.log('❌ 跳过不存在的文件:', urlPath, '（状态码:', response.status, '）');
                    continue;
                }
                
                // 解析URL获取路径信息
                const parsedUrl = new URL(fullUrl);
                const decodedPath = decodeURIComponent(parsedUrl.pathname);
                const pathParts = decodedPath.split('/');
                const fileName = pathParts.pop() || urlPath;
                const folderPath = pathParts.join('/').replace(/^\//, '');
                
                // 根据文件类型处理内容
                let content;
                if (urlPath.match(/\.(js|css|html)$/i)) {
                    content = await response.text();
                    addFile(folderPath, fileName, content, false, fullUrl);
                } else {
                    // 处理二进制文件
                    const blob = await response.blob();
                    const reader = new FileReader();
                    await new Promise((resolve) => {
                        reader.onloadend = () => {
                            const base64data = reader.result.split(',')[1];
                            addFile(folderPath, fileName, base64data, true, fullUrl);
                            resolve();
                        };
                        reader.readAsDataURL(blob);
                    });
                }
                
                // 标记为已收集
                collectedUrls.add(fullUrl);
                
            } catch (error) {

            }
        }
        
        console.log('✅ 特定URL文件收集完成');
        
    } catch (error) {

    }
}

// 检查两个URL是否属于同一个项目（相同的主机名和端口）
function isSameProject(currentUrl, resourceUrl) {
    // 检查是否为本地资源（127.0.0.1或localhost）
    const isLocalResource = resourceUrl.hostname === '127.0.0.1' || resourceUrl.hostname === 'localhost';
    const isCurrentLocal = currentUrl.hostname === '127.0.0.1' || currentUrl.hostname === 'localhost';
    
    // 如果都是本地资源且端口不同，则不是同一个项目
    if (isLocalResource && isCurrentLocal) {
        return currentUrl.port === resourceUrl.port;
    }
    
    // 非本地资源，检查完整的主机名（包括端口）
    return currentUrl.host === resourceUrl.host;
}

// 收集主页面资源
async function collectMainPageResources() {
    try {
        console.log('🔍 收集主页面资源...');
        
        // 使用当前页面URL作为baseUrl，确保资源与当前项目（端口）一致
        const baseUrl = window.location.href;
        
        // 收集CSS文件
        const cssLinks = document.querySelectorAll('link[rel="stylesheet"]');
        for (const link of cssLinks) {
            const href = link.getAttribute('href');
            if (href) {
                await collectResourceFile(href, 'css', baseUrl);
            }
        }
        
        // 收集JS文件
        const jsScripts = document.querySelectorAll('script[src]');
        for (const script of jsScripts) {
            const src = script.getAttribute('src');
            if (src) {
                await collectResourceFile(src, 'js', baseUrl);
            }
        }
        
        // 收集图片文件
        const images = document.querySelectorAll('img[src]');
        for (const img of images) {
            const src = img.getAttribute('src');
            if (src) {
                await collectResourceFile(src, 'image', baseUrl);
            }
        }
        
        // 收集字体文件（从style标签中）
        const styleTags = document.querySelectorAll('style');
        for (const style of styleTags) {
            const resources = extractResourcesFromCss(style.textContent, 'inline-style.css');
            for (const resource of resources) {
                if (resource.type === 'font') {
                    await collectResourceFile(resource.url, 'font', baseUrl);
                }
            }
        }
        
        console.log('✅ 主页面资源收集完成');
        
    } catch (error) {

    }
}

// 收集iframe中的资源 - 修复版：改进错误处理和安全性
async function collectIframeResources() {
    try {
        console.log('🔍 收集iframe中的资源（修复版）...');
        
        const iframes = document.querySelectorAll('iframe');
        
        if (iframes.length === 0) {
            console.log('ℹ️ 没有找到iframe');
            return;
        }
        
        console.log('📋 找到', iframes.length, '个iframe');
        
        for (const iframe of iframes) {
            try {
                // 跳过可能有问题的iframe源
                const iframeSrc = iframe.src || '';
                if (iframeSrc.includes('object.center') || iframeSrc.includes('reset')) {

                    continue;
                }
                
                // 检查iframe是否同源
                if (iframeSrc && iframeSrc !== 'about:blank') {
                    const iframeOrigin = new URL(iframeSrc).origin;
                    const mainOrigin = window.location.origin;
                    
                    if (iframeOrigin !== mainOrigin) {
                        continue;
                    }
                } else {
                    // 跳过about:blank或空src的iframe
                    continue;
                }
                
                // 等待iframe加载完成
                await waitForIframeLoad(iframe);
                
                // 获取iframe的内容文档
                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                
                console.log('🔍 处理iframe:', iframe.src);
                
                // 收集iframe中的CSS文件
                const cssLinks = iframeDoc.querySelectorAll('link[rel="stylesheet"]');
                for (const link of cssLinks) {
                    const href = link.getAttribute('href');
                    if (href) {
                        await collectResourceFile(href, 'css', iframe.src);
                    }
                }
                
                // 收集iframe中的JS文件
                const jsScripts = iframeDoc.querySelectorAll('script[src]');
                for (const script of jsScripts) {
                    const src = script.getAttribute('src');
                    if (src) {
                        await collectResourceFile(src, 'js', iframe.src);
                    }
                }
                
                // 收集iframe中的图片文件
                const images = iframeDoc.querySelectorAll('img[src]');
                for (const img of images) {
                    const src = img.getAttribute('src');
                    if (src) {
                        await collectResourceFile(src, 'image', iframe.src);
                    }
                }
                
            } catch (error) {
                // 详细的错误处理
                if (error.name === 'SecurityError' || error.message.includes('CORS') || error.message.includes('cross-origin')) {

                } else if (error.name === 'DOMException' && error.message.includes('blocked')) {

                } else {

                }
            }
        }
        
        console.log('✅ iframe资源收集完成');
        
    } catch (error) {

    }
}

// 等待iframe加载完成
function waitForIframeLoad(iframe) {
    return new Promise((resolve) => {
        console.log('⏳ 等待iframe加载:', iframe.src);
        
        // 如果iframe已经加载完成
        if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') {
            console.log('✅ iframe已经加载完成');
            resolve();
            return;
        }
        
        // 监听iframe加载完成事件
        const loadHandler = () => {
            iframe.removeEventListener('load', loadHandler);
            console.log('✅ iframe加载完成');
            resolve();
        };
        
        iframe.addEventListener('load', loadHandler);
        
        // 设置超时
        setTimeout(() => {
            iframe.removeEventListener('load', loadHandler);
            console.log('⚠️ iframe加载超时，继续收集');
            resolve();
        }, 5000);
    });
}

// 收集单个资源文件 - 改进版：保持目录结构 + 中文解码 + 项目隔离
async function collectResourceFile(url, type, baseUrl = window.location.href) {
    try {
        // 处理相对URL
        const absoluteUrl = new URL(url, baseUrl).href;
        
        // 跳过about:blank URL，避免fetch错误
        if (absoluteUrl.startsWith('about:')) {
            return;
        }
        
        // 项目隔离检查：确保资源与当前页面属于同一个项目（相同端口）
        const currentUrl = new URL(window.location.href);
        const resourceUrl = new URL(absoluteUrl);
        
        console.log('🔍 项目隔离检查 - 当前页面:', currentUrl.href, '当前端口:', currentUrl.port);
        console.log('🔍 项目隔离检查 - 资源URL:', absoluteUrl, '资源端口:', resourceUrl.port);
        
        if (!isSameProject(currentUrl, resourceUrl)) {
            console.log('❌ 跳过跨项目资源（不同端口）:', absoluteUrl);
            return;
        } else {
            console.log('✅ 同一项目资源（相同端口）:', absoluteUrl);
        }
        
        if (collectedUrls.has(absoluteUrl)) {
            console.log('⏭️ 跳过已收集的资源:', absoluteUrl, '（已收集资源总数:', collectedUrls.size, '）');
            return;
        }
        
        console.log('🔍 收集资源:', absoluteUrl, '类型:', type);
        
        // 标记为已收集
        collectedUrls.add(absoluteUrl);
        
        // 使用no-cache选项，确保每次都获取最新资源，避免缓存导致的跨项目资源收集问题
        // 添加更严格的缓存控制头，确保完全避免缓存问题
        const response = await fetch(absoluteUrl, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            }
        });
        
        // 检查响应状态码，如果不是200 OK，则跳过该资源
        if (!response.ok) {
            console.log('❌ 跳过不存在的资源:', absoluteUrl, '（状态码:', response.status, '）');
            collectedUrls.delete(absoluteUrl); // 从已收集列表中移除
            return;
        }
        
        // 解析URL获取路径信息 - 修复：添加中文解码
        const parsedUrl = new URL(absoluteUrl);
        const decodedPath = decodeURIComponent(parsedUrl.pathname);
        const pathParts = decodedPath.split('/');
        const fileName = pathParts.pop() || 'unknown-file';
        const folderPath = pathParts.join('/').replace(/^\//, '');
        
        console.log('📁 资源路径:', folderPath + '/' + fileName);
        
        if (type === 'image' || type === 'font') {
            const blob = await response.blob();
            const reader = new FileReader();
            
            return new Promise((resolve) => {
                reader.onloadend = () => {
                    const base64data = reader.result.split(',')[1];
                    addFile(folderPath, fileName, base64data, true, absoluteUrl);
                    resolve();
                };
                reader.readAsDataURL(blob);
            });
            
        } else {
            const content = await response.text();
            addFile(folderPath, fileName, content, false, absoluteUrl);
        }
        
    } catch (error) {
        console.log('❌ 收集资源时出错:', absoluteUrl, '错误:', error.message);
        collectedUrls.delete(absoluteUrl); // 从已收集列表中移除
    }
}

// 添加文件到收集
function addFile(folder, name, content, isBinary = false, url = null) {
    console.log('📥 添加文件:', folder + '/' + name);
    
    // 构建相对路径
    const path = folder ? folder + '/' + name : name;
    
    // 检查文件路径是否已存在
    if (collectedFiles.some(file => file.path === path)) {
        console.log('⏭️ 跳过已存在的文件路径:', path);
        return;
    }
    
    collectedFiles.push({
        folder,
        name,
        path,
        content,
        isBinary,
        size: isBinary ? content.length : (content.length || 0),
        url // 保存文件的完整URL
    });
    
    // 如果正在收集且文件树可见，实时更新
    if (isCollecting && document.getElementById('fileTree')) {
        setTimeout(showFileTree, 100);
    }
}

// 显示文件目录树
function showFileTree() {
    console.log('🌳 显示文件目录树，共', collectedFiles.length, '个文件');
    
    const fileTree = document.getElementById('fileTree');
    
    if (collectedFiles.length === 0) {
        fileTree.innerHTML = '<div class="axure-status-info">暂无文件</div>';
        return;
    }
    
    // 构建目录结构
    const directoryStructure = buildDirectoryStructure();
    
    // 生成目录树HTML
    const treeHtml = generateDirectoryTreeHtml(directoryStructure);
    
    fileTree.innerHTML = treeHtml;
}

// 构建目录结构
function buildDirectoryStructure() {
    const root = {
        type: 'directory',
        name: '',
        path: '',
        children: {}
    };
    
    collectedFiles.forEach(file => {
        const pathParts = file.path.split('/');
        let currentDir = root;
        
        // 处理路径
        for (let i = 0; i < pathParts.length; i++) {
            const part = pathParts[i];
            
            if (i === pathParts.length - 1) {
                // 最后一部分是文件名
                currentDir.children[part] = {
                    type: 'file',
                    name: part,
                    path: file.path,
                    fileType: getFileType(file.name)
                };
            } else {
                // 创建目录（如果不存在）
                if (!currentDir.children[part]) {
                    const dirPath = pathParts.slice(0, i + 1).join('/');
                    currentDir.children[part] = {
                        type: 'directory',
                        name: part,
                        path: dirPath,
                        children: {}
                    };
                }
                currentDir = currentDir.children[part];
            }
        }
    });
    
    return root;
}

// 生成目录树HTML
function generateDirectoryTreeHtml(directory, depth = 0) {
    let html = '';
    
    // 按字母顺序排序
    const sortedEntries = Object.entries(directory.children).sort((a, b) => {
        // 目录排在前面
        if (a[1].type === 'directory' && b[1].type === 'file') return -1;
        if (a[1].type === 'file' && b[1].type === 'directory') return 1;
        // 按名称排序
        return a[0].localeCompare(b[0]);
    });
    
    sortedEntries.forEach(([name, entry]) => {
        if (entry.type === 'directory') {
            html += `<div class="axure-tree-node">`;
            html += `<span class="axure-tree-indent">${'&nbsp;'.repeat(depth * 4)}</span>`;
            html += `<span class="axure-tree-icon">📁</span>`;
            html += `<span class="axure-tree-folder">${name}/</span>`;
            html += `</div>`;
            
            // 递归处理子目录
            html += generateDirectoryTreeHtml(entry, depth + 1);
        } else {
            const fileClass = `axure-tree-${entry.fileType}`;
            
            html += `<div class="axure-tree-node">`;
            html += `<span class="axure-tree-indent">${'&nbsp;'.repeat(depth * 4)}</span>`;
            html += `<span class="axure-tree-icon">${getFileIcon(entry.fileType)}</span>`;
            html += `<span class="axure-tree-file ${fileClass}">${name}</span>`;
            html += `</div>`;
        }
    });
    
    return html;
}

// 获取文件类型
function getFileType(fileName) {
    if (fileName.endsWith('.html') || fileName.endsWith('.htm')) {
        return 'html';
    } else if (fileName.endsWith('.js')) {
        return 'js';
    } else if (fileName.endsWith('.css')) {
        return 'css';
    } else if (fileName.match(/\.(png|jpg|jpeg|gif|svg|ico)$/i)) {
        return 'image';
    } else if (fileName.match(/\.(woff|woff2|ttf|eot)$/i)) {
        return 'font';
    } else {
        return 'other';
    }
}

// 获取文件图标
function getFileIcon(fileType) {
    switch (fileType) {
        case 'html': return '📄';
        case 'js': return '🔧';
        case 'css': return '🎨';
        case 'image': return '🖼️';
        case 'font': return '🔤';
        default: return '📄';
    }
}

// 从CSS中提取资源引用
function extractResourcesFromCss(cssContent, cssPath) {
    const resources = [];
    
    // 匹配background: url(...) 和 background-image: url(...)
    const bgImageRegex = /background(?:-image)?\s*:\s*[^;]*url\s*\(\s*['"]?([^'")]+)['"]?\s*\)/gi;
    let match;
    
    while ((match = bgImageRegex.exec(cssContent)) !== null) {
        const url = match[1].trim();
        if (url && !url.startsWith('data:')) {
            resources.push({
                url: url,
                type: 'image',
                source: 'background-image'
            });
        }
    }
    
    // 匹配@font-face { src: url(...) }
    const fontFaceRegex = /@font-face\s*{[^}]*src\s*:\s*[^}]*}/gi;
    let fontMatch;
    
    while ((fontMatch = fontFaceRegex.exec(cssContent)) !== null) {
        const srcContent = fontMatch[0];
        const individualUrlRegex = /url\s*\(\s*['"]?([^'")]+)['"]?\s*\)/gi;
        let urlMatch;
        
        while ((urlMatch = individualUrlRegex.exec(srcContent)) !== null) {
            const url = urlMatch[1].trim();
            if (url && !url.startsWith('data:')) {
                resources.push({
                    url: url,
                    type: 'font',
                    source: '@font-face'
                });
            }
        }
    }
    
    // 匹配@import url(...) 和 @import "..."
    const importRegex = /@import\s+(?:url\s*\(\s*['"]?([^'")]+)['"]?\s*\)|['"]([^'"]+)['"])/gi;
    
    while ((match = importRegex.exec(cssContent)) !== null) {
        const url = (match[1] || match[2]).trim();
        if (url && !url.startsWith('data:')) {
            resources.push({
                url: url,
                type: 'css',
                source: '@import'
            });
        }
    }
    
    // 匹配list-style-image: url(...)
    const listStyleRegex = /list-style(?:-image)?\s*:\s*url\s*\(\s*['"]?([^'")]+)['"]?\s*\)/gi;
    
    while ((match = listStyleRegex.exec(cssContent)) !== null) {
        const url = match[1].trim();
        if (url && !url.startsWith('data:')) {
            resources.push({
                url: url,
                type: 'image',
                source: 'list-style'
            });
        }
    }
    
    // 匹配border-image: url(...)
    const borderImageRegex = /border-image(?:-source)?\s*:\s*url\s*\(\s*['"]?([^'")]+)['"]?\s*\)/gi;
    
    while ((match = borderImageRegex.exec(cssContent)) !== null) {
        const url = match[1].trim();
        if (url && !url.startsWith('data:')) {
            resources.push({
                url: url,
                type: 'image',
                source: 'border-image'
            });
        }
    }
    
    return resources;
}

console.log('✅ Axure上传助手内容脚本 v2.1.1 已加载');
console.log('🔧 改进版：中文文件名解码 + 目录结构保持 + 自动收集');