import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { CalendarClock, CalendarOff, Clock3, Loader2, ShieldCheck, BarChart3, } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { Dialog, DialogContent } from "../../components/ui/dialog";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Switch } from "../../components/ui/switch";
import { Badge } from "../../components/ui/badge";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import DialogButtons from "./DialogButtons";
import { getLanguagesAndVersions } from "../services/contentService";
import { cn } from "../../lib/utils";
function parseSitecoreDate(rawValue) {
    const value = rawValue?.trim();
    if (!value)
        return undefined;
    if (value.match(/^\d{8}T\d{6}Z$/)) {
        const standardISO = value.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/, "$1-$2-$3T$4:$5:$6Z");
        const date = new Date(standardISO);
        return isNaN(date.getTime()) ? undefined : date;
    }
    const fallback = new Date(value);
    return isNaN(fallback.getTime()) ? undefined : fallback;
}
function toDateTimeLocalValue(date) {
    if (!date)
        return "";
    const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
    return local.toISOString().slice(0, 16);
}
function fromDateTimeLocalValue(value) {
    if (!value)
        return undefined;
    const date = new Date(value);
    return isNaN(date.getTime()) ? undefined : date;
}
function formatDateToCompactISO(date) {
    if (!date)
        return "";
    const year = date.getUTCFullYear().toString();
    const month = (date.getUTCMonth() + 1).toString().padStart(2, "0");
    const day = date.getUTCDate().toString().padStart(2, "0");
    const hours = date.getUTCHours().toString().padStart(2, "0");
    const minutes = date.getUTCMinutes().toString().padStart(2, "0");
    const seconds = date.getUTCSeconds().toString().padStart(2, "0");
    return `${year}${month}${day}T${hours}${minutes}${seconds}Z`;
}
function toTimestamp(value) {
    const date = fromDateTimeLocalValue(value);
    return date ? date.getTime() : undefined;
}
function updateLabel(value) {
    const d = value ? new Date(value) : undefined;
    return d && !isNaN(d.getTime()) ? d.toLocaleString() : "-";
}
function getNowDateTimeValue() {
    return toDateTimeLocalValue(new Date());
}
function formatTimelineEventLabel(timestamp, includeTime) {
    const date = new Date(timestamp);
    if (!includeTime) {
        return date.toLocaleDateString();
    }
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
    })}`;
}
function formatTimelineRangeLabel(start, end, includeTime) {
    const options = includeTime
        ? {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
        }
        : {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
        };
    const formatter = new Intl.DateTimeFormat(undefined, options);
    return `${formatter.format(new Date(start))} - ${formatter.format(new Date(end))}`;
}
function getVersionColor(index) {
    const palette = [
        "var(--color-feedback-blue)",
        "var(--color-component-suggestions)",
        "var(--color-component-shared)",
        "var(--color-highlight-100)",
        "var(--color-feedback-orange)",
        "var(--color-highlight-100)",
        "var(--color-feedback-green)",
        "var(--color-feedback-red)",
    ];
    return palette[index % palette.length];
}
export function PublishRestrictionsDialog({ item, onClose, }) {
    const editContext = useEditContext();
    const [isLoading, setIsLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [initialItemState, setInitialItemState] = useState({
        itemPublishable: true,
        itemPublishFrom: "",
        itemUnpublishAt: "",
    });
    const [itemState, setItemState] = useState({
        itemPublishable: true,
        itemPublishFrom: "",
        itemUnpublishAt: "",
    });
    const [initialVersionRows, setInitialVersionRows] = useState([]);
    const [versionRows, setVersionRows] = useState([]);
    const [zoomDays, setZoomDays] = useState(180);
    const [centerTs, setCenterTs] = useState(() => Date.now());
    const chartContainerRef = useRef(null);
    const timelineInteractionRef = useRef(null);
    const [chartWidth, setChartWidth] = useState(900);
    useEffect(() => {
        let cancelled = false;
        async function loadData() {
            setIsLoading(true);
            const result = await getLanguagesAndVersions(item.descriptor, {
                includePublishingRestrictions: true,
            });
            if (cancelled)
                return;
            if (result.type !== "success" || !result.data) {
                editContext?.showToast?.("Failed to load publishing restrictions.");
                setIsLoading(false);
                return;
            }
            const itemRestrictions = result.data.itemPublishingRestrictions;
            const nextItemState = {
                itemPublishable: !(itemRestrictions?.neverPublish ?? false),
                itemPublishFrom: toDateTimeLocalValue(parseSitecoreDate(itemRestrictions?.publish)),
                itemUnpublishAt: toDateTimeLocalValue(parseSitecoreDate(itemRestrictions?.unpublish)),
                neverPublishFieldId: itemRestrictions?.neverPublishFieldId,
                publishFieldId: itemRestrictions?.publishFieldId,
                unpublishFieldId: itemRestrictions?.unpublishFieldId,
            };
            const rows = (result.data.versions || [])
                .map((v) => ({
                version: v.version,
                updatedLabel: updateLabel(v.updated),
                updatedBy: v.updatedBy || "",
                versionPublishable: !(v.publishingRestrictions?.hideVersion ?? false),
                versionValidFrom: toDateTimeLocalValue(parseSitecoreDate(v.publishingRestrictions?.validFrom)),
                versionValidTo: toDateTimeLocalValue(parseSitecoreDate(v.publishingRestrictions?.validTo)),
                hideVersionFieldId: v.publishingRestrictions?.hideVersionFieldId,
                validFromFieldId: v.publishingRestrictions?.validFromFieldId,
                validToFieldId: v.publishingRestrictions?.validToFieldId,
            }))
                .sort((a, b) => b.version - a.version);
            setInitialItemState(nextItemState);
            setItemState(nextItemState);
            setInitialVersionRows(rows);
            setVersionRows(rows);
            setIsLoading(false);
        }
        loadData();
        return () => {
            cancelled = true;
        };
    }, [editContext, item.descriptor]);
    useEffect(() => {
        const resize = () => {
            if (!chartContainerRef.current)
                return;
            setChartWidth(Math.max(700, chartContainerRef.current.clientWidth - 24));
        };
        resize();
        window.addEventListener("resize", resize);
        return () => window.removeEventListener("resize", resize);
    }, []);
    useEffect(() => {
        const timelineEl = timelineInteractionRef.current;
        if (!timelineEl)
            return;
        const handleWheel = (event) => {
            if (!event.altKey)
                return;
            event.preventDefault();
            setZoomDays((prev) => {
                const next = event.deltaY > 0 ? prev * 1.15 : prev * 0.85;
                return Math.max(7, Math.min(3650, Math.round(next)));
            });
        };
        timelineEl.addEventListener("wheel", handleWheel, { passive: false });
        return () => {
            timelineEl.removeEventListener("wheel", handleWheel);
        };
    }, [isLoading]);
    const itemWindowInvalid = useMemo(() => {
        const from = fromDateTimeLocalValue(itemState.itemPublishFrom);
        const to = fromDateTimeLocalValue(itemState.itemUnpublishAt);
        return !!from && !!to && from.getTime() > to.getTime();
    }, [itemState.itemPublishFrom, itemState.itemUnpublishAt]);
    const versionWindowInvalidCount = useMemo(() => {
        return versionRows.filter((row) => {
            const from = fromDateTimeLocalValue(row.versionValidFrom);
            const to = fromDateTimeLocalValue(row.versionValidTo);
            return !!from && !!to && from.getTime() > to.getTime();
        }).length;
    }, [versionRows]);
    const hasItemChanges = useMemo(() => JSON.stringify(itemState) !== JSON.stringify(initialItemState), [initialItemState, itemState]);
    const hasVersionChanges = useMemo(() => JSON.stringify(versionRows) !== JSON.stringify(initialVersionRows), [initialVersionRows, versionRows]);
    const hasChanges = hasItemChanges || hasVersionChanges;
    const evaluateActiveVersionAt = useCallback((timestamp) => {
        if (!itemState.itemPublishable)
            return 0;
        const itemFromTs = toTimestamp(itemState.itemPublishFrom);
        const itemToTs = toTimestamp(itemState.itemUnpublishAt);
        if (itemFromTs && timestamp < itemFromTs)
            return 0;
        if (itemToTs && timestamp > itemToTs)
            return 0;
        const activeVersions = versionRows
            .filter((row) => {
            if (!row.versionPublishable)
                return false;
            const fromTs = toTimestamp(row.versionValidFrom);
            const toTs = toTimestamp(row.versionValidTo);
            if (fromTs && timestamp < fromTs)
                return false;
            if (toTs && timestamp > toTs)
                return false;
            return true;
        })
            .map((x) => x.version)
            .sort((a, b) => b - a);
        return activeVersions[0] || 0;
    }, [
        itemState.itemPublishFrom,
        itemState.itemPublishable,
        itemState.itemUnpublishAt,
        versionRows,
    ]);
    const effectiveNowVersion = useMemo(() => evaluateActiveVersionAt(Date.now()), [itemState, versionRows]);
    const effectiveStatus = useMemo(() => {
        if (!itemState.itemPublishable) {
            return { label: "Blocked by item", variant: "destructive" };
        }
        if (effectiveNowVersion === 0) {
            return { label: "No publishable version", variant: "secondary" };
        }
        return {
            label: `Will publish v${effectiveNowVersion}`,
            variant: "default",
        };
    }, [effectiveNowVersion, itemState.itemPublishable]);
    const timelineModel = useMemo(() => {
        const viewSpanMs = zoomDays * 24 * 60 * 60 * 1000;
        const viewStart = centerTs - viewSpanMs / 2;
        const viewEnd = centerTs + viewSpanMs / 2;
        const boundaries = new Set([viewStart, viewEnd]);
        const pushIfInView = (value) => {
            const ts = toTimestamp(value);
            if (ts && ts >= viewStart && ts <= viewEnd)
                boundaries.add(ts);
        };
        pushIfInView(itemState.itemPublishFrom);
        pushIfInView(itemState.itemUnpublishAt);
        versionRows.forEach((row) => {
            pushIfInView(row.versionValidFrom);
            pushIfInView(row.versionValidTo);
        });
        const points = Array.from(boundaries).sort((a, b) => a - b);
        const segments = [];
        const effectiveChangePoints = [];
        for (let i = 0; i < points.length - 1; i++) {
            const start = points[i];
            const end = points[i + 1];
            if (end <= start)
                continue;
            const midpoint = start + (end - start) / 2;
            segments.push({
                start,
                end,
                effectiveVersion: evaluateActiveVersionAt(midpoint),
            });
            if (i > 0) {
                const previous = segments[i - 1];
                const current = segments[i];
                if (previous &&
                    current &&
                    previous.effectiveVersion !== current.effectiveVersion) {
                    effectiveChangePoints.push(start);
                }
            }
        }
        const versions = [...versionRows].sort((a, b) => b.version - a.version);
        const versionMin = versions.length
            ? versions[versions.length - 1].version
            : 0;
        const versionMax = versions.length ? versions[0].version : 1;
        return {
            viewStart,
            viewEnd,
            versions,
            segments,
            effectiveChangePoints,
            versionMin,
            versionMax,
        };
    }, [centerTs, itemState, versionRows, zoomDays]);
    const effectiveTimelineEvents = useMemo(() => {
        const includeTime = zoomDays <= 31;
        const minGapPx = 80;
        const edgePaddingPx = 56;
        let lastX = -Infinity;
        return timelineModel.effectiveChangePoints
            .map((timestamp) => ({
            timestamp,
            x: 40 +
                ((timestamp - timelineModel.viewStart) /
                    (timelineModel.viewEnd - timelineModel.viewStart)) *
                    (chartWidth - 50),
        }))
            .filter((marker) => {
            if (marker.x < edgePaddingPx || marker.x > chartWidth - edgePaddingPx) {
                return false;
            }
            if (marker.x - lastX < minGapPx) {
                return false;
            }
            lastX = marker.x;
            return true;
        })
            .map((marker) => ({
            ...marker,
            label: formatTimelineEventLabel(marker.timestamp, includeTime),
        }));
    }, [chartWidth, timelineModel, zoomDays]);
    const versionColorByNumber = useMemo(() => {
        const map = new Map();
        timelineModel.versions.forEach((row, index) => {
            map.set(row.version, getVersionColor(index));
        });
        return map;
    }, [timelineModel.versions]);
    const save = async () => {
        if (!editContext)
            return;
        const updates = [];
        if (itemState.itemPublishable !== initialItemState.itemPublishable) {
            if (itemState.neverPublishFieldId) {
                updates.push({
                    itemVersion: item.descriptor.version,
                    fieldId: itemState.neverPublishFieldId,
                    rawValue: itemState.itemPublishable ? "0" : "1",
                });
            }
        }
        if (itemState.itemPublishFrom !== initialItemState.itemPublishFrom) {
            if (itemState.publishFieldId) {
                updates.push({
                    itemVersion: item.descriptor.version,
                    fieldId: itemState.publishFieldId,
                    rawValue: formatDateToCompactISO(fromDateTimeLocalValue(itemState.itemPublishFrom)),
                });
            }
        }
        if (itemState.itemUnpublishAt !== initialItemState.itemUnpublishAt) {
            if (itemState.unpublishFieldId) {
                updates.push({
                    itemVersion: item.descriptor.version,
                    fieldId: itemState.unpublishFieldId,
                    rawValue: formatDateToCompactISO(fromDateTimeLocalValue(itemState.itemUnpublishAt)),
                });
            }
        }
        for (const row of versionRows) {
            const initial = initialVersionRows.find((x) => x.version === row.version);
            if (!initial)
                continue;
            if (row.versionPublishable !== initial.versionPublishable &&
                row.hideVersionFieldId) {
                updates.push({
                    itemVersion: row.version,
                    fieldId: row.hideVersionFieldId,
                    rawValue: row.versionPublishable ? "0" : "1",
                });
            }
            if (row.versionValidFrom !== initial.versionValidFrom &&
                row.validFromFieldId) {
                updates.push({
                    itemVersion: row.version,
                    fieldId: row.validFromFieldId,
                    rawValue: formatDateToCompactISO(fromDateTimeLocalValue(row.versionValidFrom)),
                });
            }
            if (row.versionValidTo !== initial.versionValidTo && row.validToFieldId) {
                updates.push({
                    itemVersion: row.version,
                    fieldId: row.validToFieldId,
                    rawValue: formatDateToCompactISO(fromDateTimeLocalValue(row.versionValidTo)),
                });
            }
        }
        if (updates.length === 0) {
            onClose(null);
            return;
        }
        setIsSaving(true);
        try {
            for (const update of updates) {
                await editContext.operations.editField({
                    field: {
                        item: {
                            id: item.id,
                            language: item.language,
                            version: update.itemVersion,
                            database: item.database,
                        },
                        fieldId: update.fieldId,
                    },
                    rawValue: update.rawValue,
                    value: update.rawValue,
                    refresh: "none",
                });
            }
            editContext.requestRefresh("immediate");
            await editContext.loadItemVersions();
            editContext.showToast?.("Publish restrictions updated.");
            onClose("saved");
        }
        catch {
            editContext.showToast?.("Failed to update publish restrictions.");
        }
        finally {
            setIsSaving(false);
        }
    };
    if (!editContext)
        return null;
    const isSaveDisabled = isLoading ||
        isSaving ||
        !hasChanges ||
        itemWindowInvalid ||
        versionWindowInvalidCount > 0 ||
        !item.canWriteItem ||
        !item.canWriteLanguage;
    const spanMs = zoomDays * 24 * 60 * 60 * 1000;
    const includeTimeInTooltips = zoomDays <= 31;
    return (_jsx(Dialog, { open: true, onOpenChange: (open) => {
            if (!open)
                onClose(null);
        }, children: _jsxs(DialogContent, { className: "flex max-w-5xl flex-col overflow-hidden border-none p-0 shadow-2xl", style: { maxHeight: "90vh" }, showCloseButton: true, children: [_jsx(StyledDialogTitle, { icon: _jsx(Clock3, { strokeWidth: 1 }), title: "Publish Restrictions", subtitle: item.displayName || item.name }), isLoading ? (_jsxs("div", { className: "flex flex-col items-center justify-center gap-3 py-20", children: [_jsx(Loader2, { className: "text-muted-foreground h-6 w-6 animate-spin" }), _jsx("span", { className: "text-muted-foreground text-sm", children: "Loading restrictions..." })] })) : (_jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto", children: _jsxs("div", { className: "space-y-5 px-6 py-5", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Badge, { variant: effectiveStatus.variant, children: effectiveStatus.label }), itemWindowInvalid && (_jsx("span", { className: "text-feedback-red text-xs font-medium", children: "Unpublish date must be after publish date" })), versionWindowInvalidCount > 0 && (_jsxs("span", { className: "text-feedback-red text-xs font-medium", children: [versionWindowInvalidCount, " version(s) have invalid date ranges"] }))] }), _jsxs("section", { children: [_jsx("h3", { className: "text-muted-foreground mb-3 text-xs font-semibold tracking-wider", children: "Item Restrictions" }), _jsxs("div", { className: "grid gap-3 sm:grid-cols-3", children: [_jsxs("div", { className: cn("group relative rounded-xl border bg-white p-4 transition-shadow hover:shadow-sm", !itemState.itemPublishable &&
                                                    "border-feedback-red bg-feedback-red-light/30"), children: [_jsxs("div", { className: "mb-3 flex items-center gap-2", children: [_jsx("div", { className: cn("flex h-7 w-7 shrink-0 items-center justify-center rounded-lg", itemState.itemPublishable
                                                                    ? "bg-feedback-green-light text-feedback-green"
                                                                    : "bg-feedback-red-light text-feedback-red"), children: _jsx(ShieldCheck, { className: "h-4 w-4" }) }), _jsx("span", { className: "text-sm font-medium", children: "Publishable" })] }), _jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-muted-foreground text-xs", children: itemState.itemPublishable ? "Yes" : "Blocked" }), _jsx(Switch, { checked: itemState.itemPublishable, disabled: !itemState.neverPublishFieldId, onCheckedChange: (checked) => setItemState((prev) => ({
                                                                    ...prev,
                                                                    itemPublishable: Boolean(checked),
                                                                })) })] })] }), _jsxs("div", { className: "group rounded-xl border bg-white p-4 transition-shadow hover:shadow-sm", children: [_jsxs("div", { className: "mb-3 flex items-center gap-2", children: [_jsx("div", { className: "bg-feedback-blue-light text-feedback-blue flex h-7 w-7 shrink-0 items-center justify-center rounded-lg", children: _jsx(CalendarClock, { className: "h-4 w-4" }) }), _jsx("span", { className: "text-sm font-medium", children: "Publish from" })] }), _jsx(Input, { type: "datetime-local", className: "text-xs", value: itemState.itemPublishFrom, disabled: !itemState.publishFieldId, onChange: (event) => setItemState((prev) => ({
                                                            ...prev,
                                                            itemPublishFrom: event.target.value,
                                                        })) }), _jsxs("div", { className: "mt-2 flex gap-1.5", children: [_jsx(Button, { variant: "ghost", size: "sm", className: "text-2xs h-6 px-2", disabled: !itemState.publishFieldId, onClick: () => setItemState((prev) => ({
                                                                    ...prev,
                                                                    itemPublishFrom: getNowDateTimeValue(),
                                                                })), children: "Now" }), _jsx(Button, { variant: "ghost", size: "sm", className: "text-muted-foreground h-6 px-2 text-[11px]", disabled: !itemState.publishFieldId ||
                                                                    !itemState.itemPublishFrom, onClick: () => setItemState((prev) => ({
                                                                    ...prev,
                                                                    itemPublishFrom: "",
                                                                })), children: "Clear" })] })] }), _jsxs("div", { className: "group rounded-xl border bg-white p-4 transition-shadow hover:shadow-sm", children: [_jsxs("div", { className: "mb-3 flex items-center gap-2", children: [_jsx("div", { className: "bg-feedback-orange-light text-feedback-orange flex h-7 w-7 shrink-0 items-center justify-center rounded-lg", children: _jsx(CalendarOff, { className: "h-4 w-4" }) }), _jsx("span", { className: "text-sm font-medium", children: "Unpublish at" })] }), _jsx(Input, { type: "datetime-local", className: "text-xs", value: itemState.itemUnpublishAt, disabled: !itemState.unpublishFieldId, onChange: (event) => setItemState((prev) => ({
                                                            ...prev,
                                                            itemUnpublishAt: event.target.value,
                                                        })) }), _jsx("div", { className: "mt-2 flex gap-1.5", children: _jsx(Button, { variant: "ghost", size: "sm", className: "text-muted-foreground h-6 px-2 text-[11px]", disabled: !itemState.unpublishFieldId ||
                                                                !itemState.itemUnpublishAt, onClick: () => setItemState((prev) => ({
                                                                ...prev,
                                                                itemUnpublishAt: "",
                                                            })), children: "Clear" }) })] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-muted-foreground mb-3 text-xs font-semibold tracking-wider", children: "Version Restrictions" }), _jsx("div", { className: "overflow-hidden rounded-xl border", children: _jsx("div", { className: "max-h-[280px] overflow-auto", children: _jsxs("table", { className: "w-full text-sm", children: [_jsx("thead", { className: "bg-neutral-grey-5/90 sticky top-0 z-10 border-b backdrop-blur-sm", children: _jsxs("tr", { className: "text-muted-foreground text-left text-[11px] font-medium tracking-wider", children: [_jsx("th", { className: "px-4 py-2.5 whitespace-nowrap", children: "Ver." }), _jsx("th", { className: "px-4 py-2.5 whitespace-nowrap", children: "Publishable" }), _jsx("th", { className: "px-4 py-2.5 whitespace-nowrap", children: "Valid from" }), _jsx("th", { className: "px-4 py-2.5 whitespace-nowrap", children: "Valid to" }), _jsx("th", { className: "px-4 py-2.5 whitespace-nowrap", children: "Updated" }), _jsx("th", { className: "px-4 py-2.5 whitespace-nowrap", children: "By" })] }) }), _jsx("tbody", { className: "divide-y", children: versionRows.map((row, rowIdx) => {
                                                            const invalidWindow = !!toTimestamp(row.versionValidFrom) &&
                                                                !!toTimestamp(row.versionValidTo) &&
                                                                toTimestamp(row.versionValidFrom) >
                                                                    toTimestamp(row.versionValidTo);
                                                            return (_jsxs("tr", { className: cn("align-middle transition-colors", invalidWindow
                                                                    ? "bg-feedback-red-light/60"
                                                                    : rowIdx % 2 === 1
                                                                        ? "bg-neutral-grey-5/40"
                                                                        : "bg-white"), children: [_jsx("td", { className: "px-4 py-2 whitespace-nowrap", children: _jsxs("span", { className: "bg-neutral-grey-5 inline-flex h-6 min-w-8 items-center justify-center rounded-md px-1.5 text-xs font-semibold tabular-nums", children: ["v", row.version] }) }), _jsx("td", { className: "px-4 py-2", children: _jsx(Switch, { checked: row.versionPublishable, disabled: !row.hideVersionFieldId, onCheckedChange: (checked) => {
                                                                                setVersionRows((prev) => prev.map((x) => x.version === row.version
                                                                                    ? {
                                                                                        ...x,
                                                                                        versionPublishable: Boolean(checked),
                                                                                    }
                                                                                    : x));
                                                                            } }) }), _jsx("td", { className: "px-4 py-2", children: _jsx(Input, { type: "datetime-local", className: "h-8 text-xs", value: row.versionValidFrom, disabled: !row.validFromFieldId, onChange: (event) => {
                                                                                const value = event.target.value;
                                                                                setVersionRows((prev) => prev.map((x) => x.version === row.version
                                                                                    ? { ...x, versionValidFrom: value }
                                                                                    : x));
                                                                            } }) }), _jsxs("td", { className: "px-4 py-2", children: [_jsx(Input, { type: "datetime-local", className: cn("h-8 text-xs", invalidWindow &&
                                                                                    "border-feedback-red focus-visible:ring-feedback-red"), value: row.versionValidTo, disabled: !row.validToFieldId, onChange: (event) => {
                                                                                    const value = event.target.value;
                                                                                    setVersionRows((prev) => prev.map((x) => x.version === row.version
                                                                                        ? { ...x, versionValidTo: value }
                                                                                        : x));
                                                                                } }), invalidWindow && (_jsx("span", { className: "text-feedback-red mt-0.5 block text-[10px]", children: "Invalid range" }))] }), _jsx("td", { className: "text-muted-foreground px-4 py-2 text-xs whitespace-nowrap", children: row.updatedLabel }), _jsx("td", { className: "text-muted-foreground px-4 py-2 text-xs whitespace-nowrap", children: row.updatedBy || "\u2014" })] }, row.version));
                                                        }) })] }) }) })] }), _jsxs("section", { children: [_jsxs("div", { className: "mb-3 flex items-center justify-between", children: [_jsxs("h3", { className: "text-muted-foreground text-xs font-semibold tracking-wider", children: [_jsx(BarChart3, { className: "mr-1 inline-block h-3.5 w-3.5 align-text-bottom" }), "Timeline"] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Button, { variant: "outline", size: "sm", className: "h-7 px-2 text-xs", onClick: () => setCenterTs((x) => x - spanMs * 0.25), children: "\u2190 Prev" }), _jsx(Button, { variant: "outline", size: "sm", className: "h-7 px-2 text-xs", onClick: () => setCenterTs(Date.now()), children: "Today" }), _jsx(Button, { variant: "outline", size: "sm", className: "h-7 px-2 text-xs", onClick: () => setCenterTs((x) => x + spanMs * 0.25), children: "Next \u2192" })] })] }), _jsxs("div", { ref: timelineInteractionRef, className: "overflow-hidden rounded-xl border", children: [_jsxs("div", { className: "bg-neutral-grey-5/80 flex items-center gap-3 border-b px-4 py-2", children: [_jsx("span", { className: "text-muted-foreground shrink-0 text-[11px] font-medium", children: "Zoom" }), _jsx("input", { type: "range", className: "accent-primary h-1.5 w-36 cursor-pointer", min: 7, max: 3650, step: 1, value: zoomDays, onChange: (event) => setZoomDays(Number(event.target.value)) }), _jsxs("span", { className: "text-muted-foreground shrink-0 text-[11px] tabular-nums", children: [zoomDays, "d"] })] }), _jsx("div", { ref: chartContainerRef, className: "bg-white px-3 pt-2 pb-1", children: _jsxs("svg", { width: chartWidth, height: 86, className: "overflow-visible", children: [_jsx("rect", { x: 0, y: 0, width: chartWidth, height: 86, fill: "var(--color-white)", rx: 6 }), timelineModel.segments.map((segment, index) => {
                                                            const x1 = 40 +
                                                                ((segment.start - timelineModel.viewStart) /
                                                                    (timelineModel.viewEnd - timelineModel.viewStart)) *
                                                                    (chartWidth - 50);
                                                            const x2 = 40 +
                                                                ((segment.end - timelineModel.viewStart) /
                                                                    (timelineModel.viewEnd - timelineModel.viewStart)) *
                                                                    (chartWidth - 50);
                                                            if (!segment.effectiveVersion)
                                                                return null;
                                                            const fillColor = versionColorByNumber.get(segment.effectiveVersion) ??
                                                                "var(--color-feedback-blue)";
                                                            return (_jsxs(Tooltip, { delayDuration: 120, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("rect", { x: x1, y: 24, width: Math.max(0, x2 - x1), height: 18, fill: fillColor, opacity: 0.85, rx: 3 }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: _jsxs("div", { className: "space-y-0.5", children: [_jsxs("div", { className: "font-semibold", children: ["v", segment.effectiveVersion] }), _jsx("div", { children: formatTimelineRangeLabel(segment.start, segment.end, includeTimeInTooltips) })] }) })] }, `effective-${index}`));
                                                        }), _jsx("line", { x1: 40, y1: 52, x2: chartWidth - 10, y2: 52, stroke: "var(--color-neutral-grey-10)", strokeDasharray: "4 3" }), effectiveTimelineEvents.map((marker, markerIndex) => (_jsxs("g", { children: [_jsx("line", { x1: marker.x, y1: 42, x2: marker.x, y2: 52, stroke: "var(--color-neutral-grey-50)", strokeWidth: 1 }), _jsx("text", { x: marker.x, y: 63 + (markerIndex % 2) * 9, fontSize: 9, fill: "var(--color-neutral-grey-50)", textAnchor: "middle", children: marker.label })] }, `effective-event-${marker.timestamp}`))), _jsx("text", { x: 40, y: 79, fontSize: 10, fill: "var(--color-neutral-grey-50)", children: new Date(timelineModel.viewStart).toLocaleDateString() }), _jsx("text", { x: chartWidth - 140, y: 79, fontSize: 10, fill: "var(--color-neutral-grey-50)", textAnchor: "end", children: new Date(timelineModel.viewEnd).toLocaleDateString() })] }) }), _jsxs("div", { className: "text-muted-foreground bg-neutral-grey-5/60 flex items-center gap-4 border-t px-4 py-2 text-[11px]", children: [_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: "bg-neutral-grey-50 inline-block h-2.5 w-5 rounded-sm opacity-80" }), "Effective version color coding (hover bar for version)"] }), _jsx("span", { className: "ml-auto", children: "Alt+scroll to zoom" })] })] })] })] }) })), _jsxs(DialogButtons, { children: [_jsx(Button, { variant: "outline", size: "sm", onClick: () => onClose(null), children: "Cancel" }), _jsx(Button, { size: "sm", onClick: save, disabled: isSaveDisabled, children: isSaving ? "Saving..." : "Save" })] })] }) }));
}
//# sourceMappingURL=PublishRestrictionsDialog.js.map