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

export const dashboardApp: AppDefinition = {
  toolName: 'performance_dashboard',
  resourceUri: 'gsc://apps/dashboard',
  description: 'Interactive performance dashboard with KPIs, sparklines, and top queries/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). Optional, defaults to 28 days ago',
      },
      endDate: {
        type: 'string',
        description: 'End date (YYYY-MM-DD). Optional, defaults to yesterday',
      },
      days: {
        type: 'number',
        description: 'Number of days to look back (alternative to startDate/endDate)',
        default: 28,
      },
    },
    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>Performance Dashboard</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: 4px;
    }

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

    .kpi-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      margin-bottom: 24px;
    }

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

    .kpi-card .label {
      font-size: 12px;
      text-transform: uppercase;
      color: #5f6368;
      margin-bottom: 8px;
      font-weight: 500;
      letter-spacing: 0.5px;
    }

    .kpi-card .value {
      font-size: 32px;
      font-weight: 400;
      margin-bottom: 4px;
    }

    .kpi-card .trend {
      font-size: 13px;
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .trend.up {
      color: #34a853;
    }

    .trend.down {
      color: #ea4335;
    }

    .trend.neutral {
      color: #5f6368;
    }

    .chart-section {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08);
      margin-bottom: 24px;
    }

    .chart-section h2 {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 16px;
    }

    .table-section {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.08);
      margin-bottom: 24px;
    }

    .table-section h2 {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 16px;
    }

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

    thead {
      background: #f8f9fa;
    }

    th {
      text-align: left;
      padding: 12px 8px;
      font-size: 12px;
      font-weight: 500;
      text-transform: uppercase;
      color: #5f6368;
      cursor: pointer;
      user-select: none;
    }

    th:hover {
      background: #e8eaed;
    }

    th.sortable::after {
      content: '↕';
      margin-left: 4px;
      opacity: 0.3;
    }

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

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

    td {
      padding: 12px 8px;
      border-top: 1px solid #e8eaed;
      font-size: 14px;
    }

    tr:hover {
      background: #f8f9fa;
    }

    .url-cell {
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #1a73e8;
    }

    .metric {
      font-variant-numeric: tabular-nums;
    }

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

      .kpi-card,
      .chart-section,
      .table-section {
        background: #2d2d2d;
      }

      .kpi-card .label,
      th {
        color: #9aa0a6;
      }

      thead {
        background: #1e1e1e;
      }

      th:hover {
        background: #3c4043;
      }

      td {
        border-top-color: #3c4043;
      }

      tr:hover {
        background: #3c4043;
      }

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

    @media (max-width: 600px) {
      body {
        padding: 8px;
      }

      .kpi-grid {
        grid-template-columns: 1fr 1fr;
      }

      .kpi-card .value {
        font-size: 24px;
      }

      table {
        font-size: 12px;
      }

      td, th {
        padding: 8px 4px;
      }
    }
  </style>
