"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CnDragTab = void 0;
const React = __importStar(require("react"));
const react_1 = require("react");
const react_dom_1 = require("react-dom");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const core_1 = require("@dnd-kit/core");
const sortable_1 = require("@dnd-kit/sortable");
const classnames_1 = __importDefault(require("classnames"));
require("./cn-drag-tab.scss");
const SortableTabWrapper = ({ id, children }) => {
    const { attributes, listeners, setNodeRef, isDragging } = (0, sortable_1.useSortable)({ id });
    return (React.createElement("div", { ref: setNodeRef, className: (0, classnames_1.default)('cn-drag-tab__sortable-wrapper', {
            'cn-drag-tab__sortable-wrapper--dragging': isDragging,
        }), ...attributes, ...listeners }, children));
};
SortableTabWrapper.displayName = 'SortableTabWrapper';
/**
 * Portal wrapper: renders DragOverlay into document.body to escape
 * ancestors with `filter: blur(0px)` (e.g. cn-ui-page) which create
 * a containing block that breaks `position: fixed` overlay positioning.
 */
function PortaledDragOverlay({ children, ...props }) {
    return (0, react_dom_1.createPortal)(React.createElement(core_1.DragOverlay, { ...props }, children), document.body);
}
const TabContent = ({ icon, title, closeable, onClose }) => {
    const handleClose = (e) => {
        e.stopPropagation();
        onClose === null || onClose === void 0 ? void 0 : onClose();
    };
    return (React.createElement("div", { className: "cn-next-tabs-tab-inner" },
        React.createElement("div", { className: "cn-ui-tab-inner-sub cn-ui-tab-inner-sub-left" }),
        React.createElement("div", { className: "cn-ui-tab-inner-sub cn-ui-tab-inner-sub-right" }),
        icon,
        title,
        closeable && (React.createElement(cn_ui_1.CnIcon, { outerClassName: "cn-next-tabs-tab-close", size: "small", type: "close", onClick: handleClose }))));
};
TabContent.displayName = 'TabContent';
const CnDragTab = (props) => {
    var _a, _b;
    const { items, onDragStart: onDragStartProp, onDragOver: onDragOverProp, onDragCancel: onDragCancelProp, onDragEnd, disableDrag = false, className, activeKey: controlledActiveKey, defaultActiveKey, onChange, ...restTabProps } = props;
    const isControlled = controlledActiveKey !== undefined;
    const [internalActiveKey, setInternalActiveKey] = (0, react_1.useState)(String((_b = defaultActiveKey !== null && defaultActiveKey !== void 0 ? defaultActiveKey : (_a = items[0]) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : ''));
    const [draggingItem, setDraggingItem] = (0, react_1.useState)(null);
    // 非受控模式：items 变化时，若当前 activeKey 不再存在则回退到首项
    (0, react_1.useEffect)(() => {
        if (isControlled)
            return;
        const currentKeyExists = items.some((item) => String(item.key) === internalActiveKey);
        if (!currentKeyExists && items.length > 0) {
            const fallbackKey = String(items[0].key);
            setInternalActiveKey(fallbackKey);
            onChange === null || onChange === void 0 ? void 0 : onChange(fallbackKey);
        }
    }, [items, isControlled, internalActiveKey, onChange]);
    const activeKey = isControlled ? String(controlledActiveKey) : internalActiveKey;
    const handleTabChange = (0, react_1.useCallback)((key) => {
        const normalized = String(key);
        if (!isControlled) {
            setInternalActiveKey(normalized);
        }
        onChange === null || onChange === void 0 ? void 0 : onChange(normalized);
    }, [isControlled, onChange]);
    const sensors = (0, core_1.useSensors)((0, core_1.useSensor)(core_1.PointerSensor, {
        activationConstraint: {
            distance: 5,
        },
    }), (0, core_1.useSensor)(core_1.KeyboardSensor, {
        coordinateGetter: sortable_1.sortableKeyboardCoordinates,
    }));
    const itemKeys = (0, react_1.useMemo)(() => items.filter((item) => !item.disableDrag).map((item) => String(item.key)), [items]);
    const itemMap = (0, react_1.useMemo)(() => {
        const map = new Map();
        items.forEach((item) => map.set(String(item.key), item));
        return map;
    }, [items]);
    const handleDragStart = (0, react_1.useCallback)((event) => {
        const { active } = event;
        const item = itemMap.get(String(active.id));
        setDraggingItem(item || null);
        onDragStartProp === null || onDragStartProp === void 0 ? void 0 : onDragStartProp(event);
    }, [itemMap, onDragStartProp]);
    const handleDragOver = (0, react_1.useCallback)((event) => {
        onDragOverProp === null || onDragOverProp === void 0 ? void 0 : onDragOverProp(event);
    }, [onDragOverProp]);
    const handleDragCancel = (0, react_1.useCallback)(() => {
        setDraggingItem(null);
        onDragCancelProp === null || onDragCancelProp === void 0 ? void 0 : onDragCancelProp();
    }, [onDragCancelProp]);
    const handleDragEnd = (0, react_1.useCallback)((event) => {
        const { active, over } = event;
        setDraggingItem(null);
        if (!over || active.id === over.id) {
            return;
        }
        const dragActiveKey = String(active.id);
        const overKey = String(over.id);
        const oldIndex = items.findIndex((item) => String(item.key) === dragActiveKey);
        const newIndex = items.findIndex((item) => String(item.key) === overKey);
        if (oldIndex === -1 || newIndex === -1) {
            return;
        }
        const newItems = (0, sortable_1.arrayMove)(items, oldIndex, newIndex);
        onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd({
            activeKey: dragActiveKey,
            overKey,
            oldIndex,
            newIndex,
            newItems,
        });
    }, [items, onDragEnd]);
    const draggableTabRender = (0, react_1.useCallback)((key, tabProps) => {
        const normalizedKey = String(key);
        const item = itemMap.get(normalizedKey);
        const { icon, title, closeable, onClose } = tabProps;
        if (item === null || item === void 0 ? void 0 : item.disableDrag) {
            return (React.createElement(TabContent, { icon: icon, title: title, closeable: closeable, onClose: () => onClose === null || onClose === void 0 ? void 0 : onClose(normalizedKey) }));
        }
        return (React.createElement(SortableTabWrapper, { id: normalizedKey },
            React.createElement(TabContent, { icon: icon, title: title, closeable: closeable, onClose: () => onClose === null || onClose === void 0 ? void 0 : onClose(normalizedKey) })));
    }, [itemMap]);
    const tabItemNodes = (0, react_1.useMemo)(() => items.map((item) => (React.createElement(cn_ui_1.CnTabItem, { key: item.key, title: item.title, disabled: item.disabled, closeable: item.closeable, icon: item.icon, ...item.tabItemProps }, item.children))), [items]);
    if (disableDrag) {
        return (React.createElement(cn_ui_1.CnTab, { ...restTabProps, className: (0, classnames_1.default)('cn-drag-tab', className), activeKey: activeKey, onChange: handleTabChange }, tabItemNodes));
    }
    return (React.createElement("div", { className: "cn-drag-tab-container" },
        React.createElement(core_1.DndContext, { sensors: sensors, collisionDetection: core_1.closestCenter, onDragStart: handleDragStart, onDragOver: handleDragOver, onDragCancel: handleDragCancel, onDragEnd: handleDragEnd },
            React.createElement(sortable_1.SortableContext, { items: itemKeys, strategy: sortable_1.horizontalListSortingStrategy },
                React.createElement(cn_ui_1.CnTab, { ...restTabProps, className: (0, classnames_1.default)('cn-drag-tab', className), activeKey: activeKey, onChange: handleTabChange, tabRender: draggableTabRender }, tabItemNodes)),
            React.createElement(PortaledDragOverlay, { dropAnimation: null }, draggingItem && (React.createElement("div", { className: "cn-drag-tab__overlay" },
                React.createElement(TabContent, { icon: draggingItem.icon, title: draggingItem.title })))))));
};
exports.CnDragTab = CnDragTab;
exports.CnDragTab.displayName = 'CnDragTab';
