---
export const prerender = false;

import Layout from '../../layouts/Layout.astro';
import { supabase } from '../../lib/supabase';

const { slug } = Astro.params;

if (!slug) {
  return new Response('Event not found', { status: 404 });
}

// Fetch event data
const { data: event, error } = await supabase
  .from('events')
  .select(`
    *,
    organizations (
      name,
      logo
    )
  `)
  .eq('slug', slug)
  .single();

if (error || !event) {
  return Astro.redirect('/404');
}

// Get the current domain for the embed URL
const protocol = Astro.url.protocol;
const host = Astro.url.host;
const baseEmbedUrl = `${protocol}//${host}/embed/${slug}`;

// Default theme values
const defaultTheme = {
  primaryColor: '#1e293b',
  accentColor: '#3b82f6',
  backgroundColor: '#ffffff',
  textColor: '#1f2937',
  borderColor: '#e2e8f0',
  borderRadius: '8',
  fontFamily: 'system-ui, -apple-system, sans-serif',
  hidePoweredBy: false,
  hideHeader: false
};

// Function to generate embed URL with theme parameters
function generateEmbedUrl(theme: typeof defaultTheme) {
  const params = new URLSearchParams();
  Object.entries(theme).forEach(([key, value]) => {
    if (value !== defaultTheme[key as keyof typeof defaultTheme]) {
      params.append(key, value.toString());
    }
  });
  return params.toString() ? `${baseEmbedUrl}?${params.toString()}` : baseEmbedUrl;
}

// Generate embed code with theme
function generateEmbedCode(theme: typeof defaultTheme, responsive = false) {
  const embedUrl = generateEmbedUrl(theme);
  const borderStyle = `border: 1px solid ${theme.borderColor}; border-radius: ${theme.borderRadius}px; overflow: hidden;`;
  const eventTitle = event?.title || 'Ticket Widget';
  
  if (responsive) {
    return `<div style="position: relative; width: 100%; max-width: 600px; margin: 0 auto;">
  <iframe 
    src="${embedUrl}" 
    width="100%" 
    height="600" 
    frameborder="0" 
    scrolling="no"
    title="${eventTitle} - Ticket Widget"
    style="${borderStyle} display: block;"
    onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'">
  </iframe>
</div>

<${'script'}>
  // Auto-resize iframe based on content
  window.addEventListener('message', function(event) {
    if (event.data.type === 'resize') {
      const iframe = document.querySelector('iframe[src*="${embedUrl}"]');
      if (iframe) {
        iframe.style.height = event.data.height + 'px';
      }
    }
  });
</${'script'}>`;
  } else {
    return `<iframe 
  src="${embedUrl}" 
  width="100%" 
  height="600" 
  frameborder="0" 
  scrolling="no"
  title="${eventTitle} - Ticket Widget"
  style="${borderStyle}"
  onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'">
</iframe>

<${'script'}>
  // Auto-resize iframe based on content
  window.addEventListener('message', function(event) {
    if (event.data.type === 'resize') {
      const iframe = document.querySelector('iframe[src*="${embedUrl}"]');
      if (iframe) {
        iframe.style.height = event.data.height + 'px';
      }
    }
  });
</${'script'}>`;
  }
}
---

