/**
 * 生成统一的 HTML 报告模板
 */
export function generateUnifiedReportHTML(data) {
    const isBaseBuild = data.reportType === 'base-build';
    const isPlayable = data.reportType === 'playable';
    // 生成分类统计表格
    const categoryRows = Object.entries(data.byCategory)
        .sort((a, b) => b[1].size - a[1].size)
        .map(([category, stats]) => {
        const dataUrlColumn = isBaseBuild && stats.dataUrlSize
            ? `<td>${stats.dataUrlSizeFormatted}</td>`
            : '';
        return `
        <tr>
          <td>${category}</td>
          <td>${stats.count}</td>
          <td>${stats.sizeFormatted}</td>
          ${dataUrlColumn}
          <td>${stats.percentage.toFixed(2)}%</td>
          <td>
            <div class="bar" style="width: ${stats.percentage.toFixed(1)}%"></div>
          </td>
        </tr>
      `;
    }).join('');
    // 生成类型统计表格
    const typeRows = Object.entries(data.byType)
        .sort((a, b) => b[1].size - a[1].size)
        .map(([type, stats]) => {
        const dataUrlColumn = isBaseBuild && stats.dataUrlSize
            ? `<td>${stats.dataUrlSizeFormatted}</td>`
            : '';
        return `
        <tr>
          <td>${type}</td>
          <td>${stats.count}</td>
          <td>${stats.sizeFormatted}</td>
          ${dataUrlColumn}
          <td>${stats.percentage.toFixed(2)}%</td>
          <td>
            <div class="bar" style="width: ${stats.percentage.toFixed(1)}%"></div>
          </td>
        </tr>
      `;
    }).join('');
    // 生成 Top 资源表格
    const topItems = data.items.slice(0, 20);
    const itemRows = topItems.map(item => {
        const dataUrlColumn = isBaseBuild && item.dataUrlSize
            ? `<td>${item.dataUrlSizeFormatted}</td>`
            : '';
        return `
      <tr>
        <td>${item.name}</td>
        <td>${item.type}</td>
        <td>${item.category}</td>
        <td>${item.sizeFormatted}</td>
        ${dataUrlColumn}
        <td>${item.percentage.toFixed(2)}%</td>
        <td>
          <div class="bar" style="width: ${item.percentage.toFixed(1)}%"></div>
        </td>
      </tr>
    `;
    }).join('');
    // 表头
    const dataUrlHeader = isBaseBuild ? '<th>Data URL 大小</th>' : '';
    // 优化信息部分
    const optimizationSection = data.optimizationInfo ? `
    <div class="optimization-info">
      <h2>🎯 优化效果</h2>
      <div class="optimization-stats">
        <div class="optimization-item">
          <div class="optimization-label">Base Build 预估大小</div>
          <div class="optimization-value">${data.optimizationInfo.baseBuildSizeFormatted}</div>
        </div>
        <div class="optimization-item">
          <div class="optimization-label">实际打包大小</div>
          <div class="optimization-value">${data.optimizationInfo.actualSizeFormatted}</div>
        </div>
        <div class="optimization-item">
          <div class="optimization-label">优化率</div>
          <div class="optimization-value optimization-rate">${data.optimizationInfo.optimizationRate?.toFixed(1)}%</div>
        </div>
      </div>
    </div>
  ` : '';
    // Base Build 特有的预估信息
    const estimatedSection = isBaseBuild && data.estimatedHtmlSize ? `
    <div class="stat-item">
      <div class="stat-label">预估 HTML 大小</div>
      <div class="stat-value">${data.estimatedHtmlSizeFormatted}</div>
    </div>
  ` : '';
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${data.title}</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background: #1e1e1e;
      color: #e0e0e0;
      padding: 20px;
    }

    .container {
      max-width: 1400px;
      margin: 0 auto;
    }

    .header {
      background: #252526;
      padding: 30px;
      border-radius: 8px;
      margin-bottom: 20px;
      border: 1px solid #3e3e42;
    }

    .header h1 {
      font-size: 24px;
      font-weight: 600;
      color: #e0e0e0;
      margin-bottom: 20px;
    }

    .header-stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
    }

    .stat-item {
      background: #1e1e1e;
      padding: 15px;
      border-radius: 6px;
      border: 1px solid #3e3e42;
    }

    .stat-label {
      color: #888;
      font-size: 12px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      margin-bottom: 8px;
    }

    .stat-value {
      color: #4ec9b0;
      font-weight: 600;
      font-size: 20px;
    }

    .optimization-info {
      background: #252526;
      padding: 30px;
      border-radius: 8px;
      margin-bottom: 20px;
      border: 1px solid #3e3e42;
    }

    .optimization-info h2 {
      font-size: 18px;
      margin-bottom: 20px;
      color: #e0e0e0;
    }

    .optimization-stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 20px;
    }

    .optimization-item {
      background: #1e1e1e;
      padding: 20px;
      border-radius: 6px;
      border: 1px solid #3e3e42;
      text-align: center;
    }

    .optimization-label {
      color: #888;
      font-size: 13px;
      margin-bottom: 10px;
    }

    .optimization-value {
      color: #4ec9b0;
      font-weight: 600;
      font-size: 24px;
    }

    .optimization-rate {
      color: #2ecc71;
    }

    .section {
      background: #252526;
      padding: 30px;
      border-radius: 8px;
      margin-bottom: 20px;
      border: 1px solid #3e3e42;
    }

    .section h2 {
      font-size: 18px;
      margin-bottom: 20px;
      color: #e0e0e0;
    }

    table {
      width: 100%;
      border-collapse: collapse;
    }

    th, td {
      padding: 12px;
      text-align: left;
      border-bottom: 1px solid #3e3e42;
    }

    th {
      background: #1e1e1e;
      color: #888;
      font-size: 12px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      font-weight: 600;
    }

    td {
      color: #e0e0e0;
      font-size: 13px;
    }

    tr:hover {
      background: #2a2a2a;
    }

    .bar {
      height: 20px;
      background: linear-gradient(90deg, #4ec9b0, #2ecc71);
      border-radius: 4px;
      min-width: 2px;
    }

    .treemap-container {
      background: #252526;
      padding: 30px;
      border-radius: 8px;
      margin-bottom: 20px;
      border: 1px solid #3e3e42;
    }

    .treemap {
      width: 100%;
      min-height: 600px;
      position: relative;
      background: #1e1e1e;
      border-radius: 6px;
    }

    .treemap-block {
      position: absolute;
      border: 2px solid #1e1e1e;
      cursor: pointer;
      transition: all 0.2s;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 8px;
    }

    .treemap-block:hover {
      border-color: #fff;
      z-index: 10;
      transform: scale(1.02);
      box-shadow: 0 4px 12px rgba(0,0,0,0.5);
    }

    .treemap-block-label {
      font-size: 11px;
      font-weight: 600;
      color: white;
      text-align: center;
      text-shadow: 0 1px 2px rgba(0,0,0,0.8);
      word-break: break-word;
      line-height: 1.3;
    }

    .treemap-block-size {
      font-size: 10px;
      color: rgba(255,255,255,0.8);
      text-shadow: 0 1px 2px rgba(0,0,0,0.8);
      margin-top: 4px;
    }

    .tooltip {
      position: fixed;
      background: rgba(0, 0, 0, 0.95);
      color: white;
      padding: 12px;
      border-radius: 6px;
      font-size: 12px;
      pointer-events: none;
      z-index: 1000;
      display: none;
      border: 1px solid #555;
      box-shadow: 0 4px 12px rgba(0,0,0,0.5);
      max-width: 300px;
    }

    .tooltip-title {
      font-weight: 600;
      margin-bottom: 6px;
      color: #4ec9b0;
    }

    .tooltip-row {
      display: flex;
      justify-content: space-between;
      margin: 4px 0;
      gap: 20px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>${data.title}</h1>
      <div class="header-stats">
        <div class="stat-item">
          <div class="stat-label">${isBaseBuild ? '构建目录' : 'HTML 文件'}</div>
          <div class="stat-value">${data.buildPath}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">${isBaseBuild ? '文件总大小' : '文件大小'}</div>
          <div class="stat-value">${data.totalSizeFormatted}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">${isBaseBuild ? '文件数量' : '资源数量'}</div>
          <div class="stat-value">${data.items.length}</div>
        </div>
        ${estimatedSection}
      </div>
    </div>

    ${optimizationSection}

    <div class="treemap-container">
      <h2>🗺️ ${isBaseBuild ? '文件' : '资源'}分布图</h2>
      <div class="treemap" id="treemap"></div>
    </div>

    <div class="section">
      <h2>📦 按分类统计</h2>
      <table>
        <thead>
          <tr>
            <th>分类</th>
            <th>数量</th>
            <th>大小</th>
            ${dataUrlHeader}
            <th>占比</th>
            <th>可视化</th>
          </tr>
        </thead>
        <tbody>
          ${categoryRows}
        </tbody>
      </table>
    </div>

    <div class="section">
      <h2>📄 按类型统计</h2>
      <table>
        <thead>
          <tr>
            <th>类型</th>
            <th>数量</th>
            <th>大小</th>
            ${dataUrlHeader}
            <th>占比</th>
            <th>可视化</th>
          </tr>
        </thead>
        <tbody>
          ${typeRows}
        </tbody>
      </table>
    </div>

    <div class="section">
      <h2>🔝 Top 20 ${isBaseBuild ? '文件' : '资源'}</h2>
      <table>
        <thead>
          <tr>
            <th>名称</th>
            <th>类型</th>
            <th>分类</th>
            <th>大小</th>
            ${dataUrlHeader}
            <th>占比</th>
            <th>可视化</th>
          </tr>
        </thead>
        <tbody>
          ${itemRows}
        </tbody>
      </table>
    </div>
  </div>

  <div class="tooltip" id="tooltip"></div>

  <script>
    // 嵌入数据
    const reportData = ${JSON.stringify(data, null, 2)};
    const isBaseBuild = reportData.reportType === 'base-build';

    const categoryColors = {
      'engine': '#e74c3c',
      'config': '#3498db',
      'scene': '#2ecc71',
      'script': '#f39c12',
      'asset': '#9b59b6',
      'html': '#1abc9c'
    };

    const flattenItems = () => {
      return reportData.items.map(item => ({
        ...item,
        value: item.size
      }));
    };

    const layoutTreemap = (items, x, y, width, height) => {
      const sortedItems = [...items].sort((a, b) => b.value - a.value);
      const total = sortedItems.reduce((sum, item) => sum + item.value, 0);
      if (total === 0) return [];
      
      const blocks = [];
      let currentY = y;
      let rowItems = [];
      let rowSize = 0;
      
      sortedItems.forEach((item, index) => {
        rowItems.push(item);
        rowSize += item.value;
        
        const shouldBreak = rowItems.length >= 10 || index === sortedItems.length - 1;
        
        if (shouldBreak) {
          const rowRatio = rowSize / total;
          const rowHeight = height * rowRatio;
          
          let offsetX = x;
          rowItems.forEach(i => {
            const iWidth = (i.value / rowSize) * width;
            
            blocks.push({
              ...i,
              x: offsetX,
              y: currentY,
              width: Math.max(iWidth, 1),
              height: Math.max(rowHeight, 1)
            });
            
            offsetX += iWidth;
          });
          
          currentY += rowHeight;
          rowItems = [];
          rowSize = 0;
        }
      });
      
      return blocks;
    };

    const renderTreemap = () => {
      const container = document.getElementById('treemap');
      const width = container.clientWidth;
      const height = 600;
      
      container.innerHTML = '';
      container.style.height = height + 'px';

      const items = flattenItems();
      const blocks = layoutTreemap(items, 0, 0, width, height);

      blocks.forEach(block => {
        const div = document.createElement('div');
        div.className = 'treemap-block';
        div.style.left = block.x + 'px';
        div.style.top = block.y + 'px';
        div.style.width = block.width + 'px';
        div.style.height = block.height + 'px';
        div.style.background = categoryColors[block.category] || '#95a5a6';

        const showLabel = block.width > 60 && block.height > 40;

        if (showLabel) {
          const label = document.createElement('div');
          label.className = 'treemap-block-label';
          label.textContent = block.name;
          div.appendChild(label);

          const size = document.createElement('div');
          size.className = 'treemap-block-size';
          size.textContent = block.sizeFormatted;
          div.appendChild(size);
        }

        div.addEventListener('mouseenter', (e) => {
          const tooltip = document.getElementById('tooltip');
          let tooltipContent = \`
            <div class="tooltip-title">\${block.name}</div>
            <div class="tooltip-row">
              <span>类型:</span>
              <span>\${block.type}</span>
            </div>
            <div class="tooltip-row">
              <span>分类:</span>
              <span>\${block.category}</span>
            </div>
            <div class="tooltip-row">
              <span>大小:</span>
              <span>\${block.sizeFormatted}</span>
            </div>
          \`;
          
          if (isBaseBuild && block.dataUrlSize) {
            tooltipContent += \`
              <div class="tooltip-row">
                <span>Data URL:</span>
                <span>\${block.dataUrlSizeFormatted}</span>
              </div>
            \`;
          }
          
          tooltipContent += \`
            <div class="tooltip-row">
              <span>占比:</span>
              <span>\${block.percentage.toFixed(2)}%</span>
            </div>
          \`;
          
          tooltip.innerHTML = tooltipContent;
          tooltip.style.display = 'block';
          tooltip.style.left = (e.clientX + 15) + 'px';
          tooltip.style.top = (e.clientY + 15) + 'px';
        });

        div.addEventListener('mousemove', (e) => {
          const tooltip = document.getElementById('tooltip');
          tooltip.style.left = (e.clientX + 15) + 'px';
          tooltip.style.top = (e.clientY + 15) + 'px';
        });

        div.addEventListener('mouseleave', () => {
          document.getElementById('tooltip').style.display = 'none';
        });

        container.appendChild(div);
      });
    };

    renderTreemap();

    let resizeTimeout;
    window.addEventListener('resize', () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(renderTreemap, 300);
    });
  </script>
</body>
</html>`;
}
