'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { Check, ChevronDown, Loader2, Sparkles, Wand2 } from 'lucide-react';
import { toast } from 'sonner';
import { applySeoIssueFix, fetchSeoIssueFixSuggestion, fetchSeoContentBrief, fetchSeoContentResearch, generateSeoContentBrief, ignoreSeoIssue, isInlineSeoFixIssue, researchAndBriefSeoIssue, supportsSeoContentBrief, supportsSeoContentResearch, } from '../../lib/seo-service.js';
import { hasPlanFeature } from '../../lib/plan.js';
import { PlanUpgradeCallout } from '../PlanUpgradeCallout.js';
import { SeoErrorState, btnPrimary, btnSecondary } from './primitives.js';
function formatValue(value) {
    if (value === null || value === '')
        return '—';
    if (typeof value === 'boolean')
        return value ? 'Yes' : 'No';
    if (value.length > 280)
        return `${value.slice(0, 277)}…`;
    return value;
}
function ChangePreview({ changes }) {
    if (changes.length === 0)
        return null;
    return (_jsx("div", { className: "border-border overflow-x-auto rounded-md border", children: _jsxs("table", { className: "w-full min-w-[480px] text-sm", "aria-label": "Proposed SEO changes", children: [_jsx("thead", { children: _jsxs("tr", { className: "border-border bg-muted/40 text-muted-foreground border-b text-left", children: [_jsx("th", { scope: "col", className: "py-2 pr-3 pl-3 font-medium", children: "Field" }), _jsx("th", { scope: "col", className: "py-2 pr-3 font-medium", children: "Current" }), _jsx("th", { scope: "col", className: "py-2 pr-3 font-medium", children: "Proposed" })] }) }), _jsx("tbody", { className: "divide-border divide-y", children: changes.map((c) => (_jsxs("tr", { children: [_jsx("td", { className: "text-foreground py-2 pr-3 pl-3 font-medium", children: c.label }), _jsx("td", { className: "text-muted-foreground max-w-48 py-2 pr-3 wrap-break-word", children: formatValue(c.before) }), _jsx("td", { className: "text-foreground max-w-48 py-2 pr-3 wrap-break-word", children: formatValue(c.after) })] }, c.field))) })] }) }));
}
function ContentResearchCard({ research }) {
    return (_jsxs("div", { className: "border-border bg-card space-y-3 rounded-md border p-4", children: [_jsx("div", { className: "flex items-center gap-2", children: _jsxs("span", { className: "bg-accent text-foreground inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium", children: [_jsx(Sparkles, { className: "h-3 w-3", "aria-hidden": true }), "Topic research"] }) }), _jsx("p", { className: "text-foreground text-sm", children: research.summary }), _jsxs("ul", { className: "text-foreground space-y-1.5 text-sm", children: [research.focusKeyword ? (_jsxs("li", { children: [_jsx("span", { className: "text-muted-foreground", children: "Focus keyword: " }), research.focusKeyword] })) : null, research.suggestedWordCount ? (_jsxs("li", { children: [_jsx("span", { className: "text-muted-foreground", children: "Suggested length: " }), "~", research.suggestedWordCount, " words"] })) : null] }), research.outline.length > 0 ? (_jsxs("div", { children: [_jsx("p", { className: "text-muted-foreground mb-1.5 text-xs font-medium tracking-wide uppercase", children: "Suggested outline" }), _jsx("ul", { className: "text-foreground list-disc space-y-1 pl-5 text-sm", children: research.outline.map((item) => (_jsx("li", { children: item }, item))) })] })) : null, research.faqCandidates.length > 0 ? (_jsxs("div", { children: [_jsx("p", { className: "text-muted-foreground mb-1.5 text-xs font-medium tracking-wide uppercase", children: "FAQ candidates" }), _jsx("ul", { className: "text-foreground list-disc space-y-1 pl-5 text-sm", children: research.faqCandidates.map((q) => (_jsx("li", { children: q }, q))) })] })) : null] }));
}
function ContentBriefCard({ brief }) {
    return (_jsxs("div", { className: "border-border bg-card space-y-3 rounded-md border p-4", children: [_jsx("div", { className: "flex items-center gap-2", children: _jsxs("span", { className: "bg-primary/10 text-primary inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium", children: [_jsx(Sparkles, { className: "h-3 w-3", "aria-hidden": true }), "AI content brief"] }) }), _jsx("p", { className: "text-foreground text-sm", children: brief.summary }), _jsxs("ul", { className: "text-foreground space-y-1.5 text-sm", children: [brief.suggestedH1 ? (_jsxs("li", { children: [_jsx("span", { className: "text-muted-foreground", children: "Suggested H1: " }), brief.suggestedH1] })) : null, brief.targetWordCount ? (_jsxs("li", { children: [_jsx("span", { className: "text-muted-foreground", children: "Target length: " }), "~", brief.targetWordCount, ' ', "words"] })) : null, brief.keyTakeawayDraft ? (_jsxs("li", { children: [_jsx("span", { className: "text-muted-foreground", children: "GEO takeaway: " }), brief.keyTakeawayDraft] })) : null, brief.geoNote ? (_jsxs("li", { children: [_jsx("span", { className: "text-muted-foreground", children: "GEO note: " }), brief.geoNote] })) : null] }), brief.topics.length > 0 ? (_jsxs("div", { children: [_jsx("p", { className: "text-muted-foreground mb-1.5 text-xs font-medium tracking-wide uppercase", children: "Topics to cover" }), _jsx("ul", { className: "text-foreground list-disc space-y-1 pl-5 text-sm", children: brief.topics.map((topic) => (_jsx("li", { children: topic }, topic))) })] })) : null, brief.sections.map((section) => (_jsxs("div", { children: [_jsx("p", { className: "text-foreground text-sm font-medium", children: section.heading }), section.bullets.length > 0 ? (_jsx("ul", { className: "text-muted-foreground mt-1 list-disc space-y-1 pl-5 text-sm", children: section.bullets.map((bullet) => (_jsx("li", { children: bullet }, bullet))) })) : null] }, section.heading)))] }));
}
function manualPath(issue) {
    const ent = issue.entityType;
    const id = issue.entityId;
    switch (issue.fixActionType) {
        case 'edit-metadata':
        case 'edit-canonical':
        case 'edit-og':
        case 'edit-og-image':
        case 'edit-schema':
            if (ent && id) {
                return `/seo?tab=content&entityType=${ent}&entityId=${encodeURIComponent(id)}`;
            }
            return null;
        case 'edit-content':
            if (ent === 'page' && id)
                return `/pages/${id}`;
            if (ent && id) {
                return `/seo?tab=content&entityType=${ent}&entityId=${encodeURIComponent(id)}`;
            }
            return null;
        case 'fix-broken-link':
        case 'fix-link':
        case 'create-redirect':
            return '/seo?tab=redirects';
        case 'optimize-media':
            return '/media';
        case 'improve-speed':
            return '/seo?tab=technical';
        default:
            if (ent === 'page' && id)
                return `/pages/${id}`;
            return null;
    }
}
export function SeoIssueFixPanel({ issue, expanded, onChanged, onNavigate, onOpenDetails, planInfo, }) {
    const inlineFix = isInlineSeoFixIssue(issue.type);
    const contentBriefEligible = supportsSeoContentBrief(issue.type);
    const researchEligible = supportsSeoContentResearch(issue.type);
    const inlineApplyEnabled = hasPlanFeature(planInfo, 'seo.inlineApply');
    const contentBriefEnabled = hasPlanFeature(planInfo, 'seo.contentBrief');
    const contentResearchEnabled = hasPlanFeature(planInfo, 'seo.contentResearch');
    const [suggestion, setSuggestion] = useState(null);
    const [contentBrief, setContentBrief] = useState(null);
    const [contentResearch, setContentResearch] = useState(null);
    const [competitorUrls, setCompetitorUrls] = useState(['', '', '']);
    const [briefStale, setBriefStale] = useState(false);
    const [researchStale, setResearchStale] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [busy, setBusy] = useState(false);
    const [generatingBrief, setGeneratingBrief] = useState(false);
    const [researching, setResearching] = useState(false);
    useEffect(() => {
        if (!expanded) {
            setSuggestion(null);
            setContentBrief(null);
            setContentResearch(null);
            setCompetitorUrls(['', '', '']);
            setBriefStale(false);
            setResearchStale(false);
            setError(null);
            return;
        }
        let alive = true;
        setLoading(true);
        setError(null);
        async function load() {
            if (inlineFix) {
                const res = await fetchSeoIssueFixSuggestion(issue.id);
                if (!alive)
                    return;
                if (res.error)
                    setError(res.error);
                else
                    setSuggestion(res.suggestion ?? null);
                return;
            }
            if (contentBriefEligible) {
                const briefRes = await fetchSeoContentBrief(issue.id);
                if (!alive)
                    return;
                if (briefRes.error)
                    setError(briefRes.error);
                else {
                    setContentBrief(briefRes.brief ?? null);
                    setBriefStale(briefRes.stale ?? false);
                }
                if (researchEligible) {
                    const researchRes = await fetchSeoContentResearch(issue.id);
                    if (!alive)
                        return;
                    if (researchRes.error && !briefRes.error)
                        setError(researchRes.error);
                    else if (!researchRes.error) {
                        setContentResearch(researchRes.research ?? null);
                        setResearchStale(researchRes.stale ?? false);
                    }
                }
            }
        }
        load()
            .catch((e) => alive && setError(e instanceof Error ? e.message : 'Failed to load'))
            .finally(() => alive && setLoading(false));
        return () => {
            alive = false;
        };
    }, [expanded, issue.id, inlineFix, contentBriefEligible, researchEligible]);
    function parsedCompetitorUrls() {
        return competitorUrls
            .map((u) => u.trim())
            .filter(Boolean)
            .slice(0, 3);
    }
    async function handleApprove() {
        if (!suggestion?.autoFixable)
            return;
        setBusy(true);
        const res = await applySeoIssueFix(issue.id, suggestion.fingerprint);
        setBusy(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success(suggestion?.fixStrategy === 'fix-link'
            ? 'Link updated in content and issue resolved.'
            : 'Redirect created and issue resolved.');
        onChanged?.();
    }
    async function handleResearchAndBrief() {
        setResearching(true);
        const res = await researchAndBriefSeoIssue(issue.id, parsedCompetitorUrls());
        setResearching(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        if (res.research) {
            setContentResearch(res.research);
            setResearchStale(false);
        }
        if (res.brief) {
            setContentBrief(res.brief);
            setBriefStale(false);
        }
        toast.success('Research and content brief generated — review before editing the page.');
    }
    async function handleGenerateBrief() {
        setGeneratingBrief(true);
        const res = await generateSeoContentBrief(issue.id);
        setGeneratingBrief(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        if (res.brief) {
            setContentBrief(res.brief);
            setBriefStale(false);
            toast.success('Content brief generated — review before editing the page.');
        }
    }
    async function handleIgnore() {
        setBusy(true);
        const res = await ignoreSeoIssue(issue.id);
        setBusy(false);
        if (res.error)
            return toast.error(res.error);
        toast.success('Issue ignored.');
        onChanged?.();
    }
    const manualRoute = manualPath(issue);
    if (!expanded)
        return null;
    return (_jsx("tr", { children: _jsx("td", { colSpan: 5, className: "bg-muted/30 px-4 py-4", children: _jsx("div", { className: "space-y-4", children: loading ? (_jsxs("div", { className: "text-muted-foreground flex items-center gap-2 text-sm", role: "status", "aria-live": "polite", children: [_jsx(Loader2, { className: "h-4 w-4 motion-safe:animate-spin", "aria-hidden": true }), inlineFix ? 'Loading suggested fix…' : 'Loading issue details…'] })) : error ? (_jsx(SeoErrorState, { message: error })) : (_jsxs(_Fragment, { children: [!inlineFix && (issue.description || issue.recommendation) ? (_jsxs("div", { className: "space-y-2", children: [issue.description ? (_jsx("p", { className: "text-foreground text-sm", children: issue.description })) : null, issue.recommendation ? (_jsxs("p", { className: "text-muted-foreground text-sm", children: [_jsx("span", { className: "text-foreground font-medium", children: "Recommended fix: " }), issue.recommendation] })) : null] })) : null, inlineFix && suggestion ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "flex flex-wrap items-center gap-2", children: suggestion.source === 'ai' && !suggestion.aiUnavailable ? (_jsxs("span", { className: "bg-primary/10 text-primary inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium", children: [_jsx(Sparkles, { className: "h-3 w-3", "aria-hidden": true }), suggestion.fixStrategy === 'fix-link'
                                                ? 'Fix link in content'
                                                : 'AI suggestion'] })) : suggestion.source === 'deterministic' ? (_jsx("span", { className: "bg-muted text-muted-foreground rounded-full px-2.5 py-0.5 text-xs font-medium", children: suggestion.fixStrategy === 'fix-link'
                                            ? 'Content link fix'
                                            : 'Rule-based fix' })) : null }), _jsxs("div", { className: "flex items-start gap-2", children: [_jsx(Sparkles, { className: "text-primary mt-0.5 h-4 w-4 shrink-0", "aria-hidden": true }), _jsx("p", { className: "text-foreground text-sm", children: suggestion.justification })] }), _jsx(ChangePreview, { changes: suggestion.changes })] })) : null, contentBriefEligible ? (_jsxs(_Fragment, { children: [researchEligible ? (_jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: "Optional competitor URLs (SSRF-safe fetch, max 3) to enrich topic research for thin content." }), competitorUrls.map((value, index) => (_jsxs("label", { className: "block", children: [_jsxs("span", { className: "text-muted-foreground sr-only", children: ["Competitor URL ", index + 1] }), _jsx("input", { type: "url", value: value, onChange: (e) => {
                                                        const next = [...competitorUrls];
                                                        next[index] = e.target.value;
                                                        setCompetitorUrls(next);
                                                    }, placeholder: `Competitor URL ${index + 1} (optional)`, className: "border-border bg-input-background text-foreground focus-visible:ring-ring w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:outline-none" })] }, index)))] })) : null, researchStale && !contentResearch ? (_jsx("p", { className: "text-muted-foreground text-sm", role: "status", children: "Previous topic research is outdated because the page changed." })) : null, contentResearch ? _jsx(ContentResearchCard, { research: contentResearch }) : null, briefStale && !contentBrief ? (_jsx("p", { className: "text-muted-foreground text-sm", role: "status", children: "A previous content brief is outdated because the page changed. Generate a new one." })) : null, contentBrief ? _jsx(ContentBriefCard, { brief: contentBrief }) : null, !contentBrief ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "Generate an AI content brief with suggested headings, topics, and GEO guidance for your dev team." })) : null] })) : null, _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [inlineFix && suggestion?.autoFixable && inlineApplyEnabled ? (_jsxs("button", { type: "button", className: btnPrimary, onClick: handleApprove, disabled: busy, children: [_jsx(Check, { className: "h-4 w-4", "aria-hidden": true }), busy
                                            ? 'Applying…'
                                            : suggestion.fixStrategy === 'fix-link'
                                                ? 'Fix link in content'
                                                : 'Approve redirect'] })) : inlineFix && suggestion?.autoFixable && !inlineApplyEnabled ? (_jsx(PlanUpgradeCallout, { feature: "seo.inlineApply", upgradeUrl: planInfo?.upgradeUrl })) : inlineFix && suggestion?.aiUnavailable ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "Configure an AI provider in Settings \u2192 AI to enable generated fixes for this issue." })) : null, contentBriefEligible ? (_jsxs(_Fragment, { children: [!contentBriefEnabled || !contentResearchEnabled ? (_jsx(PlanUpgradeCallout, { feature: !contentResearchEnabled ? 'seo.contentResearch' : 'seo.contentBrief', upgradeUrl: planInfo?.upgradeUrl })) : null, researchEligible && contentResearchEnabled ? (_jsxs("button", { type: "button", className: !contentBrief && !contentResearch ? btnPrimary : btnSecondary, onClick: handleResearchAndBrief, disabled: busy || researching || generatingBrief, children: [_jsx(Sparkles, { className: `h-4 w-4 ${researching ? 'motion-safe:animate-pulse' : ''}`, "aria-hidden": true }), researching ? 'Researching…' : 'Research & brief'] })) : null, contentBriefEnabled ? (_jsxs("button", { type: "button", className: contentBrief ? btnSecondary : btnPrimary, onClick: handleGenerateBrief, disabled: busy || generatingBrief || researching, children: [_jsx(Wand2, { className: `h-4 w-4 ${generatingBrief ? 'motion-safe:animate-pulse' : ''}`, "aria-hidden": true }), generatingBrief
                                                    ? 'Generating brief…'
                                                    : contentBrief
                                                        ? 'Regenerate brief'
                                                        : 'Generate content brief'] })) : null] })) : null, !inlineFix && !contentBriefEligible ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "This issue requires manual follow-up in the admin or codebase." })) : null, manualRoute && onNavigate ? (_jsx("button", { type: "button", className: btnSecondary, onClick: () => onNavigate(manualRoute), disabled: busy, children: "Edit manually" })) : null, _jsx("button", { type: "button", className: btnSecondary, onClick: handleIgnore, disabled: busy, children: "Ignore" }), onOpenDetails ? (_jsx("button", { type: "button", className: "text-primary hover:bg-accent focus-visible:ring-ring rounded-md px-3 py-2 text-sm focus-visible:ring-2 focus-visible:outline-none", onClick: onOpenDetails, disabled: busy, children: "More details" })) : null] })] })) }) }) }));
}
export function SeoIssueFixToggle({ expanded, fixable, onToggle, }) {
    return (_jsxs("button", { type: "button", onClick: onToggle, "aria-expanded": expanded, className: "text-primary hover:bg-accent focus-visible:ring-ring inline-flex items-center gap-1 rounded-md px-2 py-1 text-sm focus-visible:ring-2 focus-visible:outline-none", children: [fixable ? 'Fix' : 'View', _jsx(ChevronDown, { className: `h-3.5 w-3.5 motion-safe:transition-transform ${expanded ? 'rotate-180' : ''}`, "aria-hidden": true })] }));
}
//# sourceMappingURL=SeoIssueFixPanel.js.map