// HTML混合模式（支持内嵌PHP/JS/CSS）
CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
    const htmlMode = CodeMirror.getMode(config, {
        name: "xml",
        htmlMode: true,
        multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
        multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
    });

    return {
        startState: function() {
            return {
                htmlState: CodeMirror.startState(htmlMode),
                phpState: null,
                jsState: null,
                cssState: null,
                inTag: false
            };
        },
        copyState: function(state) {
            return {
                htmlState: CodeMirror.copyState(htmlMode, state.htmlState),
                phpState: state.phpState && CodeMirror.copyState(phpMode, state.phpState),
                jsState: state.jsState && CodeMirror.copyState(jsMode, state.jsState),
                cssState: state.cssState && CodeMirror.copyState(cssMode, state.cssState),
                inTag: state.inTag
            };
        },
        token: function(stream, state) {
            // 处理PHP代码块
            if (stream.match("<?php")) {
                state.phpState = CodeMirror.startState(phpMode);
                return "keyword";
            }
            if (state.phpState) {
                if (stream.match("?>")) {
                    state.phpState = null;
                    return "keyword";
                }
                return phpMode.token(stream, state.phpState);
            }

            // 处理HTML标签内的脚本和样式
            if (state.inTag) {
                if (stream.match(/^\/\//)) {
                    stream.skipToEnd();
                    return "comment";
                }
                if (stream.match(/^\/\*/)) {
                    state.inComment = true;
                    return "comment";
                }
                if (state.inComment) {
                    if (stream.match(/\*\//)) {
                        state.inComment = false;
                        return "comment";
                    }
                    stream.skipToEnd();
                    return "comment";
                }
            }

            // 默认HTML处理
            return htmlMode.token(stream, state.htmlState);
        },
        indent: function(state, textAfter, line) {
            if (state.phpState) return phpMode.indent(state.phpState, textAfter, line);
            return htmlMode.indent(state.htmlState, textAfter, line);
        }
    };
});

// 注册HTML模式
CodeMirror.defineMIME("text/html", "htmlmixed");