import { useEffect, useState } from 'react' import { createPortal } from 'react-dom' import { Search, X } from 'lucide-react' import { ApiError } from '../lib/api' import { useT } from '../i18n/useT' import { getProduct, updateProduct } from '../services/productService' import { seoMetaPayload } from '../utils/seoMeta' import { SeoMetaFields } from './SeoMetaFields' import styles from './VariationsModal.module.css' import seoStyles from './ProductSeoModal.module.css' interface ProductSeoModalProps { open: boolean productId: string productName: string onClose: () => void } const ANIMATION_MS = 220 export function ProductSeoModal({ open, productId, productName, onClose, }: ProductSeoModalProps) { const t = useT() const [mounted, setMounted] = useState(open) const [closing, setClosing] = useState(false) const [seoMetaTitle, setSeoMetaTitle] = useState('') const [seoMetaDescription, setSeoMetaDescription] = useState('') const [isLoading, setIsLoading] = useState(false) const [isSaving, setIsSaving] = useState(false) const [error, setError] = useState('') useEffect(() => { if (open) { setMounted(true) setClosing(false) } else if (mounted) { setClosing(true) const timer = setTimeout(() => { setMounted(false) setClosing(false) }, ANIMATION_MS) return () => clearTimeout(timer) } }, [open, mounted]) useEffect(() => { if (!open || !productId) return const controller = new AbortController() void loadData(controller.signal) return () => controller.abort() }, [open, productId]) async function loadData(signal?: AbortSignal) { setIsLoading(true) setError('') try { const product = await getProduct(productId, signal) setSeoMetaTitle(product.seoMetaTitle ?? '') setSeoMetaDescription(product.seoMetaDescription ?? '') } catch (err) { if (err instanceof DOMException && err.name === 'AbortError') return if (err instanceof ApiError) { setError(err.message) } else { setError(t('products.seo.errorLoad')) } } finally { setIsLoading(false) } } async function handleSave() { setIsSaving(true) setError('') try { await updateProduct(productId, seoMetaPayload(seoMetaTitle, seoMetaDescription)) onClose() } catch (err) { if (err instanceof ApiError) { setError(err.message) } else { setError(t('products.seo.errorSave')) } } finally { setIsSaving(false) } } if (!mounted) return null return createPortal(
!isSaving && onClose()} >
e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="product-seo-title" >

{productName ?

{productName}

: null}
{isLoading ? (

{t('products.seo.loading')}

) : ( )} {error ?

{error}

: null}
, document.body, ) }