import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useRef, useEffect, useLayoutEffect } from "react";
import { flushSync } from "react-dom";
import { ChevronLeft, ChevronUp } from "lucide-react";
import { cn } from "../../lib/utils";
import { localStorageService } from "../services/localStorageService";
import { dispatchSplitterResize, SPLITTER_PANEL_SIZE_REQUEST_EVENT, } from "./splitterResizeEvent";
export const Splitter = ({ panels, localStorageKey = "splitter-sizes", expandLabel, expandButtonLabel, expandButtonTestId, direction = "horizontal", // Default to horizontal for backward compatibility
className, splitterClassName, expandButtonClassName, forceCollapseLastPanelKey, forceExpandLastPanelKey, handleContent, onPanelTransitionEnd, onLastPanelCollapsedChange, }) => {
    const totalPanels = panels.length;
    const [panelSizes, setPanelSizes] = useState(() => {
        // Load sizes from local storage on initial render
        const storedSizes = localStorageService.getItem(localStorageKey);
        if (storedSizes) {
            return storedSizes.panels;
        }
        return null; // No stored sizes, initial render will handle defaults
    });
    const panelRefs = useRef([]);
    const splitterRef = useRef(null);
    const lastPanelCollapsible = panels[panels.length - 1]?.collapsible;
    const [isLastPanelCollapsed, setIsLastPanelCollapsed] = useState(() => {
        const storedSizes = localStorageService.getItem(localStorageKey);
        if (storedSizes) {
            return storedSizes.lastCollapsed;
        }
        return true;
    });
    const [isResizing, setIsResizing] = useState(false);
    useEffect(() => {
        if (!lastPanelCollapsible)
            return;
        onLastPanelCollapsedChange?.(isLastPanelCollapsed);
    }, [
        isLastPanelCollapsed,
        lastPanelCollapsible,
        onLastPanelCollapsedChange,
    ]);
    const isPanelCollapsed = (index) => {
        const panel = panels[index];
        if (!panel)
            return false;
        return (!!panel.collapsed ||
            (!!panel.collapsible && isLastPanelCollapsed && index === totalPanels - 1));
    };
    const getPanelMinSize = React.useCallback((index) => {
        return panels[index]?.minSize ?? 50;
    }, [panels]);
    // Check if any panel size is 0 and reset if needed
    useEffect(() => {
        if (!panelSizes)
            return;
        // Utility function to reset all panel sizes to their defaults
        const resetToDefaultSizes = () => {
            if (!splitterRef.current)
                return;
            const container = splitterRef.current;
            const isHorizontal = direction === "horizontal";
            const containerSize = isHorizontal
                ? container.clientWidth
                : container.clientHeight;
            const visiblePanels = panels.filter((p) => !p.hidden);
            if (visiblePanels.length === 0)
                return;
            const minPanelSize = 50;
            const fixedPanels = visiblePanels.filter((p) => typeof p.defaultSize === "number");
            const autoPanels = visiblePanels.filter((p) => p.defaultSize === "auto");
            const sumFixed = fixedPanels.reduce((sum, p) => {
                const size = p.defaultSize;
                return sum + (typeof size === "number" ? size : 0);
            }, 0);
            const updated = {};
            if (autoPanels.length === 0) {
                const scale = containerSize > 0 && sumFixed > 0 ? containerSize / sumFixed : 1;
                visiblePanels.forEach((p) => {
                    updated[p.name] = Math.max(minPanelSize, Math.round(p.defaultSize * scale));
                });
            }
            else if (containerSize > 0) {
                const minAutoTotal = autoPanels.length * minPanelSize;
                const remainder = containerSize - sumFixed;
                if (remainder >= minAutoTotal) {
                    const per = Math.floor(remainder / autoPanels.length);
                    fixedPanels.forEach((p) => {
                        updated[p.name] = p.defaultSize;
                    });
                    autoPanels.forEach((p) => {
                        updated[p.name] = per;
                    });
                }
                else {
                    const availableForFixed = Math.max(0, containerSize - minAutoTotal);
                    const scale = sumFixed > 0 ? availableForFixed / sumFixed : 0;
                    fixedPanels.forEach((p) => {
                        updated[p.name] = Math.max(minPanelSize, Math.round(p.defaultSize * scale));
                    });
                    autoPanels.forEach((p) => {
                        updated[p.name] = minPanelSize;
                    });
                }
            }
            else {
                // Fallback when container size is 0
                fixedPanels.forEach((p) => {
                    updated[p.name] = p.defaultSize;
                });
                autoPanels.forEach((p) => {
                    updated[p.name] = minPanelSize;
                });
            }
            setPanelSizes(updated);
        };
        const hasZeroSize = Object.values(panelSizes).some((size) => typeof size === "number" && size <= 0);
        if (hasZeroSize) {
            resetToDefaultSizes();
        }
    }, [panelSizes, panels, direction]);
    useLayoutEffect(() => {
        if (panelSizes || !splitterRef.current)
            return;
        const container = splitterRef.current;
        const isHorizontal = direction === "horizontal";
        const computeAndSet = (containerSize) => {
            const visiblePanels = panels.filter((p) => !p.hidden);
            if (visiblePanels.length === 0)
                return;
            const minPanelSize = 50;
            const fixedPanels = visiblePanels.filter((p) => typeof p.defaultSize === "number");
            const autoPanels = visiblePanels.filter((p) => p.defaultSize === "auto");
            const sumFixed = fixedPanels.reduce((sum, p) => {
                const size = p.defaultSize;
                return sum + (typeof size === "number" ? size : 0);
            }, 0);
            const updated = {};
            if (autoPanels.length === 0) {
                const scale = containerSize > 0 && sumFixed > 0 ? containerSize / sumFixed : 1;
                visiblePanels.forEach((p) => {
                    updated[p.name] = Math.max(minPanelSize, Math.round(p.defaultSize * scale));
                });
            }
            else if (containerSize > 0) {
                const minAutoTotal = autoPanels.length * minPanelSize;
                const remainder = containerSize - sumFixed;
                if (remainder >= minAutoTotal) {
                    const per = Math.floor(remainder / autoPanels.length);
                    fixedPanels.forEach((p) => {
                        updated[p.name] = p.defaultSize;
                    });
                    autoPanels.forEach((p) => {
                        updated[p.name] = per;
                    });
                }
                else {
                    const availableForFixed = Math.max(0, containerSize - minAutoTotal);
                    const scale = sumFixed > 0 ? availableForFixed / sumFixed : 0;
                    fixedPanels.forEach((p) => {
                        updated[p.name] = Math.max(minPanelSize, Math.round(p.defaultSize * scale));
                    });
                    autoPanels.forEach((p) => {
                        updated[p.name] = minPanelSize;
                    });
                }
            }
            else {
                // Fallback when container size is 0
                fixedPanels.forEach((p) => {
                    updated[p.name] = p.defaultSize;
                });
                autoPanels.forEach((p) => {
                    updated[p.name] = minPanelSize;
                });
            }
            setPanelSizes(updated);
        };
        const initialSize = isHorizontal
            ? container.clientWidth
            : container.clientHeight;
        if (initialSize > 0) {
            computeAndSet(initialSize);
            return;
        }
        const ro = new ResizeObserver((entries) => {
            for (const entry of entries) {
                const size = isHorizontal
                    ? entry.contentRect.width
                    : entry.contentRect.height;
                if (size > 0) {
                    computeAndSet(size);
                    ro.disconnect();
                    break;
                }
            }
        });
        ro.observe(container);
        return () => {
            ro.disconnect();
        };
    }, [panels, panelSizes, direction]);
    useEffect(() => {
        if (panelSizes) {
            const storedSizes = {
                panels: panelSizes,
                lastCollapsed: isLastPanelCollapsed ?? false,
            };
            localStorageService.setItem(localStorageKey, storedSizes);
        }
    }, [panelSizes, localStorageKey, isLastPanelCollapsed]);
    useLayoutEffect(() => {
        if (!panelSizes)
            return;
        dispatchSplitterResize();
    }, [panelSizes, isLastPanelCollapsed]);
    useEffect(() => {
        const handlePanelSizeRequest = (event) => {
            const detail = event
                .detail;
            if (!detail ||
                detail.localStorageKey !== localStorageKey ||
                !Number.isFinite(detail.size) ||
                detail.size <= 0) {
                return;
            }
            const targetIndex = panels.findIndex((panel) => !panel.hidden && panel.name === detail.panelName);
            if (targetIndex === -1)
                return;
            const targetPanel = panels[targetIndex];
            const targetCollapsed = !!targetPanel?.collapsed ||
                (!!targetPanel?.collapsible &&
                    isLastPanelCollapsed &&
                    targetIndex === totalPanels - 1);
            if (targetCollapsed)
                return;
            const measuredSizes = { ...(panelSizes ?? {}) };
            const visibleIndices = [];
            let availablePanelSize = 0;
            const isHorizontal = direction === "horizontal";
            panels.forEach((panel, index) => {
                if (panel.hidden)
                    return;
                const collapsed = !!panel.collapsed ||
                    (!!panel.collapsible &&
                        isLastPanelCollapsed &&
                        index === totalPanels - 1);
                if (collapsed)
                    return;
                const element = panelRefs.current[index];
                const rect = element?.getBoundingClientRect();
                const measured = rect ? (isHorizontal ? rect.width : rect.height) : 0;
                const fallback = typeof measuredSizes[panel.name] === "number"
                    ? measuredSizes[panel.name]
                    : typeof panel.defaultSize === "number"
                        ? panel.defaultSize
                        : getPanelMinSize(index);
                const size = Math.max(1, Math.round(measured || fallback));
                measuredSizes[panel.name] = size;
                availablePanelSize += size;
                visibleIndices.push(index);
            });
            if (!visibleIndices.includes(targetIndex) || availablePanelSize <= 0) {
                return;
            }
            const otherVisibleIndices = visibleIndices.filter((index) => index !== targetIndex);
            const otherMinSize = otherVisibleIndices.reduce((sum, index) => sum + getPanelMinSize(index), 0);
            const targetName = panels[targetIndex].name;
            const targetMinSize = getPanelMinSize(targetIndex);
            const maxTargetSize = Math.max(targetMinSize, availablePanelSize - otherMinSize);
            const requestedTargetSize = Math.round(detail.size);
            const nextTargetSize = Math.max(targetMinSize, Math.min(requestedTargetSize, maxTargetSize));
            const currentTargetSize = typeof measuredSizes[targetName] === "number"
                ? measuredSizes[targetName]
                : targetMinSize;
            let delta = nextTargetSize - currentTargetSize;
            if (Math.abs(delta) < 1)
                return;
            const updatedSizes = { ...measuredSizes };
            const orderedOtherIndices = [
                ...otherVisibleIndices.filter((index) => index < targetIndex).reverse(),
                ...otherVisibleIndices.filter((index) => index > targetIndex),
            ];
            if (delta > 0) {
                let remaining = delta;
                for (const index of orderedOtherIndices) {
                    const panel = panels[index];
                    if (!panel)
                        continue;
                    const panelName = panel.name;
                    const currentSize = typeof updatedSizes[panelName] === "number"
                        ? updatedSizes[panelName]
                        : getPanelMinSize(index);
                    const shrinkRoom = Math.max(0, currentSize - getPanelMinSize(index));
                    const shrinkBy = Math.min(shrinkRoom, remaining);
                    if (shrinkBy > 0) {
                        updatedSizes[panelName] = currentSize - shrinkBy;
                        remaining -= shrinkBy;
                    }
                    if (remaining <= 0)
                        break;
                }
                updatedSizes[targetName] = nextTargetSize - remaining;
            }
            else {
                const growIndex = orderedOtherIndices[0];
                if (growIndex !== undefined) {
                    const growPanel = panels[growIndex];
                    if (growPanel) {
                        const growName = growPanel.name;
                        const currentGrowSize = typeof updatedSizes[growName] === "number"
                            ? updatedSizes[growName]
                            : getPanelMinSize(growIndex);
                        updatedSizes[growName] = currentGrowSize + Math.abs(delta);
                    }
                }
                updatedSizes[targetName] = nextTargetSize;
            }
            setPanelSizes(updatedSizes);
        };
        window.addEventListener(SPLITTER_PANEL_SIZE_REQUEST_EVENT, handlePanelSizeRequest);
        return () => {
            window.removeEventListener(SPLITTER_PANEL_SIZE_REQUEST_EVENT, handlePanelSizeRequest);
        };
    }, [
        direction,
        getPanelMinSize,
        isLastPanelCollapsed,
        localStorageKey,
        panelSizes,
        panels,
        totalPanels,
    ]);
    useEffect(() => {
        if (!lastPanelCollapsible || forceCollapseLastPanelKey == null) {
            return;
        }
        setIsLastPanelCollapsed(true);
    }, [forceCollapseLastPanelKey, lastPanelCollapsible]);
    useEffect(() => {
        if (!lastPanelCollapsible || forceExpandLastPanelKey == null) {
            return;
        }
        setIsLastPanelCollapsed(false);
    }, [forceExpandLastPanelKey, lastPanelCollapsible]);
    const toggleLastPanelCollapse = () => {
        if (lastPanelCollapsible) {
            if (typeof document.startViewTransition === "function") {
                document.startViewTransition(() => {
                    flushSync(() => {
                        setIsLastPanelCollapsed((prev) => {
                            const newCollapsed = !prev;
                            // When expanding, restore default sizes if needed
                            if (!newCollapsed && panelSizes) {
                                const lastPanelName = panels[panels.length - 1]?.name;
                                const lastPanelDefaultSize = panels[panels.length - 1]?.defaultSize;
                                if (lastPanelName &&
                                    lastPanelDefaultSize &&
                                    typeof lastPanelDefaultSize === "number") {
                                    // Only restore size if the panel doesn't have a stored size
                                    if (!panelSizes[lastPanelName] ||
                                        panelSizes[lastPanelName] === 0) {
                                        const updatedSizes = { ...panelSizes };
                                        updatedSizes[lastPanelName] = lastPanelDefaultSize;
                                        // Adjust the previous panel to make room
                                        const prevPanelName = panels[panels.length - 2]?.name;
                                        if (prevPanelName &&
                                            typeof panelSizes[prevPanelName] === "number") {
                                            const prevSize = panelSizes[prevPanelName];
                                            updatedSizes[prevPanelName] = Math.max(50, prevSize - lastPanelDefaultSize);
                                        }
                                        setPanelSizes(updatedSizes);
                                    }
                                }
                            }
                            return newCollapsed;
                        });
                    });
                });
            }
            else {
                flushSync(() => {
                    setIsLastPanelCollapsed((prev) => {
                        const newCollapsed = !prev;
                        // When expanding, restore default sizes if needed
                        if (!newCollapsed && panelSizes) {
                            const lastPanelName = panels[panels.length - 1]?.name;
                            const lastPanelDefaultSize = panels[panels.length - 1]?.defaultSize;
                            if (lastPanelName &&
                                lastPanelDefaultSize &&
                                typeof lastPanelDefaultSize === "number") {
                                // Only restore size if the panel doesn't have a stored size
                                if (!panelSizes[lastPanelName] ||
                                    panelSizes[lastPanelName] === 0) {
                                    const updatedSizes = { ...panelSizes };
                                    updatedSizes[lastPanelName] = lastPanelDefaultSize;
                                    // Adjust the previous panel to make room
                                    const prevPanelName = panels[panels.length - 2]?.name;
                                    if (prevPanelName &&
                                        typeof panelSizes[prevPanelName] === "number") {
                                        const prevSize = panelSizes[prevPanelName];
                                        updatedSizes[prevPanelName] = Math.max(50, prevSize - lastPanelDefaultSize);
                                    }
                                    setPanelSizes(updatedSizes);
                                }
                            }
                        }
                        return newCollapsed;
                    });
                });
            }
        }
    };
    const isLastResizer = (index) => index === panels.length - 2;
    const getFlexGrow = (index) => {
        const panelName = panels[index].name;
        if (isPanelCollapsed(index))
            return 0;
        const storedRaw = panelSizes?.[panelName];
        const raw = storedRaw ?? panels[index].defaultSize;
        if (raw === "auto")
            return 1;
        // Guard against invalid or stale tiny stored sizes that could hide panels.
        // Fresh default sizes may be relative weights until the initial layout pass.
        if (typeof raw === "number") {
            return Math.max(storedRaw === undefined ? 1 : getPanelMinSize(index), raw);
        }
        return 1;
    };
    const getExpandButton = () => {
        const isHorizontal = direction === "horizontal";
        const label = expandButtonLabel ?? "Expand panel";
        return (_jsx("div", { onClick: !isResizing ? toggleLastPanelCollapse : undefined, onKeyDown: (event) => {
                if (isResizing)
                    return;
                if (event.key !== "Enter" && event.key !== " ")
                    return;
                event.preventDefault();
                toggleLastPanelCollapse();
            }, role: "button", tabIndex: 0, "aria-label": label, title: label, "data-testid": expandButtonTestId, className: cn("bg-neutral-grey-5 text-neutral-grey-50 hover:bg-highlight-100 flex cursor-pointer items-center justify-center p-3 transition-all duration-200 select-none hover:text-white md:p-1", expandButtonClassName), style: {
                writingMode: isHorizontal ? "vertical-rl" : "horizontal-tb",
                userSelect: "none",
            }, children: expandLabel ||
                (isHorizontal ? _jsx(ChevronLeft, { size: 16 }) : _jsx(ChevronUp, { size: 16 })) }));
    };
    const getSplitter = (index, nextVisibleIndex) => {
        const isHorizontal = direction === "horizontal";
        // Find next visible panel if not provided
        const actualNextIndex = nextVisibleIndex ??
            (() => {
                let nextIdx = index + 1;
                while (nextIdx < panels.length && panels[nextIdx]?.hidden) {
                    nextIdx++;
                }
                return nextIdx < panels.length ? nextIdx : index + 1;
            })();
        const handleDragStart = (clientX, clientY) => {
            const isHorizontal = direction === "horizontal";
            const startCoord = isHorizontal ? clientX : clientY;
            // Panel sizes are used as flex-grow weights (see getFlexGrow()).
            // If we only convert the dragged pair to px while leaving other panels as stored weights,
            // flex redistribution can cause a small "jump" on the first drag update.
            // Normalize all visible panels to their current pixel sizes at drag start.
            const initialSizes = { ...(panelSizes ?? {}) };
            const panelElement = panelRefs.current[index];
            const nextPanelElement = panelRefs.current[actualNextIndex];
            if (!panelElement || !nextPanelElement) {
                return;
            }
            panels.forEach((p, i) => {
                if (p.hidden)
                    return;
                if (isPanelCollapsed(i))
                    return;
                const el = panelRefs.current[i];
                if (!el)
                    return;
                const rect = el.getBoundingClientRect();
                const sizePx = isHorizontal ? rect.width : rect.height;
                if (Number.isFinite(sizePx) && sizePx > 0) {
                    initialSizes[p.name] = Math.max(1, Math.round(sizePx));
                }
            });
            const panelName = panels[index].name;
            const nextPanelName = panels[actualNextIndex].name;
            const panelSize = typeof initialSizes[panelName] === "number"
                ? initialSizes[panelName]
                : isHorizontal
                    ? panelElement.offsetWidth
                    : panelElement.offsetHeight;
            const nextPanelSize = typeof initialSizes[nextPanelName] === "number"
                ? initialSizes[nextPanelName]
                : isHorizontal
                    ? nextPanelElement.offsetWidth
                    : nextPanelElement.offsetHeight;
            // Disable pointer events on all iframes to prevent event loss when hovering over them
            const iframes = document.querySelectorAll("iframe");
            const originalPointerEvents = new Map();
            iframes.forEach((iframe) => {
                originalPointerEvents.set(iframe, iframe.style.pointerEvents);
                iframe.style.pointerEvents = "none";
            });
            setIsResizing(true);
            let isDragging = true;
            const handleMove = (moveClientX, moveClientY) => {
                if (!isDragging)
                    return;
                const currentCoord = isHorizontal ? moveClientX : moveClientY;
                const delta = currentCoord - startCoord;
                const newPanelSize = panelSize + delta;
                const newNextPanelSize = nextPanelSize - delta;
                const panelMinSize = getPanelMinSize(index);
                const nextPanelMinSize = getPanelMinSize(actualNextIndex);
                // Check if the next panel (which could be the last panel) should be collapsed
                const isNextPanelLast = actualNextIndex === panels.length - 1;
                const isNextPanelCollapsible = panels[actualNextIndex]?.collapsible;
                if (newNextPanelSize < nextPanelMinSize &&
                    isNextPanelLast &&
                    isNextPanelCollapsible) {
                    // Auto-collapse the last panel when it reaches minimum size
                    // Update sizes to ensure the remaining panel gets the full space
                    const updatedSizes = { ...initialSizes };
                    updatedSizes[panels[index].name] = panelSize + nextPanelSize;
                    // Don't set a size for the collapsed panel - let it be handled by the collapsed state
                    setPanelSizes(updatedSizes);
                    setIsLastPanelCollapsed(true);
                    return;
                }
                if (newPanelSize < panelMinSize ||
                    newNextPanelSize < nextPanelMinSize) {
                    return;
                }
                // Ensure no panel size becomes 0 or negative
                const safePanelSize = Math.max(1, newPanelSize);
                const safeNextPanelSize = Math.max(1, newNextPanelSize);
                const updatedSizes = { ...initialSizes };
                updatedSizes[panels[index].name] = safePanelSize;
                updatedSizes[panels[actualNextIndex].name] = safeNextPanelSize;
                setPanelSizes(updatedSizes);
            };
            const handleEnd = () => {
                isDragging = false;
                setIsResizing(false);
                // Restore pointer events on all iframes
                originalPointerEvents.forEach((originalValue, iframe) => {
                    iframe.style.pointerEvents = originalValue;
                });
                // Remove all event listeners
                window.removeEventListener("mousemove", onMouseMove);
                window.removeEventListener("mouseup", onMouseUp);
                window.removeEventListener("touchmove", onTouchMove);
                window.removeEventListener("touchend", onTouchEnd);
            };
            const onMouseMove = (moveEvent) => {
                handleMove(moveEvent.clientX, moveEvent.clientY);
            };
            const onMouseUp = () => {
                handleEnd();
            };
            const onTouchMove = (moveEvent) => {
                if (moveEvent.touches.length === 1) {
                    const touch = moveEvent.touches[0];
                    if (touch) {
                        handleMove(touch.clientX, touch.clientY);
                    }
                }
            };
            const onTouchEnd = () => {
                handleEnd();
            };
            // Add both mouse and touch event listeners
            window.addEventListener("mousemove", onMouseMove);
            window.addEventListener("mouseup", onMouseUp);
            window.addEventListener("touchmove", onTouchMove, { passive: false });
            window.addEventListener("touchend", onTouchEnd);
        };
        if (lastPanelCollapsible && isLastPanelCollapsed && isLastResizer(index)) {
            return getExpandButton();
        }
        return (_jsxs("div", { "data-testid": `splitter-handle-${index}`, className: `group relative flex ${isHorizontal
                ? "h-full w-3 cursor-ew-resize md:w-[5px]"
                : "h-3 w-full cursor-ns-resize md:h-[5px]"} bg-border-default hover:bg-neutral-grey-15 shrink-0 items-center justify-center transition-colors select-none ${splitterClassName || ""}`, style: {
                touchAction: "none",
                minWidth: isHorizontal ? "5px" : undefined,
                boxSizing: "border-box",
                userSelect: "none",
                // Keep the handle above panel content *within this splitter*,
                // but avoid leaking an unnecessarily high z-index into ancestor stacking contexts.
                zIndex: 10,
            }, onDoubleClick: isLastResizer(index) ? toggleLastPanelCollapse : undefined, onMouseDown: (event) => {
                event.preventDefault();
                handleDragStart(event.clientX, event.clientY);
            }, onTouchStart: (event) => {
                if (event.touches.length === 1) {
                    const touch = event.touches[0];
                    if (touch) {
                        handleDragStart(touch.clientX, touch.clientY);
                    }
                }
            }, children: [_jsx("div", { className: "absolute z-0 md:hidden", style: {
                        top: isHorizontal ? 0 : -12,
                        bottom: isHorizontal ? 0 : -12,
                        left: isHorizontal ? -12 : 0,
                        right: isHorizontal ? -12 : 0,
                        cursor: isHorizontal ? "ew-resize" : "ns-resize",
                        pointerEvents: "auto",
                    }, onMouseDown: (event) => {
                        event.preventDefault();
                        handleDragStart(event.clientX, event.clientY);
                    }, onTouchStart: (event) => {
                        if (event.touches.length === 1) {
                            const touch = event.touches[0];
                            if (touch) {
                                handleDragStart(touch.clientX, touch.clientY);
                            }
                        }
                    } }), _jsx("div", { className: `${isHorizontal ? "h-8 w-0.5 md:h-6" : "h-0.5 w-8 md:w-6"} bg-neutral-grey-50 md:bg-neutral-grey-15 md:group-hover:bg-neutral-grey-50 rounded-full transition-colors` }), handleContent && (_jsx("div", { className: "pointer-events-auto flex items-center justify-center", onMouseDown: (e) => {
                        // Prevent starting drag when interacting with handle content
                        e.stopPropagation();
                    }, onClick: (e) => {
                        e.stopPropagation();
                    }, children: handleContent(index) }))] }));
    };
    return (_jsx("div", { className: `relative isolate flex items-stretch justify-stretch ${direction === "horizontal" ? "flex-row" : "flex-col"} ${className && /(^|\s)h-/.test(className) ? "" : "h-full"} ${className && /(^|\s)w-/.test(className) ? "" : "w-full"} overflow-hidden ${className || ""}`, ref: splitterRef, children: panels.map((panel, index) => {
            // Find the next visible panel (skip hidden ones)
            let nextVisibleIndex = index + 1;
            while (nextVisibleIndex < panels.length &&
                panels[nextVisibleIndex]?.hidden) {
                nextVisibleIndex++;
            }
            const hasNextVisiblePanel = nextVisibleIndex < panels.length;
            const nextPanel = hasNextVisiblePanel
                ? panels[nextVisibleIndex]
                : undefined;
            const panelCollapsed = isPanelCollapsed(index);
            const nextPanelCollapsed = hasNextVisiblePanel
                ? isPanelCollapsed(nextVisibleIndex)
                : false;
            const nextPanelIsCollapsedLastCollapsible = !!nextPanel?.collapsible &&
                nextPanelCollapsed &&
                nextVisibleIndex === totalPanels - 1;
            const shouldRenderSplitter = hasNextVisiblePanel &&
                !panel.hidden &&
                !nextPanel?.hidden &&
                !panelCollapsed &&
                (!nextPanelCollapsed || nextPanelIsCollapsedLastCollapsible);
            const displayPanel = !panel.hidden && (!panelCollapsed || panel.animatedCollapse);
            const hideAnimatedCollapsedPanel = panel.animatedCollapse &&
                panelCollapsed &&
                !panel.preserveVisibilityOnCollapse;
            const collapsedSize = panel.collapsedSize ?? 0;
            return (_jsxs(React.Fragment, { children: [_jsx("div", { ref: (el) => {
                            panelRefs.current[index] = el;
                        }, className: cn("relative overflow-hidden", panel.className), "data-testid": `splitter-panel-${panel.name}`, onTransitionEnd: panel.animatedCollapse && onPanelTransitionEnd
                            ? (e) => {
                                // Only the panel wrapper's own collapse transition counts,
                                // not bubbled transitions from descendants.
                                if (e.target === e.currentTarget &&
                                    (e.propertyName === "flex-grow" ||
                                        e.propertyName === "flex-basis")) {
                                    onPanelTransitionEnd(panel.name);
                                }
                            }
                            : undefined, style: {
                            flex: panelCollapsed
                                ? `0 0 ${collapsedSize}px`
                                : `${getFlexGrow(index)} 1 0px`,
                            // Keep later panels above earlier siblings so adjacent columns
                            // do not visually bleed over the panel to their right.
                            zIndex: index + 1,
                            minWidth: direction === "horizontal" && !panelCollapsed
                                ? `${getPanelMinSize(index)}px`
                                : 0,
                            minHeight: direction === "vertical" && !panelCollapsed
                                ? `${getPanelMinSize(index)}px`
                                : 0,
                            display: displayPanel ? "block" : "none",
                            opacity: panel.animatedCollapse
                                ? panelCollapsed
                                    ? 0
                                    : 1
                                : undefined,
                            visibility: hideAnimatedCollapsedPanel ? "hidden" : undefined,
                            pointerEvents: panel.animatedCollapse && panelCollapsed ? "none" : undefined,
                            transition: panel.animatedCollapse && !isResizing
                                ? "flex-grow 200ms ease-in-out, flex-basis 200ms ease-in-out, opacity 200ms ease-in-out"
                                : undefined,
                        }, children: panel.content }), shouldRenderSplitter && getSplitter(index, nextVisibleIndex)] }, panel.name));
        }) }));
};
//# sourceMappingURL=Splitter.js.map