"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import * as React from "react";
import { Check, ChevronDown, Clock3, Loader2, Plus, X } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { getCreateAndSwitchToNewVersionCommand } from "../commands/createVersionCommand";
import { getDeleteVersionCommand } from "../commands/deleteVersionCommand";
import { cn } from "../../lib/utils";
import { Button } from "../../components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandItem, CommandList, } from "../../components/ui/command";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { Badge } from "../../components/ui/badge";
import { VersionPreviewCard } from "./VersionPreviewCard";
import { parseSitecoreDate } from "../utils/sitecoreDate";
import { publishRestrictionsCommand } from "../commands/itemCommands";
// Temporarily disabled; keep the preview wiring in place so it can be re-enabled later.
const ENABLE_VERSION_SELECTOR_PREVIEWS = false;
function formatRestrictionDate(rawValue) {
    const date = parseSitecoreDate(rawValue);
    if (!date)
        return rawValue || "";
    return date.toLocaleDateString(undefined, {
        year: "numeric",
        month: "short",
        day: "numeric",
    });
}
function isFutureRestrictionDate(rawValue) {
    const date = parseSitecoreDate(rawValue);
    if (!date)
        return false;
    return date.getTime() > Date.now();
}
function VersionStatusTags({ version, isMobile, }) {
    const restrictions = version.publishingRestrictions;
    const publishedTargets = version.publishedTargets || [];
    const showValidFrom = isFutureRestrictionDate(restrictions?.validFrom);
    const showValidTo = isFutureRestrictionDate(restrictions?.validTo);
    const validFrom = showValidFrom
        ? formatRestrictionDate(restrictions?.validFrom)
        : "";
    const validTo = showValidTo
        ? formatRestrictionDate(restrictions?.validTo)
        : "";
    if (!version.isPublished &&
        !version.workflowState &&
        !restrictions?.hideVersion &&
        !validFrom &&
        !validTo) {
        return null;
    }
    return (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-1", children: [version.isPublished && (_jsxs("span", { className: "text-muted-foreground inline-flex items-center gap-1 text-[10px]", title: publishedTargets.length
                    ? `Published to ${publishedTargets.join(", ")}`
                    : "Published", "data-testid": "version-selector-published-tag", children: [_jsx("span", { className: "bg-feedback-green h-1.5 w-1.5 rounded-full" }), isMobile ? "Pub" : "Published"] })), restrictions?.hideVersion && (_jsx(Badge, { variant: "destructive", size: "sm", className: "text-2xs", title: "This version is hidden from publishing.", "data-testid": "version-selector-restriction-tag", children: "Hidden" })), validFrom && (_jsxs(Badge, { variant: "outline", size: "sm", className: "text-2xs", title: `Valid from ${validFrom}`, "data-testid": "version-selector-restriction-tag", children: ["From ", validFrom] })), validTo && (_jsxs(Badge, { variant: "outline", size: "sm", className: "text-2xs", title: `Valid to ${validTo}`, "data-testid": "version-selector-restriction-tag", children: ["To ", validTo] })), version.workflowState && (_jsx(Badge, { variant: version.isFinalState ? "default" : "outline", size: "sm", className: cn("text-2xs max-w-32", version.isFinalState &&
                    "bg-feedback-green hover:bg-feedback-green border-transparent text-white"), title: `Workflow state: ${version.workflowState}`, "data-testid": "version-selector-workflow-tag", children: _jsx("span", { className: "truncate", children: version.workflowState }) }))] }));
}
export function VersionSelector({ itemDescriptor, actualVersion, onVersionSelected, readOnly, versions, isLoading, showVersionPreviews = true, previewDateActive = false, publishRestrictionsItem, triggerClassName, }) {
    const [open, setOpen] = React.useState(false);
    const editContext = useEditContext();
    if (itemDescriptor == null)
        return;
    const showSpinner = !!isLoading;
    const showPreviews = ENABLE_VERSION_SELECTOR_PREVIEWS &&
        showVersionPreviews &&
        open &&
        !editContext?.isMobile &&
        versions.length > 0;
    const selectedVersion = previewDateActive
        ? actualVersion
        : itemDescriptor.version;
    const canOpenPublishRestrictions = !!publishRestrictionsItem &&
        publishRestrictionsItem.canWriteItem &&
        publishRestrictionsItem.canWriteLanguage;
    const getVersionLabel = () => {
        if (editContext?.isMobile) {
            if (versions.length === 0)
                return "None";
            if (previewDateActive) {
                return actualVersion ? `V(${actualVersion})` : "None";
            }
            if (itemDescriptor.version === 0) {
                return actualVersion ? `V(${actualVersion})` : "None";
            }
            return `V(${itemDescriptor.version})`;
        }
        if (versions.length === 0)
            return "No versions";
        if (previewDateActive) {
            return actualVersion ? `Version (${actualVersion})` : "No version";
        }
        if (itemDescriptor.version === 0)
            return ("Latest version" + (actualVersion ? " (" + actualVersion + ")" : ""));
        return "Version (" + itemDescriptor.version + ")";
    };
    const selectVersion = async (version) => {
        onVersionSelected(version);
        setOpen(false);
    };
    const handleCreateVersion = async () => {
        await editContext?.executeCommand({
            command: getCreateAndSwitchToNewVersionCommand({}),
        });
        setOpen(false);
    };
    const handleDeleteVersion = async () => {
        await editContext?.executeCommand({
            command: getDeleteVersionCommand({}),
        });
        setOpen(false);
        onVersionSelected(0);
    };
    const handlePublishRestrictions = async () => {
        if (!publishRestrictionsItem)
            return;
        setOpen(false);
        await editContext?.executeCommand({
            command: publishRestrictionsCommand,
            data: { items: [publishRestrictionsItem] },
        });
    };
    return (_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "select", role: "combobox", "aria-expanded": open, "data-testid": "version-selector", "data-version": selectedVersion || actualVersion, className: triggerClassName, children: [_jsxs("div", { className: "flex items-center gap-2", children: [showSpinner && (_jsx(Loader2, { className: "h-4 w-4 animate-spin", "data-testid": "version-selector-spinner", strokeWidth: 1 })), getVersionLabel(), previewDateActive && !editContext?.isMobile && (_jsx("span", { className: "text-2xs text-muted-foreground", children: "at preview date" }))] }), _jsx(ChevronDown, { className: cn("text-neutral-grey-100 hidden h-4 w-4 shrink-0 transition-transform md:block", open && "rotate-180"), strokeWidth: 1 })] }) }), _jsx(PopoverContent, { className: cn(showPreviews ? "w-md" : "w-64", "p-0"), align: "start", onInteractOutside: (event) => {
                    // The User Manual "Show me" feature drives this popover via its reveal
                    // state machine (it explicitly closes, then reopens for the next
                    // action). Radix' own dismiss-on-outside-click would fire on the
                    // Show-me button click and race that deterministic close-then-reopen
                    // sequence, so suppress it ONLY for triggers that actually drive this
                    // popover (beforeAction "open-version-selector"). Other Show-me
                    // buttons, Escape, and all other outside clicks keep their normal
                    // dismiss behaviour, so an unrelated reveal can't leave this popover
                    // stuck open.
                    const target = (event.detail.originalEvent.target ??
                        null);
                    if (target?.closest('[data-manual-show-me-before-action="open-version-selector"]')) {
                        event.preventDefault();
                    }
                }, children: _jsxs(Command, { children: [_jsxs(CommandList, { className: cn(showPreviews ? "max-h-[60vh]" : "max-h-[30vh]"), "data-testid": "version-selector-list", children: [_jsx(CommandEmpty, { children: "No versions available" }), _jsxs(CommandGroup, { children: [versions.length > 0 && (_jsxs(CommandItem, { value: "latest", onSelect: () => selectVersion(0), className: cn("flex items-center gap-2 px-2 py-2 text-xs", 
                                            // Remove background when selected (auto-focused) but not hovered
                                            "data-[selected=true]:bg-transparent", 
                                            // Force hover styles to override selected state
                                            "[&:hover]:bg-accent! [&:hover]:text-accent-foreground!"), children: [_jsx("span", { className: "flex-1", children: "Latest" }), _jsx(Check, { className: cn("h-4 w-4", selectedVersion === 0 ? "opacity-100" : "opacity-0"), strokeWidth: 1 })] }, "latest")), versions.map((x) => (_jsxs(CommandItem, { value: x.version.toString(), onSelect: () => selectVersion(x.version), className: cn(showPreviews
                                                ? "flex items-start gap-3 px-2 py-2 text-xs"
                                                : "flex items-center gap-2 px-2 py-2 text-xs", 
                                            // Remove background when selected (auto-focused) but not hovered
                                            "data-[selected=true]:bg-transparent", 
                                            // Force hover styles to override selected state
                                            "[&:hover]:bg-accent! [&:hover]:text-accent-foreground!"), children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-3", children: [showPreviews && (_jsx(VersionPreviewCard, { itemDescriptor: itemDescriptor, version: x.version })), _jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2", children: [_jsxs("span", { className: "min-w-0 shrink-0", children: ["Version ", x.version] }), _jsx(VersionStatusTags, { version: x, isMobile: !!editContext?.isMobile })] })] }), _jsx(Check, { className: cn("h-4 w-4", selectedVersion === x.version
                                                        ? "opacity-100"
                                                        : "opacity-0"), strokeWidth: 1 })] }, x.version)))] })] }), (!readOnly || publishRestrictionsItem) && (_jsxs(_Fragment, { children: [_jsx("div", { className: "border-border-default border-t" }), _jsxs("div", { className: "p-1", children: [publishRestrictionsItem && (_jsxs(CommandItem, { onSelect: handlePublishRestrictions, disabled: !canOpenPublishRestrictions, className: cn("flex items-center gap-2 px-2 py-2 text-xs", 
                                            // Remove background when selected (auto-focused) but not hovered
                                            "data-[selected=true]:bg-transparent", 
                                            // Force hover styles to override selected state
                                            "[&:hover]:bg-accent! [&:hover]:text-accent-foreground!", !canOpenPublishRestrictions &&
                                                "cursor-not-allowed opacity-50"), "data-testid": "publish-restrictions-button", children: [_jsx(Clock3, { className: "h-4 w-4", strokeWidth: 1 }), _jsx("span", { children: "Publish restrictions" })] })), publishRestrictionsItem && !readOnly && (_jsx("div", { className: "border-border-default my-1 border-t" })), !readOnly && (_jsxs(_Fragment, { children: [_jsxs(CommandItem, { onSelect: handleCreateVersion, className: cn("flex items-center gap-2 px-2 py-2 text-xs", 
                                                    // Remove background when selected (auto-focused) but not hovered
                                                    "data-[selected=true]:bg-transparent", 
                                                    // Force hover styles to override selected state
                                                    "[&:hover]:bg-accent! [&:hover]:text-accent-foreground!"), "data-testid": "version-selector-add-version", children: [_jsx(Plus, { className: "h-4 w-4", strokeWidth: 1 }), _jsx("span", { children: "Add Version" })] }), _jsxs(CommandItem, { onSelect: handleDeleteVersion, disabled: versions.length === 0, className: cn("flex items-center gap-2 px-2 py-2 text-xs", 
                                                    // Remove background when selected (auto-focused) but not hovered
                                                    "data-[selected=true]:bg-transparent", 
                                                    // Force hover styles to override selected state
                                                    "[&:hover]:bg-accent! [&:hover]:text-accent-foreground!", versions.length === 0
                                                        ? "cursor-not-allowed opacity-50"
                                                        : "text-feedback-red hover:text-feedback-red"), "data-testid": "version-selector-delete-version", children: [_jsx(X, { className: "h-4 w-4", strokeWidth: 1 }), _jsx("span", { children: "Delete Version" })] })] }))] })] }))] }) })] }));
}
//# sourceMappingURL=VersionSelector.js.map