<Layout title={`Embed Code - ${event?.title || 'Event'}`}>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100">
    <main class="max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div class="bg-white shadow-xl rounded-2xl overflow-hidden border border-slate-200">
        <div class="px-6 py-6">
          <!-- Header -->
          <div class="bg-gradient-to-r from-slate-800 to-slate-900 rounded-xl p-6 mb-6 text-white">
            <div class="flex items-center">
              {event.organizations.logo && (
                <img 
                  src={event.organizations.logo} 
                  alt={event.organizations.name}
                  class="h-12 w-12 rounded-xl mr-4 shadow-lg border-2 border-white/20"
                />
              )}
              <div>
                <h1 class="text-2xl font-light mb-1 tracking-wide">Embed Code</h1>
                <p class="text-slate-200 text-sm font-medium">{event.title}</p>
              </div>
            </div>
          </div>

          <!-- Theme Customization -->
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Theme Controls -->
            <div>
              <h2 class="text-xl font-semibold text-slate-900 mb-4">Customize Theme</h2>
              <div class="space-y-4">
                <!-- Primary Color -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Primary Color (Header)</label>
                  <div class="flex items-center space-x-3">
                    <input 
                      type="color" 
                      id="primaryColor" 
                      value="#1e293b" 
                      class="w-10 h-10 rounded border border-slate-300"
                      onchange="updateTheme()"
                    />
                    <input 
                      type="text" 
                      id="primaryColorText" 
                      value="#1e293b" 
                      class="flex-1 px-3 py-2 border border-slate-300 rounded-md text-sm font-mono"
                      onchange="document.getElementById('primaryColor').value = this.value; updateTheme()"
                    />
                  </div>
                </div>

                <!-- Accent Color -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Accent Color (Buttons)</label>
                  <div class="flex items-center space-x-3">
                    <input 
                      type="color" 
                      id="accentColor" 
                      value="#3b82f6" 
                      class="w-10 h-10 rounded border border-slate-300"
                      onchange="updateTheme()"
                    />
                    <input 
                      type="text" 
                      id="accentColorText" 
                      value="#3b82f6" 
                      class="flex-1 px-3 py-2 border border-slate-300 rounded-md text-sm font-mono"
                      onchange="document.getElementById('accentColor').value = this.value; updateTheme()"
                    />
                  </div>
                </div>

                <!-- Background Color -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Background Color</label>
                  <div class="flex items-center space-x-3">
                    <input 
                      type="color" 
                      id="backgroundColor" 
                      value="#ffffff" 
                      class="w-10 h-10 rounded border border-slate-300"
                      onchange="updateTheme()"
                    />
                    <input 
                      type="text" 
                      id="backgroundColorText" 
                      value="#ffffff" 
                      class="flex-1 px-3 py-2 border border-slate-300 rounded-md text-sm font-mono"
                      onchange="document.getElementById('backgroundColor').value = this.value; updateTheme()"
                    />
                  </div>
                </div>

                <!-- Text Color -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Text Color</label>
                  <div class="flex items-center space-x-3">
                    <input 
                      type="color" 
                      id="textColor" 
                      value="#1f2937" 
                      class="w-10 h-10 rounded border border-slate-300"
                      onchange="updateTheme()"
                    />
                    <input 
                      type="text" 
                      id="textColorText" 
                      value="#1f2937" 
                      class="flex-1 px-3 py-2 border border-slate-300 rounded-md text-sm font-mono"
                      onchange="document.getElementById('textColor').value = this.value; updateTheme()"
                    />
                  </div>
                </div>

                <!-- Border Color -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Border Color</label>
                  <div class="flex items-center space-x-3">
                    <input 
                      type="color" 
                      id="borderColor" 
                      value="#e2e8f0" 
                      class="w-10 h-10 rounded border border-slate-300"
                      onchange="updateTheme()"
                    />
                    <input 
                      type="text" 
                      id="borderColorText" 
                      value="#e2e8f0" 
                      class="flex-1 px-3 py-2 border border-slate-300 rounded-md text-sm font-mono"
                      onchange="document.getElementById('borderColor').value = this.value; updateTheme()"
                    />
                  </div>
                </div>

                <!-- Border Radius -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Border Radius (px)</label>
                  <input 
                    type="range" 
                    id="borderRadius" 
                    min="0" 
                    max="20" 
                    value="8" 
                    class="w-full"
                    onchange="document.getElementById('borderRadiusText').value = this.value; updateTheme()"
                  />
                  <input 
                    type="number" 
                    id="borderRadiusText" 
                    value="8" 
                    min="0" 
                    max="20" 
                    class="mt-2 w-20 px-3 py-2 border border-slate-300 rounded-md text-sm"
                    onchange="document.getElementById('borderRadius').value = this.value; updateTheme()"
                  />
                </div>

                <!-- Font Family -->
                <div>
                  <label class="block text-sm font-medium text-slate-700 mb-2">Font Family</label>
                  <select 
                    id="fontFamily" 
                    class="w-full px-3 py-2 border border-slate-300 rounded-md text-sm"
                    onchange="updateTheme()"
                  >
                    <option value="system-ui, -apple-system, sans-serif">System (Default)</option>
                    <option value="'Helvetica Neue', Arial, sans-serif">Helvetica</option>
                    <option value="'Times New Roman', serif">Times New Roman</option>
                    <option value="'Georgia', serif">Georgia</option>
                    <option value="'Roboto', sans-serif">Roboto</option>
                    <option value="'Open Sans', sans-serif">Open Sans</option>
                  </select>
                </div>

                <!-- Options -->
                <div class="space-y-2">
                  <label class="flex items-center">
                    <input 
                      type="checkbox" 
                      id="hideHeader" 
                      class="mr-2"
                      onchange="updateTheme()"
                    />
                    <span class="text-sm text-slate-700">Hide Header</span>
                  </label>
                  <label class="flex items-center">
                    <input 
                      type="checkbox" 
                      id="hidePoweredBy" 
                      class="mr-2"
                      onchange="updateTheme()"
                    />
                    <span class="text-sm text-slate-700">Hide "Powered by" Footer</span>
                  </label>
                </div>

                <!-- Preset Themes -->
                <div class="pt-4 border-t border-slate-200">
                  <label class="block text-sm font-medium text-slate-700 mb-3">Preset Themes</label>
                  <div class="grid grid-cols-2 gap-2">
                    <button 
                      onclick="applyPreset('default')"
                      class="p-2 border border-slate-300 rounded-md text-sm hover:bg-slate-50 transition-colors"
                    >
                      Default
                    </button>
                    <button 
                      onclick="applyPreset('minimal')"
                      class="p-2 border border-slate-300 rounded-md text-sm hover:bg-slate-50 transition-colors"
                    >
                      Minimal
                    </button>
                    <button 
                      onclick="applyPreset('dark')"
                      class="p-2 border border-slate-300 rounded-md text-sm hover:bg-slate-50 transition-colors"
                    >
                      Dark
                    </button>
                    <button 
                      onclick="applyPreset('elegant')"
                      class="p-2 border border-slate-300 rounded-md text-sm hover:bg-slate-50 transition-colors"
                    >
                      Elegant
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- Preview -->
            <div>
              <h2 class="text-xl font-semibold text-slate-900 mb-4">Preview</h2>
              <div class="bg-slate-50 rounded-lg p-4 border border-slate-200">
                <iframe 
                  id="previewFrame"
                  src={baseEmbedUrl}
                  width="100%" 
                  height="600" 
                  frameborder="0" 
                  scrolling="no"
                  title={`${event?.title || 'Event'} - Ticket Widget`}
                  style="border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;"
                  onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'">
                </iframe>
              </div>
            </div>
          </div>

          <!-- Generated Embed Code -->
          <div class="space-y-6">
            <!-- Basic Embed -->
            <div>
              <h3 class="text-lg font-semibold text-slate-900 mb-3">Basic Embed Code</h3>
              <p class="text-slate-600 text-sm mb-3">Copy and paste this code into your website HTML:</p>
              <div class="bg-slate-900 rounded-lg p-4 overflow-x-auto">
                <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap"><code id="basicEmbedCode"></code></pre>
              </div>
              <button 
                onclick="navigator.clipboard.writeText(document.getElementById('basicEmbedCode').textContent)"
                class="mt-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
              >
                Copy Code
              </button>
            </div>

            <!-- Responsive Embed -->
            <div>
              <h3 class="text-lg font-semibold text-slate-900 mb-3">Responsive Embed Code</h3>
              <p class="text-slate-600 text-sm mb-3">This version includes responsive styling and centers the widget:</p>
              <div class="bg-slate-900 rounded-lg p-4 overflow-x-auto">
                <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap"><code id="responsiveEmbedCode"></code></pre>
              </div>
              <button 
                onclick="navigator.clipboard.writeText(document.getElementById('responsiveEmbedCode').textContent)"
                class="mt-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
              >
                Copy Code
              </button>
            </div>

            <!-- Direct Link -->
            <div>
              <h3 class="text-lg font-semibold text-slate-900 mb-3">Direct Link</h3>
              <p class="text-slate-600 text-sm mb-3">You can also link directly to the embed page:</p>
              <div class="bg-slate-100 rounded-lg p-4">
                <code class="text-slate-800 text-sm font-mono break-all" id="directLink"></code>
              </div>
              <button 
                onclick="navigator.clipboard.writeText(document.getElementById('directLink').textContent)"
                class="mt-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
              >
                Copy Link
              </button>
            </div>
          </div>

          <!-- Instructions -->
          <div class="mt-8 bg-blue-50 rounded-lg p-6 border border-blue-200">
            <h3 class="text-lg font-semibold text-blue-900 mb-3">How to Use</h3>
            <ul class="text-blue-800 text-sm space-y-2">
              <li>• Copy the embed code above</li>
              <li>• Paste it into your website's HTML where you want the ticket widget to appear</li>
              <li>• The widget will automatically resize based on its content</li>
              <li>• Customers can purchase tickets directly from your website</li>
              <li>• All transactions are processed securely through our platform</li>
            </ul>
          </div>

          <!-- Features -->
          <div class="mt-6 bg-green-50 rounded-lg p-6 border border-green-200">
            <h3 class="text-lg font-semibold text-green-900 mb-3">Features</h3>
            <ul class="text-green-800 text-sm space-y-2">
              <li>• ✅ Mobile-responsive design</li>
              <li>• ✅ Automatic height adjustment</li>
              <li>• ✅ Secure payment processing</li>
              <li>• ✅ Real-time ticket availability</li>
              <li>• ✅ Branded with your organization</li>
              <li>• ✅ No additional fees for embedding</li>
            </ul>
          </div>
        </div>
      </div>
    </main>
  </div>

  <script define:vars={{ slug, event }}>
    const baseEmbedUrl = `${window.location.protocol}//${window.location.host}/embed/${slug}`;
    
    // Theme presets
    const presets = {
      default: {
        primaryColor: '#1e293b',
        accentColor: '#3b82f6',
        backgroundColor: '#ffffff',
        textColor: '#1f2937',
        borderColor: '#e2e8f0',
        borderRadius: '8',
        fontFamily: 'system-ui, -apple-system, sans-serif',
        hideHeader: false,
        hidePoweredBy: false
      },
      minimal: {
        primaryColor: '#ffffff',
        accentColor: '#000000',
        backgroundColor: '#ffffff',
        textColor: '#000000',
        borderColor: '#e5e7eb',
        borderRadius: '0',
        fontFamily: 'system-ui, -apple-system, sans-serif',
        hideHeader: true,
        hidePoweredBy: true
      },
      dark: {
        primaryColor: '#111827',
        accentColor: '#3b82f6',
        backgroundColor: '#1f2937',
        textColor: '#ffffff',
        borderColor: '#374151',
        borderRadius: '8',
        fontFamily: 'system-ui, -apple-system, sans-serif',
        hideHeader: false,
        hidePoweredBy: false
      },
      elegant: {
        primaryColor: '#7c3aed',
        accentColor: '#a855f7',
        backgroundColor: '#fefefe',
        textColor: '#1f2937',
        borderColor: '#d1d5db',
        borderRadius: '12',
        fontFamily: "'Georgia', serif",
        hideHeader: false,
        hidePoweredBy: false
      }
    };

    // Generate embed URL with theme parameters
    function generateEmbedUrl(theme) {
      const params = new URLSearchParams();
      const defaultTheme = presets.default;
      
      Object.entries(theme).forEach(([key, value]) => {
        if (value !== defaultTheme[key]) {
          params.append(key, value.toString());
        }
      });
      
      return params.toString() ? `${baseEmbedUrl}?${params.toString()}` : baseEmbedUrl;
    }

    // Generate embed code with theme
    function generateEmbedCode(theme, responsive = false) {
      const embedUrl = generateEmbedUrl(theme);
      const borderStyle = `border: 1px solid ${theme.borderColor}; border-radius: ${theme.borderRadius}px; overflow: hidden;`;
      const eventTitle = event?.title || 'Ticket Widget';
      
      if (responsive) {
        return `<div style="position: relative; width: 100%; max-width: 600px; margin: 0 auto;">
  <iframe 
    src="${embedUrl}" 
    width="100%" 
    height="600" 
    frameborder="0" 
    scrolling="no"
    title="${eventTitle} - Ticket Widget"
    style="${borderStyle} display: block;"
    onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'">
  </iframe>
</div>

<${'script'}>
  // Auto-resize iframe based on content
  window.addEventListener('message', function(event) {
    if (event.data.type === 'resize') {
      const iframe = document.querySelector('iframe[src*="${embedUrl}"]');
      if (iframe) {
        iframe.style.height = event.data.height + 'px';
      }
    }
  });
</${'script'}>`;
      } else {
        return `<iframe 
  src="${embedUrl}" 
  width="100%" 
  height="600" 
  frameborder="0" 
  scrolling="no"
  title="${eventTitle} - Ticket Widget"
  style="${borderStyle}"
  onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'">
</iframe>

<${'script'}>
  // Auto-resize iframe based on content
  window.addEventListener('message', function(event) {
    if (event.data.type === 'resize') {
      const iframe = document.querySelector('iframe[src*="${embedUrl}"]');
      if (iframe) {
        iframe.style.height = event.data.height + 'px';
      }
    }
  });
</${'script'}>`;
      }
    }

    // Get current theme from form
    function getCurrentTheme() {
      return {
        primaryColor: document.getElementById('primaryColor').value,
        accentColor: document.getElementById('accentColor').value,
        backgroundColor: document.getElementById('backgroundColor').value,
        textColor: document.getElementById('textColor').value,
        borderColor: document.getElementById('borderColor').value,
        borderRadius: document.getElementById('borderRadius').value,
        fontFamily: document.getElementById('fontFamily').value,
        hideHeader: document.getElementById('hideHeader').checked,
        hidePoweredBy: document.getElementById('hidePoweredBy').checked
      };
    }

    // Apply theme to form
    function applyThemeToForm(theme) {
      document.getElementById('primaryColor').value = theme.primaryColor;
      document.getElementById('primaryColorText').value = theme.primaryColor;
      document.getElementById('accentColor').value = theme.accentColor;
      document.getElementById('accentColorText').value = theme.accentColor;
      document.getElementById('backgroundColor').value = theme.backgroundColor;
      document.getElementById('backgroundColorText').value = theme.backgroundColor;
      document.getElementById('textColor').value = theme.textColor;
      document.getElementById('textColorText').value = theme.textColor;
      document.getElementById('borderColor').value = theme.borderColor;
      document.getElementById('borderColorText').value = theme.borderColor;
      document.getElementById('borderRadius').value = theme.borderRadius;
      document.getElementById('borderRadiusText').value = theme.borderRadius;
      document.getElementById('fontFamily').value = theme.fontFamily;
      document.getElementById('hideHeader').checked = theme.hideHeader;
      document.getElementById('hidePoweredBy').checked = theme.hidePoweredBy;
    }

    // Update theme (called when form changes)
    function updateTheme() {
      const theme = getCurrentTheme();
      
      // Update preview iframe
      const previewFrame = document.getElementById('previewFrame');
      previewFrame.src = generateEmbedUrl(theme);
      
      // Update embed codes
      document.getElementById('basicEmbedCode').textContent = generateEmbedCode(theme, false);
      document.getElementById('responsiveEmbedCode').textContent = generateEmbedCode(theme, true);
      document.getElementById('directLink').textContent = generateEmbedUrl(theme);
      
      // Sync color inputs
      document.getElementById('primaryColorText').value = theme.primaryColor;
      document.getElementById('accentColorText').value = theme.accentColor;
      document.getElementById('backgroundColorText').value = theme.backgroundColor;
      document.getElementById('textColorText').value = theme.textColor;
      document.getElementById('borderColorText').value = theme.borderColor;
    }

    // Apply preset theme
    function applyPreset(presetName) {
      const theme = presets[presetName];
      applyThemeToForm(theme);
      updateTheme();
    }

    // Auto-resize iframe based on content
    window.addEventListener('message', function(event) {
      if (event.data.type === 'resize') {
        const iframe = document.querySelector('iframe[src*="embed"]');
        if (iframe) {
          iframe.style.height = event.data.height + 'px';
        }
      }
    });

    // Initialize with default theme
    document.addEventListener('DOMContentLoaded', function() {
      updateTheme();
    });
  </script>
</Layout>