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

<ProtectedRoute>
  <SecureLayout title="Secure Payment Setup - Black Canyon Tickets" showBackLink={true} backLinkUrl="/dashboard">
    <!-- Loading State -->
    <div id="loading-state" class="min-h-screen flex items-center justify-center">
      <div class="text-center">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
        <h2 class="text-xl font-semibold text-gray-900 mb-2">Setting up payment processing</h2>
        <p class="text-gray-600">Please wait while we prepare your secure onboarding...</p>
      </div>
    </div>
    
    <div id="onboarding-container" class="animate-fadeInUp" style="display: none;">
      <!-- This will be populated by the client-side script -->
    </div>
  </SecureLayout>
</ProtectedRoute>

<script>
  // Hosted onboarding flow - no external JS dependencies
  async function initializeHostedOnboarding() {
    try {
      console.log('Starting hosted onboarding flow...');

      // Check if we have a session by making a simple API call
      const statusResponse = await fetch('/api/stripe/account-status', {
        method: 'GET',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      console.log('Status response:', statusResponse.status, statusResponse.statusText);

      if (statusResponse.status === 401) {
        console.log('Not authenticated, redirecting to login');
        window.location.href = '/login?returnTo=' + encodeURIComponent(window.location.pathname);
        return;
      }

      if (!statusResponse.ok) {
        console.error('Account status check failed:', statusResponse.status, statusResponse.statusText);
        const errorText = await statusResponse.text();
        console.error('Error response:', errorText);
        throw new Error(`Failed to check account status: ${statusResponse.status} ${statusResponse.statusText}`);
      }

      const statusData = await statusResponse.json();
      console.log('Account status:', statusData);

      // Check if user can start onboarding
      if (!statusData.can_start_onboarding) {
        const errorMessage = statusData.account_status === 'pending' ? 
          'Your organization is awaiting approval. Please contact support for assistance.' :
          'Your organization is not approved for payment processing. Please contact support.';
        
        showError(errorMessage, true);
        return;
      }

      // If already completed, redirect to dashboard
      if (statusData.stripe_onboarding_status === 'completed') {
        window.location.href = '/dashboard?success=onboarding_complete';
        return;
      }

      // Generate hosted onboarding URL
      const onboardingResponse = await fetch('/api/stripe/onboarding-url', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!onboardingResponse.ok) {
        const errorData = await onboardingResponse.json();
        throw new Error(errorData.error || 'Failed to generate onboarding URL');
      }

      const onboardingData = await onboardingResponse.json();
      console.log('Onboarding URL generated:', onboardingData);

      // Show the hosted onboarding interface
      showHostedOnboardingInterface(onboardingData);

    } catch (error) {
      console.error('Error initializing hosted onboarding:', error);
      const isConfigError = error.message && (
        error.message.includes('not configured') ||
        error.message.includes('not approved') ||
        error.message.includes('environment variable')
      );
      showError(error.message || 'Failed to initialize payment setup. Please try again or contact support.', isConfigError);
    }
  }

  function showHostedOnboardingInterface(onboardingData) {
    hideLoading();
    const container = document.getElementById('onboarding-container');
    if (container) {
      container.innerHTML = `
        <div class="min-h-screen bg-gray-50">
          <!-- Security Header -->
          <header class="bg-gray-900 border-b border-gray-700">
            <div class="max-w-4xl mx-auto px-6 py-4">
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                  <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center">
                    <span class="text-white font-bold text-sm">BCT</span>
                  </div>
                  <h1 class="text-xl font-semibold text-white">Secure Payment Setup</h1>
                </div>
                <div class="flex items-center space-x-4 text-sm text-gray-400">
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
                    </svg>
                    256-bit SSL
                  </span>
                  <span class="text-gray-500">•</span>
                  <span>Powered by Stripe</span>
                </div>
              </div>
            </div>
          </header>

          <main class="max-w-4xl mx-auto px-6 py-8">
            <!-- Onboarding Flow -->
            <div class="bg-white rounded-lg shadow-sm border">
              <div class="p-6 border-b border-gray-200">
                <div class="flex items-center justify-center space-x-2 text-sm text-gray-600">
                  <svg class="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
                  </svg>
                  <span class="text-green-600 font-medium">Secure Connection</span>
                  <span class="text-gray-400">•</span>
                  <span>Stripe Connect</span>
                  <span class="text-gray-400">•</span>
                  <span>PCI DSS Compliant</span>
                </div>
              </div>
              
              <div class="p-8">
                <div class="text-center mb-8">
                  <h2 class="text-2xl font-bold text-gray-900 mb-2">Complete Your Payment Setup</h2>
                  <p class="text-gray-600 max-w-2xl mx-auto">
                    You'll be redirected to Stripe's secure onboarding platform to complete your payment processing setup. 
                    All information is encrypted and processed by Stripe's bank-level security infrastructure.
                  </p>
                </div>

                <!-- Benefits -->
                <div class="grid md:grid-cols-3 gap-6 mb-8">
                  <div class="text-center">
                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mx-auto mb-3">
                      <svg class="w-6 h-6 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
                      </svg>
                    </div>
                    <h3 class="font-semibold text-gray-900 mb-1">Bank-Level Security</h3>
                    <p class="text-sm text-gray-600">Your data is protected by the same encryption banks use</p>
                  </div>
                  <div class="text-center">
                    <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mx-auto mb-3">
                      <svg class="w-6 h-6 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </div>
                    <h3 class="font-semibold text-gray-900 mb-1">Quick Setup</h3>
                    <p class="text-sm text-gray-600">Complete setup in just a few minutes</p>
                  </div>
                  <div class="text-center">
                    <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mx-auto mb-3">
                      <svg class="w-6 h-6 text-purple-600" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4zM18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z" />
                      </svg>
                    </div>
                    <h3 class="font-semibold text-gray-900 mb-1">Direct Payouts</h3>
                    <p class="text-sm text-gray-600">Funds deposited directly to your bank account</p>
                  </div>
                </div>

                <!-- Main Action -->
                <div class="text-center">
                  <button 
                    onclick="window.location.href='${onboardingData.onboarding_url}'"
                    class="inline-flex items-center px-8 py-4 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-semibold rounded-lg shadow-lg hover:from-blue-700 hover:to-purple-700 transform hover:scale-105 transition-all duration-200"
                  >
                    <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <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>
                    Start Secure Setup
                  </button>
                  <p class="text-xs text-gray-500 mt-3">
                    You'll return here automatically when setup is complete
                  </p>
                </div>

                <!-- Security Notice -->
                <div class="mt-8 p-4 bg-gray-50 rounded-lg border">
                  <div class="flex items-start space-x-3">
                    <div class="flex-shrink-0">
                      <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                      </svg>
                    </div>
                    <div>
                      <h4 class="text-sm font-medium text-gray-900 mb-1">Security Notice</h4>
                      <p class="text-sm text-gray-600">
                        This secure onboarding is powered by Stripe, a trusted payment processor used by millions of businesses worldwide. 
                        Your financial information is never stored on our servers and is protected by industry-leading security measures.
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Support -->
            <div class="text-center mt-6">
              <p class="text-sm text-gray-500">
                Need help? Contact our support team at{' '}
                <a href="mailto:support@blackcanyontickets.com" class="text-blue-600 hover:text-blue-800">
                  support@blackcanyontickets.com
                </a>
              </p>
            </div>
          </main>
        </div>
      `;
    }
  }

  function hideLoading() {
    const loadingState = document.getElementById('loading-state');
    const container = document.getElementById('onboarding-container');
    if (loadingState) loadingState.style.display = 'none';
    if (container) container.style.display = 'block';
  }
  
  function showError(message, isConfigError = false) {
    console.error('Hosted onboarding error:', message);
    hideLoading();
    const container = document.getElementById('onboarding-container');
    if (container) {
      container.innerHTML = `
        <div class="min-h-screen bg-gray-50 flex items-center justify-center">
          <div class="max-w-lg mx-auto bg-white rounded-lg shadow-sm border p-8 text-center">
            <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg class="w-6 h-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h2 class="text-xl font-semibold text-gray-900 mb-2">Payment Setup Error</h2>
            <p class="text-gray-600 mb-4">${message}</p>
            ${isConfigError ? `
              <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4 text-left">
                <div class="flex items-start">
                  <svg class="w-5 h-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                  </svg>
                  <div>
                    <h3 class="text-sm font-medium text-yellow-800 mb-1">Configuration Issue</h3>
                    <p class="text-sm text-yellow-700">This appears to be a setup issue. Please contact support with the error details above.</p>
                  </div>
                </div>
              </div>
            ` : ''}
            <div class="space-y-2">
              <button onclick="initializeHostedOnboarding()" class="block w-full bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-md font-medium transition-colors">
                Try Again
              </button>
              <a href="/dashboard" class="block w-full bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-md font-medium transition-colors">
                Return to Dashboard
              </a>
              <a href="mailto:support@blackcanyontickets.com?subject=Payment%20Setup%20Error&body=Error%20Details:%20${encodeURIComponent(message)}" class="block w-full bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-md font-medium transition-colors">
                Contact Support
              </a>
            </div>
          </div>
        </div>
      `;
    }
  }
  
  // Initialize when page loads - much simpler without external dependencies
  document.addEventListener('DOMContentLoaded', () => {
    // Small delay to let ProtectedRoute set up
    setTimeout(initializeHostedOnboarding, 500);
  });
</script>

<style>
  .animate-fadeInUp {
    animation: fadeInUp 0.6s ease-out forwards;
  }
  
  @keyframes fadeInUp {
    0% {
      opacity: 0;
      transform: translateY(20px);
    }
    100% {
      opacity: 1;
      transform: translateY(0);
    }
  }
</style>