'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { createRedirectRule, updateRedirectRule, } from '../../lib/seo-service.js';
import { Drawer } from './Drawer.js';
import { btnPrimary, btnSecondary } from './primitives.js';
const STATUS_CODES = [
    { value: 301, label: '301 — Permanent' },
    { value: 302, label: '302 — Temporary' },
    { value: 307, label: '307 — Temporary (preserve method)' },
    { value: 308, label: '308 — Permanent (preserve method)' },
    { value: 410, label: '410 — Gone (no destination)' },
];
const inputCls = 'w-full rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
function normalizePath(p) {
    const t = p.trim();
    if (!t)
        return '';
    if (/^https?:\/\//i.test(t))
        return t;
    return t.startsWith('/') ? t : `/${t}`;
}
export function RedirectEditorDrawer({ open, onOpenChange, rule, onSaved, }) {
    const [form, setForm] = useState({
        type: 301,
        fromPath: '',
        toPath: '',
        enabled: true,
        preserveQuery: false,
        notes: '',
    });
    const [saving, setSaving] = useState(false);
    const [clientError, setClientError] = useState(null);
    useEffect(() => {
        if (!open)
            return;
        if (rule) {
            setForm({
                type: rule.type,
                fromPath: rule.fromPath,
                toPath: rule.toPath,
                enabled: rule.enabled,
                preserveQuery: rule.preserveQuery,
                notes: rule.notes ?? '',
            });
        }
        else {
            setForm({
                type: 301,
                fromPath: '',
                toPath: '',
                enabled: true,
                preserveQuery: false,
                notes: '',
            });
        }
        setClientError(null);
    }, [open, rule]);
    const isGone = form.type === 410;
    const update = (patch) => setForm((f) => ({ ...f, ...patch }));
    async function handleSave() {
        const fromPath = normalizePath(form.fromPath);
        const toPath = isGone ? '' : normalizePath(form.toPath);
        if (!fromPath) {
            setClientError('Source path is required.');
            return;
        }
        if (!isGone && !toPath) {
            setClientError('Destination is required for redirect status codes.');
            return;
        }
        if (!isGone && fromPath === toPath) {
            setClientError('Source and destination cannot be identical (would create a loop).');
            return;
        }
        setClientError(null);
        setSaving(true);
        const payload = { ...form, fromPath, toPath };
        const res = rule
            ? await updateRedirectRule(rule.id, payload)
            : await createRedirectRule(payload);
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success(rule ? 'Redirect updated.' : 'Redirect created.');
        onOpenChange(false);
        onSaved?.();
    }
    return (_jsx(Drawer, { open: open, onOpenChange: onOpenChange, title: rule ? 'Edit redirect' : 'New redirect', width: "max-w-lg", footer: _jsxs(_Fragment, { children: [_jsx("button", { className: btnSecondary, onClick: () => onOpenChange(false), disabled: saving, children: "Cancel" }), _jsx("button", { className: btnPrimary, onClick: handleSave, disabled: saving, children: saving ? 'Saving…' : rule ? 'Save changes' : 'Create redirect' })] }), children: _jsxs("div", { className: "space-y-4", children: [clientError && (_jsx("p", { className: "text-destructive bg-destructive/10 rounded-md px-3 py-2 text-sm", role: "alert", children: clientError })), _jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-foreground text-sm font-medium", htmlFor: "redir-type", children: "Status code" }), _jsx("select", { id: "redir-type", className: inputCls, value: form.type, onChange: (e) => update({ type: Number(e.target.value) }), children: STATUS_CODES.map((s) => (_jsx("option", { value: s.value, children: s.label }, s.value))) })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-foreground text-sm font-medium", htmlFor: "redir-from", children: "Source path" }), _jsx("input", { id: "redir-from", className: inputCls, value: form.fromPath, onChange: (e) => update({ fromPath: e.target.value }), placeholder: "/old-path" })] }), !isGone && (_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-foreground text-sm font-medium", htmlFor: "redir-to", children: "Destination" }), _jsx("input", { id: "redir-to", className: inputCls, value: form.toPath, onChange: (e) => update({ toPath: e.target.value }), placeholder: "/new-path or https://example.com/page" })] })), _jsxs("div", { className: "space-y-1.5", children: [_jsxs("label", { className: "text-foreground text-sm font-medium", htmlFor: "redir-notes", children: ["Notes ", _jsx("span", { className: "text-muted-foreground font-normal", children: "(optional)" })] }), _jsx("input", { id: "redir-notes", className: inputCls, value: form.notes ?? '', onChange: (e) => update({ notes: e.target.value }), placeholder: "Why this redirect exists" })] }), _jsxs("div", { className: "border-border space-y-3 rounded-lg border p-4", children: [_jsxs("label", { className: "flex items-center justify-between gap-3", children: [_jsx("span", { className: "text-foreground text-sm font-medium", children: "Enabled" }), _jsx("input", { type: "checkbox", role: "switch", "aria-checked": !!form.enabled, checked: !!form.enabled, onChange: (e) => update({ enabled: e.target.checked }), className: "accent-primary h-4 w-4" })] }), !isGone && (_jsxs("label", { className: "flex items-center justify-between gap-3", children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "text-foreground block text-sm font-medium", children: "Preserve query string" }), _jsx("span", { className: "text-muted-foreground block text-sm", children: "Append the original query params to the destination." })] }), _jsx("input", { type: "checkbox", role: "switch", "aria-checked": !!form.preserveQuery, checked: !!form.preserveQuery, onChange: (e) => update({ preserveQuery: e.target.checked }), className: "accent-primary h-4 w-4 shrink-0" })] }))] })] }) }));
}
//# sourceMappingURL=RedirectEditorDrawer.js.map