'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as Tabs from '@radix-ui/react-tabs';
import { Bot, Loader2, AlertTriangle, Download, Layers, Users as UsersIcon, KeyRound, } from 'lucide-react';
import { useState, useEffect, useCallback, useMemo } from 'react';
import { toast } from 'sonner';
import { useApiData } from '../lib/useApiData.js';
import { cmsApi } from '../lib/api.js';
import { RelationshipField } from '../fields/RelationshipField.js';
import { GeneralSettingsTab } from './settings/GeneralSettingsTab.js';
import { SeoSettingsTab } from './settings/SeoSettingsTab.js';
import { AISettingsTab } from './settings/AISettingsTab.js';
import { AppearanceTab } from './settings/AppearanceTab.js';
import { SecurityTab } from './settings/SecurityTab.js';
import { SettingsCard } from './settings/components.js';
import { UpdatesTab } from './settings/UpdatesTab.js';
import { Users as UsersView } from './Users.js';
import { ApiKeys as ApiKeysView } from './ApiKeys.js';
/**
 * Tabs that persist through the shared footer's `handleSave` (which writes
 * `defaultLayout` into the settings global). Every other tab owns its own
 * saving, so the footer must NOT render there — otherwise it shows a
 * "Settings saved successfully!" toast while persisting nothing relevant.
 * This is an allowlist on purpose: new tabs default to self-managed.
 */
