'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect } from 'react';
import { ArrowLeft, Loader2, AlertTriangle, Trash2, X, Plus } from 'lucide-react';
import { toast } from 'sonner';
import { useApiData } from '../lib/useApiData.js';
import { cmsApi } from '../lib/api.js';
export function ScriptTagEditor({ tagId, onNavigate }) {
    const isNew = !tagId;
    const { data, loading, error } = useApiData(tagId ? `/script-tags` : null);
    const [name, setName] = useState('');
    const [code, setCode] = useState('');
    const [placement, setPlacement] = useState('head');
    const [scope, setScope] = useState('site');
    const [targetPaths, setTargetPaths] = useState([]);
    const [pathInput, setPathInput] = useState('');
    const [priority, setPriority] = useState(100);
    const [enabled, setEnabled] = useState(true);
    const [saving, setSaving] = useState(false);
    const [deleting, setDeleting] = useState(false);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    useEffect(() => {
        if (data && tagId) {
            const tags = Array.isArray(data) ? data : [];
            const tag = tags.find((t) => t.id === tagId);
            if (tag) {
                setName(tag.name ?? '');
                setCode(tag.code ?? '');
                setPlacement(tag.placement ?? 'head');
                setScope(tag.scope ?? 'site');
                setTargetPaths(tag.targetPaths ?? []);
                setPriority(tag.priority ?? 100);
                setEnabled(tag.enabled ?? true);
            }
        }
    }, [data, tagId]);
    const addPath = () => {
        const trimmed = pathInput.trim();
        if (!trimmed)
            return;
        const normalized = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
        if (!targetPaths.includes(normalized)) {
            setTargetPaths([...targetPaths, normalized]);
        }
        setPathInput('');
    };
    const removePath = (path) => {
        setTargetPaths(targetPaths.filter((p) => p !== path));
    };
    const handleSave = async () => {
        if (!name.trim()) {
            toast.error('Name is required');
            return;
        }
        if (!code.trim()) {
            toast.error('Code snippet is required');
            return;
        }
        if (scope !== 'site' && targetPaths.length === 0) {
            toast.error('At least one target path is required for this scope');
            return;
        }
        setSaving(true);
        const payload = {
            name: name.trim(),
            code,
            placement,
            scope,
            targetPaths: scope === 'site' ? [] : targetPaths,
            priority,
            enabled,
        };
        const res = isNew
            ? await cmsApi('/script-tags', { method: 'POST', body: JSON.stringify(payload) })
            : await cmsApi(`/script-tags/${tagId}`, { method: 'PUT', body: JSON.stringify(payload) });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success(isNew ? 'Tag created' : 'Tag updated');
            onNavigate?.('/script-tags');
        }
    };
    const handleDelete = async () => {
        if (!tagId)
            return;
        setDeleting(true);
        const res = await cmsApi(`/script-tags/${tagId}`, { method: 'DELETE' });
        setDeleting(false);
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Tag deleted');
            onNavigate?.('/script-tags');
        }
    };
    if (loading && !isNew) {
        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: "max-w-3xl p-3 pr-6 sm:p-4 sm:pr-8", children: [error && (_jsxs("div", { className: "mb-4 flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-3", children: [_jsx(AlertTriangle, { className: "h-5 w-5 shrink-0 text-red-600" }), _jsx("span", { className: "flex-1 text-sm text-red-800", children: error })] })), _jsxs("div", { className: "mb-6", children: [_jsxs("button", { type: "button", onClick: () => onNavigate?.('/script-tags'), className: "mb-3 flex items-center gap-1.5 text-sm text-gray-500 transition-colors hover:text-gray-700", children: [_jsx(ArrowLeft, { className: "h-4 w-4" }), "Back to Script Tags"] }), _jsx("h1", { className: "text-2xl font-semibold text-gray-900", children: isNew ? 'New Script Tag' : 'Edit Script Tag' })] }), _jsx("div", { className: "mb-6 rounded-lg border border-amber-200 bg-amber-50 p-3", children: _jsxs("div", { className: "flex items-start gap-2", children: [_jsx(AlertTriangle, { className: "mt-0.5 h-4 w-4 shrink-0 text-amber-600" }), _jsx("p", { className: "text-sm text-amber-800", children: "This code will run on public pages matching the scope below. Only add trusted code from verified sources (e.g. Google Analytics, Meta Pixel)." })] }) }), _jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "space-y-4 rounded-lg border border-gray-200 bg-white p-4", children: [_jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Name" }), _jsx("input", { type: "text", value: name, onChange: (e) => setName(e.target.value), placeholder: "e.g. Google Tag Manager, Facebook Pixel", className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Code" }), _jsx("textarea", { value: code, onChange: (e) => setCode(e.target.value), placeholder: "Paste your HTML/JavaScript snippet here...", rows: 10, className: "w-full rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", spellCheck: false }), _jsxs("p", { className: "mt-1 text-xs text-gray-500", children: ["Paste the full code snippet including ", '<script>', " tags."] })] })] }), _jsxs("div", { className: "space-y-4 rounded-lg border border-gray-200 bg-white p-4", children: [_jsx("h3", { className: "text-sm font-semibold text-gray-900", children: "Placement & Scope" }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Placement" }), _jsxs("select", { value: placement, onChange: (e) => setPlacement(e.target.value), className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", children: [_jsxs("option", { value: "head", children: ["Head \u2014 inside ", '<head>'] }), _jsxs("option", { value: "body_open", children: ["Body Open \u2014 right after ", '<body>'] }), _jsxs("option", { value: "body_close", children: ["Body Close \u2014 before ", '</body>'] })] }), _jsxs("p", { className: "mt-1 text-xs text-gray-500", children: [placement === 'head' && 'Best for analytics scripts, meta tags, and custom CSS.', placement === 'body_open' && 'Best for GTM noscript tags and early-loading scripts.', placement === 'body_close' &&
                                                'Best for chat widgets, deferred scripts, and tracking pixels.'] })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Scope" }), _jsxs("select", { value: scope, onChange: (e) => setScope(e.target.value), className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", children: [_jsx("option", { value: "site", children: "Entire Website" }), _jsx("option", { value: "parents", children: "Specific Parent Pages (includes child pages)" }), _jsx("option", { value: "urls", children: "Specific URLs (exact match)" })] })] }), scope !== 'site' && (_jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: scope === 'parents' ? 'Parent Paths' : 'URL Paths' }), _jsxs("div", { className: "flex gap-2", children: [_jsx("input", { type: "text", value: pathInput, onChange: (e) => setPathInput(e.target.value), onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                        addPath();
                                                    }
                                                }, placeholder: "/services", className: "flex-1 rounded-lg border border-gray-300 px-3 py-2 font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" }), _jsx("button", { type: "button", onClick: addPath, className: "rounded-lg border border-gray-300 px-3 py-2 text-sm transition-colors hover:bg-gray-50", children: _jsx(Plus, { className: "h-4 w-4" }) })] }), scope === 'parents' && (_jsx("p", { className: "mt-1 text-xs text-gray-500", children: "This tag will also apply to all child pages under each path." })), targetPaths.length > 0 && (_jsx("div", { className: "mt-2 flex flex-wrap gap-2", children: targetPaths.map((p) => (_jsxs("span", { className: "inline-flex items-center gap-1 rounded-full bg-gray-100 px-3 py-1 font-mono text-xs text-gray-700", children: [p, _jsx("button", { type: "button", onClick: () => removePath(p), className: "ml-0.5 text-gray-400 hover:text-gray-600", children: _jsx(X, { className: "h-3 w-3" }) })] }, p))) }))] })), _jsxs("div", { className: "grid grid-cols-2 gap-4", children: [_jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Priority" }), _jsx("input", { type: "number", value: priority, onChange: (e) => setPriority(parseInt(e.target.value, 10) || 0), min: 0, className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" }), _jsx("p", { className: "mt-1 text-xs text-gray-500", children: "Lower numbers load first (e.g. 1 = first, 100 = default)" })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Enabled" }), _jsx("div", { className: "pt-2", children: _jsx("button", { type: "button", onClick: () => setEnabled(!enabled), className: `relative h-6 w-11 shrink-0 rounded-full transition-colors ${enabled ? 'bg-blue-600' : 'bg-gray-300'}`, "aria-pressed": enabled, children: _jsx("span", { className: `absolute top-0.5 block h-5 w-5 rounded-full bg-white transition-transform ${enabled ? 'translate-x-[22px]' : 'translate-x-0.5'}` }) }) })] })] })] }), _jsxs("div", { className: "flex items-center justify-between", children: [_jsx("div", { children: !isNew && (_jsx(_Fragment, { children: showDeleteConfirm ? (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-sm text-red-600", children: "Delete this tag?" }), _jsx("button", { type: "button", onClick: handleDelete, disabled: deleting, className: "rounded-lg bg-red-600 px-3 py-1.5 text-sm text-white hover:bg-red-700 disabled:opacity-50", children: deleting ? 'Deleting...' : 'Confirm' }), _jsx("button", { type: "button", onClick: () => setShowDeleteConfirm(false), className: "rounded-lg border border-gray-300 px-3 py-1.5 text-sm hover:bg-gray-50", children: "Cancel" })] })) : (_jsxs("button", { type: "button", onClick: () => setShowDeleteConfirm(true), className: "flex items-center gap-1.5 text-sm text-red-600 transition-colors hover:text-red-700", children: [_jsx(Trash2, { className: "h-4 w-4" }), "Delete"] })) })) }), _jsxs("div", { className: "flex items-center gap-3", children: [_jsx("button", { type: "button", onClick: () => onNavigate?.('/script-tags'), className: "rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-50", children: "Cancel" }), _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...' : isNew ? 'Create Tag' : 'Save Changes' })] })] })] })] }));
}
//# sourceMappingURL=ScriptTagEditor.js.map