</head>
<body>
  <div class="header">
    <h1 id="site-title">Performance Dashboard</h1>
    <div class="meta" id="date-range"></div>
  </div>

  <div class="kpi-grid">
    <div class="kpi-card">
      <div class="label">Total Clicks</div>
      <div class="value" id="kpi-clicks">—</div>
      <div class="trend" id="trend-clicks"></div>
    </div>
    <div class="kpi-card">
      <div class="label">Total Impressions</div>
      <div class="value" id="kpi-impressions">—</div>
      <div class="trend" id="trend-impressions"></div>
    </div>
    <div class="kpi-card">
      <div class="label">Avg CTR</div>
      <div class="value" id="kpi-ctr">—</div>
      <div class="trend" id="trend-ctr"></div>
    </div>
    <div class="kpi-card">
      <div class="label">Avg Position</div>
      <div class="value" id="kpi-position">—</div>
      <div class="trend" id="trend-position"></div>
    </div>
  </div>

  <div class="chart-section">
    <h2>Clicks & Impressions Over Time</h2>
    <div id="chart-container"></div>
  </div>

  <div class="table-section">
    <h2>Top 10 Queries</h2>
    <table id="queries-table">
      <thead>
        <tr>
          <th class="sortable" data-key="query">Query</th>
          <th class="sortable" data-key="clicks">Clicks</th>
          <th class="sortable" data-key="impressions">Impressions</th>
          <th class="sortable" data-key="ctr">CTR</th>
          <th class="sortable" data-key="position">Position</th>
        </tr>
      </thead>
      <tbody id="queries-body"></tbody>
    </table>
  </div>

  <div class="table-section">
    <h2>Top 10 Pages</h2>
    <table id="pages-table">
      <thead>
        <tr>
          <th class="sortable" data-key="page">Page</th>
          <th class="sortable" data-key="clicks">Clicks</th>
          <th class="sortable" data-key="impressions">Impressions</th>
          <th class="sortable" data-key="ctr">CTR</th>
          <th class="sortable" data-key="position">Position</th>
        </tr>
      </thead>
      <tbody id="pages-body"></tbody>
    </table>
  </div>

  <script>
    const DATA = {{DATA}};

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

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

    function formatPosition(num) {
      return num.toFixed(1);
    }

    // Sparkline SVG generator
    function sparkline(data, width = 800, height = 60) {
      if (!data || data.length === 0) return '<p>No data</p>';
      
      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="\${height}" viewBox="0 0 \${width} \${height}" preserveAspectRatio="none">
        <polyline points="\${points}" fill="none" stroke="#1a73e8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>\`;
    }

    // Render KPIs
    function renderKPIs() {
      const { kpis, trends } = DATA;
      
      document.getElementById('kpi-clicks').textContent = formatNumber(kpis.totalClicks);
      document.getElementById('kpi-impressions').textContent = formatNumber(kpis.totalImpressions);
      document.getElementById('kpi-ctr').textContent = formatPercent(kpis.avgCtr);
      document.getElementById('kpi-position').textContent = formatPosition(kpis.avgPosition);

      // Trends
      renderTrend('trend-clicks', trends.clicks);
      renderTrend('trend-impressions', trends.impressions);
      renderTrend('trend-ctr', trends.ctr);
      renderTrend('trend-position', trends.position, true); // Position: down is good
    }

    function renderTrend(id, value, invertDirection = false) {
      const el = document.getElementById(id);
      if (value === 0) {
        el.className = 'trend neutral';
        el.innerHTML = '→ No change';
        return;
      }

      const isPositive = invertDirection ? value < 0 : value > 0;
      const arrow = isPositive ? '↑' : '↓';
      const className = isPositive ? 'up' : 'down';
      
      el.className = \`trend \${className}\`;
      el.innerHTML = \`\${arrow} \${Math.abs(value).toFixed(1)}%\`;
    }

    // Render chart
    function renderChart() {
      const chartHtml = sparkline(DATA.timeseries.clicks);
      document.getElementById('chart-container').innerHTML = chartHtml;
    }

    // Render tables
    function renderTable(tableId, bodyId, data, isPage = false) {
      const tbody = document.getElementById(bodyId);
      tbody.innerHTML = data.map(row => \`
        <tr>
          <td class="\${isPage ? 'url-cell' : ''}" title="\${row[isPage ? 'page' : 'query']}">\${row[isPage ? 'page' : 'query']}</td>
          <td class="metric">\${formatNumber(row.clicks)}</td>
          <td class="metric">\${formatNumber(row.impressions)}</td>
          <td class="metric">\${formatPercent(row.ctr)}</td>
          <td class="metric">\${formatPosition(row.position)}</td>
        </tr>
      \`).join('');

      // Add sort handlers
      const table = document.getElementById(tableId);
      const headers = table.querySelectorAll('th.sortable');
      headers.forEach(th => {
        th.addEventListener('click', () => sortTable(bodyId, th.dataset.key, data, isPage));
      });
    }

    let sortState = {};
    function sortTable(bodyId, key, data, isPage) {
      const currentDir = sortState[bodyId + key] || 'desc';
      const newDir = currentDir === 'desc' ? 'asc' : 'desc';
      sortState[bodyId + key] = newDir;

      // Update header classes
      const table = document.getElementById(bodyId).closest('table');
      table.querySelectorAll('th').forEach(th => {
        th.classList.remove('sorted-asc', 'sorted-desc');
      });
      const header = table.querySelector(\`th[data-key="\${key}"]\`);
      header.classList.add(\`sorted-\${newDir}\`);

      // Sort data
      const sorted = [...data].sort((a, b) => {
        let aVal = a[key];
        let bVal = b[key];
        
        if (typeof aVal === 'string') {
          return newDir === 'asc' 
            ? aVal.localeCompare(bVal)
            : bVal.localeCompare(aVal);
        }
        
        return newDir === 'asc' ? aVal - bVal : bVal - aVal;
      });

      // Re-render
      const tbody = document.getElementById(bodyId);
      tbody.innerHTML = sorted.map(row => \`
        <tr>
          <td class="\${isPage ? 'url-cell' : ''}" title="\${row[isPage ? 'page' : 'query']}">\${row[isPage ? 'page' : 'query']}</td>
          <td class="metric">\${formatNumber(row.clicks)}</td>
          <td class="metric">\${formatNumber(row.impressions)}</td>
          <td class="metric">\${formatPercent(row.ctr)}</td>
          <td class="metric">\${formatPosition(row.position)}</td>
        </tr>
      \`).join('');
    }

    // Initialize
    function init() {
      document.getElementById('site-title').textContent = DATA.siteUrl;
      document.getElementById('date-range').textContent = \`\${DATA.startDate} – \${DATA.endDate}\`;
      
      renderKPIs();
      renderChart();
      renderTable('queries-table', 'queries-body', DATA.topQueries, false);
      renderTable('pages-table', 'pages-body', DATA.topPages, true);
    }

    init();
  </script>
</body>
</html>`,
};
