import { getBlockMeta } from '@/marketing/block-registry';
import { DEFAULT_FOOTER, DEFAULT_HEADER } from '@/marketing/cms-defaults';
import { migrateFooter, migrateNav, migrateRefund } 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';

export default function Refund() {
    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 refundConfig: PageConfig = marketing?.refund
        ? migrateRefund<PageConfig>(marketing.refund as PageConfig)
        : { version: 1, sections: [] };
    const sections: Section[] = refundConfig.sections.filter(
        (s) => s.enabled !== false,
    );

    return (
        <>
            <Head title="Refund policy" />
            <PageSeo
                pageLabel="Refund policy"
                override={refundConfig.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} />;
}
