---
import Layout from '../../layouts/Layout.astro';
import { createSupabaseServerClient } from '../../lib/supabase-ssr';

// Enable server-side rendering for auth checks
export const prerender = false;

// Server-side super admin authentication check using SSR client
const supabase = createSupabaseServerClient(Astro.cookies);
const { data: { session }, error: sessionError } = await supabase.auth.getSession();

if (sessionError || !session) {
  console.error('Super dashboard auth error: No session found');
  return Astro.redirect('/login?redirect=' + encodeURIComponent('/admin/super-dashboard'));
}

// Check if user is super admin
const { data: userRecord } = await supabase
  .from('users')
  .select('role, organization_id, is_super_admin')
  .eq('id', session.user.id)
  .single();

if (!userRecord || userRecord.role !== 'admin' || !userRecord.is_super_admin) {
  console.error('Super dashboard auth error: User is not super admin');
  return Astro.redirect('/login?redirect=' + encodeURIComponent('/admin/super-dashboard'));
}

const auth = {
  user: session.user,
  session,
  isAdmin: true,
  isSuperAdmin: true,
  organizationId: userRecord.organization_id
};
---

<Layout title="Super Admin Dashboard - Portal">
  <div class="min-h-screen bg-gradient-to-br from-indigo-900 via-purple-900 to-slate-900 relative overflow-hidden">
    <!-- Animated background elements -->
    <div class="absolute inset-0 overflow-hidden">
      <div class="absolute -top-1/2 -left-1/2 w-full h-full bg-gradient-to-br from-blue-500/20 to-transparent rounded-full animate-pulse"></div>
      <div class="absolute -bottom-1/2 -right-1/2 w-full h-full bg-gradient-to-tl from-purple-500/20 to-transparent rounded-full animate-pulse" style="animation-delay: 2s;"></div>
    </div>

    <!-- Subtle grid pattern -->
    <div class="absolute inset-0 opacity-5">
      <svg width="100" height="100" viewBox="0 0 100 100" class="w-full h-full">
        <pattern id="grid" width="100" height="100" patternUnits="userSpaceOnUse">
          <path d="M 100 0 L 0 0 0 100" fill="none" stroke="currentColor" stroke-width="1"/>
        </pattern>
        <rect width="100%" height="100%" fill="url(#grid)" />
      </svg>
    </div>

    <!-- Sticky Navigation -->
    <nav class="sticky top-0 z-50 bg-white/10 backdrop-blur-xl shadow-xl border-b border-white/20">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-20">
          <div class="flex items-center space-x-8">
            <a href="/admin/super-dashboard" class="flex items-center">
              <span class="text-xl font-light text-white">
                <span class="font-bold">P</span>ortal
              </span>
              <span class="ml-2 px-2 py-1 bg-gradient-to-r from-red-500 to-orange-500 text-white rounded-md text-xs font-medium">Super Admin</span>
            </a>
          </div>
          <div class="flex items-center space-x-4">
            <a href="/admin/dashboard" class="bg-white/10 backdrop-blur-xl border border-white/20 hover:bg-white/20 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105">
              Admin View
            </a>
            <a href="/dashboard" class="bg-white/10 backdrop-blur-xl border border-white/20 hover:bg-white/20 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105">
              Organizer View
            </a>
            <span id="user-name" class="text-sm text-white font-medium"></span>
            <button id="logout-btn" class="bg-white/10 backdrop-blur-xl border border-white/20 hover:bg-white/20 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105">
              Sign Out
            </button>
          </div>
        </div>
      </div>
    </nav>

    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8 relative z-10">
      <div class="px-4 py-6 sm:px-0">
        <!-- Page Header -->
        <div class="mb-8">
          <h2 class="text-4xl md:text-5xl font-light text-white tracking-wide">Business Intelligence</h2>
          <p class="text-white/80 mt-2 text-lg font-light">Platform-wide analytics and performance insights</p>
        </div>

        <!-- Key Metrics Dashboard -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div id="revenue-card" class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-gradient-to-br from-green-500/20 to-emerald-500/20 rounded-xl flex items-center justify-center">
                <svg class="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path>
                </svg>
              </div>
              <div class="text-right">
                <p class="text-sm font-medium text-white/80">Platform Revenue</p>
                <p id="total-revenue" class="text-2xl font-light text-white">$0.00</p>
                <p id="revenue-change" class="text-sm text-green-400">+0% vs last month</p>
              </div>
            </div>
          </div>

          <div id="fees-card" class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-gradient-to-br from-purple-500/20 to-pink-500/20 rounded-xl flex items-center justify-center">
                <svg class="w-6 h-6 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                </svg>
              </div>
              <div class="text-right">
                <p class="text-sm font-medium text-white/80">Platform Fees</p>
                <p id="total-fees" class="text-2xl font-light text-white">$0.00</p>
                <p id="fees-change" class="text-sm text-purple-400">+0% vs last month</p>
              </div>
            </div>
          </div>

          <div id="organizers-card" class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-gradient-to-br from-blue-500/20 to-cyan-500/20 rounded-xl flex items-center justify-center">
                <svg class="w-6 h-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                </svg>
              </div>
              <div class="text-right">
                <p class="text-sm font-medium text-white/80">Active Organizers</p>
                <p id="active-organizers" class="text-2xl font-light text-white">0</p>
                <p id="organizers-change" class="text-sm text-blue-400">+0 this month</p>
              </div>
            </div>
          </div>

          <div id="tickets-card" class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
              <div class="w-12 h-12 bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-xl flex items-center justify-center">
                <svg class="w-6 h-6 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"></path>
                </svg>
              </div>
              <div class="text-right">
                <p class="text-sm font-medium text-white/80">Tickets Sold</p>
                <p id="total-tickets" class="text-2xl font-light text-white">0</p>
                <p id="tickets-change" class="text-sm text-yellow-400">+0 this month</p>
              </div>
            </div>
          </div>
        </div>

        <!-- Navigation Tabs -->
        <div class="mb-6">
          <nav class="flex space-x-8 border-b border-white/20">
            <button id="tab-analytics" class="tab-button border-b-2 border-indigo-400 text-white bg-white/10 py-2 px-4 text-sm font-medium transition-all duration-200 rounded-t-lg">
              Analytics
            </button>
            <button id="tab-revenue" class="tab-button border-b-2 border-transparent text-white/80 hover:text-white py-2 px-4 text-sm font-medium transition-all duration-200 hover:bg-white/10 rounded-t-lg">
              Revenue
            </button>
            <button id="tab-events" class="tab-button border-b-2 border-transparent text-white/80 hover:text-white py-2 px-4 text-sm font-medium transition-all duration-200 hover:bg-white/10 rounded-t-lg">
              Events
            </button>
            <button id="tab-organizers" class="tab-button border-b-2 border-transparent text-white/80 hover:text-white py-2 px-4 text-sm font-medium transition-all duration-200 hover:bg-white/10 rounded-t-lg">
              Organizers
            </button>
            <button id="tab-management" class="tab-button border-b-2 border-transparent text-white/80 hover:text-white py-2 px-4 text-sm font-medium transition-all duration-200 hover:bg-white/10 rounded-t-lg">
              Management
            </button>
          </nav>
        </div>

        <!-- Tab Content -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 shadow-lg rounded-2xl">
          <div id="content-analytics" class="tab-content p-6">
            <h3 class="text-2xl font-light text-white mb-6">Platform Analytics</h3>
            <div class="text-white/60">Analytics data loading...</div>
          </div>
          
          <div id="content-revenue" class="tab-content p-6 hidden">
            <h3 class="text-2xl font-light text-white mb-6">Revenue & Performance</h3>
            <div class="text-white/60">Revenue data loading...</div>
          </div>
          
          <div id="content-events" class="tab-content p-6 hidden">
            <h3 class="text-2xl font-light text-white mb-6">Events & Tickets</h3>
            <div class="text-white/60">Events data loading...</div>
          </div>
          
          <div id="content-organizers" class="tab-content p-6 hidden">
            <h3 class="text-2xl font-light text-white mb-6">Organizers</h3>
            <div class="text-white/60">Organizer data loading...</div>
          </div>
          
          <div id="content-management" class="tab-content p-6 hidden">
            <h3 class="text-2xl font-light text-white mb-6">Management</h3>
            <div class="text-white/60">Management tools loading...</div>
          </div>
        </div>
      </div>
    </main>
  </div>

  <script>
    import { adminApi } from '../../lib/admin-api-router';
    
    let currentTab = 'analytics';
    let apiInitialized = false;
    
    // Initialize admin API on page load
    async function initializeAdminApi() {
      if (!apiInitialized) {
        const initialized = await adminApi.initialize();
        if (!initialized) {
          console.error('Failed to initialize admin API');
          return false;
        }
        apiInitialized = true;
      }
      return true;
    }
    
    // Tab switching functionality
    function switchTab(tabName) {
      // Update tab buttons
      document.querySelectorAll('.tab-button').forEach(btn => {
        btn.classList.remove('border-indigo-400', 'text-white', 'bg-white/10');
        btn.classList.add('border-transparent', 'text-white/80');
      });
      
      const tabButton = document.getElementById(`tab-${tabName}`);
      if (tabButton) {
        tabButton.classList.remove('border-transparent', 'text-white/80');
        tabButton.classList.add('border-indigo-400', 'text-white', 'bg-white/10');
      }

      // Update tab content
      document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.add('hidden');
      });
      
      const tabContent = document.getElementById(`content-${tabName}`);
      if (tabContent) {
        tabContent.classList.remove('hidden');
      }
      currentTab = tabName;
      
      // Load data for the selected tab
      loadTabData(tabName);
    }

    // Load data for specific tab
    async function loadTabData(tabName) {
      try {
        // Ensure admin API is initialized
        const initialized = await initializeAdminApi();
        if (!initialized) {
          throw new Error('Failed to initialize admin API');
        }
        
        const session = adminApi.getSession();
        if (!session) {
          throw new Error('Not authenticated');
        }

        const token = session.access_token;
        const contentElement = document.getElementById(`content-${tabName}`);
        
        if (!contentElement) return;

        // Show loading state
        contentElement.innerHTML = `
          <h3 class="text-2xl font-light text-white mb-6">${getTabTitle(tabName)}</h3>
          <div class="flex items-center justify-center py-8">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
            <span class="ml-3 text-white/60">Loading ${tabName} data...</span>
          </div>
        `;

        // Determine metric based on tab
        let metric = '';
        switch (tabName) {
          case 'analytics':
            metric = 'platform_overview';
            break;
          case 'revenue':
            metric = 'revenue_breakdown';
            break;
          case 'events':
            metric = 'event_analytics';
            break;
          case 'organizers':
            metric = 'organizer_performance';
            break;
          case 'management':
            // For management tab, show management tools instead of analytics
            renderManagementTools(contentElement);
            return;
        }

        // Use adminApi to fetch data
        console.log(`Loading ${tabName} data with metric: ${metric}`);
        const data = await adminApi.getSuperAnalytics(metric);
        console.log(`Response for ${tabName}:`, data);
        
        if (!data.success) {
          const errorDetails = data.details ? JSON.stringify(data.details) : '';
          throw new Error(`${data.error || 'Failed to load data'} ${errorDetails}`);
        }

        // Render the data based on tab type
        renderTabData(tabName, data.data, contentElement);

      } catch (error) {
        console.error(`Error loading ${tabName} data:`, error);
        const contentElement = document.getElementById(`content-${tabName}`);
        if (contentElement) {
          let errorMessage = error.message;
          let errorTitle = 'Error Loading Data';
          
          if (error.name === 'AbortError') {
            errorTitle = 'Request Timeout';
            errorMessage = 'The request took too long to complete. The server may be unavailable or experiencing issues.';
          }
          
          contentElement.innerHTML = `
            <h3 class="text-2xl font-light text-white mb-6">${getTabTitle(tabName)}</h3>
            <div class="bg-red-500/20 border border-red-400/50 rounded-lg p-4">
              <p class="text-red-200 font-medium">${errorTitle}</p>
              <p class="text-red-300/80 text-sm mt-1">${errorMessage}</p>
              <details class="mt-2">
                <summary class="text-red-300/60 text-xs cursor-pointer">Debug Info</summary>
                <div class="mt-2 p-2 bg-black/20 rounded text-xs text-red-300/60">
                  <p>Tab: ${tabName}</p>
                  <p>Host: ${window.location.host}</p>
                  <p>Protocol: ${window.location.protocol}</p>
                  <p>Token: ${token ? 'Present' : 'Missing'}</p>
                  <p>Error Type: ${error.name}</p>
                </div>
              </details>
              <button onclick="loadTabData('${tabName}')" class="mt-4 glass-button text-white px-4 py-2 rounded-lg text-sm">
                Retry
              </button>
            </div>
          `;
        }
      }
    }

    // Helper function to get tab title
    function getTabTitle(tabName) {
      const titles = {
        'analytics': 'Platform Analytics',
        'revenue': 'Revenue & Performance',
        'events': 'Events & Tickets',
        'organizers': 'Organizers',
        'management': 'Management'
      };
      return titles[tabName] || tabName;
    }

    // Render management tools
    function renderManagementTools(contentElement) {
      contentElement.innerHTML = `
        <h3 class="text-2xl font-light text-white mb-6">Management</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div class="glass-card p-6">
            <h4 class="text-lg font-medium text-white mb-3">System Health</h4>
            <p class="text-glass-tertiary mb-4">Monitor system performance and health metrics</p>
            <button onclick="handleSystemStatus()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full">
              View System Status
            </button>
          </div>
          <div class="glass-card p-6">
            <h4 class="text-lg font-medium text-white mb-3">Database Tools</h4>
            <p class="text-glass-tertiary mb-4">Manage database maintenance and backups</p>
            <button onclick="handleDatabaseAdmin()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full">
              Database Admin
            </button>
          </div>
          <div class="glass-card p-6">
            <h4 class="text-lg font-medium text-white mb-3">User Management</h4>
            <p class="text-glass-tertiary mb-4">Manage user accounts and permissions</p>
            <button onclick="handleUserManagement()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full">
              User Admin
            </button>
          </div>
          <div class="glass-card p-6">
            <h4 class="text-lg font-medium text-white mb-3">Platform Settings</h4>
            <p class="text-glass-tertiary mb-4">Configure platform-wide settings and features</p>
            <button onclick="handlePlatformSettings()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full">
              Platform Config
            </button>
          </div>
          <div class="glass-card p-6">
            <h4 class="text-lg font-medium text-white mb-3">Email Templates</h4>
            <p class="text-glass-tertiary mb-4">Manage email templates and notifications</p>
            <button onclick="handleEmailTemplates()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full">
              Email Manager
            </button>
          </div>
          <div class="glass-card p-6">
            <h4 class="text-lg font-medium text-white mb-3">Security Logs</h4>
            <p class="text-glass-tertiary mb-4">View security logs and audit trails</p>
            <button onclick="handleSecurityLogs()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full">
              Security Center
            </button>
          </div>
        </div>
      `;
    }

    // Management button handlers - make them global
    window.handleSystemStatus = function() {
      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50';
      modal.innerHTML = `
        <div class="glass-card p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
          <h3 class="text-xl font-semibold text-white mb-4">System Health Status</h3>
          <div class="space-y-4">
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Database Status</span>
              <span class="text-success">Online</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">API Status</span>
              <span class="text-success">Healthy</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Storage</span>
              <span class="text-success">Available</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Memory Usage</span>
              <span class="text-warning">75%</span>
            </div>
          </div>
          <button onclick="this.closest('.fixed').remove()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full mt-4">
            Close
          </button>
        </div>
      `;
      document.body.appendChild(modal);
    }

    window.handleDatabaseAdmin = function() {
      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50';
      modal.innerHTML = `
        <div class="glass-card p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
          <h3 class="text-xl font-semibold text-white mb-4">Database Administration</h3>
          <div class="space-y-4">
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Total Tables</span>
              <span class="text-white">24</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Active Connections</span>
              <span class="text-white">12</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Storage Used</span>
              <span class="text-white">1.2 GB</span>
            </div>
            <div class="grid grid-cols-2 gap-4 mt-6">
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Run Backup
              </button>
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Optimize Tables
              </button>
            </div>
          </div>
          <button onclick="this.closest('.fixed').remove()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full mt-4">
            Close
          </button>
        </div>
      `;
      document.body.appendChild(modal);
    }

    window.handleUserManagement = function() {
      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50';
      modal.innerHTML = `
        <div class="glass-card p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
          <h3 class="text-xl font-semibold text-white mb-4">User Management</h3>
          <div class="space-y-4">
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Total Users</span>
              <span class="text-white">1,247</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Active Users (24h)</span>
              <span class="text-white">324</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Admin Users</span>
              <span class="text-white">8</span>
            </div>
            <div class="grid grid-cols-2 gap-4 mt-6">
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                View All Users
              </button>
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Add New User
              </button>
            </div>
          </div>
          <button onclick="this.closest('.fixed').remove()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full mt-4">
            Close
          </button>
        </div>
      `;
      document.body.appendChild(modal);
    }

    window.handlePlatformSettings = function() {
      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50';
      modal.innerHTML = `
        <div class="glass-card p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
          <h3 class="text-xl font-semibold text-white mb-4">Platform Settings</h3>
          <div class="space-y-4">
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Platform Name</span>
              <span class="text-white">Black Canyon Tickets</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Version</span>
              <span class="text-white">v2.1.0</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Maintenance Mode</span>
              <span class="text-success">Disabled</span>
            </div>
            <div class="grid grid-cols-2 gap-4 mt-6">
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Global Settings
              </button>
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Feature Flags
              </button>
            </div>
          </div>
          <button onclick="this.closest('.fixed').remove()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full mt-4">
            Close
          </button>
        </div>
      `;
      document.body.appendChild(modal);
    }

    window.handleEmailTemplates = function() {
      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50';
      modal.innerHTML = `
        <div class="glass-card p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
          <h3 class="text-xl font-semibold text-white mb-4">Email Templates</h3>
          <div class="space-y-4">
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Welcome Email</span>
              <span class="text-success">Active</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Ticket Confirmation</span>
              <span class="text-success">Active</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-glass-secondary">Password Reset</span>
              <span class="text-success">Active</span>
            </div>
            <div class="grid grid-cols-2 gap-4 mt-6">
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Edit Templates
              </button>
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Template Preview
              </button>
            </div>
          </div>
          <button onclick="this.closest('.fixed').remove()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full mt-4">
            Close
          </button>
        </div>
      `;
      document.body.appendChild(modal);
    }

    window.handleSecurityLogs = function() {
      const modal = document.createElement('div');
      modal.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50';
      modal.innerHTML = `
        <div class="glass-card p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
          <h3 class="text-xl font-semibold text-white mb-4">Security Logs</h3>
          <div class="space-y-4">
            <div class="bg-white/5 rounded-lg p-3">
              <div class="flex justify-between items-center">
                <span class="text-glass-secondary">Failed Login Attempts</span>
                <span class="text-error">23</span>
              </div>
              <div class="text-sm text-glass-tertiary mt-1">Last 24 hours</div>
            </div>
            <div class="bg-white/5 rounded-lg p-3">
              <div class="flex justify-between items-center">
                <span class="text-glass-secondary">Admin Actions</span>
                <span class="text-white">12</span>
              </div>
              <div class="text-sm text-glass-tertiary mt-1">Last 24 hours</div>
            </div>
            <div class="grid grid-cols-2 gap-4 mt-6">
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                View Full Log
              </button>
              <button class="glass-button text-white px-4 py-2 rounded-lg font-medium">
                Export Log
              </button>
            </div>
          </div>
          <button onclick="this.closest('.fixed').remove()" class="glass-button text-white px-4 py-2 rounded-lg font-medium w-full mt-4">
            Close
          </button>
        </div>
      `;
      document.body.appendChild(modal);
    }

    // Render tab data
    function renderTabData(tabName, data, contentElement) {
      switch (tabName) {
        case 'analytics':
          renderAnalyticsData(data, contentElement);
          break;
        case 'revenue':
          renderRevenueData(data, contentElement);
          break;
        case 'events':
          renderEventsData(data, contentElement);
          break;
        case 'organizers':
          renderOrganizersData(data, contentElement);
          break;
      }
    }

    // Render analytics data
    function renderAnalyticsData(data, contentElement) {
      const summary = data.summary || {};
      const topOrganizers = data.topOrganizers || [];
      const recentActivity = data.recentActivity || [];
      
      contentElement.innerHTML = `
        <h3 class="text-2xl font-light text-white mb-6">Platform Analytics</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.activeOrganizers || 0}</div>
            <div class="text-sm text-white/60">Active Organizers</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.totalEvents || 0}</div>
            <div class="text-sm text-white/60">Total Events</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.totalTickets || 0}</div>
            <div class="text-sm text-white/60">Tickets Sold</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${(summary.totalRevenue || 0).toFixed(2)}</div>
            <div class="text-sm text-white/60">Total Revenue</div>
          </div>
        </div>

        <!-- Additional Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${(summary.totalPlatformFees || 0).toFixed(2)}</div>
            <div class="text-sm text-white/60">Platform Fees</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.publishedEvents || 0}</div>
            <div class="text-sm text-white/60">Published Events</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${(summary.revenueGrowth || 0).toFixed(1)}%</div>
            <div class="text-sm text-white/60">Revenue Growth</div>
          </div>
        </div>

        <!-- Top Organizers -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6 mb-8">
          <h4 class="text-xl font-light text-white mb-4">Top Performing Organizers</h4>
          ${topOrganizers.length > 0 ? `
            <div class="space-y-3">
              ${topOrganizers.slice(0, 5).map(org => `
                <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                  <div>
                    <div class="text-white font-medium">${org.name}</div>
                    <div class="text-white/60 text-sm">${org.events} events • ${org.tickets} tickets</div>
                  </div>
                  <div class="text-right">
                    <div class="text-white font-medium">$${((org.revenue || 0) / 100).toFixed(2)}</div>
                    <div class="text-white/60 text-sm">Revenue</div>
                  </div>
                </div>
              `).join('')}
            </div>
          ` : `
            <div class="text-center py-8">
              <div class="text-white/60">No organizer data available</div>
            </div>
          `}
        </div>

        <!-- Recent Activity -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
          <h4 class="text-xl font-light text-white mb-4">Recent Activity</h4>
          ${recentActivity.length > 0 ? `
            <div class="space-y-3">
              ${recentActivity.slice(0, 8).map(activity => `
                <div class="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                  <div>
                    <div class="text-white font-medium">
                      ${activity.type === 'purchase' ? 'Purchase' : 
                        activity.type === 'event' ? 'Event Created' : 'Organization Joined'}
                    </div>
                    <div class="text-white/60 text-sm">
                      ${activity.type === 'purchase' ? `$${((activity.amount || 0) / 100).toFixed(2)}` : 
                        activity.type === 'event' ? activity.title : activity.name}
                    </div>
                  </div>
                  <div class="text-right">
                    <div class="text-white/60 text-sm">${new Date(activity.date).toLocaleDateString()}</div>
                  </div>
                </div>
              `).join('')}
            </div>
          ` : `
            <div class="text-center py-8">
              <div class="text-white/60">No recent activity</div>
            </div>
          `}
        </div>
      `;
    }

    // Render revenue data
    function renderRevenueData(data, contentElement) {
      const organizations = data.breakdown || [];
      const summary = data.totals || {};
      
      contentElement.innerHTML = `
        <h3 class="text-2xl font-light text-white mb-6">Revenue & Performance</h3>
        
        <!-- Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${((summary.grossRevenue || 0) / 100).toFixed(2)}</div>
            <div class="text-sm text-white/60">Total Gross Revenue</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${((summary.platformFees || 0) / 100).toFixed(2)}</div>
            <div class="text-sm text-white/60">Platform Fees</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${((summary.netRevenue || 0) / 100).toFixed(2)}</div>
            <div class="text-sm text-white/60">Net Revenue</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.transactionCount || 0}</div>
            <div class="text-sm text-white/60">Total Transactions</div>
          </div>
        </div>

        <!-- Revenue Breakdown by Organization -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
          <h4 class="text-xl font-light text-white mb-4">Revenue by Organization</h4>
          
          ${organizations.length > 0 ? `
            <div class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="border-b border-white/20">
                    <th class="text-left text-white font-medium py-3">Organization</th>
                    <th class="text-right text-white font-medium py-3">Gross Revenue</th>
                    <th class="text-right text-white font-medium py-3">Platform Fees</th>
                    <th class="text-right text-white font-medium py-3">Net Revenue</th>
                    <th class="text-right text-white font-medium py-3">Transactions</th>
                    <th class="text-right text-white font-medium py-3">Events</th>
                  </tr>
                </thead>
                <tbody>
                  ${organizations.map(org => `
                    <tr class="border-b border-white/10 hover:bg-white/5">
                      <td class="text-white py-3">${org.name}</td>
                      <td class="text-right text-white py-3">$${((org.grossRevenue || 0) / 100).toFixed(2)}</td>
                      <td class="text-right text-white py-3">$${((org.platformFees || 0) / 100).toFixed(2)}</td>
                      <td class="text-right text-white py-3">$${((org.netRevenue || 0) / 100).toFixed(2)}</td>
                      <td class="text-right text-white py-3">${org.transactionCount || 0}</td>
                      <td class="text-right text-white py-3">${org.eventCount || 0}</td>
                    </tr>
                  `).join('')}
                </tbody>
              </table>
            </div>
          ` : `
            <div class="text-center py-8">
              <div class="text-white/60">No revenue data available</div>
            </div>
          `}
        </div>
      `;
    }

    // Render events data
    function renderEventsData(data, contentElement) {
      const events = data.events || [];
      const summary = data.summary || {};
      
      contentElement.innerHTML = `
        <h3 class="text-2xl font-light text-white mb-6">Events & Tickets</h3>
        
        <!-- Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.totalEvents || 0}</div>
            <div class="text-sm text-white/60">Total Events</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.publishedEvents || 0}</div>
            <div class="text-sm text-white/60">Published Events</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.totalTicketsSold || 0}</div>
            <div class="text-sm text-white/60">Total Tickets Sold</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${(summary.avgSellThroughRate || 0).toFixed(1)}%</div>
            <div class="text-sm text-white/60">Avg Sell-Through Rate</div>
          </div>
        </div>

        <!-- Additional Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${((summary.totalRevenue || 0) / 100).toFixed(2)}</div>
            <div class="text-sm text-white/60">Total Event Revenue</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${((summary.avgTicketPrice || 0) / 100).toFixed(2)}</div>
            <div class="text-sm text-white/60">Average Ticket Price</div>
          </div>
        </div>

        <!-- Events Performance Table -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
          <h4 class="text-xl font-light text-white mb-4">Event Performance</h4>
          
          ${events.length > 0 ? `
            <div class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="border-b border-white/20">
                    <th class="text-left text-white font-medium py-3">Event</th>
                    <th class="text-center text-white font-medium py-3">Status</th>
                    <th class="text-right text-white font-medium py-3">Tickets Sold</th>
                    <th class="text-right text-white font-medium py-3">Capacity</th>
                    <th class="text-right text-white font-medium py-3">Sell-Through</th>
                    <th class="text-right text-white font-medium py-3">Revenue</th>
                    <th class="text-right text-white font-medium py-3">Avg Price</th>
                    <th class="text-right text-white font-medium py-3">Event Date</th>
                  </tr>
                </thead>
                <tbody>
                  ${events.map(event => `
                    <tr class="border-b border-white/10 hover:bg-white/5">
                      <td class="text-white py-3 max-w-xs truncate">${event.title}</td>
                      <td class="text-center py-3">
                        <span class="px-2 py-1 rounded-full text-xs ${event.isPublished ? 'bg-green-500/20 text-green-400' : 'bg-yellow-500/20 text-yellow-400'}">
                          ${event.isPublished ? 'Published' : 'Draft'}
                        </span>
                      </td>
                      <td class="text-right text-white py-3">${event.ticketsSold || 0}</td>
                      <td class="text-right text-white py-3">${event.totalCapacity || 0}</td>
                      <td class="text-right text-white py-3">${(event.sellThroughRate || 0).toFixed(1)}%</td>
                      <td class="text-right text-white py-3">$${((event.totalRevenue || 0) / 100).toFixed(2)}</td>
                      <td class="text-right text-white py-3">$${((event.avgTicketPrice || 0) / 100).toFixed(2)}</td>
                      <td class="text-right text-white py-3">${event.startTime ? new Date(event.startTime).toLocaleDateString() : 'TBD'}</td>
                    </tr>
                  `).join('')}
                </tbody>
              </table>
            </div>
          ` : `
            <div class="text-center py-8">
              <div class="text-white/60">No event data available</div>
            </div>
          `}
        </div>
      `;
    }

    // Render organizers data
    function renderOrganizersData(data, contentElement) {
      const organizers = data.organizers || [];
      const summary = data.summary || {};
      
      contentElement.innerHTML = `
        <h3 class="text-2xl font-light text-white mb-6">Organizers</h3>
        
        <!-- Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${summary.totalOrganizers || 0}</div>
            <div class="text-sm text-white/60">Total Organizers</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">${(summary.averageEventsPerOrganizer || 0).toFixed(1)}</div>
            <div class="text-sm text-white/60">Avg Events per Organizer</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${(summary.averageRevenuePerOrganizer || 0).toFixed(2)}</div>
            <div class="text-sm text-white/60">Avg Revenue per Organizer</div>
          </div>
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
            <div class="text-3xl font-light text-white">$${(summary.topPerformerRevenue || 0).toFixed(2)}</div>
            <div class="text-sm text-white/60">Top Performer Revenue</div>
          </div>
        </div>

        <!-- Organizer Performance Table -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-6">
          <h4 class="text-xl font-light text-white mb-4">Organizer Performance</h4>
          
          ${organizers.length > 0 ? `
            <div class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="border-b border-white/20">
                    <th class="text-left text-white font-medium py-3">Organizer</th>
                    <th class="text-right text-white font-medium py-3">Events</th>
                    <th class="text-right text-white font-medium py-3">Published</th>
                    <th class="text-right text-white font-medium py-3">Tickets Sold</th>
                    <th class="text-right text-white font-medium py-3">Total Revenue</th>
                    <th class="text-right text-white font-medium py-3">Platform Fees</th>
                    <th class="text-right text-white font-medium py-3">Avg/Event</th>
                    <th class="text-right text-white font-medium py-3">Joined</th>
                  </tr>
                </thead>
                <tbody>
                  ${organizers.map(org => `
                    <tr class="border-b border-white/10 hover:bg-white/5">
                      <td class="text-white py-3">${org.name}</td>
                      <td class="text-right text-white py-3">${org.eventCount || 0}</td>
                      <td class="text-right text-white py-3">${org.publishedEvents || 0}</td>
                      <td class="text-right text-white py-3">${org.ticketsSold || 0}</td>
                      <td class="text-right text-white py-3">$${(org.totalRevenue || 0).toFixed(2)}</td>
                      <td class="text-right text-white py-3">$${(org.platformFees || 0).toFixed(2)}</td>
                      <td class="text-right text-white py-3">$${(org.avgRevenuePerEvent || 0).toFixed(2)}</td>
                      <td class="text-right text-white py-3">${org.joinDate ? new Date(org.joinDate).toLocaleDateString() : 'N/A'}</td>
                    </tr>
                  `).join('')}
                </tbody>
              </table>
            </div>
          ` : `
            <div class="text-center py-8">
              <div class="text-white/60">No organizer data available</div>
            </div>
          `}
        </div>
      `;
    }

    // Add tab click listeners
    document.querySelectorAll('.tab-button').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const target = e.target as HTMLElement;
        if (target && target.id) {
          const tabName = target.id.replace('tab-', '');
          switchTab(tabName);
        }
      });
    });

    // Initialize dashboard
    async function initializeDashboard() {
      try {
        const initialized = await adminApi.initialize();
        if (!initialized) {
          window.location.href = '/';
          return;
        }

        const userInfo = adminApi.getUserInfo();
        const userNameSpan = document.getElementById('user-name');
        if (userInfo && userNameSpan) {
          userNameSpan.textContent = userInfo.name || userInfo.email;
        }

        // Set up logout button
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) {
          logoutBtn.addEventListener('click', async () => {
            await adminApi.signOut();
            window.location.href = '/';
          });
        }

        // Load initial tab data
        loadTabData(currentTab);

      } catch (error) {
        console.error('Failed to initialize dashboard:', error);
        window.location.href = '/';
      }
    }

    // Initialize when page loads
    initializeDashboard();

    // Check admin authentication
    async function checkAdminAuth() {
      const initialized = await adminApi.initialize();
      if (!initialized) {
        window.location.href = '/';
        return false;
      }

      const userInfo = adminApi.getUserInfo();
      if (userInfo) {
        document.getElementById('user-name').textContent = userInfo.name || userInfo.email;
      }

      return true;
    }

    // Load platform metrics
    async function loadPlatformMetrics() {
      try {
        const result = await adminApi.getSuperAnalytics('platform_overview');
        
        if (result.success) {
          const data = result.data.summary;
          document.getElementById('total-revenue').textContent = `$${(data.totalRevenue || 0).toLocaleString()}`;
          document.getElementById('total-fees').textContent = `$${(data.totalPlatformFees || 0).toLocaleString()}`;
          document.getElementById('active-organizers').textContent = data.activeOrganizers || 0;
          document.getElementById('total-tickets').textContent = data.totalTickets || 0;
          
          document.getElementById('revenue-change').textContent = `+${data.revenueGrowth || 0}% vs last month`;
          document.getElementById('fees-change').textContent = `+${data.feesGrowth || 0}% vs last month`;
          document.getElementById('organizers-change').textContent = `+${data.organizersThisMonth || 0} this month`;
          document.getElementById('tickets-change').textContent = `+${data.ticketsThisMonth || 0} this month`;
        } else {
          console.error('Error loading platform metrics:', result.error);
        }
      } catch (error) {
        console.error('Error loading platform metrics:', error);
      }
    }

  </script>
</Layout>
