import { useTranslator, useLocale } from '@/lib/i18n';
import LumiereTheme from './themes/lumiere';
import MarqueeTheme from './themes/marquee';
import BotanicaTheme from './themes/botanica';
import SoireeTheme from './themes/soiree';

// Premium themes are full layouts of their own (not palette swaps), keyed by theme id.
const PREMIUM_LAYOUTS: Record<string, typeof LumiereTheme> = {
    lumiere: LumiereTheme,
    marquee: MarqueeTheme,
    botanica: BotanicaTheme,
    soiree: SoireeTheme,
};

interface Section {
    id: string;
    visible: boolean;
    label: string;
    content: Record<string, string>;
}

interface Props {
    wedding: {
        partner_a_name: string;
        partner_b_name: string;
        wedding_date?: string;
        venue_name?: string;
        venue_city?: string;
        venue_country?: string;
    };
    website: {
        slug: string;
        theme: string;
        sections?: Section[];
    };
    timeline?: { id: string; title: string; start_time: string; location?: string; category?: string }[];
}

interface ThemeDef {
    bg: string;
    text: string;
    accent: string;
    accentText: string;
    border: string;
    /** Atelier-style flag — switches to editorial layout (eyebrows, hairline rules, gold). */
    atelier?: boolean;
}

const THEMES: Record<string, ThemeDef> = {
    atelier: { bg: 'bg-background',   text: 'text-foreground',   accent: 'bg-primary',     accentText: 'text-primary',     border: 'border-border',         atelier: true },
    rose:    { bg: 'bg-rose-50',      text: 'text-rose-900',     accent: 'bg-rose-600',    accentText: 'text-rose-600',    border: 'border-rose-200' },
    garden:  { bg: 'bg-green-50',     text: 'text-green-900',    accent: 'bg-green-600',   accentText: 'text-green-600',   border: 'border-green-200' },
    minimal: { bg: 'bg-white',        text: 'text-gray-900',     accent: 'bg-gray-900',    accentText: 'text-gray-900',    border: 'border-gray-200' },
    luxe:    { bg: 'bg-stone-900',    text: 'text-stone-100',    accent: 'bg-amber-500',   accentText: 'text-amber-500',   border: 'border-stone-700' },
    coastal: { bg: 'bg-sky-50',       text: 'text-sky-900',      accent: 'bg-sky-600',     accentText: 'text-sky-600',     border: 'border-sky-200' },
};

