'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useMemo, useState } from 'react';
import { Code2, Copy, Plus, Loader2, AlertTriangle, Shield, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { EnabledSwitch } from '../components/EnabledSwitch.js';
import { Button } from '../components/ui/Button.js';
import { ConfirmDialog } from '../components/ui/ConfirmDialog.js';
import { FilterPill } from '../components/ui/FilterPill.js';
import { RowActions, RowActionButton } from '../components/ui/RowActions.js';
import { SearchInput } from '../components/ui/SearchInput.js';
import { StatPill } from '../components/ui/StatPill.js';
import { InspectorPane, SplitPaneLayout, SplitPaneList } from '../components/ui/InspectorPane.js';
import { CONSENT_COLORS, CONSENT_LABELS, NO_CONSENT_COLORS, PLACEMENT_COLORS, PLACEMENT_LABELS, ScriptTagEditorPane, } from '../components/script-tags/ScriptTagEditorPane.js';
import { useApiData } from '../lib/useApiData.js';
import { cmsApi } from '../lib/api.js';
const LOCATION_FILTERS = [
    { value: 'all', label: 'All' },
    { value: 'head', label: '<head>' },
    { value: 'body_open', label: 'Body start' },
    { value: 'body_close', label: 'Body end' },
];
const CONSENT_FILTERS = [
    { value: 'all', label: 'All consent' },
    { value: 'none', label: 'No consent' },
    { value: 'analytics', label: 'Analytics' },
    { value: 'marketing', label: 'Marketing' },
    { value: 'functional', label: 'Functional' },
    { value: 'preferences', label: 'Preferences' },
];
function normalizeEnabled(value) {
    if (typeof value === 'boolean')
        return value;
    if (value === 'true' || value === 1)
        return true;
    if (value === 'false' || value === 0 || value === null)
        return false;
    return true;
}
function scopeLabel(tag) {
    const scope = String(tag.scope ?? '');
    const targetPaths = Array.isArray(tag.targetPaths) ? tag.targetPaths : [];
    if (scope === 'site')
        return 'Entire Site';
    if (scope === 'parents') {
        const count = targetPaths.length;
        return `${count} parent path${count !== 1 ? 's' : ''} + children`;
    }
    if (scope === 'urls') {
        const count = targetPaths.length;
        return `${count} URL${count !== 1 ? 's' : ''}`;
    }
    return scope || 'Custom';
}
function formatDate(value) {
    const date = new Date(value);
    if (Number.isNaN(date.getTime()))
        return '—';
    return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
function consentCategoryOf(tag) {
    return tag.consentCategory && tag.consentCategory !== '' ? tag.consentCategory : 'none';
}
export function ScriptTags({ initialSelectedId, initialNew }) {
    const { data, loading, error, refetch } = useApiData('/script-tags');
    const [togglingId, setTogglingId] = useState(null);
    const [enabledOverrides, setEnabledOverrides] = useState({});
    const [search, setSearch] = useState('');
    const [locationFilter, setLocationFilter] = useState('all');
    const [consentFilter, setConsentFilter] = useState('all');
    const [checkedIds, setCheckedIds] = useState(new Set());
    const [pendingDelete, setPendingDelete] = useState(null);
    const [selection, setSelection] = useState(initialNew
        ? { mode: 'new' }
        : initialSelectedId
            ? { mode: 'edit', id: initialSelectedId }
            : null);
    const tags = useMemo(() => (data ?? []).map((tag) => ({
        ...tag,
        enabled: enabledOverrides[tag.id] ?? normalizeEnabled(tag.enabled),
    })), [data, enabledOverrides]);
    const filteredTags = useMemo(() => {
        const query = search.trim().toLowerCase();
        return tags.filter((tag) => {
            if (locationFilter !== 'all' && tag.placement !== locationFilter)
                return false;
            if (consentFilter !== 'all' && consentCategoryOf(tag) !== consentFilter)
                return false;
            if (query && !tag.name.toLowerCase().includes(query))
                return false;
            return true;
        });
    }, [tags, locationFilter, consentFilter, search]);
    const consentGatedCount = tags.filter((t) => consentCategoryOf(t) !== 'none').length;
    const checkedVisible = filteredTags.filter((t) => checkedIds.has(t.id));
    const allVisibleChecked = filteredTags.length > 0 && checkedVisible.length === filteredTags.length;
    const selectedTag = selection?.mode === 'edit' ? (tags.find((t) => t.id === selection.id) ?? null) : null;
    const paneOpen = selection?.mode === 'new' || selectedTag !== null;
    const toggleRow = (tag) => {
        setSelection((prev) => prev?.mode === 'edit' && prev.id === tag.id ? null : { mode: 'edit', id: tag.id });
    };
    const toggleChecked = (id) => {
        setCheckedIds((prev) => {
            const next = new Set(prev);
            if (next.has(id))
                next.delete(id);
            else
                next.add(id);
            return next;
        });
    };
    const toggleAllChecked = () => {
        setCheckedIds(allVisibleChecked ? new Set() : new Set(filteredTags.map((t) => t.id)));
    };
    const clearFilters = () => {
        setSearch('');
        setLocationFilter('all');
        setConsentFilter('all');
    };
    const toggleEnabled = async (tag, nextEnabled) => {
        setEnabledOverrides((prev) => ({ ...prev, [tag.id]: nextEnabled }));
        setTogglingId(tag.id);
        const res = await cmsApi(`/script-tags/${tag.id}`, {
            method: 'PUT',
            body: JSON.stringify({ enabled: nextEnabled }),
        });
        setTogglingId(null);
        if (res.error) {
            setEnabledOverrides((prev) => {
                const { [tag.id]: _, ...rest } = prev;
                return rest;
            });
            toast.error(res.error);
            return;
        }
        const saved = normalizeEnabled(res.data?.enabled ?? nextEnabled);
        setEnabledOverrides((prev) => ({ ...prev, [tag.id]: saved }));
        refetch();
        toast.success(saved ? 'Tag enabled' : 'Tag disabled');
    };
    const duplicateTag = async (tag) => {
        const res = await cmsApi('/script-tags', {
            method: 'POST',
            body: JSON.stringify({
                name: `${tag.name} (Copy)`,
                code: tag.code,
                placement: tag.placement,
                scope: tag.scope,
                targetPaths: tag.targetPaths,
                priority: tag.priority,
                enabled: false,
                loadAsync: tag.loadAsync,
                disableInPreview: tag.disableInPreview,
                consentCategory: tag.consentCategory,
            }),
        });
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('Script duplicated (created disabled)');
        refetch();
        if (res.data?.id)
            setSelection({ mode: 'edit', id: res.data.id });
    };
    const deleteTag = async (tag) => {
        setPendingDelete(null);
        const res = await cmsApi(`/script-tags/${tag.id}`, { method: 'DELETE' });
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('Script deleted');
        setCheckedIds((prev) => {
            const next = new Set(prev);
            next.delete(tag.id);
            return next;
        });
        if (selection?.mode === 'edit' && selection.id === tag.id)
            setSelection(null);
        refetch();
    };
    const handlePaneChanged = (savedId) => {
        setEnabledOverrides({});
        refetch();
        if (savedId)
            setSelection({ mode: 'edit', id: savedId });
    };
    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: "text-primary h-6 w-6 animate-spin" }) }));
    }
    return (_jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [_jsxs("div", { className: "p-3 pr-6 pb-0 sm:p-4 sm:pr-8 sm:pb-0", children: [error && (_jsxs("div", { className: "border-destructive/30 bg-destructive/10 mb-4 flex items-center gap-3 rounded-lg border p-4", children: [_jsx(AlertTriangle, { className: "text-destructive h-5 w-5 shrink-0" }), _jsx("span", { className: "text-destructive flex-1 text-sm", children: error }), _jsx("button", { onClick: refetch, className: "border-destructive/40 text-destructive hover:bg-destructive/15 rounded-lg border px-3 py-1 text-sm transition-colors focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: "Retry" })] })), _jsxs("div", { className: "mb-4 flex items-center justify-between", children: [_jsxs("div", { children: [_jsx("h1", { className: "mb-1 text-[var(--txt)]", children: "Script Tags" }), _jsx("p", { className: "text-sm text-[var(--sub)]", children: "Inject scripts into the frontend \u2014 never into CMS rendering" }), tags.length > 0 && (_jsxs("div", { className: "mt-3 flex flex-wrap gap-1.5", children: [_jsx(StatPill, { value: tags.length, label: "Total" }), _jsx(StatPill, { value: tags.filter((t) => t.enabled).length, label: "Active", valueClassName: "text-[var(--suc)]" }), _jsx(StatPill, { value: tags.filter((t) => !t.enabled).length, label: "Inactive", valueClassName: "text-[var(--muted)]" }), _jsx(StatPill, { value: consentGatedCount, label: "Consent-gated", icon: _jsx(Shield, { size: 12, className: "text-[var(--acc)]", "aria-hidden": true }) })] }))] }), _jsx(Button, { type: "button", variant: "primary", size: "md", onClick: () => setSelection({ mode: 'new' }), leftIcon: _jsx(Plus, { size: 16, "aria-hidden": true }), children: "New Script" })] }), tags.length > 0 && (_jsxs("div", { className: "mb-3 flex flex-wrap items-center gap-2", children: [_jsx("div", { className: "w-full max-w-[260px]", children: _jsx(SearchInput, { value: search, onChange: setSearch, placeholder: "Search scripts\u2026" }) }), _jsx("div", { className: "flex gap-1", role: "group", "aria-label": "Filter by location", children: LOCATION_FILTERS.map((f) => (_jsx(FilterPill, { active: locationFilter === f.value, onClick: () => setLocationFilter(f.value), children: f.label }, f.value))) }), _jsx("div", { className: "ml-2 flex flex-wrap gap-1", role: "group", "aria-label": "Filter by consent", children: CONSENT_FILTERS.map((f) => (_jsx(FilterPill, { active: consentFilter === f.value, onClick: () => setConsentFilter(f.value), children: f.label }, f.value))) }), _jsx("span", { className: "ml-auto text-xs text-[var(--muted)]", "aria-live": "polite", children: checkedIds.size > 0 ? (_jsxs(_Fragment, { children: [checkedIds.size, " selected \u00B7", ' ', _jsx("button", { type: "button", onClick: () => setCheckedIds(new Set()), className: "rounded-sm text-[var(--acc)] hover:underline focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: "Clear" })] })) : (`${filteredTags.length} script${filteredTags.length !== 1 ? 's' : ''}`) })] }))] }), _jsxs(SplitPaneLayout, { children: [_jsx(SplitPaneList, { className: "p-4 pr-8 sm:pr-8", children: tags.length === 0 && !error ? (_jsxs("div", { className: "rounded-lg border border-[var(--bdr)] bg-[var(--card)] p-12 text-center", children: [_jsx(Code2, { className: "mx-auto mb-3 h-10 w-10 text-[var(--sub)]" }), _jsx("h3", { className: "text-sm font-medium text-[var(--txt)]", children: "No script tags yet" }), _jsx("p", { className: "mt-1 text-sm text-[var(--sub)]", children: "Add tracking codes like Google Analytics, Tag Manager, or Facebook Pixel." }), _jsx(Button, { type: "button", variant: "primary", size: "md", className: "mt-4", onClick: () => setSelection({ mode: 'new' }), leftIcon: _jsx(Plus, { size: 16, "aria-hidden": true }), children: "Add Your First Script" })] })) : filteredTags.length === 0 ? (_jsxs("div", { className: "rounded-lg border border-[var(--bdr)] bg-[var(--card)] p-12 text-center", children: [_jsx(Code2, { className: "mx-auto mb-3 h-10 w-10 text-[var(--sub)]" }), _jsx("h3", { className: "text-sm font-medium text-[var(--txt)]", children: "No scripts match your filters" }), _jsx("p", { className: "mt-1 text-sm text-[var(--sub)]", children: "Try a different search term or clear the filters." }), _jsx("button", { type: "button", onClick: clearFilters, className: "mt-3 rounded-sm text-sm text-[var(--acc)] hover:underline focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: "Clear filters" })] })) : (_jsx("div", { className: "overflow-x-auto rounded-lg border border-[var(--bdr)] bg-[var(--card)]", children: _jsxs("table", { className: "w-full min-w-[920px] text-sm", "aria-label": "Script tags", children: [_jsx("thead", { children: _jsxs("tr", { className: "bg-muted border-b border-[var(--bdr)]", children: [_jsx("th", { className: "w-9 px-3 py-3", children: _jsx("input", { type: "checkbox", checked: allVisibleChecked, onChange: toggleAllChecked, "aria-label": allVisibleChecked ? 'Deselect all scripts' : 'Select all scripts', className: "h-[15px] w-[15px] cursor-pointer accent-[var(--acc)]" }) }), _jsx("th", { className: "px-4 py-3 text-left font-medium text-[var(--sub)]", children: "Script" }), _jsx("th", { className: "px-4 py-3 text-left font-medium text-[var(--sub)]", children: "Location" }), _jsx("th", { className: "px-4 py-3 text-center font-medium text-[var(--sub)]", children: "Priority" }), _jsx("th", { className: "px-4 py-3 text-left font-medium text-[var(--sub)]", children: "Scope" }), _jsx("th", { className: "px-4 py-3 text-left font-medium text-[var(--sub)]", children: "Consent" }), _jsx("th", { className: "px-4 py-3 text-center font-medium text-[var(--sub)]", children: "Active" }), _jsx("th", { className: "px-4 py-3 text-right font-medium text-[var(--sub)]", children: "Updated" })] }) }), _jsx("tbody", { children: filteredTags.map((tag) => {
                                            const isSelected = selection?.mode === 'edit' && selection.id === tag.id;
                                            const consent = CONSENT_COLORS[consentCategoryOf(tag)] ?? NO_CONSENT_COLORS;
                                            return (_jsxs("tr", { className: `group cursor-pointer border-b border-[var(--bdr)] transition-colors last:border-0 ${isSelected ? 'bg-[var(--acc-l)]' : 'hover:bg-[var(--acc-l)]'}`, onClick: () => toggleRow(tag), children: [_jsx("td", { className: "px-3 py-[11px]", onClick: (e) => e.stopPropagation(), children: _jsx("input", { type: "checkbox", checked: checkedIds.has(tag.id), onChange: () => toggleChecked(tag.id), "aria-label": `Select ${tag.name}`, className: "h-[15px] w-[15px] cursor-pointer accent-[var(--acc)]" }) }), _jsxs("td", { className: "px-4 py-[11px]", children: [_jsx("button", { type: "button", onClick: (e) => {
                                                                    e.stopPropagation();
                                                                    toggleRow(tag);
                                                                }, "aria-expanded": isSelected, className: "text-left font-medium text-[var(--txt)] hover:text-[var(--acc)]", children: tag.name }), _jsxs("div", { className: "mt-0.5 text-[11.5px] text-[var(--muted)]", children: ["Added ", formatDate(tag.createdAt)] })] }), _jsx("td", { className: "px-4 py-[11px]", children: _jsx("span", { className: `inline-flex items-center rounded-[5px] px-2 py-[3px] text-[11.5px] font-medium ${PLACEMENT_COLORS[tag.placement] ?? 'bg-muted text-[var(--txt)]'}`, children: PLACEMENT_LABELS[tag.placement] ?? tag.placement }) }), _jsx("td", { className: "px-4 py-[11px] text-center", children: _jsx("span", { className: "inline-flex h-6 w-6 items-center justify-center rounded-full border-[1.5px] border-[var(--bdr)] bg-[var(--bg)] text-[11.5px] font-semibold text-[var(--sub)]", children: tag.priority }) }), _jsx("td", { className: "px-4 py-[11px] text-[var(--sub)]", children: scopeLabel(tag) }), _jsx("td", { className: "px-4 py-[11px]", children: _jsxs("span", { className: `inline-flex items-center gap-[3px] rounded-[4px] px-[7px] py-0.5 text-[11px] font-medium ${consent.badge}`, children: [_jsx("span", { className: `inline-block h-[5px] w-[5px] rounded-full ${consent.dot}`, "aria-hidden": true }), CONSENT_LABELS[consentCategoryOf(tag)] ?? tag.consentCategory] }) }), _jsx("td", { className: "px-4 py-[11px] text-center", onClick: (e) => e.stopPropagation(), children: _jsx(EnabledSwitch, { checked: tag.enabled, disabled: togglingId === tag.id, onCheckedChange: (next) => void toggleEnabled(tag, next), "aria-label": `${tag.enabled ? 'Disable' : 'Enable'} ${tag.name}` }) }), _jsx("td", { className: "px-4 py-[11px]", children: _jsxs("div", { className: "flex items-center justify-end gap-2", children: [_jsxs(RowActions, { children: [_jsx(RowActionButton, { "aria-label": `Duplicate ${tag.name}`, onClick: (e) => {
                                                                                e.stopPropagation();
                                                                                void duplicateTag(tag);
                                                                            }, children: _jsx(Copy, { size: 12, "aria-hidden": true }) }), _jsx(RowActionButton, { danger: true, "aria-label": `Delete ${tag.name}`, onClick: (e) => {
                                                                                e.stopPropagation();
                                                                                setPendingDelete(tag);
                                                                            }, children: _jsx(Trash2, { size: 12, "aria-hidden": true }) })] }), _jsx("span", { className: "text-xs whitespace-nowrap text-[var(--sub)]", children: formatDate(tag.updatedAt) })] }) })] }, tag.id));
                                        }) })] }) })) }), _jsx(InspectorPane, { open: paneOpen, width: 420, "aria-label": "Script editor", children: _jsx(ScriptTagEditorPane, { tag: selectedTag, onClose: () => setSelection(null), onChanged: handlePaneChanged }, selection?.mode === 'edit' ? selection.id : 'new') })] }), _jsx(ConfirmDialog, { open: pendingDelete !== null, title: "Delete script?", description: `"${pendingDelete?.name ?? 'This script'}" will stop firing on your site immediately.`, confirmLabel: "Delete", destructive: true, onConfirm: () => {
                    if (pendingDelete)
                        void deleteTag(pendingDelete);
                }, onClose: () => setPendingDelete(null) })] }));
}
//# sourceMappingURL=ScriptTags.js.map