---
import SecureLayout from '../../layouts/SecureLayout.astro';
import ProtectedRoute from '../../components/ProtectedRoute.astro';
import { verifyAuth } from '../../lib/auth-unified';

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

// Server-side authentication check
const auth = await verifyAuth(Astro.cookies);
if (!auth) {
  return Astro.redirect('/login-new');
}
---

<ProtectedRoute>
  <SecureLayout title="Organization Setup - Black Canyon Tickets" showBackLink={true} backLinkUrl="/dashboard">
    <!-- Loading State -->
    <div id="onboarding-loading" class="fixed inset-0 z-50 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="backdrop-blur-xl rounded-2xl p-8 shadow-2xl bg-white border">
        <div class="flex flex-col items-center space-y-4">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          <p class="text-lg font-medium text-gray-900">Loading organization setup...</p>
        </div>
      </div>
    </div>

    <div id="onboarding-content" class="min-h-screen bg-gray-50" style="display: none;">
      <div class="max-w-2xl mx-auto px-6 py-8">
        <!-- Progress Indicator -->
        <div class="mb-8">
          <div class="bg-white rounded-lg shadow-sm border p-6">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-lg font-semibold text-gray-900">Account Setup Progress</h2>
              <span class="text-sm text-gray-500">Step 1 of 2</span>
            </div>
            <div class="flex items-center space-x-4">
              <div class="flex items-center">
                <div class="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center">
                  <span class="text-white text-sm font-medium">1</span>
                </div>
                <span class="ml-2 text-sm font-medium text-blue-600">Organization Info</span>
              </div>
              <div class="flex-1 h-1 bg-gray-200 rounded"></div>
              <div class="flex items-center">
                <div class="w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center">
                  <span class="text-gray-500 text-sm font-medium">2</span>
                </div>
                <span class="ml-2 text-sm text-gray-500">Payment Setup</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Main Form -->
        <div class="bg-white rounded-lg shadow-sm border">
          <div class="p-6 border-b border-gray-200">
            <h1 class="text-2xl font-bold text-gray-900 mb-2">Create Your Organization</h1>
            <p class="text-gray-600">Tell us about your organization to get started with Black Canyon Tickets</p>
          </div>
          
          <form id="organization-form" class="p-6 space-y-6">
            <!-- Organization Name -->
            <div>
              <label for="organization_name" class="block text-sm font-medium text-gray-700 mb-2">
                Organization Name *
              </label>
              <input
                type="text"
                id="organization_name"
                name="organization_name"
                required
                class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="Enter your organization name"
              />
            </div>

            <!-- Business Type -->
            <div>
              <label for="business_type" class="block text-sm font-medium text-gray-700 mb-2">
                Business Type *
              </label>
              <select
                id="business_type"
                name="business_type"
                required
                class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">Select business type</option>
                <option value="individual">Individual/Sole Proprietor</option>
                <option value="company">Company/Corporation</option>
              </select>
            </div>

            <!-- Business Description -->
            <div>
              <label for="business_description" class="block text-sm font-medium text-gray-700 mb-2">
                Business Description
              </label>
              <textarea
                id="business_description"
                name="business_description"
                rows="3"
                class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="Briefly describe your organization and the types of events you host"
              ></textarea>
              <p class="mt-1 text-sm text-gray-500">Help us understand your business for faster approval</p>
            </div>

            <!-- Website URL -->
            <div>
              <label for="website_url" class="block text-sm font-medium text-gray-700 mb-2">
                Website URL
              </label>
              <input
                type="url"
                id="website_url"
                name="website_url"
                class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="https://yourwebsite.com"
              />
            </div>

            <!-- Phone Number -->
            <div>
              <label for="phone_number" class="block text-sm font-medium text-gray-700 mb-2">
                Phone Number
              </label>
              <input
                type="tel"
                id="phone_number"
                name="phone_number"
                class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="(555) 123-4567"
              />
            </div>

            <!-- Address Section -->
            <div class="border-t border-gray-200 pt-6">
              <h3 class="text-lg font-medium text-gray-900 mb-4">Business Address</h3>
              
              <div class="grid grid-cols-1 gap-4">
                <div>
                  <label for="address_line1" class="block text-sm font-medium text-gray-700 mb-2">
                    Address Line 1
                  </label>
                  <input
                    type="text"
                    id="address_line1"
                    name="address_line1"
                    class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Street address"
                  />
                </div>

                <div>
                  <label for="address_line2" class="block text-sm font-medium text-gray-700 mb-2">
                    Address Line 2
                  </label>
                  <input
                    type="text"
                    id="address_line2"
                    name="address_line2"
                    class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                    placeholder="Apartment, suite, etc. (optional)"
                  />
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <label for="city" class="block text-sm font-medium text-gray-700 mb-2">
                      City
                    </label>
                    <input
                      type="text"
                      id="city"
                      name="city"
                      class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                      placeholder="City"
                    />
                  </div>

                  <div>
                    <label for="state" class="block text-sm font-medium text-gray-700 mb-2">
                      State
                    </label>
                    <input
                      type="text"
                      id="state"
                      name="state"
                      class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                      placeholder="CO"
                    />
                  </div>

                  <div>
                    <label for="postal_code" class="block text-sm font-medium text-gray-700 mb-2">
                      ZIP Code
                    </label>
                    <input
                      type="text"
                      id="postal_code"
                      name="postal_code"
                      class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                      placeholder="81401"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- Security Notice -->
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div class="flex items-start">
                <svg class="w-5 h-5 text-blue-600 mt-0.5 mr-3" 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>
                  <h4 class="text-sm font-medium text-blue-900 mb-1">Security & Privacy</h4>
                  <p class="text-sm text-blue-800">
                    Your information is encrypted and securely stored. We'll review your application and notify you within 1-2 business days.
                  </p>
                </div>
              </div>
            </div>

            <!-- Error Message -->
            <div id="error-message" class="hidden bg-red-50 border border-red-200 rounded-lg p-4">
              <div class="flex items-start">
                <svg class="w-5 h-5 text-red-600 mt-0.5 mr-3" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
                </svg>
                <div>
                  <h4 class="text-sm font-medium text-red-900 mb-1">Error</h4>
                  <p id="error-text" class="text-sm text-red-800"></p>
                </div>
              </div>
            </div>

            <!-- Submit Button -->
            <div class="flex items-center justify-between pt-6 border-t border-gray-200">
              <p class="text-sm text-gray-500">
                * Required fields
              </p>
              <button
                type="submit"
                id="submit-btn"
                class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-md font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
              >
                Create Organization
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </SecureLayout>
</ProtectedRoute>

