import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { cn } from "../../lib/utils";
import { Check, FileIcon, Upload } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { showItemContextMenu } from "../itemContextMenu";
import { getMediaFileTypeLabel } from "./mediaFileType";
import { useEffect, useRef, useState, } from "react";
export function Thumbnails({ images, selectedImage, setSelectedImage, onMediaSelected, onHide, language, onReplaceMedia, viewMode = "grid", loading = false, }) {
    const editContext = useEditContext();
    const [selectedImageIds, setSelectedImageIds] = useState([]);
    const [replaceHoverImageId, setReplaceHoverImageId] = useState();
    const lastSelectedImageId = useRef(undefined);
    useEffect(() => {
        if (!selectedImage)
            return;
        setSelectedImageIds((ids) => (ids.length === 0 ? [selectedImage.id] : ids));
        lastSelectedImageId.current ??= selectedImage.id;
    }, [selectedImage]);
    const selectImage = (image, event) => {
        if (event.shiftKey && lastSelectedImageId.current) {
            const lastIndex = images.findIndex((x) => x.id === lastSelectedImageId.current);
            const currentIndex = images.findIndex((x) => x.id === image.id);
            if (lastIndex !== -1 && currentIndex !== -1) {
                const start = Math.min(lastIndex, currentIndex);
                const end = Math.max(lastIndex, currentIndex);
                const rangeIds = images.slice(start, end + 1).map((x) => x.id);
                setSelectedImageIds(rangeIds);
                setSelectedImage(image);
                return;
            }
        }
        if (event.ctrlKey || event.metaKey) {
            setSelectedImageIds((ids) => {
                const nextIds = ids.includes(image.id)
                    ? ids.filter((id) => id !== image.id)
                    : [...ids, image.id];
                return nextIds.length > 0 ? nextIds : [image.id];
            });
            lastSelectedImageId.current = image.id;
            setSelectedImage(image);
            return;
        }
        setSelectedImageIds([image.id]);
        lastSelectedImageId.current = image.id;
        setSelectedImage(image);
    };
    const isImageFileDrag = (event) => {
        const hasFiles = Array.from(event.dataTransfer.types).includes("Files");
        const items = Array.from(event.dataTransfer.items);
        if (items.length > 0) {
            if (hasFiles && items.some((item) => item.kind === "file")) {
                return true;
            }
            return items.some((item) => item.kind === "file" &&
                (item.type.startsWith("image/") || item.type === ""));
        }
        return Array.from(event.dataTransfer.types).includes("Files");
    };
    const handleItemFileDrag = (image, event) => {
        if (!onReplaceMedia || !isImageFileDrag(event))
            return;
        event.preventDefault();
        event.stopPropagation();
        event.dataTransfer.dropEffect = "move";
        setReplaceHoverImageId(image.id);
    };
    const handleItemDragLeave = (event) => {
        if (!onReplaceMedia || !replaceHoverImageId)
            return;
        event.preventDefault();
        event.stopPropagation();
        if (event.relatedTarget instanceof Node &&
            event.currentTarget.contains(event.relatedTarget)) {
            return;
        }
        setReplaceHoverImageId(undefined);
    };
    const handleItemDrop = (image, event) => {
        if (!onReplaceMedia || !isImageFileDrag(event))
            return;
        event.preventDefault();
        event.stopPropagation();
        setReplaceHoverImageId(undefined);
        const file = Array.from(event.dataTransfer.files)[0];
        if (file) {
            onReplaceMedia(image, file);
        }
    };
    return (_jsx("div", { "data-testid": "media-selector-thumbnails-container", className: "absolute inset-0 overflow-auto p-4", children: images.length === 0 && !loading ? (_jsxs("div", { className: "text-neutral-grey-50 flex h-full flex-col items-center justify-center", children: [_jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1", strokeLinecap: "round", strokeLinejoin: "round", className: "mb-2 opacity-20", children: [_jsx("rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2" }), _jsx("circle", { cx: "9", cy: "9", r: "2" }), _jsx("path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" })] }), _jsx("p", { className: "text-sm", children: "No media found in this folder" })] })) : images.length > 0 ? (_jsx("div", { className: cn(viewMode === "list"
                ? "flex flex-col gap-1 p-2"
                : "grid grid-cols-[repeat(auto-fill,minmax(160px,160px))] content-start justify-center gap-4"), children: images.map((t) => {
                const isSelected = selectedImageIds.includes(t.id);
                const isReplaceHover = replaceHoverImageId === t.id;
                const fileTypeLabel = getMediaFileTypeLabel(t);
                const handleDoubleClick = () => {
                    onMediaSelected(t.id);
                    onHide();
                };
                const handleContextMenu = (event) => {
                    const thumbnail = t;
                    const itemIds = isSelected ? selectedImageIds : [t.id];
                    if (!isSelected) {
                        setSelectedImageIds([t.id]);
                        lastSelectedImageId.current = t.id;
                        setSelectedImage(t);
                    }
                    void showItemContextMenu({
                        editContext,
                        event,
                        itemIds,
                        language: thumbnail.language || language,
                        version: thumbnail.version ?? 0,
                    });
                };
                const replaceOverlay = isReplaceHover ? (_jsxs("div", { className: "pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 bg-white/65 backdrop-blur-[1px]", children: [_jsx("div", { className: "bg-highlight-100 flex h-9 w-9 items-center justify-center rounded-full text-white shadow-sm", children: _jsx(Upload, { className: "h-4 w-4", strokeWidth: 1.5 }) }), _jsx("span", { className: "text-highlight-100 text-xs font-medium", children: "Replace" })] })) : null;
                if (viewMode === "list") {
                    return (_jsxs("div", { className: cn("group relative flex min-h-[72px] w-full cursor-pointer items-center gap-3 overflow-hidden rounded-lg border bg-white p-2 transition-all duration-200 hover:shadow-sm", isReplaceHover
                            ? "border-highlight-100 bg-highlight-10 ring-highlight-100/40 shadow-md ring-2"
                            : isSelected
                                ? "border-primary bg-primary/5 ring-primary ring-2"
                                : "hover:border-primary/50 border-border-default hover:bg-neutral-grey-5"), onDoubleClick: handleDoubleClick, onClick: (event) => selectImage(t, event), onDragEnter: (event) => handleItemFileDrag(t, event), onDragOver: (event) => handleItemFileDrag(t, event), onDragLeave: handleItemDragLeave, onDragEnd: () => setReplaceHoverImageId(undefined), onDrop: (event) => handleItemDrop(t, event), onContextMenu: handleContextMenu, children: [_jsx("div", { className: "flex h-14 w-14 shrink-0 items-center justify-center rounded-md bg-white", children: t.thumbUrl ? (_jsx("img", { src: t.thumbUrl, alt: t.name, className: "max-h-full max-w-full object-contain transition-transform duration-300 group-hover:scale-105", loading: "lazy" })) : (_jsx(FileIcon, { className: "text-neutral-grey-50 h-7 w-7" })) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "text-neutral-grey-100 truncate text-[12px] font-normal", title: t.name, children: t.name }), fileTypeLabel && (_jsx("p", { className: "text-neutral-grey-50 mt-1 text-[11px] font-medium", children: fileTypeLabel }))] }), _jsx("div", { className: "flex h-6 w-6 shrink-0 items-center justify-center", children: isSelected && (_jsx("div", { className: "bg-primary flex h-5 w-5 items-center justify-center rounded-full text-white shadow-sm", children: _jsx(Check, { className: "h-3.5 w-3.5 stroke-[3]" }) })) }), replaceOverlay] }, t.id));
                }
                return (_jsxs("div", { className: cn("group relative flex h-[174px] w-[160px] cursor-pointer flex-col overflow-hidden rounded-lg border bg-white transition-all duration-200 hover:shadow-md", isReplaceHover
                        ? "border-highlight-100 bg-highlight-10 ring-highlight-100/40 shadow-lg ring-2"
                        : isSelected
                            ? "border-primary ring-primary ring-2"
                            : "hover:border-primary/50 border-border-default"), onDoubleClick: handleDoubleClick, onClick: (event) => selectImage(t, event), onDragEnter: (event) => handleItemFileDrag(t, event), onDragOver: (event) => handleItemFileDrag(t, event), onDragLeave: handleItemDragLeave, onDragEnd: () => setReplaceHoverImageId(undefined), onDrop: (event) => handleItemDrop(t, event), onContextMenu: handleContextMenu, children: [_jsx("div", { className: "flex h-[124px] w-full items-center justify-center bg-white p-2", children: t.thumbUrl ? (_jsx("img", { src: t.thumbUrl, alt: t.name, className: "max-h-full max-w-full object-contain transition-transform duration-300 group-hover:scale-105", loading: "lazy" })) : (_jsx(FileIcon, { className: "text-neutral-grey-50 h-10 w-10" })) }), _jsx("div", { className: "flex min-h-[50px] w-full items-start justify-start px-2 py-2", children: _jsx("p", { className: "text-neutral-grey-100 line-clamp-2 text-left text-[12px] font-normal break-all", title: t.name, children: t.name }) }), fileTypeLabel && (_jsx("div", { className: "absolute top-1.5 left-1.5 z-10", children: _jsx("div", { className: "badge-pad-sm text-neutral-grey-50 rounded border bg-white/85 text-[10px] font-bold shadow-xs backdrop-blur-sm", children: fileTypeLabel }) })), isSelected && (_jsx("div", { className: "bg-primary/5 pointer-events-none absolute inset-0" })), isSelected && (_jsx("div", { className: "absolute top-1.5 right-1.5 z-10", children: _jsx("div", { className: "bg-primary flex h-5 w-5 items-center justify-center rounded-full text-white shadow-sm", children: _jsx(Check, { className: "h-3.5 w-3.5 stroke-[3]" }) }) })), replaceOverlay] }, t.id));
            }) })) : null }));
}
//# sourceMappingURL=Thumbnails.js.map