---
import AdminLayout from '../../../layouts/AdminLayout.astro';

const endpoint = '/api/collections/geo_locations';
const columns = ['city', 'state', 'county', 'content_generated', 'created_at'];
---

<AdminLayout title="Geo Intelligence">
  <div class="space-y-6">
    <div class="flex items-center justify-between">
      <h1 class="text-3xl font-bold text-gold-500">Geographic Locations</h1>
      <div id="item-count" class="text-sm text-gray-400">Loading...</div>
    </div>

    <div class="bg-titanium border border-edge-normal rounded-xl overflow-hidden">
      <table class="w-full">
        <thead class="bg-graphite border-b border-edge-subtle">
          <tr>
            {columns.map(col => (
              <th class="px-6 py-4 text-left text-sm font-semibold text-gray-300 uppercase tracking-wider">
                {col.replace(/_/g, ' ')}
              </th>
            ))}
          </tr>
        </thead>
        <tbody id="table-body" class="divide-y divide-edge-subtle">
          <tr>
            <td colspan={columns.length} class="px-6 py-12 text-center text-gray-500">
              Loading data...
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <script define:vars={{ endpoint, columns }}>
    async function loadData() {
      try {
        const token = localStorage.getItem('godToken') || 'jmQXoeyxWoBsB7eHzG7FmnH90f22JtaYBxXHoorhfZ-v4tT3VNEr9vvmwHqYHCDoWXHSU4DeZXApCP-Gha-YdA';
        const response = await fetch(endpoint, {
          headers: { 'X-God-Token': token }
        });
        
        if (!response.ok) throw new Error('Failed to fetch');
        
        const result = await response.json();
        const data = result.data || [];
        const total = result.meta?.total || 0;
        
        document.getElementById('item-count').textContent = `${total} total items`;
        
        const tbody = document.getElementById('table-body');
        if (data.length === 0) {
          tbody.innerHTML = `
            <tr>
              <td colspan="${columns.length}" class="px-6 py-12 text-center text-gray-500">
                No items found
              </td>
            </tr>
          `;
        } else {
          tbody.innerHTML = data.map(item => `
            <tr class="hover:bg-graphite/50 transition-colors">
              ${columns.map(col => `
                <td class="px-6 py-4 text-sm text-gray-300">
                  ${item[col] || '-'}
                </td>
              `).join('')}
            </tr>
          `).join('');
        }
      } catch (err) {
        document.getElementById('table-body').innerHTML = `
          <tr>
            <td colspan="${columns.length}" class="px-6 py-12 text-center text-red-400">
              Error: ${err.message}
            </td>
          </tr>
        `;
      }
    }
    
    loadData();
  </script>
</AdminLayout>
