init python:
    def highlight_python(code):
        """Simple Python syntax highlighter"""
        import re
        
        # Define color scheme
        colors = {
            'keywords': '#FF8080',    # Red for keywords
            'strings': '#98FB98',     # Light green for strings
            'comments': '#87CEEB',    # Sky blue for comments
            'numbers': '#DDA0DD',     # Plum for numbers
            'functions': '#FFD700',   # Gold for function names
            'default': '#FFFFFF'      # White for default text
        }
        
        # Python keywords
        keywords = {
            'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
            'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
            'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
            'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
            'while', 'with', 'yield'
        }
        
        # Split the code into lines while preserving empty lines
        lines = code.split('\n')
        highlighted_lines = []
        
        for line in lines:
            if not line.strip():
                highlighted_lines.append('')
                continue
                
            # Handle comments
            if line.strip().startswith('#'):
                highlighted_lines.append('{color=' + colors['comments'] + '}' + line + '{/color}')
                continue
            
            # Process the line
            tokens = []
            current_pos = 0
            line_length = len(line)
            
            while current_pos < line_length:
                char = line[current_pos]
                
                # Handle strings
                if char in '"\'':
                    quote = char
                    string_start = current_pos
                    current_pos += 1
                    while current_pos < line_length and line[current_pos] != quote:
                        current_pos += 1
                    if current_pos < line_length:
                        current_pos += 1
                    string_content = line[string_start:current_pos]
                    tokens.append((string_content, 'strings'))
                    continue
                
                # Handle numbers
                if char.isdigit():
                    num_start = current_pos
                    while current_pos < line_length and (line[current_pos].isdigit() or line[current_pos] == '.'):
                        current_pos += 1
                    num_content = line[num_start:current_pos]
                    tokens.append((num_content, 'numbers'))
                    continue
                
                # Handle words (keywords, functions, etc.)
                if char.isalpha() or char == '_':
                    word_start = current_pos
                    while current_pos < line_length and (line[current_pos].isalnum() or line[current_pos] == '_'):
                        current_pos += 1
                    word = line[word_start:current_pos]
                    
                    if word in keywords:
                        tokens.append((word, 'keywords'))
                    elif current_pos < line_length and line[current_pos] == '(':
                        tokens.append((word, 'functions'))
                    else:
                        tokens.append((word, 'default'))
                    continue
                
                # Handle other characters
                tokens.append((char, 'default'))
                current_pos += 1
            
            # Build the highlighted line
            highlighted_line = ''
            current_color = None
            
            for token, token_type in tokens:
                color = colors[token_type]
                if color != current_color:
                    if current_color is not None:
                        highlighted_line += '{/color}'
                    highlighted_line += '{color=' + color + '}'
                    current_color = color
                highlighted_line += token
            
            if current_color is not None:
                highlighted_line += '{/color}'
            
            highlighted_lines.append(highlighted_line)
        
        return '\n'.join(highlighted_lines)

    # Simple pin state for the code panel. Stored in the Python store so screens can access it.
    code_panel_pinned = False

    def pin_code_panel():
        global code_panel_pinned
        code_panel_pinned = True

    def unpin_code_panel():
        global code_panel_pinned
        code_panel_pinned = False

    def copy_to_clipboard(text):
        """Copy `text` to the system clipboard. Uses renpy.clipboard when available, falls back to pbcopy on macOS."""
        try:
            # Prefer Ren'Py clipboard API when available
            renpy.clipboard.set(text)
            renpy.notify("Code copied to clipboard")
            return
        except Exception:
            pass

        # Fallbacks for common platforms: macOS (pbcopy), Windows (clip), Linux (xclip/xsel)
        try:
            import subprocess
            # macOS
            p = subprocess.Popen(["pbcopy"], stdin=subprocess.PIPE)
            p.communicate(text.encode('utf-8'))
            renpy.notify("Code copied to clipboard")
            return
        except Exception:
            pass

        try:
            import subprocess
            # Windows
            p = subprocess.Popen(["clip"], stdin=subprocess.PIPE, shell=True)
            p.communicate(text.encode('utf-8'))
            renpy.notify("Code copied to clipboard")
            return
        except Exception:
            pass

        try:
            import subprocess
            # Linux with xclip
            p = subprocess.Popen(["xclip", "-selection", "clipboard"], stdin=subprocess.PIPE)
            p.communicate(text.encode('utf-8'))
            renpy.notify("Code copied to clipboard")
            return
        except Exception:
            pass

        try:
            import subprocess
            # Linux with xsel
            p = subprocess.Popen(["xsel", "--clipboard", "--input"], stdin=subprocess.PIPE)
            p.communicate(text.encode('utf-8'))
            renpy.notify("Code copied to clipboard")
            return
        except Exception:
            renpy.notify("Copy to clipboard failed")

style code_frame:
    background "#000000"  # Dark background like VS Code
    padding (80, 80)
    xsize None
    ysize None
    xalign 0.0
    yalign 0.4

style code_text:
    size 54
    color "#FFFFFF"
    xalign 0.0
    text_align 0.0

screen show_code(code_text):
    zorder 100  # Ensure it appears above other elements
    modal False  # Block interaction with elements behind
    frame:
        style "code_frame"
        vbox:
            spacing 10
            # Code content
            frame:
                background "#252526"  # Slightly lighter than the main background
                padding (10, 10)
                xalign 0.5
                yalign 0.5
                text highlight_python(code_text) style "code_text"
            # Copy button (copies the displayed code to clipboard)
            $ copyable_code = code_text.replace('{{', '{').replace('}}', '}')
            textbutton "Copy" action Function(copy_to_clipboard, copyable_code) xalign 0.5 style "menu_button"

screen show_code_panel(code_text):
    """Non-modal right-side panel for showing code. Pin state is stored in `code_panel_pinned`."""
    zorder 90
    modal False

    # Position on the right side of the screen
    frame:
        background Frame("gui/frame.png", gui.frame_borders, gui.frame_tile)
        padding (10, 10)
        xmaximum 760
        xalign 0.98
        yalign 0.15
        vbox:
            spacing 8
            hbox:
                spacing 10
                text "Code Example" style "menu_header_text" xalign 0.0
                null
                if not code_panel_pinned:
                    textbutton "Pin" action Function(pin_code_panel) style "menu_button"
                else:
                    textbutton "Unpin" action Function(unpin_code_panel) style "menu_button"
                textbutton "Close" action Hide("show_code_panel") style "menu_button"

            frame:
                background "#252526"
                padding (8, 8)
                # Scrollable viewport for long code
                viewport id "code_viewport" mousewheel True draggable True:
                    vbox:
                        text highlight_python(code_text) style "code_text"
                        null height 8

            if code_panel_pinned:
                text "Pinned: this panel will stay open." xalign 0.0

# Test the code display
label test_code_display:
    # Example usage
    $ test_code = """
def calculate_fibonacci(n):
    # Initialize first two numbers
    a, b = 0, 1
    
    # Loop n times
    for _ in range(n):
        # Print current number
        print(a)
        # Calculate next number
        a, b = b, a + b

# Test with first 10 numbers
calculate_fibonacci(10)
"""
    call screen show_code(test_code)
    return

## Very simple, robust code panel
screen code_panel_simple(code_text):
    zorder 10
    modal False
    frame:
        background "#222"
        padding (8, 8)
        xalign 0.0
        yalign 0.0
        text code_text style "code_text"