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

<Layout title="Territory Manager Application - Black Canyon Tickets">
  <div class="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900">
    <div class="container mx-auto px-4 py-12">
      <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="text-center mb-12">
          <h1 class="text-4xl font-bold text-white mb-4">Territory Manager Application</h1>
          <p class="text-xl text-blue-100">Join our team and start building your event referral business</p>
          <div class="bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-4 mt-6 max-w-2xl mx-auto">
            <p class="text-yellow-200 text-sm">
              <strong>Important:</strong> This is an independent contractor opportunity. Earnings are not guaranteed and depend on your ability to successfully refer events in your territory. Results may vary.
            </p>
          </div>
        </div>

        <!-- Progress Bar -->
        <div class="mb-8">
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="flex justify-between items-center mb-2">
              <span class="text-white text-sm">Step <span id="current-step">1</span> of 4</span>
              <span class="text-white text-sm"><span id="progress-percent">25</span>% Complete</span>
            </div>
            <div class="w-full bg-gray-700 rounded-full h-2">
              <div id="progress-bar" class="bg-gradient-to-r from-blue-500 to-purple-600 h-2 rounded-full transition-all duration-300" style="width: 25%"></div>
            </div>
          </div>
        </div>

        <!-- Application Form -->
        <form id="application-form" class="space-y-8">
          <!-- Step 1: Personal Information -->
          <div id="step-1" class="form-step">
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20">
              <h2 class="text-2xl font-bold text-white mb-6">Personal Information</h2>
              
              <div class="grid md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Full Name *</label>
                  <input type="text" id="full-name" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Email Address *</label>
                  <input type="email" id="email" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Phone Number *</label>
                  <input type="tel" id="phone" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Date of Birth *</label>
                  <input type="date" id="date-of-birth" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
              </div>
              
              <div class="mt-6">
                <label class="block text-white text-sm font-medium mb-2">Address *</label>
                <input type="text" id="street" placeholder="Street Address" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 mb-3">
                
                <div class="grid md:grid-cols-3 gap-3">
                  <input type="text" id="city" placeholder="City" required class="px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <input type="text" id="state" placeholder="State" required class="px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <input type="text" id="zip" placeholder="ZIP Code" required class="px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
              </div>
            </div>
          </div>

          <!-- Step 2: Territory and Preferences -->
          <div id="step-2" class="form-step hidden">
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20">
              <h2 class="text-2xl font-bold text-white mb-6">Territory Preferences</h2>
              
              <div class="space-y-6">
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Desired Territory *</label>
                  <select id="desired-territory" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Select a territory</option>
                    <option value="denver-metro">Denver Metro Area</option>
                    <option value="colorado-springs">Colorado Springs</option>
                    <option value="boulder-county">Boulder County</option>
                    <option value="fort-collins">Fort Collins</option>
                    <option value="grand-junction">Grand Junction</option>
                    <option value="other">Other (please specify)</option>
                  </select>
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Do you have reliable transportation? *</label>
                  <div class="flex space-x-4">
                    <label class="flex items-center">
                      <input type="radio" name="transportation" value="yes" class="mr-2">
                      <span class="text-white">Yes</span>
                    </label>
                    <label class="flex items-center">
                      <input type="radio" name="transportation" value="no" class="mr-2">
                      <span class="text-white">No</span>
                    </label>
                  </div>
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Do you have experience with events or sales? *</label>
                  <div class="flex space-x-4">
                    <label class="flex items-center">
                      <input type="radio" name="experience" value="yes" class="mr-2">
                      <span class="text-white">Yes</span>
                    </label>
                    <label class="flex items-center">
                      <input type="radio" name="experience" value="no" class="mr-2">
                      <span class="text-white">No</span>
                    </label>
                  </div>
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Why do you want to be a Territory Manager? *</label>
                  <textarea id="motivation" rows="4" required class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Tell us about your motivation and goals..."></textarea>
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Availability</label>
                  <div class="grid md:grid-cols-2 gap-6">
                    <div>
                      <label class="block text-white text-sm font-medium mb-2">Days Available</label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="monday" class="mr-2">
                          <span class="text-white">Monday</span>
                        </label>
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="tuesday" class="mr-2">
                          <span class="text-white">Tuesday</span>
                        </label>
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="wednesday" class="mr-2">
                          <span class="text-white">Wednesday</span>
                        </label>
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="thursday" class="mr-2">
                          <span class="text-white">Thursday</span>
                        </label>
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="friday" class="mr-2">
                          <span class="text-white">Friday</span>
                        </label>
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="saturday" class="mr-2">
                          <span class="text-white">Saturday</span>
                        </label>
                        <label class="flex items-center">
                          <input type="checkbox" name="days" value="sunday" class="mr-2">
                          <span class="text-white">Sunday</span>
                        </label>
                      </div>
                    </div>
                    
                    <div>
                      <label class="block text-white text-sm font-medium mb-2">Hours per week</label>
                      <input type="range" id="hours-per-week" min="5" max="40" value="20" class="w-full">
                      <div class="flex justify-between text-sm text-blue-100 mt-1">
                        <span>5</span>
                        <span id="hours-value">20</span>
                        <span>40</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Step 3: Documents -->
          <div id="step-3" class="form-step hidden">
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20">
              <h2 class="text-2xl font-bold text-white mb-6">Required Documents</h2>
              
              <div class="space-y-6">
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Government-issued ID *</label>
                  <div class="border-2 border-dashed border-white/20 rounded-lg p-6 text-center">
                    <input type="file" id="id-upload" accept=".pdf,.jpg,.jpeg,.png" required class="hidden">
                    <div id="id-upload-area" class="cursor-pointer">
                      <div class="text-4xl mb-4">📄</div>
                      <p class="text-white mb-2">Click to upload your ID</p>
                      <p class="text-sm text-blue-100">PDF, JPG, or PNG (max 10MB)</p>
                    </div>
                    <div id="id-upload-success" class="hidden">
                      <div class="text-4xl mb-4">✅</div>
                      <p class="text-green-400">ID uploaded successfully</p>
                    </div>
                  </div>
                </div>
                
                <div>
                  <label class="block text-white text-sm font-medium mb-2">Resume (Optional)</label>
                  <div class="border-2 border-dashed border-white/20 rounded-lg p-6 text-center">
                    <input type="file" id="resume-upload" accept=".pdf,.doc,.docx" class="hidden">
                    <div id="resume-upload-area" class="cursor-pointer">
                      <div class="text-4xl mb-4">📋</div>
                      <p class="text-white mb-2">Click to upload your resume</p>
                      <p class="text-sm text-blue-100">PDF, DOC, or DOCX (max 10MB)</p>
                    </div>
                    <div id="resume-upload-success" class="hidden">
                      <div class="text-4xl mb-4">✅</div>
                      <p class="text-green-400">Resume uploaded successfully</p>
                    </div>
                  </div>
                </div>
                
                <div class="bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-4">
                  <div class="flex items-start">
                    <div class="text-yellow-400 mr-3">⚠️</div>
                    <div>
                      <p class="text-yellow-100 font-medium">Background Check Required</p>
                      <p class="text-yellow-200 text-sm mt-1">A background check will be conducted after your application is approved. This is for security purposes and to protect our clients.</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Step 4: Consent and Submit -->
          <div id="step-4" class="form-step hidden">
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20">
              <h2 class="text-2xl font-bold text-white mb-6">Consent and Agreement</h2>
              
              <div class="space-y-6">
                <div class="bg-blue-500/20 border border-blue-500/50 rounded-lg p-6">
                  <h3 class="text-lg font-medium text-white mb-3">What happens next?</h3>
                  <div class="space-y-2 text-blue-100">
                    <p>1. We'll review your application within 2-3 business days</p>
                    <p>2. If approved, you'll receive an email with next steps</p>
                    <p>3. Complete the background check process</p>
                    <p>4. Access your Territory Manager portal and start training</p>
                    <p>5. Begin earning commissions on your first referral</p>
                  </div>
                </div>
                
                <div class="space-y-4">
                  <label class="flex items-start">
                    <input type="checkbox" id="consent-background" required class="mr-3 mt-1">
                    <span class="text-white">I consent to a background check being conducted as part of the application process. *</span>
                  </label>
                  
                  <label class="flex items-start">
                    <input type="checkbox" id="consent-data" required class="mr-3 mt-1">
                    <span class="text-white">I agree to the processing of my personal data as described in the <a href="/privacy" class="text-blue-400 hover:text-blue-300">Privacy Policy</a>. *</span>
                  </label>
                  
                  <label class="flex items-start">
                    <input type="checkbox" id="consent-terms" required class="mr-3 mt-1">
                    <span class="text-white">I agree to the <a href="/terms" class="text-blue-400 hover:text-blue-300">Terms of Service</a> and Territory Manager Agreement. *</span>
                  </label>
                  
                  <label class="flex items-start">
                    <input type="checkbox" id="consent-communications" class="mr-3 mt-1">
                    <span class="text-white">I would like to receive updates about new features and opportunities (optional).</span>
                  </label>
                </div>
                
                <div class="bg-green-500/20 border border-green-500/50 rounded-lg p-4">
                  <div class="flex items-start">
                    <div class="text-green-400 mr-3">✨</div>
                    <div>
                      <p class="text-green-100 font-medium">Ready to join our team?</p>
                      <p class="text-green-200 text-sm mt-1">Submit your application and we'll get back to you within 2-3 business days.</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Navigation Buttons -->
          <div class="flex justify-between items-center">
            <button type="button" id="prev-btn" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-3 rounded-lg transition-colors duration-200 hidden">
              Previous
            </button>
            <button type="button" id="next-btn" class="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg transition-all duration-200 ml-auto">
              Next
            </button>
            <button type="submit" id="submit-btn" class="bg-gradient-to-r from-green-500 to-blue-600 hover:from-green-600 hover:to-blue-700 text-white px-8 py-3 rounded-lg transition-all duration-200 hidden">
              Submit Application
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Success Modal -->
  <div id="success-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center hidden z-50">
    <div class="bg-white/10 backdrop-blur-sm rounded-lg p-8 border border-white/20 max-w-md mx-4">
      <div class="text-center">
        <div class="text-6xl mb-4">🎉</div>
        <h2 class="text-2xl font-bold text-white mb-4">Application Submitted!</h2>
        <p class="text-blue-100 mb-6">Thank you for your interest in becoming a Territory Manager. We'll review your application and get back to you within 2-3 business days.</p>
        <button id="close-modal" class="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg transition-all duration-200">
          Close
        </button>
      </div>
    </div>
  </div>

  <script>
    let currentStep = 1;
    const totalSteps = 4;

    // Elements
    const currentStepEl = document.getElementById('current-step');
    const progressPercentEl = document.getElementById('progress-percent');
    const progressBarEl = document.getElementById('progress-bar');
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');
    const submitBtn = document.getElementById('submit-btn');
    const form = document.getElementById('application-form');
    const successModal = document.getElementById('success-modal');
    const closeModal = document.getElementById('close-modal');

    // File upload handling
    const idUpload = document.getElementById('id-upload');
    const idUploadArea = document.getElementById('id-upload-area');
    const idUploadSuccess = document.getElementById('id-upload-success');
    const resumeUpload = document.getElementById('resume-upload');
    const resumeUploadArea = document.getElementById('resume-upload-area');
    const resumeUploadSuccess = document.getElementById('resume-upload-success');

    // Hours slider
    const hoursSlider = document.getElementById('hours-per-week');
    const hoursValue = document.getElementById('hours-value');

    // Update progress
    function updateProgress() {
      const percent = (currentStep / totalSteps) * 100;
      currentStepEl.textContent = currentStep;
      progressPercentEl.textContent = Math.round(percent);
      progressBarEl.style.width = percent + '%';
    }

    // Show/hide steps
    function showStep(step) {
      document.querySelectorAll('.form-step').forEach(el => el.classList.add('hidden'));
      document.getElementById(`step-${step}`).classList.remove('hidden');
      
      prevBtn.classList.toggle('hidden', step === 1);
      nextBtn.classList.toggle('hidden', step === totalSteps);
      submitBtn.classList.toggle('hidden', step !== totalSteps);
    }

    // Validate current step
    function validateStep(step) {
      const stepEl = document.getElementById(`step-${step}`);
      const requiredFields = stepEl.querySelectorAll('input[required], select[required], textarea[required]');
      
      for (const field of requiredFields) {
        if (!field.value.trim()) {
          field.focus();
          return false;
        }
      }
      
      // Step 2 specific validation
      if (step === 2) {
        const transportation = document.querySelector('input[name="transportation"]:checked');
        const experience = document.querySelector('input[name="experience"]:checked');
        
        if (!transportation || !experience) {
          return false;
        }
      }
      
      // Step 3 specific validation
      if (step === 3) {
        if (!idUpload.files.length) {
          return false;
        }
      }
      
      // Step 4 specific validation
      if (step === 4) {
        const requiredConsent = ['consent-background', 'consent-data', 'consent-terms'];
        for (const id of requiredConsent) {
          if (!document.getElementById(id).checked) {
            return false;
          }
        }
      }
      
      return true;
    }

    // Next button handler
    nextBtn.addEventListener('click', () => {
      if (validateStep(currentStep)) {
        currentStep++;
        showStep(currentStep);
        updateProgress();
      }
    });

    // Previous button handler
    prevBtn.addEventListener('click', () => {
      currentStep--;
      showStep(currentStep);
      updateProgress();
    });

    // File upload handlers
    idUploadArea.addEventListener('click', () => idUpload.click());
    idUpload.addEventListener('change', (e) => {
      if (e.target.files.length) {
        idUploadArea.classList.add('hidden');
        idUploadSuccess.classList.remove('hidden');
      }
    });

    resumeUploadArea.addEventListener('click', () => resumeUpload.click());
    resumeUpload.addEventListener('change', (e) => {
      if (e.target.files.length) {
        resumeUploadArea.classList.add('hidden');
        resumeUploadSuccess.classList.remove('hidden');
      }
    });

    // Hours slider
    hoursSlider.addEventListener('input', (e) => {
      hoursValue.textContent = e.target.value;
    });

    // Form submission
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      if (!validateStep(currentStep)) {
        return;
      }

      // Show loading state
      submitBtn.disabled = true;
      submitBtn.textContent = 'Submitting...';

      try {
        // Collect form data
        const formData = new FormData();
        
        // Personal info
        formData.append('fullName', document.getElementById('full-name').value);
        formData.append('email', document.getElementById('email').value);
        formData.append('phone', document.getElementById('phone').value);
        formData.append('dateOfBirth', document.getElementById('date-of-birth').value);
        formData.append('street', document.getElementById('street').value);
        formData.append('city', document.getElementById('city').value);
        formData.append('state', document.getElementById('state').value);
        formData.append('zip', document.getElementById('zip').value);
        
        // Territory preferences
        formData.append('desiredTerritory', document.getElementById('desired-territory').value);
        formData.append('hasTransportation', document.querySelector('input[name="transportation"]:checked').value);
        formData.append('hasExperience', document.querySelector('input[name="experience"]:checked').value);
        formData.append('motivation', document.getElementById('motivation').value);
        formData.append('hoursPerWeek', hoursSlider.value);
        
        // Days available
        const selectedDays = Array.from(document.querySelectorAll('input[name="days"]:checked')).map(cb => cb.value);
        formData.append('daysAvailable', JSON.stringify(selectedDays));
        
        // Documents
        if (idUpload.files.length) {
          formData.append('idUpload', idUpload.files[0]);
        }
        if (resumeUpload.files.length) {
          formData.append('resumeUpload', resumeUpload.files[0]);
        }
        
        // Consent
        formData.append('consentBackground', document.getElementById('consent-background').checked);
        formData.append('consentData', document.getElementById('consent-data').checked);
        formData.append('consentTerms', document.getElementById('consent-terms').checked);
        formData.append('consentCommunications', document.getElementById('consent-communications').checked);

        // Submit to API
        const response = await fetch('/api/territory-manager/apply', {
          method: 'POST',
          body: formData
        });

        if (response.ok) {
          successModal.classList.remove('hidden');
        } else {
          throw new Error('Failed to submit application');
        }
      } catch (error) {
        console.error('Submission error:', error);
        alert('There was an error submitting your application. Please try again.');
      } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Submit Application';
      }
    });

    // Close modal handler
    closeModal.addEventListener('click', () => {
      successModal.classList.add('hidden');
      window.location.href = '/';
    });

    // Initialize
    showStep(1);
    updateProgress();
  </script>
</Layout>