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

<Layout title="Territory Manager Territories - Black Canyon Tickets">
  <div class="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900">
    <div class="container mx-auto px-4 py-12">
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold text-white mb-4">Territory Manager Territories</h1>
        <p class="text-xl text-blue-100">Explore available territories and their current status</p>
      </div>

      <!-- Territory Map -->
      <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20 mb-8">
        <h2 class="text-2xl font-bold text-white mb-6">Colorado Territory Map</h2>
        <div id="territory-map" class="w-full h-96 bg-gray-800 rounded-lg relative overflow-hidden">
          <div class="absolute inset-0 flex items-center justify-center">
            <div class="text-white text-lg">Loading territory map...</div>
          </div>
        </div>
      </div>

      <!-- Territory List -->
      <div class="grid lg:grid-cols-2 gap-8">
        <!-- Available Territories -->
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
          <h3 class="text-xl font-bold text-white mb-4">Available Territories</h3>
          <div class="space-y-4" id="available-territories">
            <!-- Available territories will be loaded here -->
          </div>
        </div>

        <!-- Assigned Territories -->
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
          <h3 class="text-xl font-bold text-white mb-4">Assigned Territories</h3>
          <div class="space-y-4" id="assigned-territories">
            <!-- Assigned territories will be loaded here -->
          </div>
        </div>
      </div>

      <!-- Territory Stats -->
      <div class="grid md:grid-cols-4 gap-6 mt-8">
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
          <div class="text-3xl font-bold text-white" id="total-territories">0</div>
          <div class="text-blue-100">Total Territories</div>
        </div>
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
          <div class="text-3xl font-bold text-green-400" id="assigned-count">0</div>
          <div class="text-blue-100">Assigned</div>
        </div>
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
          <div class="text-3xl font-bold text-yellow-400" id="available-count">0</div>
          <div class="text-blue-100">Available</div>
        </div>
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
          <div class="text-3xl font-bold text-purple-400" id="total-population">0</div>
          <div class="text-blue-100">Total Population</div>
        </div>
      </div>

      <!-- Action Buttons -->
      <div class="text-center mt-8">
        <a href="/territory-manager/apply" class="inline-block bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-8 py-4 rounded-lg text-lg font-semibold transition-all duration-300 shadow-lg hover:shadow-xl mr-4">
          Apply to Manage a Territory
        </a>
        <a href="/territory-manager/dashboard" class="inline-block bg-gradient-to-r from-green-500 to-blue-600 hover:from-green-600 hover:to-blue-700 text-white px-8 py-4 rounded-lg text-lg font-semibold transition-all duration-300 shadow-lg hover:shadow-xl">
          Territory Manager Dashboard
        </a>
      </div>
    </div>
  </div>

  <script>
    let territories = [];

    // Load territories
    async function loadTerritories() {
      try {
        const response = await fetch('/api/territory-manager/territories');
        const data = await response.json();
        territories = data.territories || [];
        
        renderTerritories();
        renderMap();
        updateStats();
      } catch (error) {
        console.error('Error loading territories:', error);
      }
    }

    // Render territories
    function renderTerritories() {
      const availableContainer = document.getElementById('available-territories');
      const assignedContainer = document.getElementById('assigned-territories');
      
      const available = territories.filter(t => !t.assigned_to);
      const assigned = territories.filter(t => t.assigned_to);

      availableContainer.innerHTML = available.length ? available.map(territory => `
        <div class="bg-white/5 rounded-lg p-4 border border-white/10">
          <div class="flex justify-between items-start">
            <div>
              <h4 class="text-white font-medium">${territory.name}</h4>
              <p class="text-blue-100 text-sm">Population: ${territory.population?.toLocaleString() || 'N/A'}</p>
              <p class="text-blue-100 text-sm">Market Size: ${territory.market_size || 'N/A'}</p>
            </div>
            <div class="text-right">
              <span class="inline-block px-2 py-1 bg-green-600 text-white text-xs rounded-full">Available</span>
            </div>
          </div>
        </div>
      `).join('') : '<div class="text-blue-100 text-center py-4">No available territories</div>';

      assignedContainer.innerHTML = assigned.length ? assigned.map(territory => `
        <div class="bg-white/5 rounded-lg p-4 border border-white/10">
          <div class="flex justify-between items-start">
            <div>
              <h4 class="text-white font-medium">${territory.name}</h4>
              <p class="text-blue-100 text-sm">Population: ${territory.population?.toLocaleString() || 'N/A'}</p>
              <p class="text-blue-100 text-sm">Market Size: ${territory.market_size || 'N/A'}</p>
            </div>
            <div class="text-right">
              <span class="inline-block px-2 py-1 bg-red-600 text-white text-xs rounded-full">Assigned</span>
            </div>
          </div>
        </div>
      `).join('') : '<div class="text-blue-100 text-center py-4">No assigned territories</div>';
    }

    // Render interactive map
    function renderMap() {
      const mapContainer = document.getElementById('territory-map');
      
      // Create a simple visual map representation
      const mapHtml = `
        <div class="relative w-full h-full bg-gradient-to-br from-green-800 to-green-900 rounded-lg overflow-hidden">
          <div class="absolute inset-0 opacity-20">
            <svg viewBox="0 0 400 300" class="w-full h-full">
              <!-- Colorado outline -->
              <path d="M50 50 L350 50 L350 250 L50 250 Z" fill="none" stroke="rgba(255,255,255,0.3)" stroke-width="2"/>
              
              <!-- Territory boundaries -->
              ${territories.map((territory, index) => {
                const x = 60 + (index % 4) * 70;
                const y = 70 + Math.floor(index / 4) * 60;
                const color = territory.assigned_to ? '#ef4444' : '#22c55e';
                
                return `
                  <rect x="${x}" y="${y}" width="60" height="40" 
                        fill="${color}" opacity="0.6" 
                        stroke="white" stroke-width="1"
                        class="territory-rect cursor-pointer hover:opacity-80"
                        data-territory-id="${territory.id}"
                        data-territory-name="${territory.name}"
                        data-assigned="${territory.assigned_to ? 'true' : 'false'}">
                  </rect>
                  <text x="${x + 30}" y="${y + 25}" 
                        fill="white" text-anchor="middle" 
                        font-size="8" font-weight="bold">
                    ${territory.name.split(' ')[0]}
                  </text>
                `;
              }).join('')}
            </svg>
          </div>
          
          <!-- Map Legend -->
          <div class="absolute bottom-4 left-4 bg-black/50 rounded-lg p-3">
            <div class="text-white text-sm font-medium mb-2">Legend</div>
            <div class="flex items-center mb-1">
              <div class="w-4 h-4 bg-green-500 rounded mr-2"></div>
              <span class="text-white text-xs">Available</span>
            </div>
            <div class="flex items-center">
              <div class="w-4 h-4 bg-red-500 rounded mr-2"></div>
              <span class="text-white text-xs">Assigned</span>
            </div>
          </div>
          
          <!-- Map Title -->
          <div class="absolute top-4 left-4 text-white">
            <h3 class="text-lg font-bold">Colorado Territory Map</h3>
            <p class="text-sm opacity-75">Click territories for details</p>
          </div>
        </div>
      `;
      
      mapContainer.innerHTML = mapHtml;
      
      // Add click handlers for territories
      mapContainer.querySelectorAll('.territory-rect').forEach(rect => {
        rect.addEventListener('click', (e) => {
          const territoryId = e.target.getAttribute('data-territory-id');
          const territoryName = e.target.getAttribute('data-territory-name');
          const isAssigned = e.target.getAttribute('data-assigned') === 'true';
          
          alert(`Territory: ${territoryName}\nStatus: ${isAssigned ? 'Assigned' : 'Available'}`);
        });
      });
    }

    // Update stats
    function updateStats() {
      const totalTerritories = territories.length;
      const assignedCount = territories.filter(t => t.assigned_to).length;
      const availableCount = totalTerritories - assignedCount;
      const totalPopulation = territories.reduce((sum, t) => sum + (t.population || 0), 0);
      
      document.getElementById('total-territories').textContent = totalTerritories;
      document.getElementById('assigned-count').textContent = assignedCount;
      document.getElementById('available-count').textContent = availableCount;
      document.getElementById('total-population').textContent = totalPopulation.toLocaleString();
    }

    // Initialize
    loadTerritories();
  </script>
</Layout>