<script>
  // Handle loading state for onboarding page
  const onboardingLoading = document.getElementById('onboarding-loading') as HTMLDivElement;
  const onboardingContent = document.getElementById('onboarding-content') as HTMLDivElement;

  console.log('[ONBOARDING] Page loaded, initializing...');

  // Show content after a delay to prevent flashing
  setTimeout(() => {
    console.log('[ONBOARDING] Showing content');
    onboardingLoading.style.display = 'none';
    onboardingContent.style.display = 'block';
  }, 300);
</script>

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

  const form = document.getElementById('organization-form') as HTMLFormElement;
  const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement;
  const errorMessage = document.getElementById('error-message') as HTMLDivElement;
  const errorText = document.getElementById('error-text') as HTMLParagraphElement;

  function showError(message: string) {
    errorText.textContent = message;
    errorMessage.classList.remove('hidden');
    errorMessage.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

  function hideError() {
    errorMessage.classList.add('hidden');
  }

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    hideError();
    
    // Disable submit button
    submitBtn.disabled = true;
    submitBtn.textContent = 'Creating...';
    
    try {
      // Get current user
      const { data: { user }, error: userError } = await supabase.auth.getUser();
      if (userError || !user) {
        throw new Error('Authentication required');
      }

      // Collect form data
      const formData = new FormData(form);
      const organizationData = {
        organization_name: formData.get('organization_name'),
        business_type: formData.get('business_type'),
        business_description: formData.get('business_description') || '',
        website_url: formData.get('website_url') || '',
        phone_number: formData.get('phone_number') || '',
        address_line1: formData.get('address_line1') || '',
        address_line2: formData.get('address_line2') || '',
        city: formData.get('city') || '',
        state: formData.get('state') || '',
        postal_code: formData.get('postal_code') || '',
        country: 'US'
      };

      // Submit to API
      const response = await fetch('/api/organizations/process-signup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token}`
        },
        body: JSON.stringify(organizationData)
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to create organization');
      }

      // Handle success
      if (result.auto_approved) {
        // Auto-approved, redirect to Stripe onboarding
        window.location.href = '/onboarding/stripe?auto_approved=true';
      } else {
        // Pending approval, redirect to dashboard with message
        window.location.href = '/dashboard?status=pending_approval';
      }

    } catch (error) {
      console.error('Error creating organization:', error);
      showError(error.message || 'Failed to create organization. Please try again.');
    } finally {
      // Re-enable submit button
      submitBtn.disabled = false;
      submitBtn.textContent = 'Create Organization';
    }
  });

  // Check if user already has an organization
  async function checkExistingOrganization() {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

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

      if (userData?.organization_id) {
        // User already has an organization, redirect to dashboard
        window.location.href = '/dashboard';
      }
    } catch (error) {
      console.error('Error checking existing organization:', error);
    }
  }

  // Check on page load
  checkExistingOrganization();
</script>

<style>
  /* Form validation styles */
  .invalid {
    border-color: #ef4444;
    box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
  }
  
  .valid {
    border-color: #10b981;
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
  }
</style>