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

<Layout title="Connect Stripe Account - Black Canyon Tickets">
  <div class="min-h-screen bg-gray-50">
    <nav class="bg-white shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <a href="/dashboard" class="text-xl font-semibold text-gray-900">Black Canyon Tickets</a>
          </div>
          <div class="flex items-center">
            <a href="/dashboard" class="text-gray-600 hover:text-gray-900">← Back to Dashboard</a>
          </div>
        </div>
      </div>
    </nav>

    <main class="max-w-2xl mx-auto py-6 sm:px-6 lg:px-8">
      <div class="px-4 py-6 sm:px-0">
        <div class="bg-white shadow rounded-lg p-6">
          <div class="text-center mb-8">
            <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-indigo-100">
              <svg class="h-6 w-6 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
              </svg>
            </div>
            <h2 class="mt-4 text-2xl font-bold text-gray-900">Connect Your Stripe Account</h2>
            <p class="mt-2 text-gray-600">
              Connect your Stripe account to receive payments directly from ticket sales
            </p>
          </div>

          <div id="account-status" class="hidden mb-6">
            <div class="rounded-md bg-green-50 p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                  </svg>
                </div>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-green-800">Stripe Account Connected</h3>
                  <p class="mt-1 text-sm text-green-700">Your Stripe account is connected and ready to receive payments.</p>
                </div>
              </div>
            </div>
          </div>

          <div id="connect-section">
            <div class="space-y-4">
              <div class="border rounded-lg p-4">
                <h3 class="font-medium text-gray-900 mb-2">How It Works</h3>
                <ul class="text-sm text-gray-600 space-y-1">
                  <li>• Payments go directly to your Stripe account</li>
                  <li>• We collect a 3% + $0.30 platform fee per transaction</li>
                  <li>• You receive the remaining amount instantly</li>
                  <li>• Full transparency - see exactly what you're paying</li>
                </ul>
              </div>

              <div class="border rounded-lg p-4 bg-blue-50">
                <h3 class="font-medium text-blue-900 mb-2">Example</h3>
                <p class="text-sm text-blue-800">
                  For a $100 ticket: You receive $96.70, we collect $3.30 platform fee
                </p>
              </div>

              <button
                id="connect-stripe-btn"
                class="w-full bg-indigo-600 hover:bg-indigo-700 text-white py-3 px-4 rounded-md font-medium"
              >
                Connect with Stripe
              </button>

              <p class="text-xs text-gray-500 text-center">
                By connecting your Stripe account, you agree to our Terms of Service and Stripe's Terms of Service
              </p>
            </div>
          </div>

          <div id="loading" class="hidden text-center py-4">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
            <p class="mt-2 text-sm text-gray-500">Checking account status...</p>
          </div>
        </div>
      </div>
    </main>
  </div>
</Layout>

<script>
  import { supabase } from '../../lib/supabase';
  import { generateConnectOnboardingUrl } from '../../lib/stripe';

  const connectBtn = document.getElementById('connect-stripe-btn');
  const accountStatus = document.getElementById('account-status');
  const connectSection = document.getElementById('connect-section');
  const loading = document.getElementById('loading');

  // Check authentication
  async function checkAuth() {
    const { data: { session } } = await supabase.auth.getSession();
    if (!session) {
      window.location.href = '/';
      return null;
    }
    return session;
  }

  // Check if organization already has Stripe account
  async function checkStripeStatus() {
    try {
      loading.classList.remove('hidden');
      connectSection.classList.add('hidden');

      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error('Not authenticated');

      // Get user's organization
      const { data: userData } = await supabase
        .from('users')
        .select('organization_id')
        .eq('id', user.id)
        .single();

      if (userData?.organization_id) {
        const { data: org } = await supabase
          .from('organizations')
          .select('stripe_account_id')
          .eq('id', userData.organization_id)
          .single();

        if (org?.stripe_account_id) {
          // Account is connected
          accountStatus.classList.remove('hidden');
          loading.classList.add('hidden');
          return;
        }
      }

      // No account connected
      connectSection.classList.remove('hidden');
      loading.classList.add('hidden');
    } catch (error) {
      console.error('Error checking Stripe status:', error);
      connectSection.classList.remove('hidden');
      loading.classList.add('hidden');
    }
  }

  // Handle Connect button click
  connectBtn.addEventListener('click', async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error('Not authenticated');

      // Get user's organization
      const { data: userData } = await supabase
        .from('users')
        .select('organization_id')
        .eq('id', user.id)
        .single();

      if (!userData?.organization_id) {
        throw new Error('No organization found. Please create an event first.');
      }

      // Generate Stripe Connect URL
      const connectUrl = generateConnectOnboardingUrl(userData.organization_id);
      
      // Redirect to Stripe Connect
      window.location.href = connectUrl;
    } catch (error) {
      console.error('Error connecting Stripe:', error);
      alert('Error connecting to Stripe. Please try again.');
    }
  });

  // Initialize
  checkAuth().then(session => {
    if (session) {
      checkStripeStatus();
    }
  });
</script>