'use client';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
// packages/ui/src/internal/layout/components/AutoMetaTags.tsx
/**
 * @fileoverview Automatic meta tags system integrated with DnDev framework
 * @description Zero-config SEO with route-based meta generation - no defaults, only explicit page definitions
 *
 * This component provides comprehensive SEO meta tag management with automatic
 * generation based on route metadata and translation files. It ensures optimal
 * search engine optimization without requiring manual configuration for each page.
 *
 * **Key Features:**
 * - Zero-configuration SEO setup
 * - Automatic meta tag generation from route data
 * - Open Graph and Twitter Card support
 * - Internationalization integration
 * - Canonical URL management
 * - Structured data support
 *
 * **SEO Capabilities:**
 * - Dynamic title and description generation
 * - Social media sharing optimization
 * - Search engine indexing control
 * - Multi-language support
 * - Image and video metadata
 *
 * **Framework Integration:**
 * - Uses Helmet for meta tag management
 * - Integrates with i18n system for translations
 * - Leverages platform location for routing
 * - Supports both static and dynamic content
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 *
 * **Usage Pattern:**
 * ```tsx
 * <AutoMetaTags
 * config={{
 * siteName: "My App",
 * defaultImage: "/og-image.jpg"
 * }}
 * />
 * ```
 */
// packages/core/ui/src/components/layout/components/AutoMetaTags.tsx
import { useMemo } from 'react';
import { Helmet } from 'react-helmet-async';
import { useTranslation, useIsClient } from '@donotdev/core';
import { getDndevConfig } from '@donotdev/core';
import { useSeoConfig, useAppConfig, getPlatformEnvVar } from '@donotdev/core';
import { AssetResolver } from '@donotdev/ui';
// Platform-specific hooks via conditional exports
import { useLocation } from '@donotdev/ui/routing/hooks';
/**
 * Match pathname against route path pattern (e.g. /cars/:id or /blog/:slug/comments/:id).
 * Supports arbitrary nesting: any depth, any mix of static and :param segments.
 */
function matchRoutePath(pattern, pathname) {
    const patternSegments = pattern.split('/').filter(Boolean);
    const pathnameSegments = pathname.split('/').filter(Boolean);
    if (patternSegments.length !== pathnameSegments.length)
        return false;
    for (let i = 0; i < patternSegments.length; i++) {
        const segment = patternSegments[i];
        const pathSegment = pathnameSegments[i];
        if (segment === undefined || pathSegment === undefined)
            return false;
        if (segment.startsWith(':'))
            continue; // param matches any value
        if (segment !== pathSegment)
            return false;
    }
    return true;
}
/**
 * Get route metadata from window object (injected by build system).
 * Resolves dynamic routes by pattern (e.g. /cars/:id) so PageMeta (including namespace) is used for SEO.
 */
function getRouteMetadata(pathname, isClient) {
    if (!isClient)
        return {};
    // Try to get route metadata from build-time injection
    const config = getDndevConfig();
    const routeData = config?.routes?.mapping;
    if (routeData && Array.isArray(routeData)) {
        // 1. Exact match (static routes)
        let route = routeData.find((r) => r.path === pathname);
        if (route)
            return route.meta;
        // 2. Pattern match (dynamic routes: /cars/:id, /blog/:slug/comments/:id, etc.)
        const dynamicRoutes = routeData.filter((r) => typeof r.path === 'string' && r.path.includes(':'));
        const matches = dynamicRoutes.filter((r) => matchRoutePath(r.path, pathname));
        // Prefer most specific (longest path) so /blog/:slug/comments wins over /blog/:slug for /blog/a/comments
        if (matches.length > 0) {
            route = matches.reduce((best, r) => r.path.length > best.path.length ? r : best);
            return route.meta;
        }
    }
    // Fallback: first path segment as namespace (e.g. /cars/abc123 → ns: cars)
    const segments = pathname.split('/').filter(Boolean);
    if (segments.length > 0) {
        return { ns: segments[0] };
    }
    return {};
}
/**
 * AutoMetaTags component
 *
 * Uses configuration from AppConfigProvider context.
 * No props needed - all config comes from useSeoConfig() and useAppConfig().
 *
 * Features:
 * - Automatic route-based meta tag generation
 * - i18n integration
 * - Open Graph and Twitter Cards
 * - 100% Lighthouse SEO compliance
 */
