'use client';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
// packages/ui/src/internal/layout/components/NextJsAutoMetaTags.tsx
/**
 * @fileoverview Next.js automatic meta tags component
 * @description Next.js-specific SEO meta tag management with route-based generation
 *
 * @deprecated This component is deprecated. Metadata is now generated server-side
 * via generateMetadata() functions in page files for optimal SEO. This component
 * only works client-side and meta tags won't be in initial HTML for search engines.
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */
import { usePathname } from 'next/navigation';
import { useMemo } from 'react';
import { Helmet } from 'react-helmet-async';
import { useTranslation, getDndevConfig, useIsClient } from '@donotdev/core';
import { useAppConfig, getPlatformEnvVar } from '@donotdev/core';
/**
 * 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 config (injected by build system).
 * Resolves dynamic routes by pattern 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 && route.meta) {
            return { ...route.meta, ns: route.meta.namespace };
        }
        // 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));
        if (matches.length > 0) {
            const best = matches.reduce((a, b) => b.path.length > a.path.length ? b : a);
            if (best.meta) {
                return { ...best.meta, ns: best.meta.namespace };
            }
        }
    }
    // Fallback: first path segment as namespace
    const segments = pathname.split('/').filter(Boolean);
    if (segments.length > 0) {
        return { ns: segments[0] };
    }
    return {};
}
/**
 * Next.js-specific AutoMetaTags component
 *
 * Uses Next.js hooks directly instead of platform-aware hooks
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */
const NextJsAutoMetaTags = ({ config = {}, routeMeta: routeMetaOverride, title: titleOverride, description: descriptionOverride, image: imageOverride, additionalTags = {}, }) => {
    // Use Next.js pathname directly
    const pathname = usePathname();
    const isClient = useIsClient();
    // Memoize the namespaces to prevent hooks order issues
    const namespaces = useMemo(() => {
        return ['dndev', config.defaultNamespace || 'home'];
    }, [config.defaultNamespace]);
    const { t } = useTranslation(namespaces);
    const { defaultNamespace = 'home', defaultImage = '/og-image.png', twitterHandle, defaultAuthor, staticTags = {}, } = config;
    const siteName = config.siteName || useAppConfig('name');
    const baseUrl = getPlatformEnvVar('APP_URL') || '';
    // Get route metadata
    const routeMeta = getRouteMetadata(pathname || '/', isClient);
    const finalRouteMeta = { ...routeMeta, ...routeMetaOverride };
    // Memoize computed values for performance
    const metaData = useMemo(() => {
        // Construct absolute URL for canonical link
        const currentUrl = `${baseUrl}${pathname || '/'}`;
        const ns = finalRouteMeta.ns || defaultNamespace;
        // Get meta tags from translation files
        const pageTitle = finalRouteMeta.title || t(`${ns}:title`);
        const pageDescription = finalRouteMeta.description || t(`${ns}:description`);
        // Get the meta object and destructure it properly
        const metaObject = t(`${ns}:meta`, { returnObjects: true });
        const pageImage = finalRouteMeta.image || metaObject?.image || defaultImage;
        const pageType = finalRouteMeta.type || metaObject?.type || 'website';
        const pageKeywords = finalRouteMeta.keywords || metaObject?.keywords;
        const pageAuthor = finalRouteMeta.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: finalRouteMeta.noindex || false,
            keywords,
            author,
            publishDate: finalRouteMeta.publishDate,
            modifiedDate: finalRouteMeta.modifiedDate,
        };
    }, [
        baseUrl,
        pathname,
        finalRouteMeta,
        defaultNamespace,
        defaultImage,
        siteName,
        t,
    ]);
    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))), Object.entries(additionalTags).map(([name, content]) => (_jsx("meta", { name: name, content: content }, name))), metaData.image && metaData.image.startsWith('http') && (_jsx("link", { rel: "dns-prefetch", href: new URL(metaData.image).origin }))] }));
};
export default NextJsAutoMetaTags;
