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

export const urlHealthApp: AppDefinition = {
  toolName: 'url_health_inspector',
  resourceUri: 'gsc://apps/url-health',
  description: 'Visual health check dashboard for URL inspection results',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true,
  },
  inputSchema: {
    type: 'object',
    properties: {
      siteUrl: {
        type: 'string',
        description: 'The site URL (must be verified in Google Search Console)',
      },
      urls: {
        type: 'array',
        items: { type: 'string' },
        description: 'Array of URLs to inspect',
      },
    },
    required: ['siteUrl', 'urls'],
  },
  getHtml: () => `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>URL Health Inspector</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;
    }

    .summary-bar {
      display: flex;
      gap: 24px;
      padding: 16px;
      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);
      margin-bottom: 24px;
      flex-wrap: wrap;
    }

    .summary-item {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
    }

    .summary-dot {
      width: 12px;
      height: 12px;
      border-radius: 50%;
    }

    .summary-dot.green {
      background: #34a853;
    }

    .summary-dot.yellow {
      background: #fbbc04;
    }

    .summary-dot.red {
      background: #ea4335;
    }

    .summary-item strong {
      font-weight: 600;
      margin-right: 4px;
    }

    .cards-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 16px;
    }

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

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

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

    .status-indicator {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      flex-shrink: 0;
      margin-top: 2px;
    }

    .status-indicator.green {
      background: #34a853;
      box-shadow: 0 0 0 4px rgba(52, 168, 83, 0.1);
    }

    .status-indicator.yellow {
      background: #fbbc04;
      box-shadow: 0 0 0 4px rgba(251, 188, 4, 0.1);
    }

    .status-indicator.red {
      background: #ea4335;
      box-shadow: 0 0 0 4px rgba(234, 67, 53, 0.1);
    }

    .card-url {
      flex: 1;
      font-size: 13px;
      color: #1a73e8;
      word-break: break-all;
      cursor: pointer;
    }

    .card-url:hover {
      text-decoration: underline;
    }

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

    .status-badge.indexed {
      background: #e6f4ea;
      color: #137333;
    }

    .status-badge.warning {
      background: #fef7e0;
      color: #b06000;
    }

    .status-badge.error {
      background: #fce8e6;
      color: #c5221f;
    }

    .card-meta {
      display: flex;
      flex-direction: column;
      gap: 6px;
      font-size: 13px;
      color: #5f6368;
    }

    .meta-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .meta-label {
      font-weight: 500;
    }

    .meta-value {
      text-align: right;
    }

    .expand-btn {
      margin-top: 12px;
      padding: 8px;
      background: #f8f9fa;
      border: none;
      border-radius: 4px;
      width: 100%;
      cursor: pointer;
      font-size: 13px;
      font-weight: 500;
      color: #1a73e8;
      transition: background 0.2s;
    }

    .expand-btn:hover {
      background: #e8eaed;
    }

    .expand-btn::after {
      content: ' ▼';
      font-size: 10px;
    }

    .expand-btn.expanded::after {
      content: ' ▲';
    }

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

    .details.visible {
      display: block;
    }

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

    .details-section h4 {
      font-size: 11px;
      text-transform: uppercase;
      color: #5f6368;
      font-weight: 600;
      letter-spacing: 0.5px;
      margin-bottom: 6px;
    }

    .details-list {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .details-item {
      display: flex;
      justify-content: space-between;
      padding: 4px 0;
    }

    .check-mark {
      color: #34a853;
    }

    .x-mark {
      color: #ea4335;
    }

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

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

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

      .card-meta {
        color: #9aa0a6;
      }

      .status-badge.indexed {
        background: #0d652d;
        color: #81c995;
      }

      .status-badge.warning {
        background: #7c4a03;
        color: #fdd663;
      }

      .status-badge.error {
        background: #8a1a18;
        color: #f28b82;
      }

      .expand-btn {
        background: #3c4043;
        color: #8ab4f8;
      }

      .expand-btn:hover {
        background: #5f6368;
      }

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

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

    @media (max-width: 600px) {
      .cards-grid {
        grid-template-columns: 1fr;
      }

      .summary-bar {
        flex-direction: column;
        gap: 12px;
      }
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>URL Health Inspector</h1>
  </div>

  <div class="summary-bar">
    <div class="summary-item">
      <span class="summary-dot green"></span>
      <strong id="count-indexed">0</strong> Indexed
    </div>
    <div class="summary-item">
      <span class="summary-dot yellow"></span>
      <strong id="count-warnings">0</strong> Warnings
    </div>
    <div class="summary-item">
      <span class="summary-dot red"></span>
      <strong id="count-errors">0</strong> Errors
    </div>
  </div>

  <div class="cards-grid" id="cards-container"></div>

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

    function getStatusColor(result) {
      if (result.verdict === 'PASS') return 'green';
      if (result.verdict === 'PARTIAL' || result.verdict === 'NEUTRAL') return 'yellow';
      return 'red';
    }

    function getStatusLabel(result) {
      if (result.verdict === 'PASS') return 'indexed';
      if (result.verdict === 'PARTIAL' || result.verdict === 'NEUTRAL') return 'warning';
      return 'error';
    }

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

    function renderCard(result) {
      const statusColor = getStatusColor(result);
      const statusLabel = getStatusLabel(result);
      
      return \`
        <div class="url-card">
          <div class="card-header">
            <span class="status-indicator \${statusColor}"></span>
            <div class="card-url" title="\${result.url}">\${result.url}</div>
          </div>
          
          <span class="status-badge \${statusLabel}">\${result.coverageState || 'Unknown'}</span>
          
          <div class="card-meta">
            <div class="meta-row">
              <span class="meta-label">Last Crawled:</span>
              <span class="meta-value">\${formatDate(result.lastCrawlTime)}</span>
            </div>
            <div class="meta-row">
              <span class="meta-label">Verdict:</span>
              <span class="meta-value">\${result.verdict || 'N/A'}</span>
            </div>
            \${result.robotsTxtState ? \`
              <div class="meta-row">
                <span class="meta-label">Robots.txt:</span>
                <span class="meta-value">\${result.robotsTxtState}</span>
              </div>
            \` : ''}
          </div>
          
          <button class="expand-btn" onclick="toggleDetails('\${result.url}')">
            View Details
          </button>
          
          <div class="details" id="details-\${btoa(result.url).replace(/=/g, '')}">
            \${result.mobileUsability ? \`
              <div class="details-section">
                <h4>Mobile Usability</h4>
                <div class="details-list">
                  <div class="details-item">
                    <span>Mobile Friendly</span>
                    <span class="\${result.mobileUsability.verdict === 'PASS' ? 'check-mark' : 'x-mark'}">
                      \${result.mobileUsability.verdict === 'PASS' ? '✓' : '✗'}
                    </span>
                  </div>
                </div>
              </div>
            \` : ''}
            
            \${result.richResults ? \`
              <div class="details-section">
                <h4>Rich Results</h4>
                <div class="details-list">
                  <div class="details-item">
                    <span>Status</span>
                    <span>\${result.richResults.verdict || 'N/A'}</span>
                  </div>
                </div>
              </div>
            \` : ''}
            
            <div class="details-section">
              <h4>Index Status</h4>
              <div class="details-list">
                <div class="details-item">
                  <span>Coverage State</span>
                  <span>\${result.coverageState || 'N/A'}</span>
                </div>
                <div class="details-item">
                  <span>Indexing State</span>
                  <span>\${result.indexingState || 'N/A'}</span>
                </div>
                \${result.pageFetchState ? \`
                  <div class="details-item">
                    <span>Page Fetch</span>
                    <span>\${result.pageFetchState}</span>
                  </div>
                \` : ''}
              </div>
            </div>
          </div>
        </div>
      \`;
    }

    function toggleDetails(url) {
      const id = 'details-' + btoa(url).replace(/=/g, '');
      const details = document.getElementById(id);
      const btn = details.previousElementSibling;
      
      details.classList.toggle('visible');
      btn.classList.toggle('expanded');
    }

    function updateSummary() {
      let indexed = 0, warnings = 0, errors = 0;
      
      DATA.results.forEach(result => {
        const status = getStatusColor(result);
        if (status === 'green') indexed++;
        else if (status === 'yellow') warnings++;
        else errors++;
      });
      
      document.getElementById('count-indexed').textContent = indexed;
      document.getElementById('count-warnings').textContent = warnings;
      document.getElementById('count-errors').textContent = errors;
    }

    function init() {
      const container = document.getElementById('cards-container');
      container.innerHTML = DATA.results.map(renderCard).join('');
      updateSummary();
    }

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

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