export default function WeddingPublicSite({ wedding, website, timeline }: Props) {
    const t = useTranslator();
    const locale = useLocale();
    const theme = THEMES[website.theme] ?? THEMES.atelier;
    const sections = website.sections ?? [];
    const visible = (id: string) => sections.find(s => s.id === id)?.visible !== false;
    const content = (id: string) => sections.find(s => s.id === id)?.content ?? {};

    const coupleNames = `${wedding.partner_a_name} & ${wedding.partner_b_name}`;
    const weddingDate = wedding.wedding_date
        ? new Date(wedding.wedding_date).toLocaleDateString(locale === 'fr' ? 'fr-FR' : 'en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })
        : null;
    const venue = [wedding.venue_name, wedding.venue_city, wedding.venue_country].filter(Boolean).join(', ');

    // Premium themes render their own full layout rather than the shared one.
    const PremiumLayout = PREMIUM_LAYOUTS[website.theme];
    if (PremiumLayout) {
        return (
            <PremiumLayout
                wedding={wedding}
                content={content}
                visible={visible}
                timeline={timeline}
                coupleNames={coupleNames}
                weddingDate={weddingDate}
                venue={venue}
                t={t}
            />
        );
    }

    const rootClass = theme.atelier
        ? `atelier-light min-h-screen ${theme.bg} ${theme.text}`
        : `min-h-screen ${theme.bg} ${theme.text}`;

    return (
        <div className={rootClass}>
            {/* Hero */}
            {visible('hero') && (
                <section
                    className="min-h-screen flex flex-col items-center justify-center text-center px-6 py-20 bg-cover bg-center relative overflow-hidden"
                    style={content('hero').backgroundUrl ? { backgroundImage: `url(${content('hero').backgroundUrl})` } : {}}
                >
                    {content('hero').backgroundUrl && (
                        <>
                            <div className="absolute inset-0 bg-gradient-to-b from-black/40 via-black/20 to-black/60" />
                            <div className="absolute inset-10 border border-white/[0.10] pointer-events-none hidden sm:block" />
                        </>
                    )}
                    <div className={`relative ${content('hero').backgroundUrl ? 'text-white' : ''}`}>
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${content('hero').backgroundUrl ? 'text-white/80' : theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className={`inline-block w-12 h-px ${content('hero').backgroundUrl ? 'bg-white/70' : 'bg-primary'}`} />
                                {t('wsite.eyebrow_wedding')}
                                <span className={`inline-block w-12 h-px ${content('hero').backgroundUrl ? 'bg-white/70' : 'bg-primary'}`} />
                            </p>
                        )}
                        <h1 className="font-serif text-5xl md:text-7xl mb-5 tracking-[-0.025em] leading-[1.04]">
                            {content('hero').heading?.trim() || coupleNames}
                        </h1>
                        {weddingDate && (
                            <p className={`text-[10.5px] md:text-[11px] tracking-[0.32em] uppercase ${content('hero').backgroundUrl ? 'opacity-85' : 'opacity-75'} mb-2`}>
                                {weddingDate}
                            </p>
                        )}
                        {venue && (
                            <p className={`text-base ${content('hero').backgroundUrl ? 'opacity-80' : 'opacity-65'} font-serif italic mt-1`}>
                                {venue}
                            </p>
                        )}
                        {content('hero').subheading && (
                            <p className="mt-6 opacity-80 max-w-xl mx-auto leading-relaxed">{content('hero').subheading}</p>
                        )}
                    </div>
                    {theme.atelier && !content('hero').backgroundUrl && (
                        <p className="absolute bottom-8 text-[10px] tracking-[0.32em] uppercase text-foreground/40">
                            {t('wsite.scroll')}
                        </p>
                    )}
                </section>
            )}

            {/* Story */}
            {visible('story') && content('story').body && (
                <section className={`py-24 px-6 border-t ${theme.border}`}>
                    <div className="max-w-2xl mx-auto text-center">
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className="inline-block w-10 h-px bg-primary" />
                                {t('wsite.chapter_1')}
                            </p>
                        )}
                        <h2 className="font-serif text-3xl md:text-4xl mb-7 tracking-[-0.022em]">
                            {content('story').heading ?? t('wsite.our_story')}
                        </h2>
                        <p className="text-base leading-relaxed opacity-80 whitespace-pre-line">{content('story').body}</p>
                    </div>
                </section>
            )}

            {/* Details */}
            {visible('details') && (
                <section className={`py-24 px-6 border-t ${theme.border}`}>
                    <div className="max-w-3xl mx-auto">
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className="inline-block w-10 h-px bg-primary" />
                                {t('wsite.chapter_2')}
                            </p>
                        )}
                        <h2 className="font-serif text-3xl md:text-4xl mb-10 text-center tracking-[-0.022em]">
                            {content('details').heading ?? t('wsite.event_details')}
                        </h2>
                        {(() => {
                            const hasCeremony = !!content('details').ceremonyTime;
                            const hasReception = !!content('details').receptionTime;
                            const eventCount = (hasCeremony ? 1 : 0) + (hasReception ? 1 : 0);
                            const cardClass = theme.atelier ? `${theme.bg} p-7` : `border ${theme.border} rounded-xl p-6`;
                            // #23: centre the layout when there's only one event so the single
                            // card doesn't sit awkwardly to the left of an empty column.
                            const containerClass = eventCount === 1
                                ? 'flex justify-center'
                                : `grid grid-cols-1 md:grid-cols-2 ${theme.atelier ? 'gap-px bg-border' : 'gap-6'}`;
                            const innerWrap = eventCount === 1 ? 'max-w-md w-full text-center' : '';
                            return (
                                <div className={containerClass}>
                                    {hasCeremony && (
                                        <div className={`${cardClass} ${innerWrap}`}>
                                            <p className={`text-[10px] tracking-[0.3em] uppercase ${theme.accentText} mb-3`}>{t('wsite.ceremony')}</p>
                                            <p className="font-serif text-[1.4rem] tracking-tight mb-1.5">{content('details').ceremonyTime}</p>
                                            {content('details').ceremonyVenue && (
                                                <p className="opacity-70 text-[13px] font-serif italic">{content('details').ceremonyVenue}</p>
                                            )}
                                        </div>
                                    )}
                                    {hasReception && (
                                        <div className={`${cardClass} ${innerWrap}`}>
                                            <p className={`text-[10px] tracking-[0.3em] uppercase ${theme.accentText} mb-3`}>{t('wsite.reception')}</p>
                                            <p className="font-serif text-[1.4rem] tracking-tight mb-1.5">{content('details').receptionTime}</p>
                                            {content('details').receptionVenue && (
                                                <p className="opacity-70 text-[13px] font-serif italic">{content('details').receptionVenue}</p>
                                            )}
                                        </div>
                                    )}
                                </div>
                            );
                        })()}
                    </div>
                </section>
            )}

            {/* Timeline — #16: day-of timeline visible to guests when sections.timeline.visible AND events exist */}
            {visible('timeline') && timeline && timeline.length > 0 && (
                <section className={`py-24 px-6 border-t ${theme.border}`}>
                    <div className="max-w-2xl mx-auto">
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className="inline-block w-10 h-px bg-primary" />
                                {t('wsite.the_day')}
                            </p>
                        )}
                        <h2 className="font-serif text-3xl md:text-4xl mb-10 text-center tracking-[-0.022em]">
                            {content('timeline').heading?.trim() || t('timeline.title')}
                        </h2>
                        <div className={`divide-y ${theme.border}`}>
                            {timeline.map(ev => (
                                <div key={ev.id} className="py-4 flex items-baseline gap-6">
                                    <span className="font-serif text-[1.1rem] tracking-tight whitespace-nowrap min-w-[5rem]">{ev.start_time}</span>
                                    <div className="flex-1">
                                        <p className="font-medium">{ev.title}</p>
                                        {ev.location && <p className="opacity-70 text-sm font-serif italic">{ev.location}</p>}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </section>
            )}

            {/* RSVP — #19: free-text RSVP block; for the actual form, link to the guest's RSVP token */}
            {visible('rsvp') && content('rsvp').body?.trim() && (
                <section className={`py-24 px-6 border-t ${theme.border}`}>
                    <div className="max-w-2xl mx-auto text-center">
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className="inline-block w-10 h-px bg-primary" />
                                {t('wsite.reply')}
                            </p>
                        )}
                        <h2 className="font-serif text-3xl md:text-4xl mb-7 tracking-[-0.022em]">
                            {content('rsvp').heading?.trim() || t('rsvp.title')}
                        </h2>
                        <p className="text-base leading-relaxed opacity-80 whitespace-pre-line">{content('rsvp').body}</p>
                    </div>
                </section>
            )}

            {/* Registry — #20: free-text registry block; couple can paste links or wishlist URL */}
            {visible('registry') && content('registry').body?.trim() && (
                <section className={`py-24 px-6 border-t ${theme.border}`}>
                    <div className="max-w-2xl mx-auto text-center">
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className="inline-block w-10 h-px bg-primary" />
                                {t('wsite.with_gratitude')}
                            </p>
                        )}
                        <h2 className="font-serif text-3xl md:text-4xl mb-7 tracking-[-0.022em]">
                            {content('registry').heading?.trim() || t('wsite.registry')}
                        </h2>
                        <p className="text-base leading-relaxed opacity-80 whitespace-pre-line">{content('registry').body}</p>
                    </div>
                </section>
            )}

            {/* FAQ — #22: free-text Q&A block; could be enhanced later with structured items */}
            {visible('faq') && content('faq').body?.trim() && (
                <section className={`py-24 px-6 border-t ${theme.border}`}>
                    <div className="max-w-2xl mx-auto">
                        {theme.atelier && (
                            <p className={`text-[10.5px] tracking-[0.34em] uppercase ${theme.accentText} mb-6 flex items-center gap-3 justify-center`}>
                                <span className="inline-block w-10 h-px bg-primary" />
                                {t('wsite.good_to_know')}
                            </p>
                        )}
                        <h2 className="font-serif text-3xl md:text-4xl mb-7 text-center tracking-[-0.022em]">
                            {content('faq').heading?.trim() || t('wsite.faq')}
                        </h2>
                        <p className="text-base leading-relaxed opacity-80 whitespace-pre-line">{content('faq').body}</p>
                    </div>
                </section>
            )}

            {/* Footer */}
            <footer className={`py-7 text-center border-t ${theme.border}`}>
                <p className={`text-[10.5px] tracking-[0.28em] uppercase ${theme.atelier ? 'text-muted-foreground' : 'opacity-60'}`}>
                    {t('common.powered_by')} <span className="font-serif italic normal-case tracking-tight ml-1">WedFlow</span>
                </p>
            </footer>
        </div>
    );
}
