import { Head } from '@inertiajs/react';

type JsonLd = Record<string, unknown>;

type SeoHeadProps = {
    title: string;
    description?: string | null;
    canonicalUrl?: string | null;
    keywords?: string | null;
    imageUrl?: string | null;
    type?: 'website' | 'article' | 'product';
    jsonLd?: JsonLd | JsonLd[] | null;
};

export function SeoHead({
    title,
    description,
    canonicalUrl,
    keywords,
    imageUrl,
    type = 'website',
    jsonLd,
}: SeoHeadProps) {
    const twitterCard = imageUrl ? 'summary_large_image' : 'summary';
    const schemas = Array.isArray(jsonLd) ? jsonLd : jsonLd ? [jsonLd] : [];
    const openGraphType =
        type === 'product'
            ? 'product'
            : type === 'article'
              ? 'article'
              : 'website';

    return (
        <Head title={title}>
            {description ? (
                <meta name="description" content={description} />
            ) : null}
            {keywords ? <meta name="keywords" content={keywords} /> : null}
            {canonicalUrl ? <link rel="canonical" href={canonicalUrl} /> : null}

            <meta property="og:title" content={title} />
            {description ? (
                <meta property="og:description" content={description} />
            ) : null}
            <meta property="og:type" content={openGraphType} />
            {canonicalUrl ? (
                <meta property="og:url" content={canonicalUrl} />
            ) : null}
            {imageUrl ? <meta property="og:image" content={imageUrl} /> : null}

            <meta name="twitter:card" content={twitterCard} />
            <meta name="twitter:title" content={title} />
            {description ? (
                <meta name="twitter:description" content={description} />
            ) : null}
            {imageUrl ? <meta name="twitter:image" content={imageUrl} /> : null}

            {schemas.map((schema, index) => (
                <script key={`json-ld-${index}`} type="application/ld+json">
                    {JSON.stringify(schema)}
                </script>
            ))}
        </Head>
    );
}
