'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useId, useState } from 'react';
import { RefreshCw, Map, AlertTriangle, CheckCircle2, ExternalLink, Bot } from 'lucide-react';
import * as Switch from '@radix-ui/react-switch';
import { toast } from 'sonner';
import { fetchSitemapStatus, regenerateSitemap, fetchCrawlSettings, updateCrawlSettings, fetchRobotsTxt, updateRobotsTxt, validateRobotsTxt, fetchAiCrawlerActivity, } from '../../lib/seo-service.js';
import { SectionCard, SeoLoading, SeoErrorState, btnPrimary, btnSecondary, } from '../../components/seo/primitives.js';
import { useSeoResource } from './useSeoResource.js';
const CRAWL_TOGGLES = [
    {
        key: 'indexEntireSite',
        label: 'Index entire site',
        help: 'Allow search engines to index all public pages.',
    },
    {
        key: 'includeImagesInSitemap',
        label: 'Include images in sitemap',
        help: 'Add image entries to the XML sitemap.',
    },
    {
        key: 'includePostsInSitemap',
        label: 'Include posts in sitemap',
        help: 'Add published posts to the sitemap.',
    },
];
function Toggle({ checked, onChange, label, help, disabled, }) {
    const labelId = useId();
    const helpId = useId();
    return (_jsxs("div", { className: "flex items-center justify-between gap-3 py-2.5", children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { id: labelId, className: "text-foreground block text-sm font-medium", children: label }), _jsx("span", { id: helpId, className: "text-muted-foreground block text-sm", children: help })] }), _jsx(Switch.Root, { checked: checked, onCheckedChange: onChange, disabled: disabled, "aria-labelledby": labelId, "aria-describedby": helpId, className: "bg-input-background data-[state=checked]:bg-primary focus-visible:ring-ring relative h-[18px] w-8 shrink-0 rounded-full transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50", children: _jsx(Switch.Thumb, { className: "bg-background block h-3.5 w-3.5 translate-x-0.5 rounded-full shadow-sm transition-transform data-[state=checked]:translate-x-[14px]" }) })] }));
}
function SitemapCard() {
    const { data, loading, error, refetch } = useSeoResource(fetchSitemapStatus, []);
    const [busy, setBusy] = useState(false);
    async function handleRegenerate() {
        setBusy(true);
        const res = await regenerateSitemap();
        setBusy(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('Sitemap regenerated.');
        refetch();
    }
    return (_jsx(SectionCard, { title: "Sitemap", action: _jsxs("button", { className: btnSecondary, onClick: handleRegenerate, disabled: busy || loading, children: [_jsx(RefreshCw, { className: `h-4 w-4 ${busy ? 'animate-spin' : ''}`, "aria-hidden": true }), "Regenerate"] }), children: loading ? (_jsx(SeoLoading, { label: "Loading sitemap status\u2026" })) : error ? (_jsx(SeoErrorState, { message: error, onRetry: refetch })) : !data ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "Sitemap status unavailable." })) : (_jsxs("div", { className: "space-y-3", children: [_jsxs("a", { href: data.sitemapUrl, target: "_blank", rel: "noopener noreferrer", className: "text-primary inline-flex items-center gap-1 text-sm hover:underline", children: [_jsx(Map, { className: "h-4 w-4", "aria-hidden": true }), data.sitemapUrl, _jsx(ExternalLink, { className: "h-3.5 w-3.5", "aria-hidden": true })] }), _jsxs("dl", { className: "grid grid-cols-2 gap-3 text-sm", children: [_jsxs("div", { children: [_jsx("dt", { className: "text-muted-foreground", children: "Pages included" }), _jsx("dd", { className: "text-foreground font-medium tabular-nums", children: data.pagesIncluded })] }), _jsxs("div", { children: [_jsx("dt", { className: "text-muted-foreground", children: "Pages excluded" }), _jsx("dd", { className: "text-foreground font-medium tabular-nums", children: data.pagesExcluded })] }), _jsxs("div", { className: "col-span-2", children: [_jsx("dt", { className: "text-muted-foreground", children: "Last generated" }), _jsx("dd", { className: "text-foreground", children: data.lastGeneratedAt ? new Date(data.lastGeneratedAt).toLocaleString() : 'Never' })] })] }), data.warnings.length > 0 && (_jsx("ul", { className: "space-y-1", children: data.warnings.map((w, i) => (_jsxs("li", { className: "text-warning flex items-center gap-1.5 text-sm", children: [_jsx(AlertTriangle, { className: "h-3.5 w-3.5", "aria-hidden": true }), " ", w] }, i))) }))] })) }));
}
function CrawlCard() {
    const { data, loading, error, refetch } = useSeoResource(fetchCrawlSettings, []);
    const [settings, setSettings] = useState(null);
    const [saving, setSaving] = useState(false);
    useEffect(() => {
        if (data)
            setSettings(data);
    }, [data]);
    async function save(next, changed) {
        setSettings(next);
        setSaving(true);
        const res = await updateCrawlSettings({ [changed]: next[changed] });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            refetch();
        }
    }
    return (_jsx(SectionCard, { title: "Crawl Settings", children: loading ? (_jsx(SeoLoading, { label: "Loading crawl settings\u2026" })) : error ? (_jsx(SeoErrorState, { message: error, onRetry: refetch })) : !settings ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "Crawl settings unavailable." })) : (_jsx("div", { className: "divide-border divide-y", "aria-busy": saving, children: CRAWL_TOGGLES.map((t) => (_jsx(Toggle, { label: t.label, help: t.help, checked: settings[t.key], disabled: saving, onChange: (v) => save({ ...settings, [t.key]: v }, t.key) }, t.key))) })) }));
}
function RobotsCard() {
    const { data, loading, error, refetch } = useSeoResource(fetchRobotsTxt, []);
    const [body, setBody] = useState('');
    const [saving, setSaving] = useState(false);
    useEffect(() => {
        if (data)
            setBody(data.body);
    }, [data]);
    const validation = validateRobotsTxt(body);
    async function handleSave() {
        setSaving(true);
        const res = await updateRobotsTxt(body);
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('robots.txt saved.');
        refetch();
    }
    return (_jsx(SectionCard, { title: "robots.txt", description: "Controls which crawlers can access your site.", action: _jsx("button", { className: btnPrimary, onClick: handleSave, disabled: saving || loading || !validation.valid, children: saving ? 'Saving…' : 'Save' }), children: loading ? (_jsx(SeoLoading, { label: "Loading robots.txt\u2026" })) : error ? (_jsx(SeoErrorState, { message: error, onRetry: refetch })) : (_jsxs("div", { className: "space-y-3", children: [validation.blocksEntireSite && (_jsxs("div", { className: "border-destructive/30 bg-destructive/10 flex items-start gap-2 rounded-md border p-3", role: "alert", children: [_jsx(AlertTriangle, { className: "text-destructive mt-0.5 h-4 w-4 shrink-0", "aria-hidden": true }), _jsx("p", { className: "text-destructive text-sm", children: "This configuration blocks your entire site from all search engines. Pages will be removed from search results." })] })), _jsx("label", { className: "sr-only", htmlFor: "robots-editor", children: "robots.txt contents" }), _jsx("textarea", { id: "robots-editor", value: body, onChange: (e) => setBody(e.target.value), spellCheck: false, className: "border-border bg-input-background text-foreground focus-visible:ring-ring min-h-48 w-full rounded-md border p-3 font-mono text-sm focus-visible:ring-2 focus-visible:outline-none" }), validation.errors.length > 0 ? (_jsx("ul", { className: "space-y-1", children: validation.errors.map((e, i) => (_jsxs("li", { className: "text-destructive flex items-center gap-1.5 text-sm", children: [_jsx(AlertTriangle, { className: "h-3.5 w-3.5", "aria-hidden": true }), " ", e] }, i))) })) : (_jsxs("p", { className: "text-success flex items-center gap-1.5 text-sm", children: [_jsx(CheckCircle2, { className: "h-3.5 w-3.5", "aria-hidden": true }), " Valid robots.txt"] })), validation.warnings
                    .filter((w) => !validation.blocksEntireSite || !w.includes('blocks the entire site'))
                    .map((w, i) => (_jsxs("p", { className: "text-warning flex items-center gap-1.5 text-sm", children: [_jsx(AlertTriangle, { className: "h-3.5 w-3.5", "aria-hidden": true }), " ", w] }, i)))] })) }));
}
const SURFACE_LABELS = {
    llms: 'llms.txt',
    'llms-full': 'llms-full.txt',
    md: '.md page',
    honeypot: 'honeypot',
};
const CATEGORY_LABELS = {
    training: 'Training',
    retrieval: 'Retrieval',
    other: 'Other',
};
function AiCrawlerCard() {
    const { data, loading, error, refetch } = useSeoResource(fetchAiCrawlerActivity, []);
    return (_jsx(SectionCard, { title: "AI crawler activity", description: "Known AI crawlers seen fetching llms.txt, llms-full.txt, and .md pages. This is visibility, not a traffic channel \u2014 expect modest numbers.", action: _jsxs("button", { className: btnSecondary, onClick: () => refetch(), disabled: loading, children: [_jsx(RefreshCw, { className: `h-4 w-4 ${loading ? 'animate-spin' : ''}`, "aria-hidden": true }), "Refresh"] }), children: loading ? (_jsx(SeoLoading, { label: "Loading crawler activity\u2026" })) : error ? (_jsx(SeoErrorState, { message: error, onRetry: refetch })) : !data || !data.enabled ? (_jsx("p", { className: "text-muted-foreground text-sm", children: "Crawler tracking is unavailable. Run the latest database migration to enable it." })) : data.rows.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center gap-2 py-8 text-center", children: [_jsx(Bot, { className: "text-muted-foreground h-6 w-6", "aria-hidden": true }), _jsx("p", { className: "text-muted-foreground text-sm", children: "No AI crawler activity recorded yet." })] })) : (_jsxs("div", { className: "space-y-4", children: [_jsxs("dl", { className: "grid grid-cols-3 gap-3 text-sm", children: [_jsxs("div", { children: [_jsx("dt", { className: "text-muted-foreground", children: "Total hits" }), _jsx("dd", { className: "text-foreground font-medium tabular-nums", children: data.totals.hits })] }), _jsxs("div", { children: [_jsx("dt", { className: "text-muted-foreground", children: "Distinct bots" }), _jsx("dd", { className: "text-foreground font-medium tabular-nums", children: data.totals.bots })] }), _jsxs("div", { children: [_jsx("dt", { className: "text-muted-foreground", children: "Honeypot hits" }), _jsx("dd", { className: "text-foreground font-medium tabular-nums", children: data.totals.honeypot })] })] }), _jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "w-full text-sm", "aria-label": "AI crawler activity by bot", children: [_jsx("thead", { children: _jsxs("tr", { className: "border-border text-muted-foreground border-b text-left", children: [_jsx("th", { scope: "col", className: "py-2 pr-3 font-medium", children: "Bot" }), _jsx("th", { scope: "col", className: "py-2 pr-3 font-medium", children: "Type" }), _jsx("th", { scope: "col", className: "py-2 pr-3 font-medium", children: "Surface" }), _jsx("th", { scope: "col", className: "py-2 pr-3 text-right font-medium", children: "Hits" }), _jsx("th", { scope: "col", className: "py-2 font-medium", children: "Last seen" })] }) }), _jsx("tbody", { className: "divide-border divide-y", children: data.rows.map((r) => (_jsxs("tr", { children: [_jsx("td", { className: "text-foreground py-2 pr-3 font-medium", children: r.bot }), _jsx("td", { className: "text-muted-foreground py-2 pr-3", children: CATEGORY_LABELS[r.category] ?? r.category }), _jsx("td", { className: "text-muted-foreground py-2 pr-3", children: SURFACE_LABELS[r.surface] ?? r.surface }), _jsx("td", { className: "text-foreground py-2 pr-3 text-right tabular-nums", children: r.hits }), _jsx("td", { className: "text-muted-foreground py-2", children: new Date(r.lastSeenAt).toLocaleDateString() })] }, `${r.bot}:${r.surface}`))) })] }) })] })) }));
}
export function TechnicalTab() {
    return (_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "grid grid-cols-1 gap-4 lg:grid-cols-2", children: [_jsx(SitemapCard, {}), _jsx(CrawlCard, {})] }), _jsx(RobotsCard, {}), _jsx(AiCrawlerCard, {})] }));
}
//# sourceMappingURL=TechnicalTab.js.map