import type { AppDefinition } from './types.js';

export const cannibalizationApp: AppDefinition = {
  toolName: 'cannibalization_map',
  resourceUri: 'gsc://apps/cannibalization',
  description: 'Visual map of keyword cannibalization with expandable competing pages',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true,
  },
  inputSchema: {
    type: 'object',
    properties: {
      siteUrl: {
        type: 'string',
        description: 'The site URL (must be verified in Google Search Console)',
      },
      startDate: {
        type: 'string',
        description: 'Start date (YYYY-MM-DD)',
      },
      endDate: {
        type: 'string',
        description: 'End date (YYYY-MM-DD)',
      },
      days: {
        type: 'number',
        description: 'Number of days to look back',
      },
    },
    required: ['siteUrl'],
  },
  getHtml: () => `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Keyword Cannibalization Map</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: system-ui, -apple-system, sans-serif;
      background: #f8f9fa;
      color: #202124;
      padding: 16px;
      line-height: 1.5;
    }

    .header {
      margin-bottom: 24px;
    }

    .header h1 {
      font-size: 24px;
      font-weight: 500;
      margin-bottom: 8px;
    }

    .header p {
      font-size: 14px;
      color: #5f6368;
    }

    .controls {
      display: flex;
      gap: 12px;
      margin-bottom: 24px;
      flex-wrap: wrap;
    }

    .controls label {
      font-size: 13px;
      font-weight: 500;
      color: #5f6368;
      margin-right: 8px;
    }

    select {
      padding: 6px 12px;
      border: 1px solid #dadce0;
      border-radius: 4px;
      font-size: 13px;
      background: white;
      color: #202124;
    }

    select:focus {
      outline: none;
      border-color: #1a73e8;
    }

    .table-container {
      background: white;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08);
      overflow: hidden;
    }

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

    thead {
      background: #f8f9fa;
    }

    th {
      text-align: left;
      padding: 12px 16px;
      font-size: 12px;
      font-weight: 600;
      text-transform: uppercase;
      color: #5f6368;
      letter-spacing: 0.5px;
      cursor: pointer;
      user-select: none;
    }

    th:hover {
      background: #e8eaed;
    }

    th.sortable::after {
      content: ' ↕';
      opacity: 0.3;
    }

    th.sorted-asc::after {
      content: ' ↑';
      opacity: 1;
      color: #1a73e8;
    }

    th.sorted-desc::after {
      content: ' ↓';
      opacity: 1;
      color: #1a73e8;
    }

    .keyword-row {
      cursor: pointer;
      transition: background 0.15s;
    }

    .keyword-row:hover {
      background: #f8f9fa;
    }

    .keyword-row td {
      padding: 16px;
      border-top: 1px solid #e8eaed;
    }

    .keyword-cell {
      font-weight: 500;
      font-size: 14px;
    }

    .expand-icon {
      display: inline-block;
      margin-right: 8px;
      transition: transform 0.2s;
      font-size: 10px;
    }

    .keyword-row.expanded .expand-icon {
      transform: rotate(90deg);
    }

    .severity-badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 600;
    }

    .severity-badge.low {
      background: #e6f4ea;
      color: #137333;
    }

    .severity-badge.medium {
      background: #fef7e0;
      color: #b06000;
    }

    .severity-badge.high {
      background: #fce8e6;
      color: #c5221f;
    }

    .severity-badge.critical {
      background: #fce8e6;
      color: #a50e0e;
      font-weight: 700;
    }

    .details-row {
      display: none;
      background: #fafafa;
    }

    .details-row.visible {
      display: table-row;
    }

    .details-cell {
      padding: 16px 16px 16px 48px;
      border-top: 1px solid #e8eaed;
    }

    .pages-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .page-item {
      background: white;
      padding: 12px;
      border-radius: 4px;
      border-left: 3px solid #dadce0;
    }

    .page-item.winner {
      border-left-color: #34a853;
      background: #f0f9f4;
    }

    .page-url {
      font-size: 13px;
      color: #1a73e8;
      margin-bottom: 8px;
      word-break: break-all;
    }

    .winner-badge {
      display: inline-block;
      background: #34a853;
      color: white;
      padding: 2px 8px;
      border-radius: 3px;
      font-size: 11px;
      font-weight: 600;
      text-transform: uppercase;
      margin-left: 8px;
    }

    .page-metrics {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
      gap: 12px;
      font-size: 12px;
    }

    .page-metric {
      display: flex;
      flex-direction: column;
      gap: 2px;
    }

    .page-metric-label {
      color: #5f6368;
      font-size: 11px;
      text-transform: uppercase;
      font-weight: 500;
    }

    .page-metric-value {
      font-weight: 600;
      font-variant-numeric: tabular-nums;
    }

    .impression-bar {
      height: 6px;
      background: #e8eaed;
      border-radius: 3px;
      overflow: hidden;
      margin-top: 8px;
    }

    .impression-bar-fill {
      height: 100%;
      background: #1a73e8;
      transition: width 0.3s;
    }

    @media (prefers-color-scheme: dark) {
      body {
        background: #1e1e1e;
        color: #e8eaed;
      }

      .table-container {
        background: #2d2d2d;
      }

      thead {
        background: #1e1e1e;
      }

      th {
        color: #9aa0a6;
      }

      th:hover {
        background: #3c4043;
      }

      .keyword-row:hover {
        background: #3c4043;
      }

      .keyword-row td {
        border-top-color: #5f6368;
      }

      select {
        background: #2d2d2d;
        color: #e8eaed;
        border-color: #5f6368;
      }

      .severity-badge.low {
        background: #0d652d;
        color: #81c995;
      }

      .severity-badge.medium {
        background: #7c4a03;
        color: #fdd663;
      }

      .severity-badge.high,
      .severity-badge.critical {
        background: #8a1a18;
        color: #f28b82;
      }

      .details-row {
        background: #1e1e1e;
      }

      .details-cell {
        border-top-color: #5f6368;
      }

      .page-item {
        background: #2d2d2d;
        border-left-color: #5f6368;
      }

      .page-item.winner {
        border-left-color: #34a853;
        background: #1a3a28;
      }

      .page-url {
        color: #8ab4f8;
      }

      .page-metric-label {
        color: #9aa0a6;
      }

      .impression-bar {
        background: #3c4043;
      }
    }

    @media (max-width: 600px) {
      th, td {
        padding: 12px 8px;
        font-size: 12px;
      }

      .details-cell {
        padding: 12px 8px;
      }

      .page-metrics {
        grid-template-columns: 1fr 1fr;
      }
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Keyword Cannibalization Map</h1>
    <p>Keywords where multiple pages compete for the same ranking</p>
  </div>

  <div class="controls">
    <label for="sort-by">Sort by:</label>
    <select id="sort-by">
      <option value="severity">Severity</option>
      <option value="impressions">Impressions</option>
      <option value="pages">Number of Pages</option>
    </select>
  </div>

  <div class="table-container">
    <table>
      <thead>
        <tr>
          <th class="sortable" data-key="keyword">Keyword</th>
          <th class="sortable" data-key="pages"># Pages</th>
          <th class="sortable" data-key="impressions">Impressions</th>
          <th class="sortable" data-key="severity">Severity</th>
        </tr>
      </thead>
      <tbody id="table-body"></tbody>
    </table>
  </div>

  <script>
    const DATA = {{DATA}};
    let sortedData = [...DATA.keywords];

    function formatNumber(num) {
      if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
      return num.toLocaleString();
    }

    function formatPercent(num) {
      return (num * 100).toFixed(1) + '%';
    }

    function getSeverityClass(severity) {
      return severity.toLowerCase();
    }

    function renderKeywordRow(item, index) {
      return \`
        <tr class="keyword-row" onclick="toggleRow(\${index})">
          <td class="keyword-cell">
            <span class="expand-icon">▶</span>
            \${item.keyword}
          </td>
          <td>\${item.pages.length}</td>
          <td>\${formatNumber(item.totalImpressions)}</td>
          <td>
            <span class="severity-badge \${getSeverityClass(item.severity)}">
              \${item.severity}
            </span>
          </td>
        </tr>
        <tr class="details-row" id="details-\${index}">
          <td colspan="4" class="details-cell">
            <div class="pages-list">
              \${item.pages.map((page, pageIndex) => renderPage(page, pageIndex === 0, item.totalImpressions)).join('')}
            </div>
          </td>
        </tr>
      \`;
    }

    function renderPage(page, isWinner, totalImpressions) {
      const impressionPercent = (page.impressions / totalImpressions) * 100;
      
      return \`
        <div class="page-item \${isWinner ? 'winner' : ''}">
          <div class="page-url">
            \${page.url}
            \${isWinner ? '<span class="winner-badge">Winner</span>' : ''}
          </div>
          <div class="page-metrics">
            <div class="page-metric">
              <div class="page-metric-label">Clicks</div>
              <div class="page-metric-value">\${formatNumber(page.clicks)}</div>
            </div>
            <div class="page-metric">
              <div class="page-metric-label">Impressions</div>
              <div class="page-metric-value">\${formatNumber(page.impressions)}</div>
            </div>
            <div class="page-metric">
              <div class="page-metric-label">CTR</div>
              <div class="page-metric-value">\${formatPercent(page.ctr)}</div>
            </div>
            <div class="page-metric">
              <div class="page-metric-label">Position</div>
              <div class="page-metric-value">\${page.position.toFixed(1)}</div>
            </div>
          </div>
          <div class="impression-bar">
            <div class="impression-bar-fill" style="width: \${impressionPercent}%"></div>
          </div>
        </div>
      \`;
    }

    function renderTable() {
      const tbody = document.getElementById('table-body');
      tbody.innerHTML = sortedData.map((item, index) => renderKeywordRow(item, index)).join('');
    }

    function toggleRow(index) {
      const detailsRow = document.getElementById(\`details-\${index}\`);
      const keywordRow = detailsRow.previousElementSibling;
      
      detailsRow.classList.toggle('visible');
      keywordRow.classList.toggle('expanded');
    }

    function sortData(key) {
      const severityOrder = { critical: 4, high: 3, medium: 2, low: 1 };
      
      sortedData.sort((a, b) => {
        if (key === 'severity') {
          return severityOrder[b.severity.toLowerCase()] - severityOrder[a.severity.toLowerCase()];
        }
        if (key === 'pages') {
          return b.pages.length - a.pages.length;
        }
        if (key === 'impressions') {
          return b.totalImpressions - a.totalImpressions;
        }
        return 0;
      });
      
      renderTable();
    }

    // Event listeners
    document.getElementById('sort-by').addEventListener('change', (e) => {
      sortData(e.target.value);
    });

    // Header sort
    document.querySelectorAll('th.sortable').forEach(th => {
      th.addEventListener('click', () => {
        // Remove all sorted classes
        document.querySelectorAll('th').forEach(h => {
          h.classList.remove('sorted-asc', 'sorted-desc');
        });
        
        // Add sorted class to clicked header
        th.classList.add('sorted-desc');
        
        sortData(th.dataset.key);
      });
    });

    // Make toggleRow available globally
    window.toggleRow = toggleRow;

    // Initialize
    sortData('severity');
  </script>
</body>
</html>`,
};
