'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment, useMemo, useState } from 'react';
import { ClipboardCheck, Clock, CheckCircle2, FileDown, Sparkles } from 'lucide-react';
import { toast } from 'sonner';
import { fetchSeoIssues, fetchSeoAuditRuns, batchGenerateSeoContentBriefs, exportSeoFixBrief, isInlineSeoFixIssue, supportsSeoContentBrief, } from '../../lib/seo-service.js';
import { SectionCard, SeoLoading, SeoEmptyState, SeoErrorState, severityMeta, SeoStatusBadge, btnSecondary, } from '../../components/seo/primitives.js';
import { SeoIssueFixDrawer } from '../../components/seo/SeoIssueFixDrawer.js';
import { SeoIssueFixPanel, SeoIssueFixToggle } from '../../components/seo/SeoIssueFixPanel.js';
import { PlanUpgradeCallout } from '../../components/PlanUpgradeCallout.js';
import { hasPlanFeature } from '../../lib/plan.js';
import { useSeoResource } from './useSeoResource.js';
const SEVERITY_FILTERS = [
    { id: 'all', label: 'All' },
    { id: 'critical', label: 'Critical' },
    { id: 'warning', label: 'Warnings' },
    { id: 'info', label: 'Info' },
];
const STATUS_FILTERS = [
    { id: 'open', label: 'Open' },
    { id: 'recurring', label: 'Recurring' },
    { id: 'ignored', label: 'Ignored' },
    { id: 'resolved', label: 'Resolved' },
    { id: 'all', label: 'All' },
];
function issueStatusTone(status) {
    switch (status) {
        case 'resolved':
            return 'good';
        case 'ignored':
            return 'neutral';
        case 'recurring':
            return 'fair';
        default:
            return 'critical';
    }
}
function AuditSummaryCards({ refetchKey }) {
    const { data, loading } = useSeoResource(fetchSeoAuditRuns, [refetchKey]);
    const last = (data ?? [])[0];
    return (_jsxs("div", { className: "grid grid-cols-2 gap-4 lg:grid-cols-4", children: [_jsxs("div", { className: "border-border bg-card rounded-lg border p-4", children: [_jsxs("p", { className: "text-muted-foreground flex items-center gap-1.5 text-sm", children: [_jsx(Clock, { className: "h-3.5 w-3.5", "aria-hidden": true }), " Last audit"] }), _jsx("p", { className: "text-foreground mt-1 text-sm font-medium", children: loading ? '…' : last ? new Date(last.startedAt).toLocaleString() : 'Never' })] }), _jsxs("div", { className: "border-border bg-card rounded-lg border p-4", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: "Pages scanned" }), _jsx("p", { className: "text-foreground mt-1 text-2xl font-medium tabular-nums", children: last?.pagesScanned ?? 0 })] }), _jsxs("div", { className: "border-border bg-card rounded-lg border p-4", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: "Issues found" }), _jsx("p", { className: "text-foreground mt-1 text-2xl font-medium tabular-nums", children: last?.issuesFound ?? 0 })] }), _jsxs("div", { className: "border-border bg-card rounded-lg border p-4", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: "Site score" }), _jsx("p", { className: "text-foreground mt-1 text-2xl font-medium tabular-nums", children: last?.siteScoreAfter ?? '—' })] })] }));
}
export function AuditTab({ refetchKey = 0, initialIssueId, onNavigate, planInfo, }) {
    const [severity, setSeverity] = useState('all');
    const [status, setStatus] = useState('open');
    const [expandedIssueId, setExpandedIssueId] = useState(initialIssueId ?? null);
    const [detailIssueId, setDetailIssueId] = useState(null);
    const [exportingBrief, setExportingBrief] = useState(false);
    const [batchGenerating, setBatchGenerating] = useState(false);
    const query = useMemo(() => ({ severity, status }), [severity, status]);
    const { data, loading, error, refetch } = useSeoResource(() => fetchSeoIssues(query), [severity, status, refetchKey]);
    const issues = data ?? [];
    const briefEligibleCount = useMemo(() => issues.filter((i) => supportsSeoContentBrief(i.type)).length, [issues]);
    const batchBriefsEnabled = hasPlanFeature(planInfo, 'seo.batchContentBriefs');
    function toggleExpanded(issueId) {
        setExpandedIssueId((current) => (current === issueId ? null : issueId));
    }
    function handleChanged() {
        setExpandedIssueId(null);
        refetch();
    }
    async function handleBatchGenerateBriefs() {
        const issueIds = issues.filter((i) => supportsSeoContentBrief(i.type)).map((i) => i.id);
        if (issueIds.length === 0) {
            toast.message('No content-brief issues in the current list.');
            return;
        }
        setBatchGenerating(true);
        try {
            const res = await batchGenerateSeoContentBriefs({
                severity,
                status,
                issueIds,
                skipExisting: true,
            });
            if (res.error || !res.data) {
                toast.error(res.error ?? 'Batch generation failed.');
                return;
            }
            const { generated, skipped, failed } = res.data;
            if (generated === 0 && failed === 0) {
                toast.message(`All ${skipped} brief(s) already cached for the current filters.`);
            }
            else {
                toast.success(`Generated ${generated} brief(s)${skipped ? `, skipped ${skipped} cached` : ''}${failed ? `, ${failed} failed` : ''}.`);
            }
            refetch();
        }
        finally {
            setBatchGenerating(false);
        }
    }
    async function handleExportBrief() {
        setExportingBrief(true);
        try {
            const res = await exportSeoFixBrief({ severity, status, manualOnly: true });
            if (res.error || !res.data?.markdown) {
                toast.error(res.error ?? 'Export failed.');
                return;
            }
            const blob = new Blob([res.data.markdown], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = res.data.filename || 'seo-fix-brief.md';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            setTimeout(() => URL.revokeObjectURL(url), 0);
            if (res.data.issueCount === 0) {
                toast.message('Brief downloaded — no manual fixes matched the current filters.');
            }
            else {
                toast.success(`Exported ${res.data.issueCount} manual fix(es) for your dev team.`);
            }
        }
        finally {
            setExportingBrief(false);
        }
    }
    return (_jsxs("div", { className: "space-y-4", children: [_jsx(AuditSummaryCards, { refetchKey: refetchKey }), _jsxs(SectionCard, { children: [_jsxs("div", { className: "mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between", children: [_jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center", children: [_jsx("div", { className: "flex flex-wrap gap-1", role: "group", "aria-label": "Filter by severity", children: SEVERITY_FILTERS.map((f) => (_jsx("button", { type: "button", "aria-pressed": severity === f.id, onClick: () => setSeverity(f.id), className: `focus-visible:ring-ring rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none ${severity === f.id
                                                ? 'bg-primary text-primary-foreground'
                                                : 'text-muted-foreground hover:bg-accent hover:text-foreground'}`, children: f.label }, f.id))) }), _jsx("div", { className: "flex flex-wrap gap-1", role: "group", "aria-label": "Filter by status", children: STATUS_FILTERS.map((f) => (_jsx("button", { type: "button", "aria-pressed": status === f.id, onClick: () => setStatus(f.id), className: `focus-visible:ring-ring rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none ${status === f.id
                                                ? 'bg-accent text-foreground'
                                                : 'text-muted-foreground hover:bg-accent hover:text-foreground'}`, children: f.label }, f.id))) })] }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [batchBriefsEnabled ? (_jsxs("button", { type: "button", className: btnSecondary, onClick: handleBatchGenerateBriefs, disabled: batchGenerating || loading || briefEligibleCount === 0, "aria-busy": batchGenerating, children: [_jsx(Sparkles, { className: "h-4 w-4", "aria-hidden": true }), batchGenerating ? 'Generating…' : 'Generate briefs'] })) : (_jsx(PlanUpgradeCallout, { feature: "seo.batchContentBriefs", upgradeUrl: planInfo?.upgradeUrl })), _jsxs("button", { type: "button", className: btnSecondary, onClick: handleExportBrief, disabled: exportingBrief || loading, "aria-busy": exportingBrief, children: [_jsx(FileDown, { className: "h-4 w-4", "aria-hidden": true }), exportingBrief ? 'Exporting…' : 'Export fix brief'] })] })] }), loading ? (_jsx(SeoLoading, { label: "Loading issues\u2026" })) : error ? (_jsx(SeoErrorState, { message: error, onRetry: refetch })) : issues.length === 0 ? (_jsx(SeoEmptyState, { icon: status === 'open' ? _jsx(CheckCircle2, { size: 24 }) : _jsx(ClipboardCheck, { size: 24 }), title: status === 'open' ? 'No open issues' : 'No issues match', description: status === 'open'
                            ? 'Run an audit to scan for new issues, or adjust the filters.'
                            : 'Try a different severity or status filter.' })) : (_jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "w-full min-w-[680px] text-sm", "aria-label": "SEO issues", children: [_jsx("thead", { children: _jsxs("tr", { className: "text-muted-foreground border-border border-b text-left", children: [_jsx("th", { className: "py-2 pr-4 font-medium", children: "Severity" }), _jsx("th", { className: "py-2 pr-4 font-medium", children: "Issue" }), _jsx("th", { className: "py-2 pr-4 font-medium", children: "Page" }), _jsx("th", { className: "py-2 pr-4 font-medium", children: "Status" }), _jsx("th", { className: "py-2 text-right font-medium", children: _jsx("span", { className: "sr-only", children: "Actions" }) })] }) }), _jsx("tbody", { className: "divide-border divide-y", children: issues.map((issue) => {
                                        const meta = severityMeta(issue.severity);
                                        const expanded = expandedIssueId === issue.id;
                                        return (_jsxs(Fragment, { children: [_jsxs("tr", { className: `hover:bg-accent/40 ${expanded ? 'bg-accent/20' : ''}`, children: [_jsx("td", { className: "py-2.5 pr-4", children: _jsxs("span", { className: `inline-flex items-center gap-1.5 text-sm ${meta.text}`, children: [_jsx("span", { className: `h-1.5 w-1.5 rounded-full ${meta.dot}`, "aria-hidden": true }), meta.label] }) }), _jsxs("td", { className: "py-2.5 pr-4", children: [_jsx("span", { className: "text-foreground block font-medium", children: issue.title }), _jsx("span", { className: "text-muted-foreground block capitalize", children: issue.category })] }), _jsx("td", { className: "text-muted-foreground py-2.5 pr-4", children: _jsx("span", { className: "block truncate", children: issue.entityTitle || issue.url || '—' }) }), _jsx("td", { className: "py-2.5 pr-4", children: _jsx(SeoStatusBadge, { label: issue.status, tone: issueStatusTone(issue.status) }) }), _jsx("td", { className: "py-2.5 text-right", children: _jsx(SeoIssueFixToggle, { expanded: expanded, fixable: issue.fixable ||
                                                                    isInlineSeoFixIssue(issue.type) ||
                                                                    supportsSeoContentBrief(issue.type), onToggle: () => toggleExpanded(issue.id) }) })] }), _jsx(SeoIssueFixPanel, { issue: issue, expanded: expanded, onChanged: handleChanged, onNavigate: onNavigate, onOpenDetails: () => setDetailIssueId(issue.id), planInfo: planInfo })] }, issue.id));
                                    }) })] }) }))] }), _jsx(SeoIssueFixDrawer, { open: detailIssueId !== null, onOpenChange: (o) => !o && setDetailIssueId(null), issueId: detailIssueId, onChanged: handleChanged, onNavigate: onNavigate })] }));
}
//# sourceMappingURL=AuditTab.js.map