import { createClient } from '@supabase/supabase-js';
import { notFound } from 'next/navigation';
import { SiteRenderer } from '@kit/site-builder/components';

interface Props { params: Promise<{ slug: string }> }

export default async function ClubHomePage({ params }: Props) {
  const { slug } = await params;

  // Use anon client for public access
  const supabase = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY!,
  );

  // Resolve slug → account
  const { data: account } = await supabase.from('accounts').select('id, name').eq('slug', slug).single();
  if (!account) notFound();

  // Check site is public
  const { data: settings } = await supabase.from('site_settings').select('*').eq('account_id', account.id).eq('is_public', true).maybeSingle();
  if (!settings) notFound();

  // Get homepage
  const { data: page } = await supabase.from('site_pages').select('*')
    .eq('account_id', account.id).eq('is_homepage', true).eq('is_published', true).maybeSingle();
  if (!page) notFound();

  return (
    <div style={{ '--primary': settings.primary_color, '--secondary': settings.secondary_color, fontFamily: settings.font_family } as React.CSSProperties}>
      <SiteRenderer data={(page.puck_data ?? {}) as Record<string, unknown>} />
    </div>
  );
}
