---
export const prerender = false;

import Layout from '../layouts/Layout.astro';
import TicketCheckout from '../components/TicketCheckout.tsx';
import CustomPageRenderer from '../components/CustomPageRenderer.tsx';
import { supabase } from '../lib/supabase';

const { customSlug } = Astro.params;

// Fetch custom sales page data
const { data: customPage, error: pageError } = await supabase
  .from('custom_sales_pages')
  .select(`
    *,
    template:custom_page_templates(*),
    event:events(
      *,
      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('custom_slug', customSlug)
  .eq('is_active', true)
  .single();

if (pageError || !customPage) {
  return Astro.redirect('/404');
}

// Update view count
await supabase
  .from('custom_sales_pages')
  .update({ 
    view_count: (customPage.view_count || 0) + 1,
    last_viewed_at: new Date().toISOString()
  })
  .eq('id', customPage.id);

const event = customPage.event;

// Determine which page data to use (page-specific override or template)
const pageData = customPage.page_data || customPage.template?.page_data || {};
const customCss = [customPage.template?.custom_css, customPage.custom_css].filter(Boolean).join('\n');

// 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
});

// SEO metadata
const metaTitle = customPage.meta_title || `${event.title} - ${event.organizations.name}`;
const metaDescription = customPage.meta_description || event.description;
const ogImage = customPage.og_image_url || event.image_url;
---

<Layout title={metaTitle} description={metaDescription} image={ogImage}>
  {customCss && (
    <style is:inline set:html={customCss}></style>
  )}
  
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100">
    <main class="max-w-7xl mx-auto py-4 sm:py-6 px-4 sm:px-6 lg:px-8">
      <CustomPageRenderer 
        pageData={pageData}
        event={event}
        formattedDate={formattedDate}
        formattedTime={formattedTime}
        client:load
      />
    </main>
  </div>
</Layout>