'use client';
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { cloneElement, isValidElement, useEffect, useId, useState } from 'react';
import { Sparkles, Check } from 'lucide-react';
import { toast } from 'sonner';
import { fetchSeoContentRecord, updateSeoFields, generateSeoField, } from '../../lib/seo-service.js';
import { Drawer } from './Drawer.js';
import { SeoLoading, SeoErrorState, btnPrimary, btnSecondary, gradeMeta } from './primitives.js';
const META_TITLE_MAX = 60;
const META_DESC_MAX = 160;
function CharCount({ value, max }) {
    const over = value.length > max;
    return (_jsxs("span", { className: `text-xs ${over ? 'text-destructive' : 'text-muted-foreground'}`, children: [value.length, "/", max] }));
}
function Field({ label, children, hint, }) {
    // Associate the visible label with its control for screen readers. We inject
    // a generated id onto the single child input/textarea (unless it already has
    // one) and point the <label htmlFor> at it.
    const generatedId = useId();
    let control = children;
    if (isValidElement(children) && children.props.id == null) {
        control = cloneElement(children, { id: generatedId });
    }
    const controlId = isValidElement(control) ? control.props.id : undefined;
    return (_jsxs("div", { className: "space-y-1.5", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("label", { htmlFor: controlId, className: "text-foreground text-sm font-medium", children: label }), hint] }), control] }));
}
const inputCls = 'w-full rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
export function SeoEditorDrawer({ open, onOpenChange, entityType, entityId, onSaved, }) {
    const [record, setRecord] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [saving, setSaving] = useState(false);
    const [aiBusy, setAiBusy] = useState(null);
    const [form, setForm] = useState({});
    useEffect(() => {
        if (!open || !entityType || !entityId)
            return;
        let alive = true;
        setLoading(true);
        setError(null);
        fetchSeoContentRecord(entityType, entityId)
            .then((rec) => {
            if (!alive)
                return;
            if (!rec) {
                setError('Could not load this record.');
                return;
            }
            setRecord(rec);
            setForm({
                metaTitle: rec.metaTitle ?? '',
                metaDescription: rec.metaDescription ?? '',
                canonicalUrl: rec.canonicalUrl ?? '',
                focusKeyword: rec.focusKeyword ?? '',
                ogTitle: rec.ogTitle ?? '',
                ogDescription: rec.ogDescription ?? '',
                noindex: rec.noindex,
                nofollow: rec.nofollow,
            });
        })
            .catch((e) => alive && setError(e instanceof Error ? e.message : 'Failed to load'))
            .finally(() => alive && setLoading(false));
        return () => {
            alive = false;
        };
    }, [open, entityType, entityId]);
    const update = (patch) => setForm((f) => ({ ...f, ...patch }));
    async function handleAiGenerate(field) {
        if (!entityType || !entityId)
            return;
        setAiBusy(field);
        try {
            const result = await generateSeoField(field, { entityType, entityId });
            if (result.unavailable) {
                toast.error('AI is not configured. Add an AI provider to enable suggestions.');
                return;
            }
            if (result.text) {
                update({ [field]: result.text });
                toast.success('AI suggestion applied — review before saving.');
            }
            else {
                toast.error('No suggestion was returned.');
            }
        }
        catch {
            toast.error('AI request failed.');
        }
        finally {
            setAiBusy(null);
        }
    }
    async function handleSave() {
        if (!entityType || !entityId)
            return;
        setSaving(true);
        const res = await updateSeoFields(entityType, entityId, form);
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('SEO fields saved.');
        onOpenChange(false);
        onSaved?.();
    }
    const title = form.metaTitle || record?.title || 'Untitled';
    const desc = form.metaDescription || 'No meta description set. Search engines may generate one.';
    const url = record?.url ?? '';
    function aiButton(field) {
        return (_jsxs("button", { type: "button", onClick: () => handleAiGenerate(field), disabled: aiBusy !== null, className: "text-primary hover:bg-accent focus-visible:ring-ring inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium focus-visible:ring-2 focus-visible:outline-none disabled:opacity-60", children: [_jsx(Sparkles, { className: `h-3.5 w-3.5 ${aiBusy === field ? 'animate-pulse' : ''}`, "aria-hidden": true }), aiBusy === field ? 'Generating…' : 'AI Generate'] }));
    }
    return (_jsx(Drawer, { open: open, onOpenChange: onOpenChange, title: "Edit SEO", description: record?.title, footer: _jsxs(_Fragment, { children: [_jsx("button", { className: btnSecondary, onClick: () => onOpenChange(false), disabled: saving, children: "Cancel" }), _jsx("button", { className: btnPrimary, onClick: handleSave, disabled: saving || loading, children: saving ? 'Saving…' : 'Save changes' })] }), children: loading ? (_jsx(SeoLoading, {})) : error ? (_jsx(SeoErrorState, { message: error })) : record ? (_jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "border-border rounded-lg border p-4", children: [_jsx("p", { className: "text-muted-foreground mb-2 text-xs font-medium tracking-wide uppercase", children: "Google preview" }), _jsx("p", { className: "text-success truncate text-sm", children: url }), _jsx("p", { className: "text-primary text-lg leading-snug", children: title }), _jsx("p", { className: "text-muted-foreground line-clamp-2 text-sm", children: desc })] }), _jsx(Field, { label: "Meta title", hint: _jsxs("span", { className: "flex items-center gap-2", children: [_jsx(CharCount, { value: form.metaTitle ?? '', max: META_TITLE_MAX }), aiButton('metaTitle')] }), children: _jsx("input", { className: inputCls, value: form.metaTitle ?? '', onChange: (e) => update({ metaTitle: e.target.value }), placeholder: "Page title for search results" }) }), _jsx(Field, { label: "Meta description", hint: _jsxs("span", { className: "flex items-center gap-2", children: [_jsx(CharCount, { value: form.metaDescription ?? '', max: META_DESC_MAX }), aiButton('metaDescription')] }), children: _jsx("textarea", { className: `${inputCls} min-h-20 resize-y`, value: form.metaDescription ?? '', onChange: (e) => update({ metaDescription: e.target.value }), placeholder: "Short summary shown under the title in search results" }) }), _jsx(Field, { label: "Focus keyword", hint: aiButton('focusKeyword'), children: _jsx("input", { className: inputCls, value: form.focusKeyword ?? '', onChange: (e) => update({ focusKeyword: e.target.value }), placeholder: "Primary keyword this page targets" }) }), _jsx(Field, { label: "Canonical URL", children: _jsx("input", { className: inputCls, value: form.canonicalUrl ?? '', onChange: (e) => update({ canonicalUrl: e.target.value }), placeholder: url || 'https://example.com/page' }) }), _jsxs("div", { className: "space-y-4", children: [_jsx("p", { className: "text-foreground text-sm font-medium", children: "Social sharing" }), _jsx(Field, { label: "Open Graph title", hint: aiButton('ogTitle'), children: _jsx("input", { className: inputCls, value: form.ogTitle ?? '', onChange: (e) => update({ ogTitle: e.target.value }), placeholder: form.metaTitle || 'Title when shared on social media' }) }), _jsx(Field, { label: "Open Graph description", hint: aiButton('ogDescription'), children: _jsx("textarea", { className: `${inputCls} min-h-16 resize-y`, value: form.ogDescription ?? '', onChange: (e) => update({ ogDescription: e.target.value }), placeholder: form.metaDescription || 'Description when shared on social media' }) }), _jsxs("div", { className: "border-border overflow-hidden rounded-lg border", children: [record.ogImage ? (
                                // eslint-disable-next-line @next/next/no-img-element
                                _jsx("img", { src: record.ogImage, alt: `Social preview for ${record.title}`, className: "bg-muted aspect-[1200/630] w-full object-cover" })) : (_jsx("div", { className: "bg-muted text-muted-foreground flex aspect-[1200/630] w-full items-center justify-center text-sm", children: "No OG image set" })), _jsxs("div", { className: "p-3", children: [_jsx("p", { className: "text-muted-foreground truncate text-xs uppercase", children: url.replace(/^https?:\/\//, '').split('/')[0] }), _jsx("p", { className: "text-foreground truncate text-sm font-medium", children: form.ogTitle || title }), _jsx("p", { className: "text-muted-foreground line-clamp-1 text-sm", children: form.ogDescription || desc })] })] })] }), _jsxs("div", { className: "border-border space-y-3 rounded-lg border p-4", children: [_jsxs("label", { className: "flex items-center justify-between gap-3", children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "text-foreground block text-sm font-medium", children: "No-index" }), _jsx("span", { className: "text-muted-foreground block text-sm", children: "Hide this page from search engines." })] }), _jsx("input", { type: "checkbox", role: "switch", "aria-checked": !!form.noindex, checked: !!form.noindex, onChange: (e) => update({ noindex: e.target.checked }), className: "accent-primary h-4 w-4" })] }), _jsxs("label", { className: "flex items-center justify-between gap-3", children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "text-foreground block text-sm font-medium", children: "No-follow" }), _jsx("span", { className: "text-muted-foreground block text-sm", children: "Tell crawlers not to follow links on this page." })] }), _jsx("input", { type: "checkbox", role: "switch", "aria-checked": !!form.nofollow, checked: !!form.nofollow, onChange: (e) => update({ nofollow: e.target.checked }), className: "accent-primary h-4 w-4" })] })] }), (() => {
                    const meta = gradeMeta(record.seoGrade);
                    return (_jsxs("div", { className: `flex items-center gap-2 rounded-lg px-3 py-2 text-sm ${meta.bg} ${meta.text}`, children: [_jsx(Check, { className: "h-4 w-4", "aria-hidden": true }), "Current SEO score: ", _jsx("span", { className: "font-medium", children: record.seoScore }), " (", meta.label, ")"] }));
                })()] })) : null }));
}
//# sourceMappingURL=SeoEditorDrawer.js.map