import { useEffect, useRef } from 'react';

/**
 * "Marquee" — a bold, modern, asymmetric wedding-site theme.
 *
 * The counterpoint to Lumière: left-aligned and editorial rather than centered
 * and romantic. A split-screen hero, oversized Fraunces type, a confident
 * claret accent, hard rules and numbered sections (Nº 01 …). Same section data
 * model as every other theme — a one-click switch.
 */

interface Props {
    wedding: { partner_a_name: string; partner_b_name: string };
    content: (id: string) => Record<string, string>;
    visible: (id: string) => boolean;
    timeline?: { id: string; title: string; start_time: string; location?: string }[];
    coupleNames: string;
    weddingDate: string | null;
    venue: string;
    t: (key: string, replacements?: Record<string, string | number>) => string;
}

export default function MarqueeTheme({ wedding, content, visible, timeline, coupleNames, weddingDate, venue, t }: Props) {
    const rootRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const els = rootRef.current?.querySelectorAll<HTMLElement>('[data-reveal]');
        if (!els || !els.length) return;
        const io = new IntersectionObserver(
            (entries) => entries.forEach((e) => {
                if (e.isIntersecting) { e.target.classList.add('is-in'); io.unobserve(e.target); }
            }),
            { rootMargin: '0px 0px -12% 0px', threshold: 0.1 },
        );
        els.forEach((el) => io.observe(el));
        return () => io.disconnect();
    }, []);

    const hero = content('hero');
    const heroImg = hero.backgroundUrl?.trim();
    const story = content('story');
    const details = content('details');
    const hasCeremony = !!details.ceremonyTime;
    const hasReception = !!details.receptionTime;
    const rsvp = content('rsvp');
    const registry = content('registry');
    const faq = content('faq');

    // Section index numbers (Nº 01, 02…) assigned only to visible content blocks.
    let n = 0;
    const num = () => String(++n).padStart(2, '0');

    return (
        <div ref={rootRef} className="marquee">
            <link rel="preconnect" href="https://fonts.googleapis.com" />
            <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
            <link
                rel="stylesheet"
                href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,600;0,9..144,900;1,9..144,500&family=Archivo:wght@400;500;600;700&display=swap"
            />
            <style>{MARQUEE_CSS}</style>

            {/* ── Hero (split) ─────────────────────────────────────── */}
            {visible('hero') && (
                <header className={`mq-hero${heroImg ? ' mq-hero--split' : ''}`}>
                    <div className="mq-hero__type">
                        <p className="mq-kicker mq-fade" style={{ animationDelay: '0.1s' }}>
                            <span>Nº 01</span> · {t('wsite.eyebrow_wedding')}
                        </p>
                        <h1 className="mq-names">
                            <span className="mq-fade" style={{ animationDelay: '0.2s' }}>{wedding.partner_a_name}</span>
                            <span className="mq-amp mq-fade" style={{ animationDelay: '0.32s' }}>and</span>
                            <span className="mq-outline mq-fade" style={{ animationDelay: '0.44s' }}>{wedding.partner_b_name}</span>
                        </h1>
                        <div className="mq-hero__meta mq-fade" style={{ animationDelay: '0.6s' }}>
                            {weddingDate && <span className="mq-date">{weddingDate}</span>}
                            {venue && <span className="mq-venue">{venue}</span>}
                        </div>
                        {hero.subheading && (
                            <p className="mq-hero__sub mq-fade" style={{ animationDelay: '0.7s' }}>{hero.subheading}</p>
                        )}
                    </div>
                    {heroImg && (
                        <div className="mq-hero__image mq-fade" style={{ animationDelay: '0.3s', backgroundImage: `url(${heroImg})` }} />
                    )}
                </header>
            )}

            {/* ── Story ────────────────────────────────────────────── */}
            {visible('story') && story.body && (
                <Section index={num()} eyebrow={t('wsite.chapter_1')} title={story.heading || t('wsite.our_story')}>
                    <p className="mq-prose">{story.body}</p>
                </Section>
            )}

            {/* ── Details ──────────────────────────────────────────── */}
            {visible('details') && (hasCeremony || hasReception) && (
                <Section index={num()} eyebrow={t('wsite.chapter_2')} title={details.heading || t('wsite.event_details')}>
                    <div className="mq-details">
                        {hasCeremony && (
                            <div className="mq-detail">
                                <span className="mq-detail__label">{t('wsite.ceremony')}</span>
                                <span className="mq-detail__time">{details.ceremonyTime}</span>
                                {details.ceremonyVenue && <span className="mq-detail__venue">{details.ceremonyVenue}</span>}
                            </div>
                        )}
                        {hasReception && (
                            <div className="mq-detail">
                                <span className="mq-detail__label">{t('wsite.reception')}</span>
                                <span className="mq-detail__time">{details.receptionTime}</span>
                                {details.receptionVenue && <span className="mq-detail__venue">{details.receptionVenue}</span>}
                            </div>
                        )}
                    </div>
                </Section>
            )}

            {/* ── Timeline ─────────────────────────────────────────── */}
            {visible('timeline') && timeline && timeline.length > 0 && (
                <Section index={num()} eyebrow={t('wsite.the_day')} title={content('timeline').heading?.trim() || t('timeline.title')}>
                    <ol className="mq-timeline">
                        {timeline.map((ev) => (
                            <li key={ev.id} className="mq-timeline__row">
                                <span className="mq-timeline__time">{ev.start_time}</span>
                                <span className="mq-timeline__title">{ev.title}</span>
                                {ev.location && <span className="mq-timeline__loc">{ev.location}</span>}
                            </li>
                        ))}
                    </ol>
                </Section>
            )}

            {/* ── RSVP / Registry / FAQ ────────────────────────────── */}
            {visible('rsvp') && rsvp.body?.trim() && (
                <Section index={num()} eyebrow={t('wsite.reply')} title={rsvp.heading?.trim() || t('rsvp.title')}>
                    <p className="mq-prose">{rsvp.body}</p>
                </Section>
            )}
            {visible('registry') && registry.body?.trim() && (
                <Section index={num()} eyebrow={t('wsite.with_gratitude')} title={registry.heading?.trim() || t('wsite.registry')}>
                    <p className="mq-prose">{registry.body}</p>
                </Section>
            )}
            {visible('faq') && faq.body?.trim() && (
                <Section index={num()} eyebrow={t('wsite.good_to_know')} title={faq.heading?.trim() || t('wsite.faq')}>
                    <p className="mq-prose">{faq.body}</p>
                </Section>
            )}

            {/* ── Footer ───────────────────────────────────────────── */}
            <footer className="mq-footer" data-reveal>
                <p className="mq-footer__names">{coupleNames}</p>
                {weddingDate && <p className="mq-footer__date">{weddingDate}</p>}
                <p className="mq-footer__brand">{t('common.powered_by')} <span>WedFlow</span></p>
            </footer>
        </div>
    );
}

