import { PageProps } from '@/types';
import { Head, usePage } from '@inertiajs/react';

/** `<` is escaped so structured data can never close the script tag early. */
const safeJson = (o: unknown) => JSON.stringify(o).replace(/</g, '\\u003c');

/**
 * Meta tags, Open Graph, Twitter card and JSON-LD for the current page.
 * Defaults come from the server-provided `seo` prop; props here override them.
 */
export default function Seo({ title, description, image, canonical, noindex, type = 'website' }: { title?: string; description?: string | null; image?: string | null; canonical?: string; noindex?: boolean; type?: 'website' | 'article' | 'profile' }) {
    const { site, seo } = usePage<PageProps>().props;
    const desc = (description ?? seo?.description)?.slice(0, 300);
    const img = image ?? seo?.image ?? undefined;
    const url = canonical ?? seo?.canonical ?? site.canonical;
    const hidden = noindex ?? seo?.noindex ?? false;
    const fullTitle = title ? `${title} · ${site.name}` : site.name;

    return (
        <Head>
            {title && <title>{title}</title>}
            {desc && <meta head-key="description" name="description" content={desc} />}
            <link head-key="canonical" rel="canonical" href={url} />
            {hidden && <meta head-key="robots" name="robots" content="noindex, follow" />}

            <meta head-key="og:site_name" property="og:site_name" content={site.name} />
            <meta head-key="og:type" property="og:type" content={type} />
            <meta head-key="og:title" property="og:title" content={fullTitle} />
            {desc && <meta head-key="og:description" property="og:description" content={desc} />}
            <meta head-key="og:url" property="og:url" content={url} />
            {img && <meta head-key="og:image" property="og:image" content={img} />}

            <meta head-key="twitter:card" name="twitter:card" content={img ? 'summary_large_image' : 'summary'} />
            <meta head-key="twitter:title" name="twitter:title" content={fullTitle} />
            {desc && <meta head-key="twitter:description" name="twitter:description" content={desc} />}
            {img && <meta head-key="twitter:image" name="twitter:image" content={img} />}

            {seo?.jsonLd?.map((o, i) => (
                <script key={i} head-key={`ld-${i}`} type="application/ld+json">{safeJson(o)}</script>
            ))}
        </Head>
    );
}

/** For pages that must stay out of search results (account, admin, auth). */
export function NoIndex() {
    return <Head><meta head-key="robots" name="robots" content="noindex, nofollow" /></Head>;
}
