class GistEditor {
    constructor(textareaId, langSelectId) {
        this.editor = null;
        this.initialized = false;
        this.textareaId = textareaId || "gist-source-editor";
        this.langSelectId = langSelectId || "gist-language";
    }

    init() {
        if (this.initialized) return;
        if (typeof CodeMirror === "undefined") return;

        const textarea = document.getElementById(this.textareaId);
        if (!textarea) return;
        this.initialized = true;

        this.editor = CodeMirror.fromTextArea(textarea, {
            lineNumbers: true,
            mode: textarea.dataset.language || "plaintext",
            theme: "monokai",
            indentUnit: 4,
            tabSize: 4,
            lineWrapping: true,
            extraKeys: {
                "Ctrl-S": () => {
                    const form = textarea.closest("form");
                    if (form) {
                        this.editor.save();
                        form.submit();
                    }
                },
            },
        });

        this.editor.setSize(null, 400);

        const langSelect = document.getElementById(this.langSelectId);
        if (langSelect) {
            langSelect.addEventListener("change", () => {
                let mode = langSelect.value;
                const modeMap = {
                    "c": "text/x-csrc",
                    "cpp": "text/x-c++src",
                    "java": "text/x-java",
                    "bash": "text/x-sh",
                    "ruby": "text/x-ruby",
                    "php": "text/x-php",
                    "perl": "text/x-perl",
                    "haskell": "text/x-haskell",
                    "lua": "text/x-lua",
                    "elixir": "text/x-elixir",
                    "dart": "text/x-dart",
                    "r": "text/x-rsrc",
                    "scala": "text/x-scala",
                };
                this.editor.setOption("mode", modeMap[mode] || mode);
            });
        }

        const form = textarea.closest("form");
        if (form) {
            form.addEventListener("submit", () => {
                this.editor.save();
            });
        }
    }

    refresh() {
        if (this.editor) {
            setTimeout(() => this.editor.refresh(), 100);
        }
    }
}
window.GistEditor = GistEditor;
