---
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 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('Admin dashboard auth error: No session found');
  return Astro.redirect('/login-new?redirect=' + encodeURIComponent('/admin/dashboard'));
}

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

if (userError) {
  console.error('Admin dashboard user lookup error:', userError);
  return Astro.redirect('/login?redirect=' + encodeURIComponent('/admin/dashboard'));
}

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

const auth = {
  user: session.user,
  session,
  isAdmin: true,
  isSuperAdmin: false, // Super admin logic can be added later if needed
  organizationId: userRecord.organization_id
};
---

<Layout title="Admin Dashboard - Portal">
  <!-- Modern dark background with animated elements -->
  <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 class="absolute top-1/4 left-1/4 w-96 h-96 bg-gradient-to-br from-cyan-500/10 to-blue-500/10 rounded-full animate-pulse" style="animation-delay: 1s;"></div>
      <div class="absolute bottom-1/4 right-1/4 w-96 h-96 bg-gradient-to-br from-pink-500/10 to-purple-500/10 rounded-full animate-pulse" style="animation-delay: 3s;"></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/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-white/20 text-white rounded-md text-xs font-medium">Admin</span>
            </a>
            <div class="hidden md:flex items-center space-x-6">
              <span class="text-white font-semibold">Admin Dashboard</span>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <a 
              id="super-admin-link"
              href="/admin/super-dashboard" 
              class="bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105 hidden"
            >
              Super Admin
            </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">Platform Administration</h2>
          <p class="text-white/80 mt-2 text-lg font-light">Manage users, organizations, and platform settings</p>
        </div>

        <!-- Stats Cards -->
        <div id="stats-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <!-- Stats will be loaded here -->
        </div>

        <!-- Navigation Tabs -->
        <div class="mb-6">
          <nav class="flex space-x-8">
            <button
              id="tab-overview"
              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"
            >
              Overview
            </button>
            <button
              id="tab-organizations"
              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"
            >
              Organizations
            </button>
            <button
              id="tab-users"
              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"
            >
              Users
            </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-tickets"
              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"
            >
              Tickets
            </button>
            <button
              id="tab-settings"
              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"
            >
              Settings
            </button>
          </nav>
        </div>

        <!-- Tab Content -->
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 shadow-lg rounded-2xl">
          <!-- Overview Tab -->
          <div id="content-overview" class="tab-content p-6">
            <h3 class="text-lg font-medium text-white mb-6">Platform Overview</h3>
            
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- Recent Activity -->
              <div>
                <h4 class="text-sm font-medium text-white mb-3">Recent Activity</h4>
                <div id="recent-activity" class="space-y-3">
                  <!-- Activity items will be loaded here -->
                </div>
              </div>

              <!-- Quick Actions -->
              <div>
                <h4 class="text-sm font-medium text-white mb-3">Quick Actions</h4>
                <div class="space-y-3">
                  <button 
                    id="create-test-event-btn"
                    onclick="createTestEvent()"
                    class="w-full text-left px-4 py-3 bg-white/10 backdrop-blur-xl rounded-lg hover:bg-gray-100 transition-colors duration-200"
                  >
                    <div class="text-sm font-medium text-white">Create Test Event</div>
                    <div class="text-xs text-white/80">Setup demo event with sample data</div>
                  </button>
                  <button 
                    id="create-admin-user-btn"
                    onclick="createAdminUser()"
                    class="w-full text-left px-4 py-3 bg-white/10 backdrop-blur-xl rounded-lg hover:bg-gray-100 transition-colors duration-200"
                  >
                    <div class="text-sm font-medium text-white">Create Admin User</div>
                    <div class="text-xs text-white/80">Add new administrator account</div>
                  </button>
                  <button 
                    id="quick-settings-btn"
                    onclick="goToSettings()"
                    class="w-full text-left px-4 py-3 bg-white/10 backdrop-blur-xl rounded-lg hover:bg-gray-100 transition-colors duration-200"
                  >
                    <div class="text-sm font-medium text-white">Platform Settings</div>
                    <div class="text-xs text-white/80">Configure platform-wide settings</div>
                  </button>
                  <button 
                    id="export-data-btn"
                    onclick="exportPlatformData()"
                    class="w-full text-left px-4 py-3 bg-white/10 backdrop-blur-xl rounded-lg hover:bg-gray-100 transition-colors duration-200"
                  >
                    <div class="text-sm font-medium text-white">Export Data</div>
                    <div class="text-xs text-white/80">Download platform reports</div>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- Organizations Tab -->
          <div id="content-organizations" class="tab-content p-6 hidden">
            <div class="flex justify-between items-center mb-6">
              <h3 class="text-lg font-medium text-white">Organizations</h3>
              <button
                id="create-org-btn"
                class="bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white px-4 py-2 rounded-xl text-sm font-medium backdrop-blur-xl shadow-lg border border-white/20 transition-all"
              >
                Create Organization
              </button>
            </div>
            <div id="organizations-table">
              <!-- Organizations table will be loaded here -->
            </div>
          </div>

          <!-- Users Tab -->
          <div id="content-users" class="tab-content p-6 hidden">
            <div class="flex justify-between items-center mb-6">
              <h3 class="text-lg font-medium text-white">Users</h3>
              <button
                id="create-user-btn"
                class="bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white px-4 py-2 rounded-xl text-sm font-medium backdrop-blur-xl shadow-lg border border-white/20 transition-all"
              >
                Create User
              </button>
            </div>
            <div id="users-table">
              <!-- Users table will be loaded here -->
            </div>
          </div>

          <!-- Events Tab -->
          <div id="content-events" class="tab-content p-6 hidden">
            <h3 class="text-lg font-medium text-white mb-6">All Events</h3>
            <div id="events-table">
              <!-- Events table will be loaded here -->
            </div>
          </div>

          <!-- Tickets Tab -->
          <div id="content-tickets" class="tab-content p-6 hidden">
            <h3 class="text-lg font-medium text-white mb-6">Ticket Sales</h3>
            <div id="tickets-table">
              <!-- Tickets table will be loaded here -->
            </div>
          </div>

          <!-- Settings Tab -->
          <div id="content-settings" class="tab-content p-6 hidden">
            <h3 class="text-lg font-medium text-white mb-6">Platform Settings</h3>
            <div id="settings-form">
              <!-- Settings form will be loaded here -->
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</Layout>

