import { useEffect } from 'react'; import { appConfig } from '@/config/appConfig'; interface PageMetadata { readonly title: string; readonly description?: string; readonly canonicalPath?: string; readonly image?: string; readonly type?: 'website' | 'article'; } function setMeta(attribute: 'name' | 'property', key: string, content: string): void { let element = document.head.querySelector(`meta[${attribute}="${key}"]`); if (!element) { element = document.createElement('meta'); element.setAttribute(attribute, key); document.head.appendChild(element); } element.content = content; } function setCanonical(canonicalPath: string | undefined): void { const baseUrl = appConfig.baseUrl.replace(/\/$/, ''); const href = canonicalPath ? new URL(canonicalPath, `${baseUrl}/`).toString() : baseUrl; let element = document.head.querySelector('link[rel="canonical"]'); if (!element) { element = document.createElement('link'); element.rel = 'canonical'; document.head.appendChild(element); } element.href = href; } export function usePageMetadata({ title, description, canonicalPath, image, type = 'website' }: PageMetadata): void { useEffect(() => { const fullTitle = title.includes(appConfig.name) ? title : `${title} ยท ${appConfig.name}`; const resolvedDescription = description ?? 'Explore mechanical systems through a premium engineering catalogue and interactive 3D-ready reference shell.'; document.title = fullTitle; setMeta('name', 'description', resolvedDescription); setMeta('property', 'og:title', fullTitle); setMeta('property', 'og:description', resolvedDescription); setMeta('property', 'og:type', type); setMeta('property', 'og:site_name', appConfig.name); setMeta('name', 'twitter:card', image ? 'summary_large_image' : 'summary'); setMeta('name', 'twitter:title', fullTitle); setMeta('name', 'twitter:description', resolvedDescription); if (image) { setMeta('property', 'og:image', image); setMeta('name', 'twitter:image', image); } setCanonical(canonicalPath); }, [canonicalPath, description, image, title, type]); }