export const AutoMetaTags = () => {
    const { t } = useTranslation();
    const location = useLocation();
    const seoConfig = useSeoConfig();
    const isClient = useIsClient();
    const siteName = useAppConfig('name');
    const baseUrl = getPlatformEnvVar('APP_URL') || '';
    // Get route metadata — computed from current pathname and client flag
    const routeMeta = getRouteMetadata(location.pathname, isClient);
    // Memoize computed values for performance — must be called before any early return
    const metaData = useMemo(() => {
        if (!seoConfig)
            return null;
        const { defaultNamespace = 'home', defaultImage } = seoConfig;
        // Construct absolute URL for canonical link
        const currentUrl = `${baseUrl}${location.pathname}`;
        const ns = routeMeta.ns || defaultNamespace;
        // Get meta tags from translation files
        const pageTitle = routeMeta.title || t(`${ns}:title`);
        const pageDescription = routeMeta.description || t(`${ns}:description`);
        // Get the meta object and destructure it properly
        const metaObject = t(`${ns}:meta`, { returnObjects: true });
        const pageImage = routeMeta.image || metaObject?.image || defaultImage;
        const pageType = routeMeta.type || metaObject?.type || 'website';
        const pageKeywords = routeMeta.keywords || metaObject?.keywords;
        const pageAuthor = routeMeta.author || metaObject?.author;
        // Only use values that are actually defined (not empty strings or undefined)
        const title = pageTitle && pageTitle !== `${ns}:title` ? pageTitle : undefined;
        const description = pageDescription && pageDescription !== `${ns}:description`
            ? pageDescription
            : undefined;
        const image = pageImage || undefined;
        const type = pageType || 'website';
        const keywords = pageKeywords || undefined;
        const author = pageAuthor || undefined;
        // Build full title with site name if title exists, otherwise just use site name
        const fullTitle = title ? `${title} | ${siteName}` : siteName;
        // Use relative image path instead of constructing absolute URL
        // This prevents crashes from invalid baseUrl and works in all modes
        const imagePath = image && image.startsWith('http') ? image : image ? image : undefined;
        return {
            title: fullTitle,
            description,
            image: imagePath,
            url: currentUrl,
            type,
            noindex: routeMeta.noindex || false,
            keywords,
            author,
            publishDate: routeMeta.publishDate,
            modifiedDate: routeMeta.modifiedDate,
        };
    }, [location.pathname, routeMeta, siteName, baseUrl, seoConfig, t]);
    // Return null if SEO is disabled — after all hooks have been called
    if (!seoConfig || !metaData)
        return null;
    const { twitterHandle, staticTags = {} } = seoConfig;
    return (_jsxs(Helmet, { children: [_jsx("title", { children: metaData.title }), metaData.description && (_jsx("meta", { name: "description", content: metaData.description })), _jsx("link", { rel: "canonical", href: metaData.url }), metaData.keywords && (_jsx("meta", { name: "keywords", content: Array.isArray(metaData.keywords)
                    ? metaData.keywords.join(', ')
                    : metaData.keywords })), metaData.author && _jsx("meta", { name: "author", content: metaData.author }), metaData.noindex && _jsx("meta", { name: "robots", content: "noindex, nofollow" }), _jsx("meta", { property: "og:title", content: metaData.title }), metaData.description && (_jsx("meta", { property: "og:description", content: metaData.description })), _jsx("meta", { property: "og:url", content: metaData.url }), _jsx("meta", { property: "og:type", content: metaData.type }), metaData.image && _jsx("meta", { property: "og:image", content: metaData.image }), _jsx("meta", { property: "og:site_name", content: siteName }), metaData.type === 'article' && (_jsxs(_Fragment, { children: [metaData.author && (_jsx("meta", { property: "article:author", content: metaData.author })), metaData.publishDate && (_jsx("meta", { property: "article:published_time", content: metaData.publishDate })), metaData.modifiedDate && (_jsx("meta", { property: "article:modified_time", content: metaData.modifiedDate }))] })), _jsx("meta", { name: "twitter:card", content: "summary_large_image" }), _jsx("meta", { name: "twitter:title", content: metaData.title }), metaData.description && (_jsx("meta", { name: "twitter:description", content: metaData.description })), metaData.image && _jsx("meta", { name: "twitter:image", content: metaData.image }), twitterHandle && (_jsx("meta", { name: "twitter:site", content: `@${twitterHandle}` })), metaData.author && (_jsx("meta", { name: "twitter:creator", content: metaData.author })), _jsx("meta", { name: "format-detection", content: "telephone=no" }), _jsx("meta", { name: "mobile-web-app-capable", content: "yes" }), _jsx("meta", { name: "apple-mobile-web-app-status-bar-style", content: "default" }), Object.entries(staticTags).map(([name, content]) => (_jsx("meta", { name: name, content: content }, name))), baseUrl && (_jsx("link", { rel: "alternate", type: "application/rss+xml", title: `${siteName} Blog`, href: `${baseUrl}/rss.xml` })), metaData.image && metaData.image.startsWith('http') && (_jsx("link", { rel: "dns-prefetch", href: new URL(metaData.image).origin })), _jsx("script", { type: "application/ld+json", children: JSON.stringify({
                    '@context': 'https://schema.org',
                    '@type': metaData.type === 'article' ? 'Article' : 'WebPage',
                    name: metaData.title,
                    ...(metaData.description && { description: metaData.description }),
                    url: metaData.url,
                    ...(metaData.image && { image: metaData.image }),
                    ...(metaData.type === 'article' && {
                        ...(metaData.author && {
                            author: {
                                '@type': 'Person',
                                name: metaData.author,
                            },
                        }),
                        ...(metaData.publishDate && {
                            datePublished: metaData.publishDate,
                        }),
                        ...(metaData.modifiedDate && {
                            dateModified: metaData.modifiedDate,
                        }),
                    }),
                    publisher: {
                        '@type': 'Organization',
                        name: siteName,
                        logo: {
                            '@type': 'ImageObject',
                            url: AssetResolver.assetExists('/icon-512x512.png')
                                ? '/icon-512x512.png'
                                : AssetResolver.assetExists('/icon-192x192.png')
                                    ? '/icon-192x192.png'
                                    : '/logo.svg',
                        },
                    },
                }) })] }));
};
/**
 * AutoMetaTags retrieves all configuration from AppConfigProvider.
 * Page-specific overrides should be configured through AppConfig or route metadata.
 */
export default AutoMetaTags;
