import { getBlockMeta } from '@/marketing/block-registry';
import { DEFAULT_FOOTER, DEFAULT_HEADER } from '@/marketing/cms-defaults';
import { migrateAbout, migrateFooter, migrateNav } from '@/marketing/cms-migrator';
import type { FooterConfig, HeaderConfig, PageConfig, Section } from '@/marketing/cms-types';
import PageSeo from '@/marketing/PageSeo';
import { Footer, Nav } from '@/marketing/shared';
import type { SharedProps } from '@/types/inertia';
import { Head, usePage } from '@inertiajs/react';
import type { ReactNode } from 'react';

/* Thin dispatcher mirroring Welcome.tsx. Reads `marketing.about.sections`
 * from shared props and routes each section through BLOCK_REGISTRY. The
 * legacy hardcoded Hero / Origin / Principles / Behind / FinalCta sections
 * are now sourced from MarketingDefaults::about() — admin edits via
 * /admin/marketing → About tab. */
export default function About() {
    const page = usePage<SharedProps>();
    const { auth, branding, marketing } = page.props;
    const siteName = branding?.site_name || 'AppShot AI';
    const navConfig = marketing?.nav
        ? migrateNav<HeaderConfig>(marketing.nav as HeaderConfig)
        : DEFAULT_HEADER;
    const footerConfig = marketing?.footer
        ? migrateFooter<FooterConfig>(marketing.footer as FooterConfig)
        : DEFAULT_FOOTER;

    const aboutConfig: PageConfig = marketing?.about
        ? migrateAbout<PageConfig>(marketing.about as PageConfig)
        : { version: 1, sections: [] };
    const sections: Section[] = aboutConfig.sections.filter(
        (s) => s.enabled !== false,
    );

    return (
        <>
            <Head title="About" />
            <PageSeo
                pageLabel="About"
                override={aboutConfig.seo}
                sections={sections}
            />
            <div className="flex min-h-screen flex-col bg-background font-sans text-foreground antialiased">
                <Nav
                    siteName={siteName}
                    authed={!!auth.user}
                    branding={branding}
                    nav={navConfig}
                />
                <main className="flex-1">
                    {sections.map((section) => (
                        <div key={section.id}>{renderSection(section)}</div>
                    ))}
                </main>
                <Footer
                    siteName={siteName}
                    branding={branding}
                    footer={footerConfig}
                />
            </div>
        </>
    );
}

function renderSection(section: Section): ReactNode {
    const meta = getBlockMeta(section.type);
    if (!meta) return null;
    const Renderer = meta.renderer;
    return <Renderer section={section} />;
}
