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

export const contentDecayApp: AppDefinition = {
  toolName: 'content_decay_tracker',
  resourceUri: 'gsc://apps/content-decay',
  description: 'Visual tracker for declining pages with sparkline trends and actionable insights',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true,
  },
  inputSchema: {
    type: 'object',
    properties: {
      siteUrl: {
        type: 'string',
        description: 'The site URL (must be verified in Google Search Console)',
      },
      lookbackDays: {
        type: 'number',
        description: 'Days to look back for trend analysis',
        default: 90,
      },
      comparisonDays: {
        type: 'number',
        description: 'Days to compare for peak vs recent',
        default: 7,
      },
    },
    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>Content Decay Tracker</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;
    }

    .summary {
      display: flex;
      gap: 16px;
      margin-bottom: 24px;
      flex-wrap: wrap;
    }

    .summary-card {
      background: white;
      padding: 16px;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08);
      flex: 1;
      min-width: 150px;
    }

    .summary-card .label {
      font-size: 11px;
      text-transform: uppercase;
      color: #5f6368;
      margin-bottom: 4px;
      font-weight: 600;
      letter-spacing: 0.5px;
    }

    .summary-card .value {
      font-size: 28px;
      font-weight: 400;
    }

    .summary-card.mild .value {
      color: #fbbc04;
    }

    .summary-card.moderate .value {
      color: #f29900;
    }

    .summary-card.critical .value {
      color: #ea4335;
    }

    .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;
    }

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

    .page-card {
      background: white;
      border-radius: 8px;
      padding: 16px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08);
      transition: box-shadow 0.2s;
      cursor: pointer;
    }

    .page-card:hover {
      box-shadow: 0 4px 6px rgba(0,0,0,0.15), 0 2px 4px rgba(0,0,0,0.1);
    }

    .page-header {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      margin-bottom: 12px;
    }

    .page-url {
      flex: 1;
      font-size: 14px;
      color: #1a73e8;
      word-break: break-all;
    }

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

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

    .severity-badge.moderate {
      background: #fce8e6;
      color: #d93f0b;
    }

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

    .page-content {
      display: grid;
      grid-template-columns: 200px 1fr;
      gap: 16px;
      align-items: center;
    }

    .sparkline-container {
      height: 60px;
      background: #f8f9fa;
      border-radius: 4px;
      padding: 8px;
    }

    .page-stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 12px;
    }

    .stat-item {
      display: flex;
      flex-direction: column;
      gap: 2px;
    }

    .stat-label {
      font-size: 11px;
      text-transform: uppercase;
      color: #5f6368;
      font-weight: 500;
      letter-spacing: 0.5px;
    }

    .stat-value {
      font-size: 16px;
      font-weight: 600;
      font-variant-numeric: tabular-nums;
    }

    .stat-value.decline {
      color: #ea4335;
    }

    .details {
      display: none;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #e8eaed;
    }

    .details.visible {
      display: block;
    }

    .details-section {
      margin-bottom: 12px;
    }

    .details-section h4 {
      font-size: 12px;
      font-weight: 600;
      margin-bottom: 8px;
      color: #5f6368;
    }

    .details-info {
      display: flex;
      flex-direction: column;
      gap: 6px;
      font-size: 13px;
    }

    .info-row {
      display: flex;
      justify-content: space-between;
    }

    .info-label {
      color: #5f6368;
    }

    .recommendations {
      background: #e8f0fe;
      padding: 12px;
      border-radius: 4px;
      border-left: 3px solid #1a73e8;
    }

    .recommendations h4 {
      color: #1a73e8;
      margin-bottom: 8px;
    }

    .recommendations ul {
      margin-left: 20px;
      font-size: 13px;
      color: #174ea6;
    }

    .recommendations li {
      margin-bottom: 4px;
    }

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

      .summary-card,
      .page-card {
        background: #2d2d2d;
      }

      .summary-card .label,
      .stat-label {
        color: #9aa0a6;
      }

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

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

      .severity-badge.moderate {
        background: #8a1a18;
        color: #f28b82;
      }

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

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

      .sparkline-container {
        background: #1e1e1e;
      }

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

      .details-section h4,
      .info-label {
        color: #9aa0a6;
      }

      .recommendations {
        background: #1a3a52;
        border-left-color: #8ab4f8;
      }

      .recommendations h4 {
        color: #aecbfa;
      }

      .recommendations ul {
        color: #aecbfa;
      }
    }

    @media (max-width: 768px) {
      .page-content {
        grid-template-columns: 1fr;
      }

      .sparkline-container {
        height: 80px;
      }

      .summary {
        flex-direction: column;
      }
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Content Decay Tracker</h1>
    <p>Pages experiencing traffic decline</p>
  </div>

  <div class="summary">
    <div class="summary-card mild">
      <div class="label">Mild Decay</div>
      <div class="value" id="count-mild">0</div>
    </div>
    <div class="summary-card moderate">
      <div class="label">Moderate Decay</div>
      <div class="value" id="count-moderate">0</div>
    </div>
    <div class="summary-card critical">
      <div class="label">Critical Decay</div>
      <div class="value" id="count-critical">0</div>
    </div>
  </div>

  <div class="controls">
    <label for="sort-by">Sort by:</label>
    <select id="sort-by">
      <option value="severity">Severity</option>
      <option value="absoluteLoss">Absolute Loss</option>
      <option value="percentDrop">% Drop</option>
      <option value="daysSincePeak">Days Since Peak</option>
    </select>
  </div>

  <div class="pages-list" id="pages-container"></div>

  <script>
    const DATA = {{DATA}};
    let sortedPages = [...DATA.pages];

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

    function formatDate(dateStr) {
      const date = new Date(dateStr);
      return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
    }

    // SVG Sparkline generator
    function sparkline(data, width = 200, height = 44) {
      if (!data || data.length === 0) return '';
      
      const max = Math.max(...data);
      const min = Math.min(...data);
      const range = max - min || 1;
      
      const points = data.map((v, i) => 
        \`\${(i / (data.length - 1)) * width},\${height - ((v - min) / range) * height}\`
      ).join(' ');
      
      return \`<svg width="100%" height="100%" viewBox="0 0 \${width} \${height}" preserveAspectRatio="none">
        <polyline points="\${points}" fill="none" stroke="#ea4335" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>\`;
    }

    function getRecommendations(severity) {
      if (severity === 'Critical') {
        return '<li>Immediate content audit required</li><li>Check for technical SEO issues (404s, canonicals)</li><li>Review competing SERP content</li><li>Consider content refresh or rewrite</li>';
      } else if (severity === 'Moderate') {
        return '<li>Update content with fresh information</li><li>Improve internal linking to this page</li><li>Check for keyword cannibalization</li><li>Add new media or visual content</li>';
      }
      return '<li>Monitor for continued decline</li><li>Minor content updates may help</li><li>Review analytics for user behavior changes</li>';
    }

    function renderPageCard(page, index) {
      const sparklineHtml = sparkline(page.trend);
      
      return \`
        <div class="page-card" onclick="toggleDetails(\${index})">
          <div class="page-header">
            <div class="page-url" title="\${page.url}">\${page.url}</div>
            <span class="severity-badge \${page.severity.toLowerCase()}">\${page.severity}</span>
          </div>
          
          <div class="page-content">
            <div class="sparkline-container">
              \${sparklineHtml}
            </div>
            
            <div class="page-stats">
              <div class="stat-item">
                <div class="stat-label">Peak Clicks</div>
                <div class="stat-value">\${formatNumber(page.peakClicks)}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">Recent Clicks</div>
                <div class="stat-value">\${formatNumber(page.recentClicks)}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">Drop</div>
                <div class="stat-value decline">-\${page.percentDrop.toFixed(1)}%</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">Days Since Peak</div>
                <div class="stat-value">\${page.daysSincePeak}</div>
              </div>
            </div>
          </div>

          <div class="details" id="details-\${index}">
            <div class="details-section">
              <h4>Timeline Details</h4>
              <div class="details-info">
                <div class="info-row">
                  <span class="info-label">Peak Date:</span>
                  <span>\${formatDate(page.peakDate)}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">Peak Clicks:</span>
                  <span>\${formatNumber(page.peakClicks)}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">Recent Average:</span>
                  <span>\${formatNumber(page.recentClicks)} clicks/day</span>
                </div>
                <div class="info-row">
                  <span class="info-label">Absolute Loss:</span>
                  <span class="decline">-\${formatNumber(page.absoluteLoss)} clicks</span>
                </div>
              </div>
            </div>

            <div class="recommendations">
              <h4>Recommended Actions</h4>
              <ul>
                \${getRecommendations(page.severity)}
              </ul>
            </div>
          </div>
        </div>
      \`;
    }

    function renderPages() {
      const container = document.getElementById('pages-container');
      container.innerHTML = sortedPages.map((page, index) => renderPageCard(page, index)).join('');
    }

    function updateSummary() {
      const counts = { mild: 0, moderate: 0, critical: 0 };
      
      DATA.pages.forEach(page => {
        const severity = page.severity.toLowerCase();
        if (counts[severity] !== undefined) counts[severity]++;
      });
      
      document.getElementById('count-mild').textContent = counts.mild;
      document.getElementById('count-moderate').textContent = counts.moderate;
      document.getElementById('count-critical').textContent = counts.critical;
    }

    function sortPages(key) {
      const severityOrder = { critical: 3, moderate: 2, mild: 1 };
      
      sortedPages.sort((a, b) => {
        if (key === 'severity') {
          return severityOrder[b.severity.toLowerCase()] - severityOrder[a.severity.toLowerCase()];
        }
        if (key === 'absoluteLoss') {
          return b.absoluteLoss - a.absoluteLoss;
        }
        if (key === 'percentDrop') {
          return b.percentDrop - a.percentDrop;
        }
        if (key === 'daysSincePeak') {
          return a.daysSincePeak - b.daysSincePeak;
        }
        return 0;
      });
      
      renderPages();
    }

    function toggleDetails(index) {
      const details = document.getElementById(\`details-\${index}\`);
      details.classList.toggle('visible');
    }

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

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

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