'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * SEO Operations Center — five-tab workflow surface (Overview / Content /
 * Technical / Redirects / Audit). Tab + deep-link state is driven by the
 * `?tab=` query string so audits, issues, redirects, and content editors are
 * all linkable. All data flows through `lib/seo-service.ts`.
 */
import * as Tabs from '@radix-ui/react-tabs';
import { LayoutDashboard, FileText, Settings2, ArrowRightLeft, ClipboardCheck, RefreshCw, Bot, } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import { ErrorBoundary } from '../components/ErrorBoundary.js';
import { fetchSeoOverview, runSeoAudit } from '../lib/seo-service.js';
import { ScorePill, btnPrimary, btnSecondary } from '../components/seo/primitives.js';
import { SeoCopilotDrawer } from '../components/seo/SeoCopilotDrawer.js';
import { useSeoResource } from './seo/useSeoResource.js';
import { OverviewTab } from './seo/OverviewTab.js';
import { ContentTab } from './seo/ContentTab.js';
import { TechnicalTab } from './seo/TechnicalTab.js';
import { RedirectsTab } from './seo/RedirectsTab.js';
import { AuditTab } from './seo/AuditTab.js';
const TABS = [
    { id: 'overview', label: 'Overview', icon: LayoutDashboard },
    { id: 'content', label: 'Content SEO', icon: FileText },
    { id: 'technical', label: 'Technical', icon: Settings2 },
    { id: 'redirects', label: 'Redirects', icon: ArrowRightLeft },
    { id: 'audit', label: 'Audit', icon: ClipboardCheck },
];
function normalizeTab(tab) {
    const valid = TABS.map((t) => t.id);
    return (valid.includes(tab ?? '') ? tab : 'overview');
}
/** Read tab + deep-link query params from the current URL. */
function readUrlState() {
    if (typeof window === 'undefined') {
        return { tab: null, entityType: null, entityId: null, issueId: null };
    }
    const params = new URLSearchParams(window.location.search);
    return {
        tab: params.get('tab'),
        entityType: params.get('entityType'),
        entityId: params.get('entityId'),
        issueId: params.get('issueId'),
    };
}
export function SEO({ onNavigate, initialTab = 'overview' }) {
    const initialUrl = readUrlState();
    const [activeTab, setActiveTab] = useState(normalizeTab(initialUrl.tab ?? initialTab));
    const [refetchKey, setRefetchKey] = useState(0);
    const [auditing, setAuditing] = useState(false);
    const [copilotOpen, setCopilotOpen] = useState(false);
    const [deepLink, setDeepLink] = useState(initialUrl);
    // Overview resource is owned here so the header score pill and the Overview
    // tab share a single request; `refetchKey` re-runs it after an audit.
    const overviewResource = useSeoResource(fetchSeoOverview, [refetchKey]);
    // Keep tab + deep links in sync with browser back/forward navigation.
    useEffect(() => {
        function sync() {
            const url = readUrlState();
            setActiveTab(normalizeTab(url.tab ?? initialTab));
            setDeepLink(url);
        }
        window.addEventListener('popstate', sync);
        return () => window.removeEventListener('popstate', sync);
    }, [initialTab]);
    useEffect(() => {
        const url = readUrlState();
        setActiveTab(normalizeTab(url.tab ?? initialTab));
        setDeepLink(url);
    }, [initialTab]);
    const changeTab = useCallback((tab) => {
        const next = normalizeTab(tab);
        setActiveTab(next);
        setDeepLink({ tab: next, entityType: null, entityId: null, issueId: null });
        onNavigate?.(`/seo?tab=${next}`);
    }, [onNavigate]);
    const handleRunAudit = useCallback(async () => {
        setAuditing(true);
        const res = await runSeoAudit('full');
        setAuditing(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('Audit complete.');
        setRefetchKey((k) => k + 1);
    }, []);
    const score = overviewResource.data?.siteScore.score;
    const badgeCounts = useMemo(() => {
        const summary = overviewResource.data?.issuesSummary;
        return { audit: summary ? summary.critical + summary.warning : 0 };
    }, [overviewResource.data]);
    return (_jsxs("div", { className: "space-y-6 p-6", children: [_jsxs("header", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between", children: [_jsxs("div", { children: [_jsx("h1", { className: "text-foreground text-2xl font-medium", children: "SEO Operations Center" }), _jsx("p", { className: "text-muted-foreground mt-1 text-sm", children: "Monitor, fix, and automate SEO across your content, redirects, and technical setup." })] }), _jsxs("div", { className: "flex items-center gap-3", children: [typeof score === 'number' && (_jsxs("span", { className: "text-muted-foreground flex items-center gap-2 text-sm", children: ["Site score ", _jsx(ScorePill, { score: score })] })), _jsxs("button", { className: btnSecondary, onClick: () => setCopilotOpen(true), children: [_jsx(Bot, { className: "h-4 w-4", "aria-hidden": true }), "AI Copilot"] }), _jsxs("button", { className: btnPrimary, onClick: handleRunAudit, disabled: auditing, children: [_jsx(RefreshCw, { className: `h-4 w-4 ${auditing ? 'animate-spin' : ''}`, "aria-hidden": true }), auditing ? 'Running audit…' : 'Run audit'] })] })] }), _jsx(SeoCopilotDrawer, { open: copilotOpen, onOpenChange: setCopilotOpen }), _jsxs(Tabs.Root, { value: activeTab, onValueChange: changeTab, children: [_jsx(Tabs.List, { className: "border-border flex gap-1 overflow-x-auto border-b", "aria-label": "SEO sections", children: TABS.map((t) => {
                            const Icon = t.icon;
                            const badge = t.id === 'audit' ? badgeCounts.audit : 0;
                            return (_jsxs(Tabs.Trigger, { value: t.id, className: "text-muted-foreground hover:text-foreground data-[state=active]:text-foreground data-[state=active]:border-primary focus-visible:ring-ring -mb-px flex items-center gap-2 border-b-2 border-transparent px-3 py-2.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none", children: [_jsx(Icon, { className: "h-4 w-4", "aria-hidden": true }), t.label, badge > 0 && (_jsx("span", { className: "bg-destructive/10 text-destructive ml-1 rounded-full px-1.5 py-0.5 text-xs font-medium tabular-nums", children: badge }))] }, t.id));
                        }) }), _jsx("div", { className: "pt-6", children: _jsxs(ErrorBoundary, { children: [_jsx(Tabs.Content, { value: "overview", tabIndex: -1, children: activeTab === 'overview' && (_jsx(OverviewTab, { resource: overviewResource, onOpenIssue: (issueId) => onNavigate?.(`/seo?tab=audit&issueId=${issueId}`), onConnectSearchConsole: () => toast.info('Google Search Console integration is coming soon. Demo performance data is available in local development.') })) }), _jsx(Tabs.Content, { value: "content", tabIndex: -1, children: activeTab === 'content' && (_jsx(ContentTab, { initialEntityType: deepLink.entityType, initialEntityId: deepLink.entityId })) }), _jsx(Tabs.Content, { value: "technical", tabIndex: -1, children: activeTab === 'technical' && _jsx(TechnicalTab, {}) }), _jsx(Tabs.Content, { value: "redirects", tabIndex: -1, children: activeTab === 'redirects' && _jsx(RedirectsTab, {}) }), _jsx(Tabs.Content, { value: "audit", tabIndex: -1, children: activeTab === 'audit' && (_jsx(AuditTab, { refetchKey: refetchKey, initialIssueId: deepLink.issueId, onNavigate: onNavigate })) })] }) })] })] }));
}
//# sourceMappingURL=SEO.js.map