"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeModal = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const path_browserify_1 = __importDefault(require("path-browserify"));
// Import PatternFly components
const react_code_editor_1 = require("@patternfly/react-code-editor");
const react_core_1 = require("@patternfly/react-core");
const FileDetails_1 = __importStar(require("../FileDetails"));
const Chatbot_1 = require("../Chatbot");
const ChatbotModal_1 = __importDefault(require("../ChatbotModal/ChatbotModal"));
// Try to lazy load - some consumers need to be below a certain bundle size, but can't use the CDN and don't have webpack
let monacoInstance = null;
const loadMonaco = () => __awaiter(void 0, void 0, void 0, function* () {
    if (!monacoInstance) {
        const [monaco, { loader }] = yield Promise.all([Promise.resolve().then(() => __importStar(require('monaco-editor'))), Promise.resolve().then(() => __importStar(require('@monaco-editor/react')))]);
        monacoInstance = monaco;
        loader.config({ monaco });
    }
    return monacoInstance;
});
const CodeModal = (_a) => {
    var { fileName, code, codeEditorControlClassName: codeEditorClassName, handleModalToggle, isCopyEnabled, isLineNumbersVisible, isModalOpen, isReadOnly, onPrimaryAction, onSecondaryAction, primaryActionBtn, secondaryActionBtn, title, displayMode = Chatbot_1.ChatbotDisplayMode.default, isCompact, modalHeaderClassName, modalBodyClassName, modalFooterClassName, spinnerAriaLabel = 'Loading' } = _a, props = __rest(_a, ["fileName", "code", "codeEditorControlClassName", "handleModalToggle", "isCopyEnabled", "isLineNumbersVisible", "isModalOpen", "isReadOnly", "onPrimaryAction", "onSecondaryAction", "primaryActionBtn", "secondaryActionBtn", "title", "displayMode", "isCompact", "modalHeaderClassName", "modalBodyClassName", "modalFooterClassName", "spinnerAriaLabel"]);
    const [newCode, setNewCode] = (0, react_1.useState)(code);
    const [editorInstance, setEditorInstance] = (0, react_1.useState)(null);
    const [isEditorReady, setIsEditorReady] = (0, react_1.useState)(false);
    const [isMonacoLoading, setIsMonacoLoading] = (0, react_1.useState)(false);
    const [isMonacoLoaded, setIsMonacoLoaded] = (0, react_1.useState)(false);
    const containerRef = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        if (isModalOpen && !isMonacoLoaded && !isMonacoLoading) {
            setIsMonacoLoading(true);
            loadMonaco()
                .then(() => {
                setIsMonacoLoaded(true);
                setIsMonacoLoading(false);
            })
                .catch((error) => {
                // eslint-disable-next-line no-console
                console.error('Failed to load Monaco editor:', error);
                setIsMonacoLoading(false);
            });
        }
    }, [isModalOpen, isMonacoLoaded, isMonacoLoading]);
    (0, react_1.useEffect)(() => {
        if (!isModalOpen || !isEditorReady || !editorInstance || !containerRef.current) {
            return;
        }
        const handleResize = () => {
            if (editorInstance && isEditorReady && isModalOpen) {
                try {
                    window.requestAnimationFrame(() => {
                        editorInstance.layout();
                    });
                }
                catch (error) {
                    // eslint-disable-next-line no-console
                    console.error('ChatBot code modal layout error:', error);
                }
            }
        };
        const observer = (0, react_core_1.getResizeObserver)(containerRef.current, handleResize);
        return () => {
            observer();
        };
    }, [editorInstance, isEditorReady, isModalOpen]);
    const handlePrimaryAction = (_event) => {
        handleModalToggle(_event);
        if (!isReadOnly) {
            onPrimaryAction(_event, newCode);
        }
        else {
            onPrimaryAction(_event);
        }
    };
    const handleSecondaryAction = (_event) => {
        handleModalToggle(_event);
        onSecondaryAction(_event);
    };
    const onEditorDidMount = (editor, monaco) => {
        setEditorInstance(editor);
        monaco.editor.getModels()[0].updateOptions({ tabSize: 5 });
        if (containerRef.current) {
            setIsEditorReady(true);
            editor.layout();
            editor.focus();
        }
    };
    const onCodeChange = (value) => {
        if (!isReadOnly) {
            setNewCode(value);
        }
    };
    const renderMonacoEditor = () => {
        if (isMonacoLoading) {
            return ((0, jsx_runtime_1.jsx)(react_core_1.Bullseye, { children: (0, jsx_runtime_1.jsx)(react_core_1.Spinner, { "aria-label": spinnerAriaLabel }) }));
        }
        if (isMonacoLoaded) {
            return ((0, jsx_runtime_1.jsx)(react_code_editor_1.CodeEditor, Object.assign({ isDarkTheme: true, isLineNumbersVisible: isLineNumbersVisible, isLanguageLabelVisible: true, isCopyEnabled: isCopyEnabled, isReadOnly: isReadOnly, code: newCode, language: FileDetails_1.extensionToLanguage[path_browserify_1.default.extname(fileName).slice(1)], onEditorDidMount: onEditorDidMount, onCodeChange: onCodeChange, className: codeEditorClassName, isFullHeight: true, options: {
                    glyphMargin: false,
                    folding: false,
                    // prevents Monaco from handling resizing itself
                    // was causing ResizeObserver issues
                    automaticLayout: false
                } }, props)));
        }
        return null;
    };
    const modal = ((0, jsx_runtime_1.jsxs)(ChatbotModal_1.default, { isOpen: isModalOpen, onClose: handleModalToggle, ouiaId: "CodeModal", "aria-labelledby": "code-modal-title", "aria-describedby": "code-modal", className: `pf-chatbot__code-modal ${isCompact ? 'pf-m-compact' : ''} pf-chatbot__code-modal--${displayMode}`, displayMode: displayMode, isCompact: isCompact, children: [(0, jsx_runtime_1.jsx)(react_core_1.ModalHeader, { className: modalHeaderClassName, title: title, labelId: "code-modal-title" }), (0, jsx_runtime_1.jsx)(react_core_1.ModalBody, { className: modalBodyClassName, id: "code-modal-body", children: (0, jsx_runtime_1.jsxs)(react_core_1.Stack, { className: "pf-chatbot__code-modal-body", children: [(0, jsx_runtime_1.jsx)(react_core_1.StackItem, { className: "pf-chatbot__code-modal-file-details", children: (0, jsx_runtime_1.jsx)(FileDetails_1.default, { fileName: fileName }) }), (0, jsx_runtime_1.jsx)("div", { className: "pf-v6-l-stack__item pf-chatbot__code-modal-editor", ref: containerRef, children: renderMonacoEditor() })] }) }), (0, jsx_runtime_1.jsxs)(react_core_1.ModalFooter, { className: modalFooterClassName, children: [(0, jsx_runtime_1.jsx)(react_core_1.Button, { isBlock: true, variant: "primary", onClick: handlePrimaryAction, form: "code-modal-form", children: primaryActionBtn }, "code-modal-primary"), (0, jsx_runtime_1.jsx)(react_core_1.Button, { isBlock: true, variant: "link", onClick: handleSecondaryAction, children: secondaryActionBtn }, "code-modal-secondary")] })] }));
    return modal;
};
exports.CodeModal = CodeModal;
exports.default = exports.CodeModal;
