'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useId, useState } from 'react';
import { AlertTriangle, CheckCircle2, ExternalLink, ImageIcon, Info, Loader2, RefreshCw, Search, Upload, X, } from 'lucide-react';
import { MediaPickerModal } from '../../components/MediaPickerModal.js';
import { SEOConfigPanel } from '../../components/SEOConfigPanel.js';
import { ConfirmDangerousSettingDialog, SettingsCard, SettingsSaveBar, SettingsSourceBadge, SettingsToggleRow, SettingsValidationSummary, } from './components.js';
import { META_DESCRIPTION_MAX, META_DESCRIPTION_MIN, useSeoSettings, validateTitleTemplateClient, } from './useSeoSettings.js';
const INPUT_CLASS = 'w-full rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60';
const LABEL_CLASS = 'mb-1 flex items-center gap-2 text-sm font-medium text-foreground';
const SUPPORTED_TOKENS = [
    '%page%',
    '%site%',
    '%type%',
    '%separator%',
    '%author%',
    '%date%',
    '%category%',
    '%tag%',
];
/** Sample data used to render a live title preview. */
function previewTitle(template, siteName) {
    const tpl = template.trim() === '' ? '%page% — %site%' : template;
    const vars = {
        page: 'Sample Page Title',
        site: siteName || 'Your Site',
        type: 'Page',
        separator: '|',
        author: 'Jane Doe',
        date: new Date().toISOString().slice(0, 10),
        category: 'News',
        tag: 'guide',
    };
    return tpl
        .replace(/%(\w+)%/g, (_, k) => vars[k] ?? '')
        .replace(/\s+/g, ' ')
        .replace(/^[\s\-–—|·•]+/, '')
        .replace(/[\s\-–—|·•]+$/, '')
        .trim();
}
export function SeoSettingsTab({ onNavigate, role }) {
    const canEdit = role === 'ADMIN';
    const seo = useSeoSettings(canEdit);
    if (seo.loading) {
        return (_jsxs("div", { className: "space-y-4", "aria-busy": "true", "aria-live": "polite", children: [_jsx("span", { className: "sr-only", children: "Loading SEO settings\u2026" }), [0, 1, 2, 3].map((i) => (_jsxs("div", { className: "border-border bg-card rounded-lg border p-6", children: [_jsx("div", { className: "bg-muted mb-4 h-4 w-40 animate-pulse rounded" }), _jsxs("div", { className: "space-y-3", children: [_jsx("div", { className: "bg-muted h-9 w-full animate-pulse rounded" }), _jsx("div", { className: "bg-muted h-9 w-full animate-pulse rounded" })] })] }, i)))] }));
    }
    return (_jsxs("div", { className: "space-y-4", children: [_jsx(SeoWorkspaceCallout, { onNavigate: onNavigate }), seo.loadError && (_jsxs("div", { role: "alert", className: "border-destructive/30 bg-destructive/10 text-destructive flex items-center gap-3 rounded-lg border p-3 text-sm", children: [_jsx(AlertTriangle, { size: 16, className: "shrink-0", "aria-hidden": "true" }), _jsx("span", { className: "flex-1", children: seo.loadError }), _jsx("button", { type: "button", onClick: seo.refetch, className: "border-destructive/40 rounded-md border px-3 py-1 transition-colors hover:opacity-80", children: "Retry" })] })), !canEdit && (_jsxs("div", { className: "border-border bg-muted text-muted-foreground flex items-center gap-2 rounded-lg border p-3 text-sm", children: [_jsx(Info, { size: 16, className: "shrink-0", "aria-hidden": "true" }), "You have read-only access to SEO defaults. Only administrators can make changes."] })), _jsx(SettingsValidationSummary, { issues: seo.issues }), _jsx(MetaDefaultsCard, { seo: seo, canEdit: canEdit }), _jsx(SearchEngineVerificationCard, { seo: seo, canEdit: canEdit }), _jsx(SitemapDefaultsCard, { seo: seo, canEdit: canEdit, onNavigate: onNavigate }), _jsxs("details", { className: "border-border bg-card group rounded-lg border", children: [_jsxs("summary", { className: "text-foreground flex cursor-pointer list-none items-center justify-between p-4 text-base font-medium", children: [_jsx("span", { children: "Advanced & per-collection SEO" }), _jsx("span", { className: "text-muted-foreground text-sm font-normal group-open:hidden", children: "Show" }), _jsx("span", { className: "text-muted-foreground hidden text-sm font-normal group-open:inline", children: "Hide" })] }), _jsxs("div", { className: "border-border border-t p-4", children: [_jsx("p", { className: "text-muted-foreground mb-4 text-sm", children: "Site name, social handle, per-collection schema, and route toggles. These share the same SEO configuration as the defaults above." }), _jsx(SEOConfigPanel, {})] })] }), seo.saveState === 'error' && seo.saveError && (_jsxs("div", { role: "alert", className: "border-destructive/30 bg-destructive/10 text-destructive flex items-center gap-3 rounded-lg border p-3 text-sm", children: [_jsx(AlertTriangle, { size: 16, className: "shrink-0", "aria-hidden": "true" }), _jsx("span", { className: "flex-1", children: seo.saveError }), _jsx("button", { type: "button", onClick: seo.save, className: "border-destructive/40 rounded-md border px-3 py-1 transition-colors hover:opacity-80", children: "Retry" })] })), _jsx(SettingsSaveBar, { dirty: seo.dirty, canEdit: canEdit, hasErrors: seo.hasErrors, saveState: seo.saveState, onSave: seo.save, onReset: seo.reset })] }));
}
// ---------------------------------------------------------------------------
// Full SEO workspace callout
// ---------------------------------------------------------------------------
function SeoWorkspaceCallout({ onNavigate }) {
    return (_jsxs("div", { className: "border-border bg-accent/40 flex items-center gap-4 rounded-lg border p-4", children: [_jsx("span", { className: "bg-brand/10 text-brand flex h-10 w-10 shrink-0 items-center justify-center rounded-lg", children: _jsx(Search, { size: 20, "aria-hidden": "true" }) }), _jsxs("div", { className: "flex-1", children: [_jsx("p", { className: "text-foreground text-base font-medium", children: "Looking for the full SEO workspace?" }), _jsx("p", { className: "text-muted-foreground text-sm", children: "These are site-wide defaults. Per-page meta, audits, redirects and AI recovery live in the SEO dashboard." })] }), _jsxs("button", { type: "button", onClick: () => onNavigate?.('/seo'), className: "border-border text-foreground hover:bg-accent inline-flex shrink-0 items-center gap-2 rounded-md border px-4 py-2 text-base font-medium transition-colors", children: [_jsx(ExternalLink, { size: 16, "aria-hidden": "true" }), "Open SEO"] })] }));
}
// ---------------------------------------------------------------------------
// Meta Defaults
// ---------------------------------------------------------------------------
function MetaDefaultsCard({ seo, canEdit }) {
    const templateId = useId();
    const descId = useId();
    const [pickerOpen, setPickerOpen] = useState(false);
    const { form, setField, issues, sources } = seo;
    const templateIssue = issues.find((i) => i.field === 'titleTemplate');
    const descIssue = issues.find((i) => i.field === 'defaultMetaDescription');
    const tplValidation = validateTitleTemplateClient(form.titleTemplate);
    const descLen = form.defaultMetaDescription.trim().length;
    const descCountClass = descLen > META_DESCRIPTION_MAX || (descLen > 0 && descLen < META_DESCRIPTION_MIN)
        ? 'text-warning'
        : 'text-muted-foreground';
    const templateEditable = sources.titleTemplate?.editable !== false && canEdit;
    const descEditable = sources.defaultMetaDescription?.editable !== false && canEdit;
    const imageEditable = sources.defaultOgImage?.editable !== false && canEdit;
    return (_jsxs(SettingsCard, { title: "Meta Defaults", description: "Fallback page title, description, and social image applied when a page defines none of its own.", children: [_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { children: [_jsxs("label", { htmlFor: templateId, className: LABEL_CLASS, children: ["Title template", _jsx(SettingsSourceBadge, { meta: sources.titleTemplate })] }), _jsx("input", { id: templateId, type: "text", value: form.titleTemplate, disabled: !templateEditable, placeholder: "%page% \u2014 %site%", "aria-invalid": templateIssue?.severity === 'error', onChange: (e) => setField('titleTemplate', e.target.value), className: INPUT_CLASS }), _jsxs("p", { className: "text-muted-foreground mt-1 text-sm", children: ["Tokens: ", SUPPORTED_TOKENS.join(' '), ". Applied to all pages without a custom SEO title."] }), templateIssue ? (_jsx("p", { className: "text-destructive mt-1 text-sm", children: templateIssue.message })) : (tplValidation.valid && (_jsxs("p", { className: "text-muted-foreground mt-1 text-sm", children: ["Preview:", ' ', _jsx("span", { className: "text-foreground font-medium", children: previewTitle(form.titleTemplate, seo.siteName) })] })))] }), _jsxs("div", { children: [_jsxs("label", { htmlFor: descId, className: LABEL_CLASS, children: ["Default meta description", _jsx(SettingsSourceBadge, { meta: sources.defaultMetaDescription })] }), _jsx("textarea", { id: descId, rows: 3, value: form.defaultMetaDescription, disabled: !descEditable, "aria-describedby": `${descId}-count`, onChange: (e) => setField('defaultMetaDescription', e.target.value), className: `${INPUT_CLASS} resize-y` }), _jsxs("div", { className: "mt-1 flex items-center justify-between gap-2", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: "Used when a page or post defines no description of its own." }), _jsxs("span", { id: `${descId}-count`, className: `text-sm ${descCountClass}`, children: [descLen, "/", META_DESCRIPTION_MAX] })] }), descIssue && _jsx("p", { className: "text-warning mt-1 text-sm", children: descIssue.message })] }), _jsxs("div", { children: [_jsxs("span", { className: LABEL_CLASS, children: ["Default social share image", _jsx(SettingsSourceBadge, { meta: sources.defaultOgImage })] }), _jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "border-border bg-muted flex h-16 w-28 shrink-0 items-center justify-center overflow-hidden rounded-md border", children: form.defaultOgImage ? (
                                        // eslint-disable-next-line @next/next/no-img-element
                                        _jsx("img", { src: form.defaultOgImage, alt: "Default social share preview", className: "h-full w-full object-cover" })) : (_jsx(ImageIcon, { size: 20, className: "text-muted-foreground", "aria-hidden": "true" })) }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("button", { type: "button", onClick: () => setPickerOpen(true), disabled: !imageEditable, className: "border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-60", children: [_jsx(Upload, { size: 14, "aria-hidden": "true" }), form.defaultOgImage ? 'Replace' : 'Choose image'] }), form.defaultOgImage && imageEditable && (_jsxs("button", { type: "button", onClick: () => {
                                                            setField('defaultOgImage', '');
                                                            setField('defaultSocialImageAssetId', '');
                                                        }, className: "text-muted-foreground hover:text-destructive inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors", children: [_jsx(X, { size: 14, "aria-hidden": "true" }), "Remove"] }))] }), _jsx("p", { className: "text-muted-foreground text-sm", children: "1200\u00D7630 recommended" })] })] })] })] }), _jsx(SeoPreviewCard, { title: previewTitle(form.titleTemplate, seo.siteName), url: seo.siteUrl || 'https://example.com', description: form.defaultMetaDescription.trim() || 'Your default meta description appears here.', image: form.defaultOgImage, siteName: seo.siteName }), _jsx(MediaPickerModal, { open: pickerOpen, onClose: () => setPickerOpen(false), accept: "image/*", onSelect: (url) => setField('defaultOgImage', url), onSelectItem: (item) => setField('defaultSocialImageAssetId', item.id) })] }));
}
function SeoPreviewCard({ title, url, description, image, siteName, }) {
    return (_jsxs("div", { className: "border-border mt-4 grid gap-4 border-t pt-4 sm:grid-cols-2", children: [_jsxs("div", { className: "border-border rounded-lg border p-3", children: [_jsx("p", { className: "text-muted-foreground mb-2 text-xs font-medium tracking-wide uppercase", children: "Search preview" }), _jsx("p", { className: "text-success truncate text-sm", children: url }), _jsx("p", { className: "text-primary truncate text-lg leading-snug", children: title }), _jsx("p", { className: "text-muted-foreground line-clamp-2 text-sm", children: description })] }), _jsxs("div", { className: "border-border overflow-hidden rounded-lg border", children: [_jsx("div", { className: "bg-muted flex aspect-1200/630 items-center justify-center", children: image ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        _jsx("img", { src: image, alt: "Social share preview", className: "h-full w-full object-cover" })) : (_jsx(ImageIcon, { size: 24, className: "text-muted-foreground", "aria-hidden": "true" })) }), _jsxs("div", { className: "p-3", children: [_jsx("p", { className: "text-muted-foreground truncate text-xs uppercase", children: siteName || new URL(url).hostname }), _jsx("p", { className: "text-foreground truncate text-sm font-medium", children: title }), _jsx("p", { className: "text-muted-foreground line-clamp-1 text-xs", children: description })] })] })] }));
}
// ---------------------------------------------------------------------------
// Search Engine Verification
// ---------------------------------------------------------------------------
function VerificationField({ label, field, placeholder, value, onChange, disabled, }) {
    const id = useId();
    const hasValue = value.trim().length > 0;
    return (_jsxs("div", { children: [_jsxs("label", { htmlFor: id, className: LABEL_CLASS, children: [label, hasValue && (_jsxs("span", { className: "text-muted-foreground border-border bg-muted inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-xs", children: [_jsx(CheckCircle2, { size: 11, className: "text-success", "aria-hidden": "true" }), "Saved"] }))] }), _jsx("input", { id: id, type: "text", autoComplete: "off", spellCheck: false, value: value, disabled: disabled, placeholder: placeholder, onChange: (e) => onChange(field, e.target.value), className: INPUT_CLASS })] }));
}
function SearchEngineVerificationCard({ seo, canEdit }) {
    const { form, setField } = seo;
    const onChange = (key, value) => setField(key, value);
    return (_jsxs(SettingsCard, { title: "Search Engine Verification", description: "Paste the verification token from each provider. We render only safe meta tags into your site's head \u2014 never arbitrary HTML.", children: [_jsxs("div", { className: "space-y-4", children: [_jsx(VerificationField, { label: "Google Search Console", field: "googleVerification", placeholder: "google-site-verification\u2026", value: form.googleVerification, onChange: onChange, disabled: !canEdit }), _jsx(VerificationField, { label: "Bing Webmaster Tools", field: "bingVerification", placeholder: "msvalidate.01\u2026", value: form.bingVerification, onChange: onChange, disabled: !canEdit })] }), _jsxs("details", { className: "group mt-4", children: [_jsxs("summary", { className: "text-brand cursor-pointer list-none text-sm hover:underline", children: [_jsx("span", { className: "group-open:hidden", children: "More providers" }), _jsx("span", { className: "hidden group-open:inline", children: "Fewer providers" })] }), _jsxs("div", { className: "mt-4 space-y-4", children: [_jsx(VerificationField, { label: "Yandex", field: "yandexVerification", placeholder: "yandex-verification\u2026", value: form.yandexVerification, onChange: onChange, disabled: !canEdit }), _jsx(VerificationField, { label: "Pinterest", field: "pinterestVerification", placeholder: "p:domain_verify\u2026", value: form.pinterestVerification, onChange: onChange, disabled: !canEdit }), _jsx(VerificationField, { label: "Facebook domain verification", field: "facebookDomainVerification", placeholder: "facebook-domain-verification\u2026", value: form.facebookDomainVerification, onChange: onChange, disabled: !canEdit })] })] })] }));
}
// ---------------------------------------------------------------------------
// Sitemap Defaults
// ---------------------------------------------------------------------------
function SitemapDefaultsCard({ seo, canEdit, onNavigate, }) {
    const [pendingDisable, setPendingDisable] = useState(false);
    const { form, setField, sitemap, siteUrl, isProduction, regenerateSitemap, regenerating } = seo;
    function requestAutoGenerate(value) {
        // Turning auto-generation off on production can let the sitemap go stale.
        if (!value && isProduction) {
            setPendingDisable(true);
            return;
        }
        setField('autoGenerateSitemap', value);
    }
    const lastGenerated = sitemap?.lastGeneratedAt
        ? new Date(sitemap.lastGeneratedAt).toLocaleString()
        : 'Never';
    return (_jsxs(SettingsCard, { title: "Sitemap", description: "Control XML sitemap generation and whether search engines are pinged on publish.", children: [!siteUrl && (_jsxs("div", { className: "border-warning/30 bg-warning/10 text-warning mb-4 flex items-start gap-2 rounded-md border p-3 text-sm", children: [_jsx(AlertTriangle, { size: 16, className: "mt-0.5 shrink-0", "aria-hidden": "true" }), "Site URL is not set \u2014 sitemap URLs may be incorrect. Set it in Settings \u2192 General."] })), _jsxs("div", { className: "space-y-4", children: [_jsx(SettingsToggleRow, { label: "Auto-generate XML sitemap", description: "Rebuild the sitemap whenever content is published.", checked: form.autoGenerateSitemap, disabled: !canEdit, onChange: requestAutoGenerate }), _jsx(SettingsToggleRow, { label: "Ping search engines on publish", description: "Notify Google and Bing when the sitemap changes.", checked: form.pingOnPublish, disabled: !canEdit || !form.autoGenerateSitemap, onChange: (v) => setField('pingOnPublish', v) })] }), _jsxs("div", { className: "border-border mt-4 space-y-2 border-t pt-4", children: [_jsxs("div", { className: "flex items-center justify-between gap-2 text-sm", children: [_jsx("span", { className: "text-muted-foreground", children: "Sitemap URL" }), sitemap?.sitemapUrl ? (_jsxs("a", { href: sitemap.sitemapUrl, target: "_blank", rel: "noreferrer", className: "text-brand inline-flex items-center gap-1 font-medium hover:underline", children: ["View sitemap", _jsx(ExternalLink, { size: 13, "aria-hidden": "true" })] })) : (_jsx("span", { className: "text-foreground font-medium", children: "/sitemap.xml" }))] }), _jsx(SummaryRow, { label: "Last generated", value: lastGenerated }), _jsx(SummaryRow, { label: "Included URLs", value: String(sitemap?.pagesIncluded ?? '—') }), _jsx(SummaryRow, { label: "Excluded URLs", value: String(sitemap?.pagesExcluded ?? '—') }), _jsxs("div", { className: "flex items-center justify-between gap-2 pt-1", children: [_jsxs("button", { type: "button", onClick: regenerateSitemap, disabled: !canEdit || regenerating, className: "border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-60", children: [regenerating ? (_jsx(Loader2, { size: 14, className: "animate-spin", "aria-hidden": "true" })) : (_jsx(RefreshCw, { size: 14, "aria-hidden": "true" })), "Regenerate now"] }), onNavigate && (_jsx("button", { type: "button", onClick: () => onNavigate('/seo?tab=technical'), className: "text-brand text-sm hover:underline", children: "Manage in SEO Technical \u2192" }))] })] }), _jsx(ConfirmDangerousSettingDialog, { open: pendingDisable, title: "Stop auto-generating the sitemap on production?", description: "Your sitemap may go stale as content changes, which can hurt how quickly search engines discover new pages.", confirmLabel: "Turn Off", onConfirm: () => {
                    setField('autoGenerateSitemap', false);
                    setPendingDisable(false);
                }, onCancel: () => setPendingDisable(false) })] }));
}
function SummaryRow({ label, value }) {
    return (_jsxs("div", { className: "flex items-center justify-between gap-2 text-sm", children: [_jsx("span", { className: "text-muted-foreground", children: label }), _jsx("span", { className: "text-foreground font-medium", children: value })] }));
}
//# sourceMappingURL=SeoSettingsTab.js.map