import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useEffect, useRef, useState, } from "react";
import { cn } from "../../lib/utils";
import { Splitter } from "../ui/Splitter";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Pin, PinOff } from "lucide-react";
import { CloseButton } from "../../components/ui/close-button";
export function SidebarPanel({ sidebar, editContext, active, onClose, detached, paddingRight, sidebarId, onDragOver, onDrop, isFirstInStack = true, isStackLocked = false, suppressStackDropZones = false, }) {
    const resolvedPanels = sidebar.panels.map((x) => {
        if (typeof x === "function") {
            return x(editContext);
        }
        return x;
    });
    // Is icon pinned to toolbar? (used for drag-to-reorder functionality)
    const isPinned = sidebarId
        ? editContext.pinnedSidebars.includes(sidebarId)
        : false;
    // Is panel "pinned" open (stays visible when selecting another)?
    // Use the stack-level prop if provided, otherwise fall back to individual check
    const isLocked = isStackLocked ||
        (sidebarId ? editContext.lockedSidebars.includes(sidebarId) : false);
    const [dropZone, setDropZone] = useState(null);
    const containerRef = useRef(null);
    useEffect(() => {
        if (suppressStackDropZones) {
            setDropZone(null);
        }
    }, [suppressStackDropZones]);
    const handlePanelDragOver = useCallback((e) => {
        // Preserve existing drag-over behavior (used for horizontal reordering)
        onDragOver?.(e);
        e.preventDefault();
        if (!sidebarId || suppressStackDropZones) {
            setDropZone(null);
            return;
        }
        // `getData()` is unavailable during dragover, so inspect advertised types.
        const hasSidebarData = e.dataTransfer.types.includes("text/alpaca-sidebar") ||
            e.dataTransfer.types.includes("text/alpaca-sidebar-icon");
        if (!hasSidebarData) {
            setDropZone(null);
            return;
        }
        const target = e.currentTarget;
        if (!target)
            return;
        const rect = target.getBoundingClientRect();
        const ratio = rect.height > 0 ? (e.clientY - rect.top) / rect.height : 0.5;
        // Top/bottom zones stack vertically; center zone preserves existing reorder behavior.
        if (ratio < 0.25)
            setDropZone("before");
        else if (ratio > 0.75)
            setDropZone("after");
        else
            setDropZone("reorder");
    }, [onDragOver, sidebarId, suppressStackDropZones]);
    const handlePanelDragLeave = useCallback((e) => {
        // Only clear dropZone if we're actually leaving the panel container
        // (not just moving to a child element)
        const relatedTarget = e.relatedTarget;
        const container = containerRef.current;
        const isStillInside = container && relatedTarget && container.contains(relatedTarget);
        if (isStillInside) {
            // Moving to a child element - don't clear dropZone
            return;
        }
        setDropZone(null);
    }, [sidebarId]);
    const handlePanelDrop = useCallback((e) => {
        e.preventDefault();
        try {
            if (sidebarId) {
                const sourceSidebarId = e.dataTransfer.getData("text/alpaca-sidebar") ||
                    e.dataTransfer.getData("text/alpaca-sidebar-icon");
                if (sourceSidebarId &&
                    sourceSidebarId !== sidebarId &&
                    (dropZone === "before" || dropZone === "after")) {
                    if (!editContext.openSidebars.includes(sourceSidebarId)) {
                        editContext.openSidebar(sourceSidebarId, {
                            preserveOpenSidebars: true,
                        });
                    }
                    editContext.stackSidebar(sourceSidebarId, sidebarId, dropZone);
                    setDropZone(null);
                    return;
                }
            }
        }
        finally {
            setDropZone(null);
        }
        // Fall back to existing drop handling (horizontal reordering).
        onDrop?.(e);
    }, [dropZone, editContext, onDrop, sidebarId]);
    const renderHeaderIcon = (icon) => {
        if (!icon)
            return null;
        if (typeof icon === "string") {
            return _jsx("i", { className: cn(icon, "pi mr-1.5 ml-1.5") });
        }
        if (React.isValidElement(icon)) {
            const element = icon;
            return (_jsx("div", { className: "text-neutral-grey-100 mr-2 ml-1.5 shrink-0", children: React.cloneElement(element, {
                    className: cn("size-4", element.props.className),
                    size: element.props.size ?? 16,
                    strokeWidth: element.props.strokeWidth ?? 1.5,
                }) }));
        }
        return _jsx("div", { className: "mr-2 ml-1.5 shrink-0", children: icon });
    };
    const getHeader = (panel, index) => {
        if (panel.header)
            return panel.header({ panel, index });
        const headerIcon = panel.hideHeaderIcon
            ? null
            : (panel.icon ?? sidebar.icon);
        // All sidebars are draggable for stacking; first panel header is the drag handle.
        const isDraggable = !!(index === 0 && sidebarId);
        return (_jsxs("div", { className: cn("border-border-default text-neutral-grey-100 relative flex items-center border-b p-2 text-sm font-medium"), draggable: isDraggable, onDragStart: (e) => {
                if (sidebarId) {
                    e.dataTransfer.setData("text/alpaca-sidebar", sidebarId);
                    e.dataTransfer.effectAllowed = "move";
                }
            }, onDragEnd: () => {
                // Drag end handled by parent
            }, children: [index === 0 && sidebarId && isLocked && !editContext.isMobile && (_jsx("div", { className: "bg-highlight-100 absolute top-0 bottom-0 left-0 w-1" })), renderHeaderIcon(headerIcon), _jsx("div", { className: "min-w-0 flex-1 truncate", children: panel.title }), index === 0 &&
                    sidebarId &&
                    isFirstInStack &&
                    !editContext.isMobile && (_jsx(SimpleIconButton, { onClick: (e) => {
                        e.stopPropagation();
                        editContext.toggleSidebarLock(sidebarId);
                    }, "data-testid": "sidebar-pin-button", icon: isLocked ? (_jsx(PinOff, { size: 14, strokeWidth: 1, absoluteStrokeWidth: true })) : (_jsx(Pin, { size: 14, strokeWidth: 1, absoluteStrokeWidth: true })), label: isLocked
                        ? "Unpin stack (will close when switching)"
                        : "Pin stack open (stays visible)", className: "ml-2" })), index === 0 && (_jsx(CloseButton, { onClick: onClose, label: "Close", className: "ml-2" }))] }));
    };
    // Single panel - no splitter needed
    if (resolvedPanels.length === 1) {
        const panel = resolvedPanels[0];
        if (!panel)
            return _jsx("div", { className: "hidden h-full" });
        return (_jsxs("div", { ref: containerRef, className: cn("relative h-full", detached ? "p-2" : "border-border-default border-r", !active ? "hidden" : "", paddingRight ? "pr-2" : "pr-0"), onDragOver: handlePanelDragOver, onDragLeave: handlePanelDragLeave, onDrop: handlePanelDrop, "data-testid": sidebarId ? `sidebar-panel-${sidebarId}` : undefined, children: [_jsxs("div", { className: cn("flex h-full flex-col bg-white", detached ? "border-border-default rounded-md border" : ""), children: [!panel.hideHeader && getHeader(panel, 0), _jsx("div", { className: "relative flex-1 overflow-hidden", children: _jsx("div", { className: cn("absolute inset-0", panel.noOverflow ? "" : "overflow-y-auto"), children: panel.content }) })] }), sidebarId &&
                    !suppressStackDropZones &&
                    (dropZone === "before" || dropZone === "after") && (_jsx("div", { className: cn("absolute inset-x-0 z-10 flex items-center justify-center", dropZone === "before" ? "top-0" : "bottom-0"), style: { height: "80px" }, onDrop: handlePanelDrop, onDragOver: handlePanelDragOver, children: _jsxs("div", { className: "bg-highlight-100/15 border-highlight-100 pointer-events-none flex h-full w-full items-center justify-center gap-2 border-2 border-dashed", children: [_jsx("svg", { className: "text-highlight-100 size-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2, children: dropZone === "before" ? (_jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 15l7-7 7 7" })) : (_jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19 9l-7 7-7-7" })) }), _jsxs("span", { className: "text-highlight-100 text-xs font-medium", children: ["Drop to stack ", dropZone === "before" ? "above" : "below"] })] }) }))] }));
    }
    // Multiple panels - use existing Splitter component
    const splitterPanels = resolvedPanels.map((panel, index) => ({
        // Use stable names so persisted sizes map correctly per panel
        name: panel.name || `panel-${index}`,
        // Respect each panel's initialSize (treat as proportional weight)
        defaultSize: panel.initialSize ?? 50,
        content: (_jsxs("div", { className: "flex h-full flex-col bg-white", children: [!panel.hideHeader && getHeader(panel, index), _jsx("div", { className: "relative flex-1 overflow-hidden", children: _jsx("div", { className: cn("absolute inset-0", panel.noOverflow ? "" : "overflow-y-auto"), children: panel.content }) })] })),
    }));
    return (_jsxs("div", { ref: containerRef, className: cn("relative h-full", !active ? "hidden" : ""), onDragOver: handlePanelDragOver, onDragLeave: handlePanelDragLeave, onDrop: handlePanelDrop, "data-testid": sidebarId ? `sidebar-panel-${sidebarId}` : undefined, children: [_jsx(Splitter, { panels: splitterPanels, direction: "vertical", 
                // Key per workspace and panel composition to avoid cross-workspace collisions
                localStorageKey: `sidebar-${editContext.workspaceId}-${splitterPanels
                    .map((p) => p.name)
                    .join("-")}`, className: cn(detached ? "p-2" : "border-border-default border-r") }), sidebarId &&
                !suppressStackDropZones &&
                (dropZone === "before" || dropZone === "after") && (_jsx("div", { className: cn("absolute inset-x-0 z-10 flex items-center justify-center", dropZone === "before" ? "top-0" : "bottom-0"), style: { height: "80px" }, onDrop: handlePanelDrop, onDragOver: handlePanelDragOver, children: _jsxs("div", { className: "bg-highlight-100/15 border-highlight-100 pointer-events-none flex h-full w-full items-center justify-center gap-2 border-2 border-dashed", children: [_jsx("svg", { className: "text-highlight-100 size-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2, children: dropZone === "before" ? (_jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 15l7-7 7 7" })) : (_jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M19 9l-7 7-7-7" })) }), _jsxs("span", { className: "text-highlight-100 text-xs font-medium", children: ["Drop to stack ", dropZone === "before" ? "above" : "below"] })] }) }))] }));
}
//# sourceMappingURL=SidebarPanel.js.map