/** Numbered, left-aligned content block with a sticky index column. */
function Section({ index, eyebrow, title, children }: { index: string; eyebrow: string; title: string; children: React.ReactNode }) {
    return (
        <section className="mq-section" data-reveal>
            <div className="mq-section__index">Nº {index}</div>
            <div className="mq-section__body">
                <p className="mq-eyebrow">{eyebrow}</p>
                <h2 className="mq-h2">{title}</h2>
                {children}
            </div>
        </section>
    );
}

const MARQUEE_CSS = `
.marquee {
    --paper: #F4F0E8;
    --ink: #181410;
    --muted: #6F665A;
    --accent: #8C2F39;
    --line: #1814101a;
    --serif: 'Fraunces', Georgia, serif;
    --sans: 'Archivo', system-ui, sans-serif;

    background: var(--paper);
    color: var(--ink);
    font-family: var(--sans);
    min-height: 100vh;
    overflow-x: hidden;
}
.marquee *, .marquee *::before, .marquee *::after { box-sizing: border-box; }

.mq-kicker, .mq-eyebrow {
    font-family: var(--sans); font-weight: 600;
    font-size: 11px; letter-spacing: 0.2em; text-transform: uppercase;
    color: var(--accent); margin: 0;
}
.mq-kicker span { color: var(--ink); }

/* ── Hero ─────────────────────────────────────────────────── */
.mq-hero {
    min-height: 100svh; display: grid; align-items: center;
    grid-template-columns: 1fr; padding: clamp(80px, 12vh, 140px) clamp(28px, 7vw, 96px) 64px;
    position: relative;
}
.mq-hero--split { grid-template-columns: 1.05fr 0.95fr; gap: clamp(32px, 5vw, 72px); }
.mq-hero__type { max-width: 720px; }
.mq-hero .mq-kicker { margin-bottom: 30px; }

.mq-names {
    font-family: var(--serif); font-weight: 900;
    font-size: clamp(3.4rem, 11vw, 8.5rem); line-height: 0.92;
    letter-spacing: -0.03em; margin: 0; text-transform: uppercase;
    font-optical-sizing: auto;
}
.mq-names span { display: block; }
.mq-amp {
    font-weight: 500; font-style: italic; text-transform: lowercase;
    font-size: 0.34em; color: var(--accent); letter-spacing: -0.01em;
    margin: 0.08em 0 0.08em 0.05em;
}
.mq-outline {
    color: transparent;
    -webkit-text-stroke: 1.5px var(--ink);
    text-stroke: 1.5px var(--ink);
}

.mq-hero__meta { display: flex; flex-wrap: wrap; gap: 8px 28px; margin-top: 38px; align-items: baseline; }
.mq-date { font-family: var(--sans); font-weight: 600; font-size: 13px; letter-spacing: 0.2em; text-transform: uppercase; }
.mq-venue { font-family: var(--serif); font-style: italic; font-size: 1.2rem; color: var(--muted); }
.mq-hero__sub { font-family: var(--serif); font-size: 1.2rem; line-height: 1.6; color: var(--muted); max-width: 34rem; margin: 22px 0 0; }

.mq-hero__image {
    align-self: stretch; min-height: 60vh; margin: 0;
    background-size: cover; background-position: center;
    border: 1px solid var(--line);
    filter: grayscale(0.12) contrast(1.02);
}

/* ── Sections ─────────────────────────────────────────────── */
.mq-section {
    display: grid; grid-template-columns: 140px 1fr;
    gap: clamp(24px, 5vw, 72px);
    max-width: 1180px; margin: 0 auto;
    padding: clamp(64px, 10vw, 116px) clamp(28px, 7vw, 96px);
    border-top: 1.5px solid var(--ink);
}
.mq-section__index {
    font-family: var(--sans); font-weight: 700; font-size: 13px;
    letter-spacing: 0.16em; color: var(--accent); padding-top: 6px;
    position: sticky; top: 28px; align-self: start; height: fit-content;
}
.mq-section__body { max-width: 760px; }
.mq-eyebrow { margin-bottom: 18px; }
.mq-h2 {
    font-family: var(--serif); font-weight: 600;
    font-size: clamp(2rem, 5vw, 3.6rem); line-height: 1.02;
    letter-spacing: -0.02em; margin: 0 0 28px; text-transform: none;
}
.mq-prose { font-family: var(--serif); font-size: clamp(1.12rem, 1.5vw, 1.35rem); line-height: 1.7; color: #3A332B; white-space: pre-line; margin: 0; }

/* ── Details ──────────────────────────────────────────────── */
.mq-details { display: grid; gap: 0; }
.mq-detail {
    display: grid; grid-template-columns: 1fr auto; align-items: baseline;
    gap: 6px 20px; padding: 24px 0; border-bottom: 1px solid var(--line);
}
.mq-detail:first-child { border-top: 1px solid var(--line); }
.mq-detail__label { grid-row: 1; font-family: var(--sans); font-weight: 600; font-size: 11px; letter-spacing: 0.2em; text-transform: uppercase; color: var(--accent); }
.mq-detail__time { grid-row: 1; grid-column: 2; font-family: var(--serif); font-weight: 600; font-size: clamp(1.5rem, 3vw, 2.2rem); }
.mq-detail__venue { grid-column: 1 / -1; font-family: var(--serif); font-style: italic; color: var(--muted); font-size: 1.1rem; }

/* ── Timeline ─────────────────────────────────────────────── */
.mq-timeline { list-style: none; margin: 0; padding: 0; }
.mq-timeline__row {
    display: grid; grid-template-columns: 110px 1fr; align-items: baseline;
    gap: 4px 24px; padding: 20px 0; border-bottom: 1px solid var(--line);
}
.mq-timeline__row:first-child { border-top: 1px solid var(--line); }
.mq-timeline__time { font-family: var(--sans); font-weight: 700; font-size: 1.05rem; color: var(--accent); letter-spacing: 0.02em; }
.mq-timeline__title { font-family: var(--serif); font-weight: 600; font-size: clamp(1.3rem, 2.4vw, 1.7rem); }
.mq-timeline__loc { grid-column: 2; font-family: var(--serif); font-style: italic; color: var(--muted); font-size: 1.05rem; }

/* ── Footer ───────────────────────────────────────────────── */
.mq-footer { border-top: 1.5px solid var(--ink); padding: clamp(56px, 8vw, 96px) clamp(28px, 7vw, 96px); }
.mq-footer__names { font-family: var(--serif); font-weight: 900; text-transform: uppercase; font-size: clamp(2rem, 7vw, 4.5rem); line-height: 0.95; letter-spacing: -0.02em; margin: 0; }
.mq-footer__date { font-family: var(--sans); font-weight: 600; font-size: 12px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--muted); margin: 18px 0 0; }
.mq-footer__brand { font-family: var(--sans); font-size: 10px; letter-spacing: 0.24em; text-transform: uppercase; color: var(--muted); margin: 30px 0 0; }
.mq-footer__brand span { font-family: var(--serif); font-style: italic; text-transform: none; letter-spacing: 0; font-size: 14px; color: var(--accent); margin-left: 4px; }

/* ── Motion ───────────────────────────────────────────────── */
@keyframes mqRise { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } }
.mq-fade { opacity: 0; animation: mqRise 1s cubic-bezier(0.2,0.7,0.2,1) forwards; }
[data-reveal] { opacity: 0; transform: translateY(28px); transition: opacity 0.9s ease, transform 0.9s cubic-bezier(0.2,0.7,0.2,1); }
[data-reveal].is-in { opacity: 1; transform: none; }
@media (prefers-reduced-motion: reduce) {
    .mq-fade, [data-reveal] { animation: none !important; opacity: 1 !important; transform: none !important; transition: none !important; }
}

@media (max-width: 820px) {
    .mq-hero--split { grid-template-columns: 1fr; }
    .mq-hero__image { min-height: 46vh; order: -1; }
    .mq-section { grid-template-columns: 1fr; gap: 12px; }
    .mq-section__index { position: static; }
}
`;