<script>
  import { adminApi } from '../../lib/admin-api-router';

  const userNameSpan = document.getElementById('user-name');
  const logoutBtn = document.getElementById('logout-btn');
  const statsContainer = document.getElementById('stats-container');

  let currentTab = 'overview';
  let currentOrgId = null;

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

    const userInfo = adminApi.getUserInfo();
    if (userInfo && userNameSpan) {
      userNameSpan.textContent = userInfo.name || userInfo.email;
    }

    // Check if user has super admin privileges
    try {
      const response = await fetch('/api/admin/check-super-admin', {
        method: 'GET',
        credentials: 'include'
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.success && result.data.isSuperAdmin) {
          // Show super admin link
          const superAdminLink = document.getElementById('super-admin-link');
          if (superAdminLink) {
            superAdminLink.classList.remove('hidden');
          }
        }
      }
    } catch (error) {
      console.log('Super admin check failed:', error);
    }

    return true;
  }

  // Load platform statistics
  async function loadStats() {
    try {
      const stats = await adminApi.getPlatformStats();
      
      if (stats.error) {
        throw new Error(stats.error);
      }

      const statsContainer = document.getElementById('stats-container');
      if (!statsContainer) return;
      
      statsContainer.innerHTML = `
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6 hover:shadow-xl hover:-translate-y-2 transition-all duration-200 ease-out cursor-pointer">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-12 h-12 bg-gradient-to-br from-blue-500/20 to-purple-500/20 rounded-xl flex items-center justify-center shadow-lg">
                <svg class="w-6 h-6 style="color: var(--glass-text-accent);"" 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>
            <div class="ml-5">
              <p class="text-sm font-semibold text-white/80 uppercase tracking-wide">Active Organizers</p>
              <p class="text-3xl font-light text-white">${stats.organizations}</p>
            </div>
          </div>
        </div>
        
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6 hover:shadow-xl hover:-translate-y-2 transition-all duration-200 ease-out cursor-pointer">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <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 shadow-lg">
                <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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                </svg>
              </div>
            </div>
            <div class="ml-5">
              <p class="text-sm font-semibold text-white/80 uppercase tracking-wide">Total Events</p>
              <p class="text-3xl font-light text-white">${stats.events}</p>
            </div>
          </div>
        </div>
        
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6 hover:shadow-xl hover:-translate-y-2 transition-all duration-200 ease-out cursor-pointer">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <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 shadow-lg">
                <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>
            <div class="ml-5">
              <p class="text-sm font-semibold text-white/80 uppercase tracking-wide">Tickets Sold</p>
              <p class="text-3xl font-light text-white">${stats.tickets}</p>
            </div>
          </div>
        </div>
        
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg p-6 hover:shadow-xl hover:-translate-y-2 transition-all duration-200 ease-out cursor-pointer">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <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 shadow-lg">
                <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="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>
            <div class="ml-5">
              <p class="text-sm font-semibold text-white/80 uppercase tracking-wide">Platform Fees</p>
              <p class="text-3xl font-light text-white">$${(stats.platformFees / 100).toFixed(2)}</p>
            </div>
          </div>
        </div>
      `;
    } catch (error) {
      console.error('Error loading stats:', error);
      const statsContainer = document.getElementById('stats-container');
      if (statsContainer) {
        statsContainer.innerHTML = `
          <div class="col-span-full bg-red-50 border border-red-200 rounded-xl p-6">
            <p class="text-red-600 font-medium">Error loading statistics</p>
            <p class="text-red-500 text-sm">${(error as Error).message}</p>
          </div>
        `;
      }
    }
  }

  // Tab switching
  function switchTab(tabName: string) {
    // 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 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 tab-specific data
    loadTabContent(tabName);
  }

  // Load content for specific tab
  async function loadTabContent(tabName: string) {
    switch (tabName) {
      case 'overview':
        await loadRecentActivity();
        break;
      case 'organizations':
        await loadOrganizations();
        break;
      case 'users':
        await loadUsers();
        break;
      case 'events':
        await loadEvents();
        break;
      case 'tickets':
        await loadTickets();
        break;
      case 'settings':
        await loadSettings();
        break;
    }
  }

  // Load recent activity for overview tab
  async function loadRecentActivity() {
    try {
      const activities = await adminApi.getRecentActivity();

      const activityHtml = activities.length > 0 ? activities.map(activity => `
        <div class="flex items-start space-x-3 p-3 bg-white/10 backdrop-blur-xl rounded-lg">
          <div class="text-lg">${activity.icon}</div>
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-white">${activity.title}</p>
            <p class="text-xs text-white/80">${activity.subtitle}</p>
            <p class="text-xs text-white/60 mt-1">${activity.time.toLocaleString()}</p>
          </div>
        </div>
      `).join('') : `
        <div class="text-center py-8">
          <div class="text-4xl mb-2">📊</div>
          <p class="text-white/80">No recent activity</p>
          <p class="text-white/60 text-sm">Activity will appear here as users interact with the platform</p>
        </div>
      `;

      document.getElementById('recent-activity').innerHTML = activityHtml;

    } catch (error) {
      console.error('Error loading recent activity:', error);
      document.getElementById('recent-activity').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading recent activity</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  // Load organizations
  async function loadOrganizations() {
    try {
      const orgs = await adminApi.getOrganizations();

      const tableContainer = document.getElementById('organizations-table');
      tableContainer.innerHTML = `
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-white/10">
            <thead class="bg-white/10 backdrop-blur-xl">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Organization</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Users</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Platform Fee</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Fee Type</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Created</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Actions</th>
              </tr>
            </thead>
            <tbody class="bg-white/5 divide-y divide-white/10">
              ${orgs.map(org => `
                <tr id="org-row-${org.id}">
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm font-medium text-white">${org.name}</div>
                    <div class="text-sm text-white/80">${org.stripe_account_id ? 'Stripe Connected' : 'No Stripe'}</div>
                    ${org.platform_fee_notes ? `<div class="text-xs text-white/60 mt-1">${org.platform_fee_notes}</div>` : ''}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white">
                    ${org.user_count || 0}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white">
                    ${formatFeeDisplay(org)}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white/80">
                    ${org.platform_fee_type?.replace(/_/g, ' ') || 'percentage + fixed'}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white/80">
                    ${new Date(org.created_at).toLocaleDateString()}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button 
                      onclick="editOrganizationFees('${org.id}')" 
                      class="text-indigo-600 hover:text-indigo-900 mr-3"
                    >
                      Edit Fees
                    </button>
                    <button class="text-white/70 hover:text-white mr-3">View</button>
                    <button class="text-red-600 hover:text-red-900">Deactivate</button>
                  </td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        
        <!-- Fee Edit Modal -->
        <div id="fee-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
          <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="inline-block align-bottom bg-white/10 backdrop-blur-xl border border-white/20 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
              <form id="fee-form" class="bg-white/5 backdrop-blur-xl px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                  <div class="w-full">
                    <h3 class="text-lg leading-6 font-medium text-white mb-4">
                      Edit Platform Fees
                    </h3>
                    
                    <div class="space-y-4">
                      <div>
                        <label class="block text-sm font-medium text-white/80">Organization Name</label>
                        <p id="modal-org-name" class="text-sm text-white bg-white/10 backdrop-blur-xl p-2 rounded"></p>
                      </div>
                      
                      <div>
                        <label for="fee-type" class="block text-sm font-medium text-white/80">Fee Structure</label>
                        <select id="fee-type" name="fee_type" class="mt-1 block w-full border-white/20 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                          <option value="percentage_plus_fixed">Percentage + Fixed Fee</option>
                          <option value="percentage_only">Percentage Only</option>
                          <option value="fixed_only">Fixed Fee Only</option>
                        </select>
                      </div>
                      
                      <div id="percentage-field">
                        <label for="fee-percentage" class="block text-sm font-medium text-white/80">Percentage Fee (%)</label>
                        <input 
                          type="number" 
                          id="fee-percentage" 
                          name="fee_percentage" 
                          step="0.01" 
                          min="0" 
                          max="50"
                          class="mt-1 block w-full border-white/20 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          placeholder="3.50"
                        />
                        <p class="text-xs text-white/80 mt-1">Enter as percentage (e.g., 3.5 for 3.5%)</p>
                      </div>
                      
                      <div id="fixed-field">
                        <label for="fee-fixed" class="block text-sm font-medium text-white/80">Fixed Fee ($)</label>
                        <input 
                          type="number" 
                          id="fee-fixed" 
                          name="fee_fixed" 
                          step="0.01" 
                          min="0"
                          class="mt-1 block w-full border-white/20 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          placeholder="0.30"
                        />
                        <p class="text-xs text-white/80 mt-1">Fixed fee per transaction in dollars</p>
                      </div>
                      
                      <div>
                        <label for="fee-model" class="block text-sm font-medium text-white/80">Fee Payment Model</label>
                        <select id="fee-model" name="fee_model" class="mt-1 block w-full border-white/20 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                          <option value="customer_pays">Customer Pays Fee (Separate Line Item)</option>
                          <option value="absorbed_in_price">Fee Absorbed in Ticket Price</option>
                        </select>
                        <p class="text-xs text-white/80 mt-1">Choose whether customers see fees separately or included in ticket price</p>
                      </div>
                      
                      <div>
                        <label for="fee-notes" class="block text-sm font-medium text-white/80">Notes (Optional)</label>
                        <textarea 
                          id="fee-notes" 
                          name="fee_notes" 
                          rows="3"
                          class="mt-1 block w-full border-white/20 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          placeholder="Special arrangements, discounts, etc."
                        ></textarea>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="mt-5 sm:mt-6 sm:flex sm:flex-row-reverse">
                  <button 
                    type="submit" 
                    class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-indigo-600 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:ml-3 sm:w-auto sm:text-sm"
                  >
                    Save Changes
                  </button>
                  <button 
                    type="button" 
                    onclick="closeFeeModal()" 
                    class="mt-3 w-full inline-flex justify-center rounded-md border border-white/20 shadow-sm px-4 py-2 bg-white text-base font-medium text-white/80 hover:bg-white/10 backdrop-blur-xl focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:w-auto sm:text-sm"
                  >
                    Cancel
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      `;
      
      // Add event listeners for fee form
      setupFeeFormListeners();
      
    } catch (error) {
      console.error('Error loading organizations:', error);
    }
  }

  // Format fee display
  function formatFeeDisplay(org) {
    const percentage = (org.platform_fee_percentage * 100).toFixed(2);
    const fixed = org.platform_fee_fixed.toFixed(2);
    
    switch (org.platform_fee_type) {
      case 'percentage_only':
        return `${percentage}%`;
      case 'fixed_only':
        return `$${fixed}`;
      case 'percentage_plus_fixed':
      default:
        return `${percentage}% + $${fixed}`;
    }
  }

  // Load users
  async function loadUsers() {
    try {
      console.log('Loading users...');
      const users = await adminApi.getUsers();
      
      console.log('Users loaded:', users.length || 0, 'users');
      console.log('Users data:', users);

      const tableContainer = document.getElementById('users-table');
      tableContainer.innerHTML = `
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-white/10">
            <thead class="bg-white/10 backdrop-blur-xl">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">User</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Organization</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Role</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Status</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Last Login</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Actions</th>
              </tr>
            </thead>
            <tbody class="bg-white/5 divide-y divide-white/10">
              ${users.map(user => `
                <tr>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm font-medium text-white">${user.name || user.email}</div>
                    <div class="text-sm text-white/80">${user.email}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white">
                    ${user.organizations?.name || 'No Organization'}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-green-100 text-green-800'
                    }">
                      ${user.role}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      user.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }">
                      ${user.is_active ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white/80">
                    ${user.last_login ? new Date(user.last_login).toLocaleDateString() : 'Never'}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button class="text-indigo-600 hover:text-indigo-900 mr-3">Edit</button>
                    <button class="text-red-600 hover:text-red-900">
                      ${user.is_active ? 'Deactivate' : 'Activate'}
                    </button>
                  </td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
      `;
    } catch (error) {
      console.error('Error loading users:', error);
    }
  }

  // Load events
  async function loadEvents() {
    try {
      const events = await adminApi.getEvents();

      const tableContainer = document.getElementById('events-table');
      
      if (events.length === 0) {
        tableContainer.innerHTML = `
          <div class="text-center py-12">
            <div class="text-white/80 text-lg">No events found</div>
            <div class="text-white/60 text-sm mt-2">Create a test event to get started.</div>
          </div>
        `;
        return;
      }

      tableContainer.innerHTML = `
        <!-- Desktop Table View -->
        <div class="hidden md:block overflow-x-auto">
          <table class="min-w-full divide-y divide-white/10">
            <thead class="bg-white/10 backdrop-blur-xl">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Event</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Organizer</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Venue</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Date</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Status</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-white/80 uppercase tracking-wider">Actions</th>
              </tr>
            </thead>
            <tbody class="bg-white/5 divide-y divide-white/10">
              ${events.map(event => `
                <tr>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm font-medium text-white">${event.title}</div>
                    <div class="text-sm text-white/80">${event.slug}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-white">${event.organizations?.name || 'No Organization'}</div>
                    <div class="text-sm text-white/80">${event.users?.name || event.users?.email || 'Unknown'}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white">
                    ${event.venues?.name || event.venue || 'No venue'}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-white">
                    ${new Date(event.start_time).toLocaleDateString()}
                    <div class="text-xs text-white/80">${new Date(event.start_time).toLocaleTimeString()}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      new Date(event.start_time) > new Date() ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                    }">
                      ${new Date(event.start_time) > new Date() ? 'Upcoming' : 'Past'}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <a href="/events/${event.id}/manage" class="text-indigo-600 hover:text-indigo-900 mr-3" target="_blank">Manage</a>
                    <a href="/e/${event.slug}" class="text-green-600 hover:text-green-900 mr-3" target="_blank">Public</a>
                  </td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>

        <!-- Mobile Card View -->
        <div class="md:hidden space-y-4">
          ${events.map(event => `
            <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200 ease-out p-4">
              <div class="flex justify-between items-start mb-3">
                <div class="flex-1">
                  <h4 class="text-lg font-medium text-white mb-1">${event.title}</h4>
                  <p class="text-sm text-white/80">${event.slug}</p>
                </div>
                <span class="px-2 py-1 text-xs font-semibold rounded-full ${
                  new Date(event.start_time) > new Date() ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                }">
                  ${new Date(event.start_time) > new Date() ? 'Upcoming' : 'Past'}
                </span>
              </div>
              
              <div class="space-y-2 mb-4">
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                  </svg>
                  <span class="text-white">${event.organizations?.name || 'No Organization'}</span>
                </div>
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                  </svg>
                  <span class="text-white">${event.venues?.name || event.venue || 'No venue'}</span>
                </div>
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                  </svg>
                  <span class="text-white">${new Date(event.start_time).toLocaleDateString()}</span>
                  <span class="text-white/80 ml-2">${new Date(event.start_time).toLocaleTimeString()}</span>
                </div>
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" 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>
                  <span class="text-white">${event.ticket_type_count || 0} ticket types</span>
                </div>
              </div>
              
              <div class="flex space-x-3 pt-3 border-t border-gray-100">
                <a 
                  href="/events/${event.id}/manage" 
                  class="flex-1 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white text-center px-4 py-2 rounded-lg text-sm font-medium transition-all backdrop-blur-xl shadow-lg border border-white/20"
                  target="_blank"
                >
                  Manage
                </a>
                <a 
                  href="/e/${event.slug}" 
                  class="flex-1 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white text-center px-4 py-2 rounded-lg text-sm font-medium transition-all backdrop-blur-xl shadow-lg border border-white/20"
                  target="_blank"
                >
                  View Public
                </a>
              </div>
            </div>
          `).join('')}
        </div>
      `;
    } catch (error) {
      console.error('Error loading events:', error);
      document.getElementById('events-table').innerHTML = '<p class="text-red-600">Error loading events</p>';
    }
  }

  // Load tickets
  async function loadTickets() {
    try {
      const tickets = await adminApi.getTickets();

      if (tickets.length === 0) {
        document.getElementById('tickets-table').innerHTML = `
          <div class="text-center py-8">
            <svg class="w-16 h-16 mx-auto text-gray-300 mb-4" 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>
            <p class="text-white/80 text-lg">No tickets sold yet</p>
            <p class="text-white/60 text-sm mt-1">Platform-wide ticket sales will appear here</p>
          </div>
        `;
        return;
      }

      const ticketsHtml = `
        <div class="mb-6">
          <h3 class="text-lg font-semibold text-white">Recent Tickets (${tickets.length})</h3>
        </div>

        <!-- Desktop Table View -->
        <div class="hidden md:block bg-white/10 backdrop-blur-xl rounded-xl shadow-sm border border-white/20 overflow-hidden">
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-white/10 backdrop-blur-xl border-b border-white/20">
                <tr>
                  <th class="text-left py-3 px-4 font-medium text-white/80">Ticket ID</th>
                  <th class="text-left py-3 px-4 font-medium text-white/80">Event</th>
                  <th class="text-left py-3 px-4 font-medium text-white/80">Customer</th>
                  <th class="text-left py-3 px-4 font-medium text-white/80">Price</th>
                  <th class="text-left py-3 px-4 font-medium text-white/80">Status</th>
                  <th class="text-left py-3 px-4 font-medium text-white/80">Purchase Date</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-white/10">
                ${tickets.map(ticket => `
                  <tr class="hover:bg-white/10 backdrop-blur-xl">
                    <td class="py-3 px-4">
                      <div class="font-mono text-sm text-white/70">${ticket.uuid.substring(0, 8)}...</div>
                    </td>
                    <td class="py-3 px-4">
                      <div class="text-sm">
                        <div class="font-medium text-white">${ticket.events?.title || 'Unknown Event'}</div>
                        <div class="text-white/80">${ticket.events?.venue || 'No venue'}</div>
                      </div>
                    </td>
                    <td class="py-3 px-4">
                      <div class="text-sm">
                        <div class="font-medium text-white">${ticket.purchaser_name || 'Not provided'}</div>
                        <div class="text-white/80">${ticket.purchaser_email}</div>
                      </div>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm font-medium text-white">$${ticket.price}</span>
                    </td>
                    <td class="py-3 px-4">
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${ticket.checked_in ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                        ${ticket.checked_in ? 'Checked In' : 'Not Checked In'}
                      </span>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm text-white/80">${new Date(ticket.created_at).toLocaleDateString()}</span>
                      <br>
                      <span class="text-xs text-white/80">${new Date(ticket.created_at).toLocaleTimeString()}</span>
                    </td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>
        </div>

        <!-- Mobile Card View -->
        <div class="md:hidden space-y-4">
          ${tickets.map(ticket => `
            <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200 ease-out p-4">
              <div class="flex justify-between items-start mb-3">
                <div class="flex-1">
                  <h4 class="text-lg font-medium text-white mb-1">${ticket.events?.title || 'Unknown Event'}</h4>
                  <p class="text-sm text-white/80 font-mono">#${ticket.uuid.substring(0, 8)}...</p>
                </div>
                <span class="px-2 py-1 text-xs font-semibold rounded-full ${ticket.checked_in ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                  ${ticket.checked_in ? 'Checked In' : 'Pending'}
                </span>
              </div>
              
              <div class="space-y-2 mb-4">
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                  </svg>
                  <span class="text-white">${ticket.purchaser_name || 'Not provided'}</span>
                </div>
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                  </svg>
                  <span class="text-white">${ticket.purchaser_email}</span>
                </div>
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                  </svg>
                  <span class="text-white">${ticket.events?.organizations?.name || 'Unknown'}</span>
                </div>
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                  </svg>
                  <span class="text-white">${ticket.events?.venue || 'No venue'}</span>
                </div>
              </div>
              
              <div class="flex justify-between items-center pt-3 border-t border-gray-100">
                <div class="flex items-center text-sm">
                  <svg class="w-4 h-4 text-white/60 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                  </svg>
                  <span class="text-white/80">${new Date(ticket.created_at).toLocaleDateString()}</span>
                </div>
                <div class="text-lg font-semibold text-white">
                  $${ticket.price}
                </div>
              </div>
            </div>
          `).join('')}
        </div>
      `;

      document.getElementById('tickets-table').innerHTML = ticketsHtml;
    } catch (error) {
      console.error('Error loading tickets:', error);
      document.getElementById('tickets-table').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading tickets</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  // Load settings
  async function loadSettings() {
    try {
      // For now, we'll create a settings form for basic platform configuration
      const settingsHtml = `
        <div class="max-w-4xl space-y-8">
          <!-- Platform Configuration -->
          <div class="bg-white/10 backdrop-blur-xl rounded-2xl shadow-lg border border-white/20 overflow-hidden hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200 ease-out">
            <div class="px-6 py-4 border-b border-white/20 bg-white/10 backdrop-blur-xl">
              <h3 class="text-lg font-semibold text-white">Platform Configuration</h3>
              <p class="text-sm text-white/70 mt-1">Manage platform-wide settings and policies</p>
            </div>
            <div class="p-6 space-y-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium text-white/80 mb-2">Default Platform Fee (%)</label>
                  <input 
                    type="number" 
                    id="platform-fee-percent"
                    class="w-full px-3 py-2 border border-white/20 rounded-lg focus:ring-2 focus:ring-2"
                    placeholder="5.0"
                    step="0.1"
                    min="0"
                    max="100"
                  >
                  <p class="text-xs text-white/80 mt-1">Percentage charged on each ticket sale</p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-white/80 mb-2">Default Processing Fee ($)</label>
                  <input 
                    type="number" 
                    id="processing-fee"
                    class="w-full px-3 py-2 border border-white/20 rounded-lg focus:ring-2 focus:ring-2"
                    placeholder="2.50"
                    step="0.01"
                    min="0"
                  >
                  <p class="text-xs text-white/80 mt-1">Fixed fee per transaction</p>
                </div>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-white/80 mb-2">Platform Name</label>
                <input 
                  type="text" 
                  id="platform-name"
                  class="w-full px-3 py-2 border border-white/20 rounded-lg focus:ring-2 focus:ring-2"
                  value="Black Canyon Tickets"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-white/80 mb-2">Support Email</label>
                <input 
                  type="email" 
                  id="support-email"
                  class="w-full px-3 py-2 border border-white/20 rounded-lg focus:ring-2 focus:ring-2"
                  placeholder="support@blackcanyontickets.com"
                >
              </div>
            </div>
          </div>

          <!-- Email Templates -->
          <div class="bg-white/10 backdrop-blur-xl rounded-2xl shadow-lg border border-white/20 overflow-hidden hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200 ease-out">
            <div class="px-6 py-4 border-b border-white/20 bg-white/10 backdrop-blur-xl">
              <h3 class="text-lg font-semibold text-white">Email Templates</h3>
              <p class="text-sm text-white/70 mt-1">Customize automated email communications</p>
            </div>
            <div class="p-6">
              <div class="space-y-4">
                <div>
                  <label class="flex items-center">
                    <input type="checkbox" id="ticket-confirmation-enabled" class="rounded border-white/20 focus:ring-2">
                    <span class="ml-2 text-sm font-medium text-white/80">Send ticket confirmation emails</span>
                  </label>
                </div>
                <div>
                  <label class="flex items-center">
                    <input type="checkbox" id="event-reminders-enabled" class="rounded border-white/20 focus:ring-2">
                    <span class="ml-2 text-sm font-medium text-white/80">Send event reminder emails</span>
                  </label>
                </div>
                <div>
                  <label class="flex items-center">
                    <input type="checkbox" id="organizer-notifications-enabled" class="rounded border-white/20 focus:ring-2">
                    <span class="ml-2 text-sm font-medium text-white/80">Send organizer sale notifications</span>
                  </label>
                </div>
              </div>
            </div>
          </div>

          <!-- User Management -->
          <div class="bg-white/10 backdrop-blur-xl rounded-2xl shadow-lg border border-white/20 overflow-hidden hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200 ease-out">
            <div class="px-6 py-4 border-b border-white/20 bg-white/10 backdrop-blur-xl">
              <h3 class="text-lg font-semibold text-white">User Management</h3>
              <p class="text-sm text-white/70 mt-1">Platform access and permissions</p>
            </div>
            <div class="p-6 space-y-4">
              <div>
                <label class="flex items-center">
                  <input type="checkbox" id="auto-approve-organizers" class="rounded border-white/20 focus:ring-2">
                  <span class="ml-2 text-sm font-medium text-white/80">Auto-approve new organizer accounts</span>
                </label>
              </div>
              <div>
                <label class="flex items-center">
                  <input type="checkbox" id="allow-public-registration" class="rounded border-white/20 focus:ring-2">
                  <span class="ml-2 text-sm font-medium text-white/80">Allow public organizer registration</span>
                </label>
              </div>
            </div>
          </div>

          <!-- Save Button -->
          <div class="flex justify-end">
            <button 
              onclick="saveSettings()"
              class="bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white px-8 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              Save Settings
            </button>
          </div>
        </div>
      `;

      document.getElementById('settings-form').innerHTML = settingsHtml;
      
      // Load current settings values (you would fetch these from a settings table)
      loadCurrentSettings();
      
    } catch (error) {
      console.error('Error loading settings:', error);
      document.getElementById('settings-form').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading settings</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  // Load current settings (placeholder - would load from database)
  async function loadCurrentSettings() {
    // Set default values or load from database
    document.getElementById('platform-fee-percent').value = '5.0';
    document.getElementById('processing-fee').value = '2.50';
    document.getElementById('platform-name').value = 'Black Canyon Tickets';
    document.getElementById('support-email').value = 'support@blackcanyontickets.com';
    
    // Set checkbox defaults
    document.getElementById('ticket-confirmation-enabled').checked = true;
    document.getElementById('event-reminders-enabled').checked = true;
    document.getElementById('organizer-notifications-enabled').checked = true;
    document.getElementById('auto-approve-organizers').checked = false;
    document.getElementById('allow-public-registration').checked = true;
  }

  // Save settings function
  async function saveSettings() {
    try {
      const platformFeePercent = document.getElementById('platform-fee-percent') as HTMLInputElement;
      const processingFee = document.getElementById('processing-fee') as HTMLInputElement;
      const platformName = document.getElementById('platform-name') as HTMLInputElement;
      const supportEmail = document.getElementById('support-email') as HTMLInputElement;
      const ticketConfirmation = document.getElementById('ticket-confirmation-enabled') as HTMLInputElement;
      const eventReminders = document.getElementById('event-reminders-enabled') as HTMLInputElement;
      const organizerNotifications = document.getElementById('organizer-notifications-enabled') as HTMLInputElement;
      const autoApprove = document.getElementById('auto-approve-organizers') as HTMLInputElement;
      const allowPublicReg = document.getElementById('allow-public-registration') as HTMLInputElement;
      
      const settings = {
        platform_fee_percent: platformFeePercent ? parseFloat(platformFeePercent.value) : 0,
        processing_fee: processingFee ? parseFloat(processingFee.value) : 0,
        platform_name: platformName ? platformName.value : '',
        support_email: supportEmail ? supportEmail.value : '',
        ticket_confirmation_enabled: ticketConfirmation ? ticketConfirmation.checked : false,
        event_reminders_enabled: eventReminders ? eventReminders.checked : false,
        organizer_notifications_enabled: organizerNotifications ? organizerNotifications.checked : false,
        auto_approve_organizers: autoApprove ? autoApprove.checked : false,
        allow_public_registration: allowPublicReg ? allowPublicReg.checked : false
      };

      // In a real implementation, you would save these to a platform_settings table
      console.log('Settings to save:', settings);
      
      // Show success message
      const button = document.querySelector('button[onclick="saveSettings()"]') as HTMLButtonElement;
      if (button) {
        const originalText = button.textContent;
        button.textContent = 'Saved!';
        button.classList.add('bg-green-600');
        
        setTimeout(() => {
          if (button) {
            button.textContent = originalText;
            button.classList.remove('bg-green-600');
          }
        }, 2000);
      }
      
    } catch (error) {
      console.error('Error saving settings:', error);
      alert('Error saving settings: ' + (error as Error).message);
    }
  }

  // Event 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);
      }
    });
  });

  if (logoutBtn) {
    logoutBtn.addEventListener('click', async () => {
      await adminApi.signOut();
      window.location.href = '/';
    });
  }

  // Fee management functions
  function setupFeeFormListeners() {
    const feeForm = document.getElementById('fee-form');
    const feeTypeSelect = document.getElementById('fee-type');
    
    if (feeForm) {
      feeForm.addEventListener('submit', saveFees);
    }
    
    if (feeTypeSelect) {
      feeTypeSelect.addEventListener('change', toggleFeeFields);
    }
  }

  function toggleFeeFields() {
    const feeTypeEl = document.getElementById('fee-type') as HTMLSelectElement;
    if (!feeTypeEl) return;
    
    const feeType = feeTypeEl.value;
    const percentageField = document.getElementById('percentage-field');
    const fixedField = document.getElementById('fixed-field');
    
    switch (feeType) {
      case 'percentage_only':
        if (percentageField) percentageField.style.display = 'block';
        if (fixedField) fixedField.style.display = 'none';
        break;
      case 'fixed_only':
        if (percentageField) percentageField.style.display = 'none';
        if (fixedField) fixedField.style.display = 'block';
        break;
      case 'percentage_plus_fixed':
      default:
        if (percentageField) percentageField.style.display = 'block';
        if (fixedField) fixedField.style.display = 'block';
        break;
    }
  }

  async function editOrganizationFees(orgId: string) {
    try {
      currentOrgId = orgId;
      
      // Fetch organization data
      const org = await adminApi.getOrganization(orgId);
      
      if (!org) {
        throw new Error('Organization not found');
      }
      
      // Populate modal form
      const modalOrgName = document.getElementById('modal-org-name');
      if (modalOrgName) {
        modalOrgName.textContent = org.name;
      }
      
      const feeType = document.getElementById('fee-type') as HTMLSelectElement;
      if (feeType) {
        feeType.value = org.platform_fee_type || 'percentage_plus_fixed';
      }
      
      const feePercentage = document.getElementById('fee-percentage') as HTMLInputElement;
      if (feePercentage) {
        feePercentage.value = ((org.platform_fee_percentage || 0) * 100).toFixed(2);
      }
      
      const feeFixed = document.getElementById('fee-fixed') as HTMLInputElement;
      if (feeFixed) {
        feeFixed.value = (org.platform_fee_fixed || 0).toFixed(2);
      }
      
      const feeModel = document.getElementById('fee-model') as HTMLSelectElement;
      if (feeModel) {
        feeModel.value = org.platform_fee_model || 'customer_pays';
      }
      
      const feeNotes = document.getElementById('fee-notes') as HTMLTextAreaElement;
      if (feeNotes) {
        feeNotes.value = org.platform_fee_notes || '';
      }
      
      // Show/hide fields based on fee type
      toggleFeeFields();
      
      // Show modal
      const modal = document.getElementById('fee-modal');
      if (modal) {
        modal.classList.remove('hidden');
      }
      
    } catch (error) {
      console.error('Error loading organization:', error);
      alert('Error loading organization data');
    }
  }

  function closeFeeModal() {
    const modal = document.getElementById('fee-modal');
    if (modal) {
      modal.classList.add('hidden');
    }
    currentOrgId = null;
  }

  async function saveFees(e: Event) {
    e.preventDefault();
    
    if (!currentOrgId) return;
    
    try {
      const formData = new FormData(e.target as HTMLFormElement);
      const feeType = formData.get('fee_type') as string;
      const percentageValue = parseFloat(formData.get('fee_percentage') as string) / 100; // Convert to decimal
      const fixedValue = parseFloat(formData.get('fee_fixed') as string) * 100; // Convert to cents
      const feeModel = formData.get('fee_model') as string;
      const notes = formData.get('fee_notes') as string;
      
      const feeData = {
        platform_fee_type: feeType,
        platform_fee_model: feeModel,
        platform_fee_notes: notes || null,
        platform_fee_percentage: 0,
        platform_fee_fixed: 0
      };
      
      // Only set fields that should be used based on fee type
      switch (feeType) {
        case 'percentage_only':
          feeData.platform_fee_percentage = percentageValue;
          feeData.platform_fee_fixed = 0;
          break;
        case 'fixed_only':
          feeData.platform_fee_percentage = 0;
          feeData.platform_fee_fixed = fixedValue;
          break;
        case 'percentage_plus_fixed':
        default:
          feeData.platform_fee_percentage = percentageValue;
          feeData.platform_fee_fixed = fixedValue;
          break;
      }
      
      const result = await adminApi.updateOrganizationFees(currentOrgId, feeData);
        
      if (!result.success) {
        throw new Error(result.error);
      }
      
      // Close modal and refresh table
      closeFeeModal();
      await loadOrganizations();
      
      // Show success message
      alert('Platform fees updated successfully!');
      
    } catch (error) {
      console.error('Error saving fees:', error);
      alert('Error saving fees: ' + (error as Error).message);
    }
  }

  // Quick Actions Implementation
  async function createTestEvent() {
    try {
      const button = document.getElementById('create-test-event-btn') as HTMLButtonElement;
      if (!button) return;
      
      const originalContent = button.innerHTML;
      button.innerHTML = `
        <div class="text-sm font-medium text-white">Creating...</div>
        <div class="text-xs text-white/80">Setting up demo event</div>
      `;
      button.disabled = true;

      const result = await adminApi.createTestEvent();
      
      if (!result.success) {
        throw new Error(result.error);
      }

      button.innerHTML = `
        <div class="text-sm font-medium text-green-600">✓ Created!</div>
        <div class="text-xs text-green-500">Demo event ready</div>
      `;

      setTimeout(() => {
        if (button) {
          button.innerHTML = originalContent;
          button.disabled = false;
        }
      }, 3000);

      // Refresh stats and recent activity
      await loadStats();
      await loadRecentActivity();

    } catch (error) {
      console.error('Error creating test event:', error);
      alert('Error creating test event: ' + (error as Error).message);
      
      const button = document.getElementById('create-test-event-btn') as HTMLButtonElement;
      if (button) {
        button.innerHTML = `
          <div class="text-sm font-medium text-white">Create Test Event</div>
          <div class="text-xs text-white/80">Setup demo event with sample data</div>
        `;
        button.disabled = false;
      }
    }
  }

  async function createAdminUser() {
    const email = prompt('Enter email for new admin user:');
    const name = prompt('Enter name for new admin user:');
    
    if (!email || !name) {
      alert('Email and name are required');
      return;
    }

    try {
      // In a real implementation, you would use Supabase Auth to create the user
      // For now, we'll show what would happen
      alert(`Admin user would be created:\nEmail: ${email}\nName: ${name}\n\nNote: This would typically send an invitation email to the user.`);
      
      console.log('Would create admin user:', { email, name, role: 'admin' });
      
    } catch (error) {
      console.error('Error creating admin user:', error);
      alert('Error creating admin user: ' + (error as Error).message);
    }
  }

  function goToSettings() {
    switchTab('settings');
  }

  async function exportPlatformData() {
    try {
      const button = document.getElementById('export-data-btn') as HTMLButtonElement;
      if (!button) return;
      
      const originalContent = button.innerHTML;
      button.innerHTML = `
        <div class="text-sm font-medium text-white">Exporting...</div>
        <div class="text-xs text-white/80">Generating CSV report</div>
      `;
      button.disabled = true;

      // Get platform data
      const supabase = adminApi.getSupabaseClient();
      const [eventsResult, usersResult, ticketsResult, orgsResult] = await Promise.all([
        supabase.from('events').select('*'),
        supabase.from('users').select('*'),
        supabase.from('tickets').select('*'),
        supabase.from('organizations').select('*')
      ]);

      // Create CSV content
      const csvData = {
        events: eventsResult.data || [],
        users: usersResult.data || [],
        tickets: ticketsResult.data || [],
        organizations: orgsResult.data || []
      };

      // Create summary report
      const summaryCSV = [
        'Platform Summary Report',
        `Generated: ${new Date().toLocaleString()}`,
        '',
        'Metric,Count',
        `Organizations,${csvData.organizations.length}`,
        `Users,${csvData.users.length}`,
        `Events,${csvData.events.length}`,
        `Tickets Sold,${csvData.tickets.length}`,
        `Total Revenue,$${csvData.tickets.reduce((sum, t) => sum + parseFloat(t.price || 0), 0).toFixed(2)}`,
        `Platform Fees,$${csvData.tickets.reduce((sum, t) => sum + (t.platform_fee_charged || 0), 0) / 100}`
      ].join('\n');

      // Download CSV
      const blob = new Blob([summaryCSV], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `platform-summary-${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      button.innerHTML = `
        <div class="text-sm font-medium text-green-600">✓ Downloaded!</div>
        <div class="text-xs text-green-500">Report exported</div>
      `;

      setTimeout(() => {
        button.innerHTML = originalContent;
        button.disabled = false;
      }, 3000);

    } catch (error) {
      console.error('Error exporting data:', error);
      alert('Error exporting data: ' + (error as Error).message);
      
      const button = document.getElementById('export-data-btn') as HTMLButtonElement;
      if (button) {
        button.innerHTML = `
          <div class="text-sm font-medium text-white">Export Data</div>
          <div class="text-xs text-white/80">Download platform reports</div>
        `;
        button.disabled = false;
      }
    }
  }

  // Make functions globally available
  window.editOrganizationFees = editOrganizationFees;
  window.closeFeeModal = closeFeeModal;
  window.saveSettings = saveSettings;
  window.createTestEvent = createTestEvent;
  window.createAdminUser = createAdminUser;
  window.goToSettings = goToSettings;
  window.exportPlatformData = exportPlatformData;

  // Initialize
  checkAdminAuth().then(session => {
    if (session) {
      loadStats();
      switchTab('overview');
    }
  });
</script>