-- Lua Mode for Lumacs
-- Extracted from init.lua

define_major_mode("lua-mode", {
    file_patterns = {"%.lua$"},
    comment_syntax = "--",

    highlight = function()
        local buf = editor.buffer
        buf:clear_styles()

        -- Keywords to highlight
        local keywords = {
            "function", "local", "end", "if", "then", "else", "elseif",
            "for", "while", "do", "return", "break", "and", "or", "not",
            "true", "false", "nil", "in", "repeat", "until"
        }

        -- Highlight each line
        for line_num = 0, buf:line_count() - 1 do
            local line_text = buf:line(line_num)

            -- Highlight keywords
            for _, keyword in ipairs(keywords) do
                local start_pos = 1
                while true do
                    local pattern = "%f[%w]" .. keyword .. "%f[%W]"
                    local pos = string.find(line_text, pattern, start_pos)
                    if not pos then break end

                    local range = lumacs.Range(
                        lumacs.Position(line_num, pos - 1),
                        lumacs.Position(line_num, pos + #keyword - 1)
                    )

                    buf:set_style(range, lumacs.TextAttribute(lumacs.ColorType.Keyword, 0))
                    start_pos = pos + #keyword
                end
            end

            -- Highlight strings
            local start_pos = 1
            while true do
                local quote_start = string.find(line_text, '"', start_pos, true)
                if not quote_start then break end

                local quote_end = string.find(line_text, '"', quote_start + 1, true)
                if not quote_end then break end

                local range = lumacs.Range(
                    lumacs.Position(line_num, quote_start - 1),
                    lumacs.Position(line_num, quote_end)
                )

                buf:set_style(range, lumacs.TextAttribute(lumacs.ColorType.String, 0))
                start_pos = quote_end + 1
            end

            -- Highlight comments
            local comment_pos = string.find(line_text, "--", 1, true)
            if comment_pos then
                local range = lumacs.Range(
                    lumacs.Position(line_num, comment_pos - 1),
                    lumacs.Position(line_num, #line_text)
                )

                buf:set_style(range, lumacs.TextAttribute(lumacs.ColorType.Comment, 0))
            end
        end
    end,

    setup = function()
        editor:message("[lua-mode] Lua mode activated")
    end,

    cleanup = function()
        editor:message("[lua-mode] Lua mode deactivated")
    end,

    keybindings = {
        -- Lua-specific keybindings can go here
    }
})