---
export const prerender = false;

import TicketCheckout from '../../components/TicketCheckout.tsx';
import { supabase } from '../../lib/supabase';

const { slug } = Astro.params;

if (!slug) {
  return new Response('Event not found', { status: 404 });
}
const url = Astro.url;

// Extract theme parameters from URL
const primaryColor = url.searchParams.get('primaryColor') || '#1e293b';
const accentColor = url.searchParams.get('accentColor') || '#3b82f6';
const backgroundColor = url.searchParams.get('backgroundColor') || '#ffffff';
const textColor = url.searchParams.get('textColor') || '#1f2937';
const borderColor = url.searchParams.get('borderColor') || '#e2e8f0';
const borderRadius = url.searchParams.get('borderRadius') || '8';
const fontFamily = url.searchParams.get('fontFamily') || 'system-ui, -apple-system, sans-serif';
const hidePoweredBy = url.searchParams.get('hidePoweredBy') === 'true';
const hideHeader = url.searchParams.get('hideHeader') === 'true';

// Fetch event data with ticket types
const { data: event, error } = await supabase
  .from('events')
  .select(`
    *,
    availability_display_mode,
    availability_threshold,
    show_sold_out,
    low_stock_threshold,
    availability_messages,
    organizations (
      name,
      logo,
      platform_fee_type,
      platform_fee_percentage,
      platform_fee_fixed
    ),
    ticket_types (
      id,
      name,
      description,
      price,
      quantity_available,
      quantity_sold,
      is_active,
      sale_start_time,
      sale_end_time,
      sort_order
    )
  `)
  .eq('slug', slug)
  .single();

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

// Format date for display
const eventDate = new Date(event.start_time);
const formattedDate = eventDate.toLocaleDateString('en-US', {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric'
});
const formattedTime = eventDate.toLocaleTimeString('en-US', {
  hour: 'numeric',
  minute: '2-digit',
  hour12: true
});
---

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{event.title} - Tickets</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style define:vars={{ fontFamily, textColor, backgroundColor, borderRadius, primaryColor, accentColor, borderColor }}>
    body {
      margin: 0;
      padding: 0;
      font-family: var(--fontFamily);
      color: var(--textColor);
    }
    
    /* Make the widget responsive */
    .widget-container {
      width: 100%;
      max-width: none;
      background: var(--backgroundColor);
      border-radius: calc(var(--borderRadius) * 1px);
      overflow: hidden;
    }
    
    /* Compact styling for embed */
    .embed-header {
      background: var(--primaryColor);
      color: white;
      padding: 1rem;
      border-radius: calc(var(--borderRadius) * 1px) calc(var(--borderRadius) * 1px) 0 0;
      margin-bottom: 1rem;
    }
    
    .embed-content {
      padding: 1rem;
    }
    
    .accent-color {
      color: var(--accentColor);
    }
    
    .accent-bg {
      background-color: var(--accentColor);
    }
    
    .border-custom {
      border-color: var(--borderColor);
    }
    
    .rounded-custom {
      border-radius: calc(var(--borderRadius) * 1px);
    }
    
    .btn-primary {
      background-color: var(--accentColor);
      border-color: var(--accentColor);
    }
    
    .btn-primary:hover {
      background-color: var(--accentColor);
      opacity: 0.9;
      border-color: var(--accentColor);
    }
    
    @media (max-width: 640px) {
      .embed-header {
        padding: 0.75rem;
      }
      .embed-content {
        padding: 0.75rem;
      }
    }
  </style>
</head>
<body>
  <div class="widget-container">
    <!-- Event Image -->
    {event.image_url && (
      <div class="w-full h-32 sm:h-40 overflow-hidden">
        <img 
          src={event.image_url} 
          alt={event.title}
          class="w-full h-full object-cover"
        />
      </div>
    )}
    
    <div class="embed-content">
      <!-- Compact Header -->
      {!hideHeader && (
        <div class="embed-header">
          <div class="flex items-center justify-between flex-wrap gap-2">
            <div class="flex items-center min-w-0">
              {event.organizations.logo && (
                <img 
                  src={event.organizations.logo} 
                  alt={event.organizations.name}
                  class="h-8 w-8 rounded-custom mr-3 flex-shrink-0"
                />
              )}
              <div class="min-w-0">
                <h1 class="text-lg font-semibold mb-0 truncate">{event.title}</h1>
                <p class="text-sm opacity-80 truncate">{event.organizations.name}</p>
              </div>
            </div>
            <div class="text-right flex-shrink-0">
              <p class="text-xs opacity-80 uppercase tracking-wide">Event Date</p>
              <p class="text-sm font-semibold">{formattedDate}</p>
              <p class="text-xs opacity-80">{formattedTime}</p>
            </div>
          </div>
        </div>
      )}

      <!-- Event Details (Compact) -->
      <div class="rounded-custom p-3 mb-4" style={`background-color: ${backgroundColor === '#ffffff' ? '#f8fafc' : backgroundColor + '20'};`}>
        <div class="space-y-2">
          <div class="flex items-center text-sm">
            <svg class="h-4 w-4 mr-2 flex-shrink-0 accent-color" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            <span class="font-medium mr-2" style={`color: ${textColor}`}>Venue:</span>
            <span style={`color: ${textColor}aa`}>{event.venue}</span>
          </div>
          <div class="flex items-center text-sm">
            <svg class="h-4 w-4 mr-2 flex-shrink-0 accent-color" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span class="font-medium mr-2" style={`color: ${textColor}`}>When:</span>
            <span style={`color: ${textColor}aa`}>{formattedDate} at {formattedTime}</span>
          </div>
        </div>
      </div>

      <!-- Ticket Checkout -->
      <div class="border rounded-custom p-4" style={`background-color: ${backgroundColor}; border-color: ${borderColor};`}>
        <h2 class="text-lg font-semibold mb-3" style={`color: ${textColor}`}>Get Your Tickets</h2>
        <TicketCheckout event={event as any} client:load />
      </div>

      <!-- Powered by footer -->
      {!hidePoweredBy && (
        <div class="text-center mt-4 pt-3" style={`border-top: 1px solid ${borderColor};`}>
          <p class="text-xs" style={`color: ${textColor}aa`}>
            Powered by <a href="https://portal.blackcanyontickets.com" target="_blank" class="accent-color hover:underline">Black Canyon Tickets</a>
          </p>
        </div>
      )}
    </div>
  </div>

  <script>
    // Auto-resize iframe to fit content
    function resizeIframe() {
      const height = document.body.scrollHeight;
      window.parent.postMessage({
        type: 'resize',
        height: height
      }, '*');
    }
    
    // Initial resize
    setTimeout(resizeIframe, 100);
    
    // Resize on window resize
    window.addEventListener('resize', resizeIframe);
    
    // Resize when content changes (like when ticket selection changes)
    const observer = new MutationObserver(resizeIframe);
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true
    });
  </script>
</body>
</html>