const GLOBAL_SAVE_TABS = new Set(['layout']);
function readSettingsTabFromUrl() {
    if (typeof window === 'undefined')
        return null;
    return new URLSearchParams(window.location.search).get('tab');
}
export function Settings({ config, onNavigate, session, initialTab = 'general', } = {}) {
    const { data, loading, error, refetch } = useApiData('/globals/settings');
    const [activeTab, setActiveTab] = useState(() => readSettingsTabFromUrl() ?? initialTab);
    const [saving, setSaving] = useState(false);
    // Layout defaults
    const [defaultLayout, setDefaultLayout] = useState({});
    const layoutConfig = config?.layout;
    const layoutRegions = layoutConfig?.regions
        ? Object.entries(layoutConfig.regions).map(([name, region]) => ({
            name,
            collection: region.collection,
            label: region.label ?? name.charAt(0).toUpperCase() + name.slice(1),
        }))
        : [];
    const hasLayoutRegions = layoutRegions.length > 0;
    // Valid tab ids, with `layout` only available when the project configures
    // layout regions. Used to normalise deep links and keep the URL honest.
    const availableTabs = useMemo(() => [
        'general',
        'appearance',
        ...(hasLayoutRegions ? ['layout'] : []),
        'security',
        'users',
        'api-keys',
        'seo',
        'ai',
        'updates',
    ], [hasLayoutRegions]);
    const normalizeTab = useCallback((tab) => tab && availableTabs.includes(tab) ? tab : 'general', [availableTabs]);
    // Drive the active tab from the `?tab=` query param so tabs are deep-linkable
    // and survive browser back/forward (the legacy /users and /api-keys routes
    // land here via `initialTab`).
    useEffect(() => {
        function sync() {
            setActiveTab(normalizeTab(readSettingsTabFromUrl() ?? initialTab));
        }
        sync();
        window.addEventListener('popstate', sync);
        return () => window.removeEventListener('popstate', sync);
    }, [normalizeTab, initialTab]);
    const changeTab = useCallback((tab) => {
        const next = normalizeTab(tab);
        setActiveTab(next);
        onNavigate?.(`/settings?tab=${next}`);
    }, [normalizeTab, onNavigate]);
    useEffect(() => {
        if (data) {
            if (data.defaultLayout && typeof data.defaultLayout === 'object') {
                setDefaultLayout(data.defaultLayout);
            }
        }
    }, [data]);
    const handleSave = async () => {
        setSaving(true);
        const layoutPayload = Object.keys(defaultLayout).length > 0 ? { defaultLayout } : {};
        // Read-modify-write: the General tab owns site info / SEO defaults in the
        // same global blob, so merge against a fresh fetch instead of overwriting.
        const current = await cmsApi('/globals/settings');
        const res = await cmsApi('/globals/settings', {
            method: 'PUT',
            body: JSON.stringify({
                ...(current.data ?? {}),
                ...layoutPayload,
            }),
        });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Settings saved successfully!');
        }
    };
    const tabTriggerClass = 'text-muted-foreground hover:text-foreground data-[state=active]:border-brand data-[state=active]:text-brand px-4 py-2 text-base font-medium transition-colors data-[state=active]:border-b-2';
    if (loading) {
        return (_jsx("div", { className: "flex h-64 items-center justify-center p-3 pr-6 sm:p-4 sm:pr-8", children: _jsx(Loader2, { className: "h-6 w-6 animate-spin text-blue-600" }) }));
    }
    return (_jsxs("div", { className: "p-3 pr-6 sm:p-4 sm:pr-8", children: [error && (_jsxs("div", { role: "alert", className: "border-destructive/30 bg-destructive/10 text-destructive mb-4 flex items-center gap-3 rounded-lg border p-3 text-sm", children: [_jsx(AlertTriangle, { size: 20, className: "shrink-0", "aria-hidden": "true" }), _jsx("span", { className: "flex-1", children: error }), _jsx("button", { onClick: refetch, className: "border-destructive/40 rounded-md border px-3 py-1 transition-colors hover:opacity-80", children: "Retry" })] })), _jsxs("div", { className: "mb-4", children: [_jsx("h1", { className: "text-foreground mb-1 text-2xl font-medium", children: "Settings" }), _jsx("p", { className: "text-muted-foreground text-sm", children: "Manage your CMS configuration" })] }), _jsxs(Tabs.Root, { value: activeTab, onValueChange: changeTab, children: [_jsxs(Tabs.List, { className: "border-border mb-4 flex gap-1 overflow-x-auto border-b", children: [_jsx(Tabs.Trigger, { value: "general", className: tabTriggerClass, children: "General" }), _jsx(Tabs.Trigger, { value: "appearance", className: tabTriggerClass, children: "Appearance" }), hasLayoutRegions && (_jsx(Tabs.Trigger, { value: "layout", className: tabTriggerClass, children: _jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx(Layers, { className: "h-4 w-4" }), "Layout"] }) })), _jsx(Tabs.Trigger, { value: "security", className: tabTriggerClass, children: "Security" }), _jsx(Tabs.Trigger, { value: "users", className: tabTriggerClass, children: _jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx(UsersIcon, { className: "h-4 w-4" }), "Users"] }) }), _jsx(Tabs.Trigger, { value: "api-keys", className: tabTriggerClass, children: _jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx(KeyRound, { className: "h-4 w-4" }), "API Keys"] }) }), _jsx(Tabs.Trigger, { value: "seo", className: tabTriggerClass, children: "SEO" }), _jsx(Tabs.Trigger, { value: "ai", className: tabTriggerClass, children: _jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx(Bot, { className: "h-4 w-4" }), "AI"] }) }), _jsx(Tabs.Trigger, { value: "updates", className: tabTriggerClass, children: _jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx(Download, { className: "h-4 w-4" }), "Updates"] }) })] }), _jsx(Tabs.Content, { value: "general", children: _jsx(GeneralSettingsTab, { onNavigate: onNavigate, role: session?.user?.role }) }), _jsx(Tabs.Content, { value: "appearance", className: "space-y-4", children: _jsx(AppearanceTab, { role: session?.user?.role, config: config }) }), hasLayoutRegions && (_jsxs(Tabs.Content, { value: "layout", className: "space-y-4", children: [_jsx(SettingsCard, { title: "Default Layout Variants", description: "Select the default header, footer, and other layout variants used site-wide. Pages can override these individually or inherit from parent pages.", children: _jsx("div", { className: "space-y-4", children: layoutRegions.map((region) => (_jsx(RelationshipField, { label: `Default ${region.label}`, value: defaultLayout[region.name] ?? '', onChange: (val) => {
                                            setDefaultLayout((prev) => {
                                                const next = { ...prev };
                                                if (val && typeof val === 'string') {
                                                    next[region.name] = val;
                                                }
                                                else {
                                                    delete next[region.name];
                                                }
                                                return next;
                                            });
                                        }, relationTo: region.collection, helpText: `The ${region.label.toLowerCase()} variant used when no page in the ancestor chain specifies one` }, region.name))) }) }), _jsx(SettingsCard, { title: "How Layout Inheritance Works", children: _jsxs("ul", { className: "text-muted-foreground space-y-1.5 text-sm", children: [_jsxs("li", { className: "flex items-start gap-2", children: [_jsx("span", { className: "bg-brand/10 text-brand mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-medium", children: "1" }), _jsx("span", { children: "Each page can assign specific layout variants (header, footer, etc.) from the document editor." })] }), _jsxs("li", { className: "flex items-start gap-2", children: [_jsx("span", { className: "bg-brand/10 text-brand mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-medium", children: "2" }), _jsxs("span", { children: ["Child pages automatically inherit their parent's layout. For example,", ' ', _jsx("code", { className: "bg-muted rounded px-1 font-mono", children: "/hampton-roads/thank-you" }), ' ', "inherits from", ' ', _jsx("code", { className: "bg-muted rounded px-1 font-mono", children: "/hampton-roads" }), "."] })] }), _jsxs("li", { className: "flex items-start gap-2", children: [_jsx("span", { className: "bg-brand/10 text-brand mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-medium", children: "3" }), _jsx("span", { children: "If no page in the ancestor chain sets a variant, the defaults configured above are used." })] })] }) })] })), _jsx(Tabs.Content, { value: "security", className: "space-y-4", children: _jsx(SecurityTab, { role: session?.user?.role, onNavigate: onNavigate }) }), _jsx(Tabs.Content, { value: "seo", className: "space-y-4", children: _jsx(SeoSettingsTab, { onNavigate: onNavigate, role: session?.user?.role }) }), _jsx(Tabs.Content, { value: "ai", className: "space-y-4", children: _jsx(AISettingsTab, { role: session?.user?.role }) }), _jsx(Tabs.Content, { value: "users", children: _jsx(UsersView, { onNavigate: onNavigate, embedded: true }) }), _jsx(Tabs.Content, { value: "api-keys", children: _jsx(ApiKeysView, { onNavigate: onNavigate, embedded: true }) }), _jsx(Tabs.Content, { value: "updates", className: "space-y-4", children: _jsx(UpdatesTab, { role: session?.user?.role }) })] }), GLOBAL_SAVE_TABS.has(activeTab) && (_jsx("div", { className: "mt-6 flex justify-end", children: _jsx("button", { type: "button", onClick: handleSave, disabled: saving, className: "rounded-lg bg-blue-600 px-6 py-2 text-sm text-white transition-colors hover:bg-blue-700 disabled:opacity-50", children: saving ? 'Saving...' : 'Save Changes' }) }))] }));
}
//# sourceMappingURL=Settings.js.map