function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { Info } from "@sofa-design/icons";
import { ConfigProvider } from "antd";
import classNames from "clsx";
import isHotkey from "is-hotkey";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import ReactDOM from "react-dom";
import { Editor, Transforms } from "slate";
import { ReactEditor } from "slate-react";
import { useLocale } from "../../../../I18n";
import { useEditorStore } from "../../store";
import { getOffsetLeft } from "../../utils/dom";
import { EditorUtils } from "../../utils/editorUtils";
import { JINJA_PANEL_PREFIX_CLS, useJinjaTemplatePanelStyle } from "./style";
import { getJinjaTemplateData, JINJA_DOC_LINK } from "./templates";
var PANEL_MAX_HEIGHT = 320;
function getPosition(nodeEl) {
    var rect = nodeEl.getBoundingClientRect();
    var left = getOffsetLeft(nodeEl, document.body) + 0;
    var top = rect.bottom + window.scrollY;
    var viewportHeight = document.documentElement.clientHeight;
    var spaceBelow = viewportHeight - rect.bottom;
    if (spaceBelow < PANEL_MAX_HEIGHT && rect.top > PANEL_MAX_HEIGHT) {
        return {
            left: left,
            bottom: viewportHeight - rect.top
        };
    }
    return {
        left: left,
        top: top
    };
}
export var JinjaTemplatePanel = function JinjaTemplatePanel() {
    var _ref, _ref1, _ref2, _ref3;
    var _context_getPrefixCls;
    var _useEditorStore = useEditorStore(), markdownEditorRef = _useEditorStore.markdownEditorRef, markdownContainerRef = _useEditorStore.markdownContainerRef, openJinjaTemplate = _useEditorStore.openJinjaTemplate, setOpenJinjaTemplate = _useEditorStore.setOpenJinjaTemplate, jinjaAnchorPath = _useEditorStore.jinjaAnchorPath, setJinjaAnchorPath = _useEditorStore.setJinjaAnchorPath, editorProps = _useEditorStore.editorProps;
    var jinjaConfig = editorProps === null || editorProps === void 0 ? void 0 : editorProps.jinja;
    var templatePanelConfig = (jinjaConfig === null || jinjaConfig === void 0 ? void 0 : jinjaConfig.templatePanel) && _type_of(jinjaConfig.templatePanel) === 'object' ? jinjaConfig.templatePanel : undefined;
    var trigger = (_ref = templatePanelConfig === null || templatePanelConfig === void 0 ? void 0 : templatePanelConfig.trigger) !== null && _ref !== void 0 ? _ref : '{}';
    var docLink = (_ref1 = jinjaConfig === null || jinjaConfig === void 0 ? void 0 : jinjaConfig.docLink) !== null && _ref1 !== void 0 ? _ref1 : JINJA_DOC_LINK;
    var notFoundContent = (_ref2 = templatePanelConfig === null || templatePanelConfig === void 0 ? void 0 : templatePanelConfig.notFoundContent) !== null && _ref2 !== void 0 ? _ref2 : null;
    var itemsConfig = templatePanelConfig === null || templatePanelConfig === void 0 ? void 0 : templatePanelConfig.items;
    var locale = useLocale();
    var defaultItems = useMemo(function() {
        return getJinjaTemplateData(locale);
    }, [
        locale
    ]);
    var _useState = _sliced_to_array(useState(defaultItems), 2), items = _useState[0], setItems = _useState[1];
    var _useState1 = _sliced_to_array(useState(false), 2), loading = _useState1[0], setLoading = _useState1[1];
    var _useState2 = _sliced_to_array(useState(0), 2), activeIndex = _useState2[0], setActiveIndex = _useState2[1];
    var _useState3 = _sliced_to_array(useState({
        left: 0
    }), 2), position = _useState3[0], setPosition = _useState3[1];
    var domRef = useRef(null);
    var context = React.useContext(ConfigProvider.ConfigContext);
    var prefixCls = (_ref3 = context === null || context === void 0 ? void 0 : (_context_getPrefixCls = context.getPrefixCls) === null || _context_getPrefixCls === void 0 ? void 0 : _context_getPrefixCls.call(context, 'agentic-md-editor-jinja-panel')) !== null && _ref3 !== void 0 ? _ref3 : JINJA_PANEL_PREFIX_CLS;
    var _useJinjaTemplatePanelStyle = useJinjaTemplatePanelStyle(prefixCls), wrapSSR = _useJinjaTemplatePanelStyle.wrapSSR, hashId = _useJinjaTemplatePanelStyle.hashId;
    var close = useCallback(function() {
        setOpenJinjaTemplate === null || setOpenJinjaTemplate === void 0 ? void 0 : setOpenJinjaTemplate(false);
        setJinjaAnchorPath === null || setJinjaAnchorPath === void 0 ? void 0 : setJinjaAnchorPath(null);
        setActiveIndex(0);
    }, [
        setOpenJinjaTemplate,
        setJinjaAnchorPath
    ]);
    var handleClickOutside = useCallback(function(e) {
        var target = e.target;
        if (domRef.current && !domRef.current.contains(target)) {
            close();
        }
    }, [
        close
    ]);
    useEffect(function() {
        if (!openJinjaTemplate) return;
        if (typeof itemsConfig === 'function') {
            setLoading(true);
            var editor = markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : markdownEditorRef.current;
            itemsConfig({
                editor: editor
            }).then(function(list) {
                setItems(Array.isArray(list) ? list : defaultItems);
            }).catch(function(err) {
                setItems(defaultItems);
                if (process.env.NODE_ENV !== 'production') {
                    console.error('[JinjaTemplatePanel] Failed to load template items:', err);
                }
            }).finally(function() {
                return setLoading(false);
            });
        } else if (Array.isArray(itemsConfig)) {
            setItems(itemsConfig);
        } else {
            setItems(defaultItems);
        }
    }, [
        openJinjaTemplate,
        itemsConfig,
        markdownEditorRef,
        defaultItems
    ]);
    useEffect(function() {
        if (!openJinjaTemplate || !jinjaAnchorPath || !(markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : markdownEditorRef.current)) return;
        var editor = markdownEditorRef.current;
        try {
            var _Editor_node = _sliced_to_array(Editor.node(editor, jinjaAnchorPath), 1), node = _Editor_node[0];
            if (node) {
                var el = ReactEditor.toDOMNode(editor, node);
                if (el) {
                    var pos = getPosition(el);
                    setPosition(pos);
                }
            }
        } catch (unused) {
            setPosition({
                left: 0
            });
        }
    }, [
        openJinjaTemplate,
        jinjaAnchorPath,
        markdownEditorRef
    ]);
    useEffect(function() {
        if (!openJinjaTemplate) return;
        if (typeof window === 'undefined') return;
        window.addEventListener('click', handleClickOutside);
        return function() {
            return window.removeEventListener('click', handleClickOutside);
        };
    }, [
        openJinjaTemplate,
        handleClickOutside
    ]);
    var insertTemplate = useCallback(function(item) {
        var editor = markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : markdownEditorRef.current;
        if (!editor || !jinjaAnchorPath || !setOpenJinjaTemplate) return;
        try {
            var _Editor_before;
            var end = Editor.end(editor, jinjaAnchorPath);
            var start = (_Editor_before = Editor.before(editor, end, {
                distance: trigger.length
            })) !== null && _Editor_before !== void 0 ? _Editor_before : end;
            Transforms.delete(editor, {
                at: {
                    anchor: start,
                    focus: end
                }
            });
            Transforms.insertText(editor, item.template, {
                at: start
            });
            EditorUtils.focus(editor);
        } finally{
            close();
        }
    }, [
        markdownEditorRef,
        jinjaAnchorPath,
        trigger.length,
        setOpenJinjaTemplate,
        close
    ]);
    var keydown = useCallback(function(e) {
        if (!openJinjaTemplate) return;
        if (isHotkey('esc', e)) {
            e.preventDefault();
            close();
            EditorUtils.focus(markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : markdownEditorRef.current);
            return;
        }
        if (e.key === 'ArrowUp') {
            e.preventDefault();
            setActiveIndex(function(i) {
                return i > 0 ? i - 1 : items.length - 1;
            });
            return;
        }
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            setActiveIndex(function(i) {
                return i < items.length - 1 ? i + 1 : 0;
            });
            return;
        }
        if (e.key === 'Enter' && items[activeIndex]) {
            e.preventDefault();
            e.stopPropagation();
            insertTemplate(items[activeIndex]);
        }
    }, [
        openJinjaTemplate,
        close,
        markdownEditorRef,
        items,
        activeIndex,
        insertTemplate
    ]);
    useEffect(function() {
        var container = markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : markdownContainerRef.current;
        if (!container) return;
        container.addEventListener('keydown', keydown);
        return function() {
            return container.removeEventListener('keydown', keydown);
        };
    }, [
        markdownContainerRef,
        keydown
    ]);
    useEffect(function() {
        setActiveIndex(0);
    }, [
        items
    ]);
    if (!openJinjaTemplate) return null;
    var panel = wrapSSR(/*#__PURE__*/ React.createElement("div", {
        ref: domRef,
        role: "listbox",
        "aria-label": "Jinja template list",
        className: classNames(prefixCls, hashId),
        style: {
            position: 'absolute',
            zIndex: 9999,
            left: position.left,
            top: position.top,
            bottom: position.bottom
        },
        onMouseDown: function onMouseDown(e) {
            return e.preventDefault();
        }
    }, /*#__PURE__*/ React.createElement("div", {
        className: "".concat(prefixCls, "-content")
    }, /*#__PURE__*/ React.createElement("div", {
        className: "".concat(prefixCls, "-header")
    }, /*#__PURE__*/ React.createElement("div", {
        className: "".concat(prefixCls, "-title")
    }, locale['jinja.panel.title']), docLink ? /*#__PURE__*/ React.createElement("div", {
        className: "".concat(prefixCls, "-doc-link"),
        onClick: function onClick(e) {
            e.preventDefault();
            window.open(docLink, '_blank');
        }
    }, /*#__PURE__*/ React.createElement(Info, null), locale['jinja.panel.docLink']) : null), /*#__PURE__*/ React.createElement("div", {
        className: "".concat(prefixCls, "-list-box")
    }, loading ? /*#__PURE__*/ React.createElement("div", {
        style: {
            padding: 12,
            color: 'var(--color-text-secondary)'
        }
    }, locale.loading) : items.length === 0 ? notFoundContent !== null && notFoundContent !== void 0 ? notFoundContent : /*#__PURE__*/ React.createElement("div", {
        style: {
            padding: 12,
            color: 'var(--color-text-secondary)'
        }
    }, locale['jinja.panel.noTemplates']) : items.map(function(item, i) {
        return /*#__PURE__*/ React.createElement("div", {
            key: i,
            role: "option",
            "aria-selected": i === activeIndex,
            className: classNames("".concat(prefixCls, "-item"), _define_property({}, "".concat(prefixCls, "-item-active"), i === activeIndex)),
            onMouseDown: function onMouseDown(e) {
                e.preventDefault();
                insertTemplate(item);
            },
            onMouseEnter: function onMouseEnter() {
                return setActiveIndex(i);
            }
        }, /*#__PURE__*/ React.createElement("span", {
            className: "".concat(prefixCls, "-item-title")
        }, item.title), item.description ? /*#__PURE__*/ React.createElement("span", {
            className: "".concat(prefixCls, "-item-desc")
        }, item.description) : null);
    })))));
    return /*#__PURE__*/ ReactDOM.createPortal(panel, document.body);
};
