---
import SecureLayout from '../../layouts/SecureLayout.astro';
import ProtectedRoute from '../../components/ProtectedRoute.astro';
---

<ProtectedRoute>
  <SecureLayout title="Territory Manager Dashboard - Black Canyon Tickets">
    <div class="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900">
      <!-- Header -->
      <div class="bg-white/10 backdrop-blur-sm border-b border-white/20">
        <div class="container mx-auto px-4 py-6">
          <div class="flex justify-between items-center">
            <div>
              <h1 class="text-3xl font-bold text-white">Territory Manager Dashboard</h1>
              <p class="text-blue-100" id="welcome-message">Welcome back, Territory Manager!</p>
            </div>
            <div class="flex items-center space-x-4">
              <div class="bg-white/10 backdrop-blur-sm rounded-lg px-4 py-2 border border-white/20">
                <div class="text-sm text-blue-100">Territory</div>
                <div class="text-white font-medium" id="territory-name">Loading...</div>
              </div>
              <div class="bg-white/10 backdrop-blur-sm rounded-lg px-4 py-2 border border-white/20">
                <div class="text-sm text-blue-100">Rank</div>
                <div class="text-white font-medium">#<span id="current-rank">-</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="container mx-auto px-4 py-8">
        <!-- Development Disclaimer -->
        <div class="mb-8 max-w-4xl mx-auto bg-orange-500/10 border border-orange-500/20 rounded-lg p-4">
          <div class="text-orange-300 text-sm">
            <strong>⚠️ Development Feature:</strong> This Territory Manager system is currently in development and may not be fully functional. Some features may not work as expected.
          </div>
        </div>
        
        <!-- Stats Cards -->
        <div class="grid md:grid-cols-4 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-3xl font-bold text-white" id="total-earnings">$0</div>
                <div class="text-blue-100">Total Earnings</div>
              </div>
              <div class="text-4xl">💰</div>
            </div>
            <div class="mt-2 text-sm text-green-400" id="earnings-change">+$0 this month</div>
          </div>
          
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-3xl font-bold text-white" id="events-referred">0</div>
                <div class="text-blue-100">Events Referred</div>
              </div>
              <div class="text-4xl">🎫</div>
            </div>
            <div class="mt-2 text-sm text-blue-400" id="events-change">+0 this month</div>
          </div>
          
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-3xl font-bold text-white" id="success-rate">0%</div>
                <div class="text-blue-100">Success Rate</div>
              </div>
              <div class="text-4xl">📈</div>
            </div>
            <div class="mt-2 text-sm text-purple-400" id="rate-change">+0% this month</div>
          </div>
          
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-3xl font-bold text-white" id="pending-payouts">0</div>
                <div class="text-blue-100">Pending Payouts</div>
              </div>
              <div class="text-4xl">⏳</div>
            </div>
            <div class="mt-2 text-sm text-yellow-400" id="payout-amount">$0 pending</div>
          </div>
        </div>

        <!-- Quick Actions -->
        <div class="grid md:grid-cols-3 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
            <div class="text-4xl mb-4">📝</div>
            <h3 class="text-xl font-bold text-white mb-2">Submit a Lead</h3>
            <p class="text-blue-100 mb-4">Add a new event lead to your pipeline</p>
            <button onclick="window.location.href='/territory-manager/leads/new'" class="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg transition-all duration-200">
              Add Lead
            </button>
          </div>
          
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
            <div class="text-4xl mb-4">🔗</div>
            <h3 class="text-xl font-bold text-white mb-2">Generate Referral Link</h3>
            <p class="text-blue-100 mb-4">Create a custom referral link for events</p>
            <button onclick="generateReferralLink()" class="bg-gradient-to-r from-green-500 to-blue-600 hover:from-green-600 hover:to-blue-700 text-white px-6 py-3 rounded-lg transition-all duration-200">
              Generate Link
            </button>
          </div>
          
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 text-center">
            <div class="text-4xl mb-4">📊</div>
            <h3 class="text-xl font-bold text-white mb-2">View Reports</h3>
            <p class="text-blue-100 mb-4">Check your earnings and performance</p>
            <button onclick="window.location.href='/territory-manager/reports'" class="bg-gradient-to-r from-purple-500 to-pink-600 hover:from-purple-600 hover:to-pink-700 text-white px-6 py-3 rounded-lg transition-all duration-200">
              View Reports
            </button>
          </div>
        </div>

        <!-- Main Content Grid -->
        <div class="grid lg:grid-cols-2 gap-8">
          <!-- Recent Activity -->
          <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">Recent Activity</h3>
            <div class="space-y-4" id="recent-activity">
              <!-- Activity items will be loaded here -->
            </div>
            <div class="mt-4 text-center">
              <a href="/territory-manager/activity" class="text-blue-400 hover:text-blue-300 text-sm">View All Activity</a>
            </div>
          </div>

          <!-- Earnings Chart -->
          <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">Earnings Overview</h3>
            <canvas id="earnings-chart" class="w-full h-64"></canvas>
          </div>

          <!-- Active Leads -->
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-xl font-bold text-white">Active Leads</h3>
              <a href="/territory-manager/leads" class="text-blue-400 hover:text-blue-300 text-sm">View All</a>
            </div>
            <div class="space-y-3" id="active-leads">
              <!-- Lead items will be loaded here -->
            </div>
          </div>

          <!-- Achievements -->
          <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">Recent Achievements</h3>
            <div class="space-y-3" id="achievements">
              <!-- Achievement items will be loaded here -->
            </div>
            <div class="mt-4 text-center">
              <a href="/territory-manager/achievements" class="text-blue-400 hover:text-blue-300 text-sm">View All Achievements</a>
            </div>
          </div>
        </div>

        <!-- Notifications -->
        <div class="mt-8 bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold text-white">Notifications</h3>
            <button onclick="markAllAsRead()" class="text-blue-400 hover:text-blue-300 text-sm">Mark All Read</button>
          </div>
          <div class="space-y-3" id="notifications">
            <!-- Notification items will be loaded here -->
          </div>
        </div>
      </div>
    </div>

    <!-- Referral Link Modal -->
    <div id="referral-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center hidden z-50">
      <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20 max-w-md w-full mx-4">
        <h2 class="text-2xl font-bold text-white mb-4">Referral Link Generated</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-white text-sm font-medium mb-2">Your Referral Link</label>
            <div class="flex">
              <input type="text" id="referral-link" readonly class="flex-1 px-4 py-2 bg-white/10 border border-white/20 rounded-l-lg text-white">
              <button onclick="copyReferralLink()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-r-lg transition-colors duration-200">
                Copy
              </button>
            </div>
          </div>
          <div>
            <label class="block text-white text-sm font-medium mb-2">QR Code</label>
            <div class="bg-white p-4 rounded-lg">
              <div id="qr-code" class="w-32 h-32 bg-gray-200 mx-auto flex items-center justify-center">
                QR Code
              </div>
            </div>
          </div>
        </div>
        <div class="flex justify-end mt-6">
          <button onclick="closeReferralModal()" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors duration-200">
            Close
          </button>
        </div>
      </div>
    </div>

    <script>
      let territoryManagerData = null;
      let chartInstance = null;

      // Load dashboard data using the centralized router
      async function loadDashboardData() {
        try {
          const { territoryManagerRouter } = await import('../../lib/territory-manager-router');
          const data = await territoryManagerRouter.loadDashboard();
          
          if (data.error) {
            console.error('Dashboard error:', data.error);
            return;
          }
          
          territoryManagerData = data;
          updateDashboard(data);
        } catch (error) {
          console.error('Error loading dashboard data:', error);
        }
      }

      // Update dashboard with data
      function updateDashboard(data) {
        // Update welcome message
        document.getElementById('welcome-message').textContent = `Welcome back, ${data.profile?.full_name || 'Territory Manager'}!`;
        
        // Update territory name
        document.getElementById('territory-name').textContent = data.territory?.name || 'Unassigned';
        
        // Update stats
        document.getElementById('total-earnings').textContent = `$${data.stats.total_commission.toLocaleString()}`;
        document.getElementById('events-referred').textContent = data.stats.total_events_referred;
        document.getElementById('success-rate').textContent = `${Math.round(data.stats.success_rate * 100)}%`;
        document.getElementById('pending-payouts').textContent = data.stats.pending_payouts;
        document.getElementById('current-rank').textContent = data.stats.rank;
        
        // Update changes
        document.getElementById('earnings-change').textContent = `+$${data.stats.current_month_commission.toLocaleString()} this month`;
        document.getElementById('payout-amount').textContent = `$${data.stats.pending_payouts * 0.40} pending`;
        
        // Load recent activity
        loadRecentActivity(data.recent_activity || []);
        
        // Load active leads
        loadActiveLeads(data.active_leads || []);
        
        // Load achievements
        loadAchievements(data.achievements || []);
        
        // Load notifications
        loadNotifications(data.notifications || []);
        
        // Update earnings chart
        updateEarningsChart(data.earnings_history || []);
      }

      // Load recent activity
      function loadRecentActivity(activities) {
        const container = document.getElementById('recent-activity');
        container.innerHTML = activities.length ? activities.map(activity => `
          <div class="flex items-center space-x-3 p-3 bg-white/5 rounded-lg">
            <div class="text-2xl">${getActivityIcon(activity.type)}</div>
            <div class="flex-1">
              <div class="text-white text-sm">${activity.message}</div>
              <div class="text-blue-100 text-xs">${new Date(activity.created_at).toLocaleDateString()}</div>
            </div>
          </div>
        `).join('') : '<div class="text-blue-100 text-center py-4">No recent activity</div>';
      }

      // Load active leads
      function loadActiveLeads(leads) {
        const container = document.getElementById('active-leads');
        container.innerHTML = leads.length ? leads.map(lead => `
          <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
            <div>
              <div class="text-white font-medium">${lead.event_name}</div>
              <div class="text-blue-100 text-sm">${lead.organizer_contact.name}</div>
            </div>
            <div class="text-right">
              <div class="text-sm px-2 py-1 rounded-full ${getStatusColor(lead.status)}">${lead.status}</div>
            </div>
          </div>
        `).join('') : '<div class="text-blue-100 text-center py-4">No active leads</div>';
      }

      // Load achievements
      function loadAchievements(achievements) {
        const container = document.getElementById('achievements');
        container.innerHTML = achievements.length ? achievements.map(achievement => `
          <div class="flex items-center space-x-3 p-3 bg-white/5 rounded-lg">
            <div class="text-2xl">🏆</div>
            <div class="flex-1">
              <div class="text-white font-medium">${achievement.name}</div>
              <div class="text-blue-100 text-sm">${achievement.description}</div>
            </div>
            <div class="text-green-400 text-sm">+$${achievement.reward_amount}</div>
          </div>
        `).join('') : '<div class="text-blue-100 text-center py-4">No achievements yet</div>';
      }

      // Load notifications
      function loadNotifications(notifications) {
        const container = document.getElementById('notifications');
        container.innerHTML = notifications.length ? notifications.map(notification => `
          <div class="flex items-center space-x-3 p-3 bg-white/5 rounded-lg ${notification.read ? 'opacity-60' : ''}">
            <div class="text-2xl">${getNotificationIcon(notification.type)}</div>
            <div class="flex-1">
              <div class="text-white font-medium">${notification.title}</div>
              <div class="text-blue-100 text-sm">${notification.message}</div>
            </div>
            <div class="text-blue-200 text-xs">${new Date(notification.created_at).toLocaleDateString()}</div>
          </div>
        `).join('') : '<div class="text-blue-100 text-center py-4">No notifications</div>';
      }

      // Update earnings chart
      function updateEarningsChart(data) {
        const ctx = document.getElementById('earnings-chart').getContext('2d');
        
        if (chartInstance) {
          chartInstance.destroy();
        }

        chartInstance = new Chart(ctx, {
          type: 'line',
          data: {
            labels: data.map(d => new Date(d.date).toLocaleDateString()),
            datasets: [{
              label: 'Monthly Earnings',
              data: data.map(d => d.amount),
              borderColor: 'rgb(59, 130, 246)',
              backgroundColor: 'rgba(59, 130, 246, 0.1)',
              tension: 0.4
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                labels: {
                  color: 'white'
                }
              }
            },
            scales: {
              x: {
                ticks: {
                  color: 'rgba(255, 255, 255, 0.7)'
                },
                grid: {
                  color: 'rgba(255, 255, 255, 0.1)'
                }
              },
              y: {
                ticks: {
                  color: 'rgba(255, 255, 255, 0.7)',
                  callback: function(value) {
                    return '$' + value.toLocaleString();
                  }
                },
                grid: {
                  color: 'rgba(255, 255, 255, 0.1)'
                }
              }
            }
          }
        });
      }

      // Generate referral link using the centralized router
      async function generateReferralLink() {
        try {
          const { territoryManagerRouter } = await import('../../lib/territory-manager-router');
          const result = await territoryManagerRouter.generateReferralLink();
          
          if (result.success && result.referralLink) {
            document.getElementById('referral-link').value = result.referralLink.url;
            document.getElementById('referral-modal').classList.remove('hidden');
          } else {
            console.error('Failed to generate referral link:', result.error);
          }
        } catch (error) {
          console.error('Error generating referral link:', error);
        }
      }

      // Copy referral link
      function copyReferralLink() {
        const linkInput = document.getElementById('referral-link');
        linkInput.select();
        document.execCommand('copy');
        
        // Show feedback
        const copyBtn = event.target;
        const originalText = copyBtn.textContent;
        copyBtn.textContent = 'Copied!';
        copyBtn.classList.add('bg-green-600');
        
        setTimeout(() => {
          copyBtn.textContent = originalText;
          copyBtn.classList.remove('bg-green-600');
        }, 2000);
      }

      // Close referral modal
      function closeReferralModal() {
        document.getElementById('referral-modal').classList.add('hidden');
      }

      // Mark all notifications as read using the centralized router
      async function markAllAsRead() {
        try {
          const { territoryManagerRouter } = await import('../../lib/territory-manager-router');
          const result = await territoryManagerRouter.markAllNotificationsAsRead();
          
          if (result.success) {
            loadDashboardData();
          } else {
            console.error('Failed to mark notifications as read:', result.error);
          }
        } catch (error) {
          console.error('Error marking notifications as read:', error);
        }
      }

      // Utility functions
      function getActivityIcon(type) {
        const icons = {
          'lead_created': '📝',
          'event_converted': '🎉',
          'payout_received': '💰',
          'achievement_earned': '🏆'
        };
        return icons[type] || '📋';
      }

      function getStatusColor(status) {
        const colors = {
          'cold': 'bg-gray-600 text-white',
          'contacted': 'bg-blue-600 text-white',
          'confirmed': 'bg-green-600 text-white',
          'converted': 'bg-purple-600 text-white',
          'dead': 'bg-red-600 text-white'
        };
        return colors[status] || 'bg-gray-600 text-white';
      }

      function getNotificationIcon(type) {
        const icons = {
          'payout': '💰',
          'achievement': '🏆',
          'lead_update': '📝',
          'system': '🔔'
        };
        return icons[type] || '📋';
      }

      // Initialize dashboard
      loadDashboardData();
    </script>

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  </SecureLayout>
</ProtectedRoute>