'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Inline redirect editor pane — design-parity replacement for the old
 * `RedirectEditorDrawer` overlay. Rendered inside an `<InspectorPane>` beside
 * the redirect rules table. Same fields, validation, and create/update save
 * paths as the drawer; only the presentation pattern changed.
 */
import { useState } from 'react';
import { Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { createRedirectRule, updateRedirectRule, } from '../../lib/seo-service.js';
import { InspectorPaneBody, InspectorPaneFooter, InspectorPaneHeader, InspectorPaneSection, } from '../ui/InspectorPane.js';
import { Toggle } from '../ui/Toggle.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-[7px] border border-[var(--bdr)] bg-[var(--card)] px-2.5 py-1.5 text-[12.5px] text-[var(--txt)] placeholder:text-[var(--muted)] focus:border-[var(--acc)] focus:outline-none';
const labelCls = 'mb-1 block text-[11.5px] font-medium text-[var(--sub)]';
function normalizePath(p) {
    const t = p.trim();
    if (!t)
        return '';
    if (/^https?:\/\//i.test(t))
        return t;
    return t.startsWith('/') ? t : `/${t}`;
}
function PaneToggleRow({ label, hint, checked, onCheckedChange, variant, }) {
    return (_jsxs("div", { className: "flex items-center justify-between gap-3 py-1.5", children: [_jsxs("div", { className: "min-w-0", children: [_jsx("div", { className: "text-[12.5px] font-medium text-[var(--txt)]", children: label }), hint && _jsx("div", { className: "text-[11px] text-[var(--muted)]", children: hint })] }), _jsx(Toggle, { checked: checked, onCheckedChange: onCheckedChange, variant: variant, "aria-label": label })] }));
}
export function RedirectEditorPane({ rule, onClose, onSaved, onDelete }) {
    // The parent keys this pane by rule id, so initializing from props is safe.
    const [form, setForm] = useState(() => rule
        ? {
            type: rule.type,
            fromPath: rule.fromPath,
            toPath: rule.toPath,
            enabled: rule.enabled,
            preserveQuery: rule.preserveQuery,
            notes: rule.notes ?? '',
        }
        : {
            type: 301,
            fromPath: '',
            toPath: '',
            enabled: true,
            preserveQuery: false,
            notes: '',
        });
    const [saving, setSaving] = useState(false);
    const [clientError, setClientError] = useState(null);
    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.');
        onSaved?.();
    }
    return (_jsxs(_Fragment, { children: [_jsxs(InspectorPaneHeader, { onClose: onClose, closeLabel: "Close redirect editor", children: [_jsx("div", { className: "truncate text-[13.5px] font-semibold text-[var(--txt)]", children: rule ? 'Edit redirect' : 'New redirect' }), rule && (_jsx("div", { className: "mt-0.5 truncate font-mono text-[11.5px] text-[var(--muted)]", children: rule.fromPath }))] }), _jsxs(InspectorPaneBody, { children: [clientError && (_jsx("div", { className: "px-4 pt-3.5", children: _jsx("p", { className: "rounded-[7px] bg-[var(--err-l)] px-3 py-2 text-[12px] text-[var(--err)]", role: "alert", children: clientError }) })), _jsxs(InspectorPaneSection, { title: "Rule", children: [_jsxs("div", { className: "mb-3", children: [_jsx("label", { className: labelCls, 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: "mb-3", children: [_jsx("label", { className: labelCls, 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: "mb-3 last:mb-0", children: [_jsx("label", { className: labelCls, 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(InspectorPaneSection, { title: "Options", children: [_jsx(PaneToggleRow, { label: "Enabled", checked: !!form.enabled, onCheckedChange: (v) => update({ enabled: v }), variant: "enabled" }), !isGone && (_jsx(PaneToggleRow, { label: "Preserve query string", hint: "Append the original query params to the destination.", checked: !!form.preserveQuery, onCheckedChange: (v) => update({ preserveQuery: v }) })), _jsxs("div", { className: "mt-2", children: [_jsxs("label", { className: labelCls, htmlFor: "redir-notes", children: ["Notes ", _jsx("span", { className: "font-normal text-[var(--muted)]", children: "(optional)" })] }), _jsx("input", { id: "redir-notes", className: inputCls, value: form.notes ?? '', onChange: (e) => update({ notes: e.target.value }), placeholder: "Why this redirect exists" })] })] })] }), _jsx(InspectorPaneFooter, { children: _jsxs("div", { className: "flex items-center gap-2", children: [rule && onDelete && (_jsx("button", { type: "button", onClick: () => onDelete(rule), disabled: saving, "aria-label": `Delete redirect ${rule.fromPath}`, className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-[7px] border border-[var(--bdr)] text-[var(--err)] transition-colors duration-[var(--motion-fast)] hover:bg-[var(--err-l)] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none disabled:opacity-50", children: _jsx(Trash2, { size: 16, "aria-hidden": true }) })), _jsx("button", { type: "button", onClick: () => void handleSave(), disabled: saving, className: "bg-primary text-primary-foreground min-w-0 flex-1 rounded-[7px] px-3 py-2 text-[13px] font-semibold transition-colors duration-[var(--motion-fast)] hover:opacity-90 focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50", children: saving ? 'Saving…' : rule ? 'Save changes' : 'Create redirect' })] }) })] }));
}
//# sourceMappingURL=RedirectEditorPane.js.map