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

interface SEOProps {
    title?: string;
    description?: string;
    image?: string;
    type?: 'website' | 'article' | 'product';
    schema?: any;
}

export default function SEO({ 
    title, 
    description, 
    image, 
    type = 'website',
    schema
}: SEOProps) {
    const { props } = usePage<any>();
    const appUrl = props.app_url || window.location.origin;
    const branding = props.branding;
    const seoSettings = props.seo;
    
    const siteName = branding?.name || 'Altivate Solutions';
    const defaultTitle = seoSettings?.title || `${siteName} | Growth Strategy & Digital Solutions`;
    const fullTitle = title ? `${title} | ${siteName}` : defaultTitle;
    const defaultDescription = seoSettings?.description || branding?.tagline || 'We help SMEs and startups scale through proven growth frameworks.';
    const keywords = seoSettings?.keywords || '';
    
    // Ensure absolute image URL
    const ogImage = image 
        ? (image.startsWith('http') ? image : `${appUrl}${image}`)
        : `${appUrl}/og-image.png`; // Fallback to a default OG image

    const canonical = typeof window !== 'undefined' ? window.location.href : appUrl;

    return (
        <Head>
            <title>{fullTitle}</title>
            <meta name="description" content={description || defaultDescription} />
            {keywords && <meta name="keywords" content={keywords} />}
            
            {/* Open Graph / Facebook */}
            <meta property="og:type" content={type} />
            <meta property="og:url" content={canonical} />
            <meta property="og:title" content={fullTitle} />
            <meta property="og:description" content={description || defaultDescription} />
            <meta property="og:image" content={ogImage} />
            <meta property="og:site_name" content={siteName} />

            {/* Twitter */}
            <meta name="twitter:card" content="summary_large_image" />
            <meta name="twitter:url" content={canonical} />
            <meta name="twitter:title" content={fullTitle} />
            <meta name="twitter:description" content={description || defaultDescription} />
            <meta name="twitter:image" content={ogImage} />

            <link rel="canonical" href={canonical} />

            {/* Structured Data (JSON-LD) */}
            {schema && (
                <script type="application/ld+json">
                    {JSON.stringify(schema)}
                </script>
            )}
        </Head>
    );
}
