'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { Sparkles, ArrowRight, ExternalLink, Image as ImageIcon, Gauge } from 'lucide-react';
import { toast } from 'sonner';
import { fetchSeoIssue, resolveSeoIssue, ignoreSeoIssue, reopenSeoIssue, explainSeoIssue, } from '../../lib/seo-service.js';
import { Drawer } from './Drawer.js';
import { SeoLoading, SeoErrorState, severityMeta, btnPrimary, btnSecondary } from './primitives.js';
/** Map a fix action to a destination route within the admin. */
function fixRoute(issue) {
    const ent = issue.entityType;
    const id = issue.entityId;
    switch (issue.fixActionType) {
        case 'edit-metadata':
        case 'edit-canonical':
        case 'edit-og':
        case 'edit-schema':
            if (ent && id) {
                return {
                    label: 'Edit content SEO',
                    path: `/seo?tab=content&entityType=${ent}&entityId=${encodeURIComponent(id)}`,
                    icon: _jsx(ArrowRight, { className: "h-4 w-4", "aria-hidden": true }),
                };
            }
            return null;
        case 'fix-broken-link':
        case 'create-redirect':
            return {
                label: 'Open redirects',
                path: '/seo?tab=redirects',
                icon: _jsx(ArrowRight, { className: "h-4 w-4", "aria-hidden": true }),
            };
        case 'optimize-media':
            return {
                label: 'Open Media Center',
                path: '/media',
                icon: _jsx(ImageIcon, { className: "h-4 w-4", "aria-hidden": true }),
            };
        case 'improve-speed':
            return {
                label: 'Technical settings',
                path: '/seo?tab=technical',
                icon: _jsx(Gauge, { className: "h-4 w-4", "aria-hidden": true }),
            };
        default:
            return null;
    }
}
export function SeoIssueFixDrawer({ open, onOpenChange, issueId, onChanged, onNavigate, }) {
    const [issue, setIssue] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [busy, setBusy] = useState(false);
    const [explanation, setExplanation] = useState(null);
    const [explaining, setExplaining] = useState(false);
    useEffect(() => {
        if (!open || !issueId)
            return;
        let alive = true;
        setLoading(true);
        setError(null);
        setExplanation(null);
        fetchSeoIssue(issueId)
            .then((i) => {
            if (!alive)
                return;
            if (!i)
                setError('Issue not found.');
            else
                setIssue(i);
        })
            .catch((e) => alive && setError(e instanceof Error ? e.message : 'Failed to load'))
            .finally(() => alive && setLoading(false));
        return () => {
            alive = false;
        };
    }, [open, issueId]);
    async function mutate(fn, successMsg) {
        if (!issue)
            return;
        setBusy(true);
        const res = await fn(issue.id);
        setBusy(false);
        if (res.error)
            return toast.error(res.error);
        toast.success(successMsg);
        onOpenChange(false);
        onChanged?.();
    }
    async function handleExplain() {
        if (!issue)
            return;
        setExplaining(true);
        const res = await explainSeoIssue(issue.id);
        setExplaining(false);
        if (res.unavailable) {
            toast.error('AI is not configured.');
            return;
        }
        setExplanation(res.text ?? 'No explanation available.');
    }
    const route = issue ? fixRoute(issue) : null;
    return (_jsx(Drawer, { open: open, onOpenChange: onOpenChange, title: "Issue detail", width: "max-w-lg", footer: issue ? (_jsxs(_Fragment, { children: [issue.status === 'ignored' ? (_jsx("button", { className: btnSecondary, onClick: () => mutate(reopenSeoIssue, 'Issue reopened.'), disabled: busy, children: "Reopen" })) : (_jsx("button", { className: btnSecondary, onClick: () => mutate(ignoreSeoIssue, 'Issue ignored.'), disabled: busy, children: "Ignore" })), route && onNavigate ? (_jsxs("button", { className: btnPrimary, onClick: () => {
                        onNavigate(route.path);
                        onOpenChange(false);
                    }, children: [route.icon, route.label] })) : (_jsx("button", { className: btnPrimary, onClick: () => mutate(resolveSeoIssue, 'Issue resolved.'), disabled: busy, children: "Mark resolved" }))] })) : null, children: loading ? (_jsx(SeoLoading, {})) : error ? (_jsx(SeoErrorState, { message: error })) : issue ? (_jsxs("div", { className: "space-y-4", children: [(() => {
                    const meta = severityMeta(issue.severity);
                    return (_jsxs("span", { className: `inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ${meta.bg} ${meta.text}`, children: [_jsx("span", { className: `h-1.5 w-1.5 rounded-full ${meta.dot}`, "aria-hidden": true }), meta.label, " \u00B7 ", issue.category] }));
                })(), _jsxs("div", { children: [_jsx("h3", { className: "text-foreground text-base font-medium", children: issue.title }), issue.entityTitle && (_jsx("p", { className: "text-muted-foreground mt-0.5 text-sm", children: issue.entityTitle }))] }), issue.url && (_jsxs("a", { href: issue.url, target: "_blank", rel: "noopener noreferrer", className: "text-primary inline-flex items-center gap-1 text-sm hover:underline", children: [issue.url, _jsx(ExternalLink, { className: "h-3.5 w-3.5", "aria-hidden": true })] })), issue.description && _jsx("p", { className: "text-foreground text-sm", children: issue.description }), issue.impact && (_jsxs("div", { className: "border-border rounded-md border p-3", children: [_jsx("p", { className: "text-muted-foreground text-xs font-medium tracking-wide uppercase", children: "Impact" }), _jsx("p", { className: "text-foreground mt-1 text-sm", children: issue.impact })] })), issue.recommendation && (_jsxs("div", { className: "border-border rounded-md border p-3", children: [_jsx("p", { className: "text-muted-foreground text-xs font-medium tracking-wide uppercase", children: "Recommendation" }), _jsx("p", { className: "text-foreground mt-1 text-sm", children: issue.recommendation })] })), _jsxs("div", { className: "border-border rounded-md border p-3", children: [_jsxs("button", { onClick: handleExplain, disabled: explaining, className: "text-primary focus-visible:ring-ring inline-flex items-center gap-1.5 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none disabled:opacity-60", children: [_jsx(Sparkles, { className: `h-4 w-4 ${explaining ? 'animate-pulse' : ''}`, "aria-hidden": true }), explaining ? 'Asking AI…' : 'Explain with AI'] }), explanation && _jsx("p", { className: "text-foreground mt-2 text-sm", children: explanation })] })] })) : null }));
}
//# sourceMappingURL=SeoIssueFixDrawer.js.map