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

const SITE_NAME = import.meta.env.VITE_APP_NAME || 'Upepo Finance';

const DEFAULT_DESCRIPTION =
    'Upepo Finance is the MFI operating system for East Africa — loans, savings, accounting, HR, and collections, built for microfinance institutions.';

const DEFAULT_IMAGE = '/images/logo.png';

interface SeoProps {
    /** Raw page title, without the site name — the global title callback appends " - Upepo Finance". */
    title: string;
    description?: string;
    /** Absolute URL or a path relative to the app origin. */
    image?: string;
    type?: 'website' | 'article' | 'profile';
    /** Marks the page as unsuitable for indexing (internal/showcase pages). */
    noindex?: boolean;
    children?: ReactNode;
}

export default function Seo({
    title,
    description = DEFAULT_DESCRIPTION,
    image = DEFAULT_IMAGE,
    type = 'website',
    noindex = false,
    children,
}: SeoProps) {
    const { ziggy } = usePage<PageProps>().props;
    const origin = ziggy?.url ?? '';
    const canonicalUrl = ziggy?.location ?? origin;
    const absoluteImage = image.startsWith('http')
        ? image
        : `${origin}${image}`;

    return (
        <Head title={title}>
            <meta name="description" content={description} />
            <link rel="canonical" href={canonicalUrl} />
            {noindex && <meta name="robots" content="noindex, nofollow" />}

            <meta property="og:site_name" content={SITE_NAME} />
            <meta property="og:type" content={type} />
            <meta property="og:title" content={title} />
            <meta property="og:description" content={description} />
            <meta property="og:image" content={absoluteImage} />
            <meta property="og:url" content={canonicalUrl} />

            <meta name="twitter:card" content="summary_large_image" />
            <meta name="twitter:title" content={title} />
            <meta name="twitter:description" content={description} />
            <meta name="twitter:image" content={absoluteImage} />

            {children}
        </Head>
    );
}
