import math
import random
import time
import threading
import json
import traceback
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import sys
import ctypes
import copy
import os
import logging
from logging.handlers import RotatingFileHandler
import tkinter.font as tkfont
import mido
from collections import deque

APP_VERSION = "6.0"
APP_CODENAME = "Sovereign Engine"

# Crisp rendering + correct sizing on Windows laptops with 125%/150% display scaling.
HIGH_DPI_AWARE = True
if HIGH_DPI_AWARE and sys.platform == 'win32':
    try:
        ctypes.windll.shcore.SetProcessDpiAwareness(1)
    except Exception:
        try: ctypes.windll.user32.SetProcessDPIAware()
        except Exception: pass
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(f'mauvezone.stochasticcomposer.{APP_VERSION}')
    except Exception:
        pass

# Default Windows timer granularity is ~15.6 ms, which makes time.sleep(0.001) in the
# scheduler/clock threads jittery. Ask for 1 ms so notes land on the grid.
if sys.platform == 'win32':
    try: ctypes.windll.winmm.timeBeginPeriod(1)
    except Exception: pass

try:
    import rtmidi
    import mido.backends.rtmidi
    mido.set_backend('mido.backends.rtmidi')
except Exception:
    pass

# The Mauve Zone Aesthetic
BG_GRAD_TOP = "#342236"      
BG_GRAD_BOT = "#1a161b"      
PANEL_COLOR = "#1c171d"      
FG_COLOR = "#d4cdbf"         
HEADER_BG = "#140e15"        
HEADER_FG = "#e8dfce"        
ACCENT_BRUISED = "#4a3045"   
INPUT_BG = "#0f0a10"         
INPUT_FG = "#d6ccbf"         
SEPIA_DARK = "#33241b"       
SEPIA_ACTIVE = "#b34722"     
LED_OFF = "#0a070a"          
LED_ON = "#d43d1e"           
MEM_PLAY_BORDER = "#f0e6d2"  # steady border on the M slot that is currently looping
MEM_FLASH = "#ff8a4c"        # blink on every loop start of that slot

# v5.0 Milestone Cyberdeck / Eurorack Palettes
V_AMBER_LOW = "#5e2d1d"
V_AMBER_MID = "#b34722"
V_AMBER_HIGH = "#ff8a4c"
V_AMBER_PEAK = "#ffe066"
V_PLASMA_LOW = "#331e42"
V_PLASMA_MID = "#8c3fa8"
V_PLASMA_HIGH = "#e05fe6"
V_PLASMA_PEAK = "#64d8cb"

FONT_MAIN = ('Consolas', 11)
FONT_BOLD = ('Consolas', 11, 'bold')
FONT_SMALL = ('Consolas', 9)
FONT_HDR_TITLE = ('Consolas', 8)
FONT_HDR_BTN = ('Consolas', 8)
SLIDER_LEN = 106

GLOBAL_PHYSICS_STATE = {}


def make_scale_value_editable(scale, label, variable, minimum, maximum, integer=True):
    """Keep the value label visually unchanged; double-click to edit it inline.

    Clicking or dragging anywhere on the scale maps directly to a value. The
    Scale's own mouse bindings are replaced for these gestures so trough clicks
    jump to the clicked position rather than stepping by pages.
    """
    def display_value(*_):
        try:
            value = float(variable.get())
            label.config(text=str(int(round(value))) if integer else f"{value:g}")
        except (ValueError, tk.TclError):
            pass

    def commit(entry, original):
        try:
            raw = entry.get().strip()
            value = float(raw)
            if not math.isfinite(value):
                raise ValueError
            value = max(minimum, min(maximum, value))
            if integer:
                value = int(round(value))
            variable.set(value)
            scale.set(value)
            callback = getattr(scale, "_mauve_on_value_commit", None)
            if callback:
                callback()
        except (ValueError, tk.TclError):
            pass
        finally:
            try:
                entry.destroy()
            except tk.TclError:
                pass
            display_value()

    def begin_edit(_event=None):
        if not label.winfo_exists():
            return
        entry = tk.Entry(
            label, justify="center", relief="flat", bd=0,
            highlightthickness=0, bg=label.cget("bg"), fg=label.cget("fg"),
            insertbackground=label.cget("fg"), font=label.cget("font"),
            width=max(2, len(label.cget("text")) + 1),
        )
        entry.place(x=0, y=0, relwidth=1, relheight=1)
        entry.insert(0, label.cget("text"))
        entry.select_range(0, "end")
        entry.focus_set()
        finished = {"done": False}

        def finish(_event=None):
            if not finished["done"]:
                finished["done"] = True
                commit(entry, label)
            return "break"

        def cancel(_event=None):
            if not finished["done"]:
                finished["done"] = True
                try:
                    entry.destroy()
                except tk.TclError:
                    pass
                display_value()
            return "break"

        entry.bind("<Return>", finish)
        entry.bind("<KP_Enter>", finish)
        entry.bind("<Escape>", cancel)
        entry.bind("<FocusOut>", finish)
        return "break"

    def value_at(event):
        try:
            low_xy = scale.coords(minimum)
            high_xy = scale.coords(maximum)
            if not low_xy or not high_xy:
                return
            if str(scale.cget("orient")) == "vertical":
                pos, low_pos, high_pos = event.y, low_xy[1], high_xy[1]
            else:
                pos, low_pos, high_pos = event.x, low_xy[0], high_xy[0]
            if high_pos == low_pos:
                value = minimum
            else:
                fraction = (pos - low_pos) / (high_pos - low_pos)
                value = minimum + fraction * (maximum - minimum)
            value = max(minimum, min(maximum, value))
            if integer:
                value = int(round(value))
            variable.set(value)
            scale.set(value)
        except (tk.TclError, ValueError, ZeroDivisionError):
            pass

    def press(event):
        scale._mauve_scale_dragging = True
        value_at(event)
        return "break"

    def drag(event):
        if getattr(scale, "_mauve_scale_dragging", False):
            value_at(event)
        return "break"

    def release(_event):
        scale._mauve_scale_dragging = False
        callback = getattr(scale, "_mauve_on_release", None)
        if callback:
            callback()
        return "break"

    label.bind("<Double-Button-1>", begin_edit)
    label.configure(cursor="xterm")
    scale.bind("<Button-1>", press)
    scale.bind("<B1-Motion>", drag)
    scale.bind("<ButtonRelease-1>", release)
    trace_id = variable.trace_add("write", display_value)

    def remove_trace(event):
        if event.widget is label:
            try:
                variable.trace_remove("write", trace_id)
            except (tk.TclError, ValueError):
                pass

    label.bind("<Destroy>", remove_trace, add="+")
    display_value()

ROOT_NOTES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

SCALES = {
    "Major (Ionian)": [0, 2, 4, 5, 7, 9, 11],
    "Natural Minor (Aeolian)": [0, 2, 3, 5, 7, 8, 10],
    "Harmonic Minor": [0, 2, 3, 5, 7, 8, 11],
    "Melodic Minor (Ascending)": [0, 2, 3, 5, 7, 9, 11],
    "Dorian": [0, 2, 3, 5, 7, 9, 10],
    "Mixolydian": [0, 2, 4, 5, 7, 9, 10],
    "Lydian": [0, 2, 4, 6, 7, 9, 11],
    "Major Pentatonic": [0, 2, 4, 7, 9],
    "Minor Pentatonic": [0, 3, 5, 7, 10],
    "Phrygian Dominant": [0, 1, 4, 5, 7, 8, 10],
    "Locrian": [0, 1, 3, 5, 6, 8, 10],
    "Whole Tone": [0, 2, 4, 6, 8, 10],
    "Diminished (HW)": [0, 1, 3, 4, 6, 7, 9, 10],
    "Byzantine (Double Harm.)": [0, 1, 4, 5, 7, 8, 11],
    "Hungarian Minor": [0, 2, 3, 6, 7, 8, 11],
    "Hirajoshi": [0, 2, 3, 7, 8],
    "In Sen": [0, 1, 5, 7, 10],
    "Prometheus": [0, 2, 4, 6, 9, 10],
    "Enigmatic": [0, 1, 4, 6, 8, 10, 11],
    "Phrygian": [0, 1, 3, 5, 7, 8, 10],
    "Lydian Dominant (Overtone)": [0, 2, 4, 6, 7, 9, 10],
    "Super Locrian (Altered)": [0, 1, 3, 4, 6, 8, 10],
    "Ukrainian Dorian (Romanian)": [0, 2, 3, 6, 7, 9, 10],
    "Persian": [0, 1, 4, 5, 6, 8, 11],
    "Blues Hexatonic": [0, 3, 5, 6, 7, 10],
    "Iwato": [0, 1, 5, 6, 10],
    "Pelog (Balinese Gamelan)": [0, 1, 3, 7, 8],
    "Neapolitan Minor": [0, 1, 3, 5, 7, 8, 11],
    "Bebop Dominant": [0, 2, 4, 5, 7, 9, 10, 11],
    "Chromatic": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
}

INTERVAL_NAMES = {0: "R", 1: "m2", 2: "M2", 3: "m3", 4: "M3", 5: "4", 6: "d5", 7: "5", 8: "m6", 9: "M6", 10: "m7", 11: "M7", 12: "Oct"}

RECIPES = {
    "Custom / Manual": {},
    "The Monolith (Root, 5th, Octave)": {0: 100, 7: 100, 12: 100},
    "Tragic Gothic (m3, m6 Dominant)": {0: 60, 3: 100, 7: 40, 8: 100, 12: 50},
    "Unstable Void (M2, d5, m7)": {0: 40, 2: 90, 6: 100, 10: 90, 12: 20},
    "Terry Riley Drone (Root, M2, 5th)": {0: 100, 2: 100, 7: 100},
    "Ascending Tension (4th, 5th, M7)": {0: 30, 5: 90, 7: 90, 11: 100},
    "Fever Dream (M3, M6, M7)": {0: 50, 4: 90, 9: 90, 11: 80},
    "Ancient Hollow (4ths and 5ths)": {0: 80, 5: 100, 7: 100, 12: 80},
    "Mauve Zone Abyss (Root, m2, 4, m6)": {0: 100, 1: 70, 5: 80, 8: 100},
    "Lovecraftian Ritual (Root, M3, d5, M7)": {0: 80, 4: 100, 6: 100, 11: 90},
    "EBM Body Hammer (Root, m3, Oct)": {0: 100, 3: 80, 12: 100},
    "Industrial Sludge (Root, m2, d5)": {0: 100, 1: 90, 6: 100},
    "Acid Bassline (Root, m3, 4, m7)": {0: 100, 3: 80, 5: 60, 10: 90, 12: 70},
    "Nitzer Ebb Drive (Root, 5th, m7, Oct)": {0: 100, 7: 80, 10: 90, 12: 100},
    "Cyberpunk Arp (Root, m2, 5th, m6)": {0: 90, 1: 80, 7: 100, 8: 90, 12: 60},
    "Berlin School Sequencer (Root, 5th, m7, Oct)": {0: 100, 7: 90, 10: 75, 12: 95},
    "Vangelis Blade Runner (Root, 4, 5, m7, Oct)": {0: 90, 2: 70, 5: 85, 7: 100, 10: 80, 12: 60},
    "Kavinsky Synthwave (Root, M2, m3, 5, Oct)": {0: 100, 2: 60, 3: 90, 7: 95, 12: 85},
    "Weeping Blues Lead (Root, m3, d5, 5, m7)": {0: 95, 3: 85, 6: 75, 7: 90, 10: 80},
    "Gamelan Mystic Bells (Root, m2, m3, 5, m6)": {0: 85, 1: 90, 3: 80, 7: 100, 8: 95},
    "Persian Desert Mirage (Root, m2, M3, 4, d5, m6)": {0: 100, 1: 85, 4: 90, 5: 70, 6: 95, 8: 85},
    "Detroit Techno Chord (Root, m3, 5, m7)": {0: 100, 3: 90, 5: 60, 7: 95, 10: 90},
    "Xenakis Micro-Cluster (Root, m2, M2, d5)": {0: 90, 1: 100, 2: 95, 6: 85},
    "Total Chromatic Chaos": {i: 80 for i in range(13)}
}

# Saves made before the meter names gained a [steps] suffix still load: old name -> current name.
ADDITIVE_ALIASES = {
    "Paeon First (3-2)": "Paeon First (3-2) [5]",
    "Paeon Fourth (2-3)": "Paeon Fourth (2-3) [5]",
    "Epitrite First (3-2-2)": "Epitrite First (3-2-2) [7]",
    "Epitrite Second (2-3-2)": "Epitrite Second (2-3-2) [7]",
    "Dochmiac (3-2-3)": "Dochmiac (3-2-3) [8]",
    "Cretic (3-2-3-2)": "Cretic (3-2-3-2) [10]",
    "Zeibekiko / Aksak (2-2-2-3)": "Zeibekiko / Aksak (2-2-2-3) [9]",
    "Kalamatianos / Lesnoto (3-2-2)": "Kalamatianos / Lesnoto (3-2-2) [7]",
    "Tresillo / Bikutsi (3-3-2)": "Tresillo / Bikutsi (3-3-2) [8]",
    "Cinquillo (2-1-2-1-2)": "Cinquillo (2-1-2-1-2) [8]",
    "Bembe 12/8 (2-2-3-2-3)": "Bembe (2-2-3-2-3) [12]",
    "Fume Fume (3-2-2-2-3)": "Fume Fume (3-2-2-2-3) [12]",
    "Mangambeu (2-3-2-2)": "Mangambeu (2-3-2-2) [9]",
    "Samai Thaqil (3-2-2-3)": "Samai Thaqil (3-2-2-3) [10]",
    "Ayoub / Zar (2-2-4)": "Ayoub / Zar Ritual (2-2-4) [8]",
    "Chiftetelli (2-2-4-2-2-4)": "Chiftetelli (2-2-4-2-2-4) [16]",
    "Rachenitsa (2-2-3)": "Rachenitsa (2-2-3) [7]",
    "Kopanitsa (2-2-3-2-2)": "Kopanitsa (2-2-3-2-2) [11]",
    "Postupano (2-2-2-3-2-2)": "Postupano (2-2-2-3-2-2) [13]",
    "90s Boom Bap (3-1-3-1-3-1-3-1)": "90s Boom Bap (3-1-3-1-3-1-3-1) [16]",
    "EBM Body Hammer (3-3-2-4-4)": "EBM Body Hammer (3-3-2-4-4) [16]",
    "Industrial Sludge (6-6-4)": "Industrial Sludge (6-6-4) [16]",
    "Meshuggah Djent (5-5-3-3)": "Meshuggah Djent (5-5-3-3) [16]",
    "Noh-kan Breath (4-2-2)": "Noh-kan Breath (4-2-2) [8]",
    "Kagura Syncopation (2-3-2-1)": "Kagura Syncopation (2-3-2-1) [8]",
    "Gagaku Court Slow (3-3-2-2-2-2-2)": "Gagaku Court Slow (3-3-2-2-2-2-2) [16]",
    "Four-on-the-Floor (4-4-4-4)": "Four-on-the-Floor (4-4-4-4) [16]",
}

def resolve_additive_meter(name):
    return name if name in ADDITIVE_METERS else ADDITIVE_ALIASES.get(name, name)

ADDITIVE_METERS = {
    # --- ANCIENT GREEK & POETIC METERS ---
    "Paeon First (3-2) [5]": [3, 2],
    "Paeon Fourth (2-3) [5]": [2, 3],
    "Epitrite First (3-2-2) [7]": [3, 2, 2],
    "Epitrite Second (2-3-2) [7]": [2, 3, 2],
    "Dochmiac (3-2-3) [8]": [3, 2, 3],
    "Ruins of Athens (2-3-3-2) [10]": [2, 3, 3, 2],
    "Cretic (3-2-3-2) [10]": [3, 2, 3, 2],
    "Choriambic (3-2-2-3) [10]": [3, 2, 2, 3],

    # --- BALKAN & MIDDLE EASTERN ---
    "Rachenitsa (2-2-3) [7]": [2, 2, 3],
    "Kalamatianos / Lesnoto (3-2-2) [7]": [3, 2, 2],
    "Zeibekiko / Aksak (2-2-2-3) [9]": [2, 2, 2, 3],
    "Samai Thaqil (3-2-2-3) [10]": [3, 2, 2, 3],
    "Kopanitsa (2-2-3-2-2) [11]": [2, 2, 3, 2, 2],
    "Macedonian Beranche (3-2-2-3-2) [12]": [3, 2, 2, 3, 2],
    "Postupano (2-2-2-3-2-2) [13]": [2, 2, 2, 3, 2, 2],
    "Sandansko Horo (2-2-2-3-2-2-2-2-3-2-2) [22]": [2, 2, 2, 3, 2, 2, 2, 2, 3, 2, 2],

    # --- RITUAL, TRANCE & GLOBAL ---
    "Ayoub / Zar Ritual (2-2-4) [8]": [2, 2, 4],
    "Tresillo / Bikutsi (3-3-2) [8]": [3, 3, 2],
    "Cinquillo (2-1-2-1-2) [8]": [2, 1, 2, 1, 2],
    "Mangambeu (2-3-2-2) [9]": [2, 3, 2, 2],
    "Bembe (2-2-3-2-3) [12]": [2, 2, 3, 2, 3],
    "Fume Fume (3-2-2-2-3) [12]": [3, 2, 2, 2, 3],
    "Persian Daf (3-3-4-2) [12]": [3, 3, 4, 2],
    "Chiftetelli (2-2-4-2-2-4) [16]": [2, 2, 4, 2, 2, 4],
    "Gamelan Gong Cycle (4-4-4-2-2) [16]": [4, 4, 4, 2, 2],
    "Gagaku Court Slow (3-3-2-2-2-2-2) [16]": [3, 3, 2, 2, 2, 2, 2],

    # --- INDUSTRIAL, EBM & EAST COAST HIP HOP ---
    "Four-on-the-Floor (4-4-4-4) [16]": [4, 4, 4, 4],
    "90s Boom Bap (3-1-3-1-3-1-3-1) [16]": [3, 1, 3, 1, 3, 1, 3, 1],
    "Shaolin Stagger (3-2-1-2-3-2-1-2) [16]": [3, 2, 1, 2, 3, 2, 1, 2], 
    "EBM Body Hammer (3-3-2-4-4) [16]": [3, 3, 2, 4, 4],
    "Frontal Drive (4-2-2-4-2-2) [16]": [4, 2, 2, 4, 2, 2],
    "Industrial Sludge (6-6-4) [16]": [6, 6, 4],
    
    # --- HAUNTOLOGY & EXPERIMENTAL ---
    "Cantara Procession (6-2-4) [12]": [6, 2, 4],
    "Lovegrove Drone (4-2-4-2-4) [16]": [4, 2, 4, 2, 4], 
    "Noh-kan Breath (4-2-2) [8]": [4, 2, 2],
    "Kagura Syncopation (2-3-2-1) [8]": [2, 3, 2, 1],
    "Sacrificial Dance (2-3-2-2-3) [12]": [2, 3, 2, 2, 3],
    "Polymetric Tension (7-7-2) [16]": [7, 7, 2],
    "Meshuggah Djent (5-5-3-3) [16]": [5, 5, 3, 3],
    "Void Collapse (9-7) [16]": [9, 7]
}

RECIPE_GROUPS = [
    ("MANUAL", ["Custom / Manual"]),
    ("BERLIN SCHOOL & CINEMATIC", [
        "Berlin School Sequencer (Root, 5th, m7, Oct)",
        "Vangelis Blade Runner (Root, 4, 5, m7, Oct)",
        "Kavinsky Synthwave (Root, M2, m3, 5, Oct)",
        "Detroit Techno Chord (Root, m3, 5, m7)"
    ]),
    ("BLUES & GLOBAL RITUAL", [
        "Weeping Blues Lead (Root, m3, d5, 5, m7)",
        "Gamelan Mystic Bells (Root, m2, m3, 5, m6)",
        "Persian Desert Mirage (Root, m2, M3, 4, d5, m6)",
        "Lovecraftian Ritual (Root, M3, d5, M7)"
    ]),
    ("DRONES & MINIMALISM", [
        "The Monolith (Root, 5th, Octave)",
        "Terry Riley Drone (Root, M2, 5th)",
        "Ancient Hollow (4ths and 5ths)"
    ]),
    ("INDUSTRIAL & EBM", [
        "EBM Body Hammer (Root, m3, Oct)",
        "Industrial Sludge (Root, m2, d5)",
        "Nitzer Ebb Drive (Root, 5th, m7, Oct)",
        "Acid Bassline (Root, m3, 4, m7)"
    ]),
    ("DARK AMBIENT & GOTHIC", [
        "Tragic Gothic (m3, m6 Dominant)",
        "Unstable Void (M2, d5, m7)",
        "Mauve Zone Abyss (Root, m2, 4, m6)",
        "Ascending Tension (4th, 5th, M7)",
        "Fever Dream (M3, M6, M7)",
        "Cyberpunk Arp (Root, m2, 5th, m6)"
    ]),
    ("CHAOS & AVANT-GARDE", [
        "Xenakis Micro-Cluster (Root, m2, M2, d5)",
        "Total Chromatic Chaos"
    ])
]

ADDITIVE_GROUPS = [
    ("ANCIENT GREEK & POETIC", [
        "Paeon First (3-2) [5]", "Paeon Fourth (2-3) [5]",
        "Epitrite First (3-2-2) [7]", "Epitrite Second (2-3-2) [7]",
        "Dochmiac (3-2-3) [8]", "Ruins of Athens (2-3-3-2) [10]",
        "Cretic (3-2-3-2) [10]", "Choriambic (3-2-2-3) [10]"
    ]),
    ("BALKAN & MIDDLE EASTERN", [
        "Rachenitsa (2-2-3) [7]", "Kalamatianos / Lesnoto (3-2-2) [7]",
        "Zeibekiko / Aksak (2-2-2-3) [9]", "Samai Thaqil (3-2-2-3) [10]",
        "Kopanitsa (2-2-3-2-2) [11]", "Macedonian Beranche (3-2-2-3-2) [12]",
        "Postupano (2-2-2-3-2-2) [13]", "Sandansko Horo (2-2-2-3-2-2-2-2-3-2-2) [22]"
    ]),
    ("RITUAL, TRANCE & GLOBAL", [
        "Ayoub / Zar Ritual (2-2-4) [8]", "Tresillo / Bikutsi (3-3-2) [8]",
        "Cinquillo (2-1-2-1-2) [8]", "Mangambeu (2-3-2-2) [9]",
        "Bembe (2-2-3-2-3) [12]", "Fume Fume (3-2-2-2-3) [12]",
        "Persian Daf (3-3-4-2) [12]", "Chiftetelli (2-2-4-2-2-4) [16]",
        "Gamelan Gong Cycle (4-4-4-2-2) [16]", "Gagaku Court Slow (3-3-2-2-2-2-2) [16]"
    ]),
    ("INDUSTRIAL, EBM & HIP HOP", [
        "Four-on-the-Floor (4-4-4-4) [16]", "90s Boom Bap (3-1-3-1-3-1-3-1) [16]",
        "Shaolin Stagger (3-2-1-2-3-2-1-2) [16]", "EBM Body Hammer (3-3-2-4-4) [16]",
        "Frontal Drive (4-2-2-4-2-2) [16]", "Industrial Sludge (6-6-4) [16]"
    ]),
    ("HAUNTOLOGY & EXPERIMENTAL", [
        "Cantara Procession (6-2-4) [12]", "Lovegrove Drone (4-2-4-2-4) [16]",
        "Noh-kan Breath (4-2-2) [8]", "Kagura Syncopation (2-3-2-1) [8]",
        "Sacrificial Dance (2-3-2-2-3) [12]", "Polymetric Tension (7-7-2) [16]",
        "Meshuggah Djent (5-5-3-3) [16]", "Void Collapse (9-7) [16]"
    ])
]

EUCLID_GROUPS = [
    ("MANUAL", ["Custom / Manual"]),
    ("SPARSE & RITUAL", [
        "Four-on-the-Floor (16:4:0)",
        "Paeon First / Slow Ritual (16:3:0)",
        "Heartbeat / Sludge (16:2:0)",
        "Deep Void (24:3:0)",
        "Empty Corridor (32:5:0)",
        "Suspended Animation (32:3:0)"
    ]),
    ("INDUSTRIAL & EBM", [
        "Frontal Assault (16:7:0)",
        "EBM Body Hammer (16:9:0)",
        "Staggered Drive (16:5:2)",
        "Cybernetic Roll (16:11:0)",
        "Motorik / Krautrock (16:8:0)",
        "Uneven Stomp (16:13:0)"
    ]),
    ("COMPLEX SYNCOPATION", [
        "Cuban Tresillo / Habanera (8:3:0)",
        "Cuban Cinquillo (8:5:0)",
        "Bossa-Nova Necklace (16:5:0)",
        "Son Clave (16:5:2)",
        "Samba Necklace (16:7:0)",
        "Rumba / Luba (16:9:0)",
        "Aksak - Turkey (9:4:0)",
        "Ruchenitza - Bulgaria (7:3:0)",
        "York-Samai - Arab (6:5:0)",
        "Nawakhat - Arab (7:5:0)"
    ]),
    ("BUSY & GLITCHY", [
        "Agbekor / Standard Bell (12:5:0)",
        "Mpre / Ashanti - Ghana (12:7:0)",
        "Aka Pygmies Lower (24:11:0)",
        "Aka Pygmies Upper (24:13:0)",
        "Frank Zappa - Black Page (19:11:0)",
        "Fractured Glass (32:17:0)",
        "Micro-Stutter (32:23:0)",
        "Swarm (32:29:0)"
    ]),
    ("THE FRINGES", [
        "Tchaikovsky / Take Five (5:2:0)", 
        "Khafif-e-ramal - 13th C. Persian (5:3:0)",
        "Pink Floyd - Money (7:3:0)",
        "Macedonian Limp (13:5:0)",
        "Asymmetrical Orbit (11:4:0)",
        "Moussorgsky Promenade (11:5:0)",
        "Prime Collapse (17:7:0)",
        "Alien Transmission (23:9:0)",
        "Polymetric Grind (29:13:0)"
    ])
]

def _setup_logging():
    """Errors go to ~/MauveZone/mauve_zone.log (plus the console when there is one)."""
    lg = logging.getLogger("mauvezone")
    if lg.handlers: return lg
    lg.setLevel(logging.INFO)
    fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    if sys.stderr is not None:
        sh = logging.StreamHandler(); sh.setFormatter(fmt); lg.addHandler(sh)
    try:
        d = os.path.join(os.path.expanduser("~"), "MauveZone")
        os.makedirs(d, exist_ok=True)
        fh = RotatingFileHandler(os.path.join(d, "mauve_zone.log"), maxBytes=500000, backupCount=2, encoding="utf-8")
        fh.setFormatter(fmt); lg.addHandler(fh)
    except Exception:
        pass
    return lg

log = _setup_logging()
_log_throttle = {}

def log_exc(where, min_gap=5.0):
    """Log the current exception, at most once per `min_gap` seconds per call site (no log floods)."""
    now = time.monotonic()
    if now - _log_throttle.get(where, -1e9) >= min_gap:
        _log_throttle[where] = now
        try: log.exception("Error in %s", where)
        except Exception: pass

# How often a mutation re-rolls into a fresh variation, by MUT amount: (up to this amount, every N loops).
# Stronger mutation changes more often, down to every half loop at the top end.
MUT_REROLL_BANDS = [(20, 4.0), (40, 3.0), (60, 2.0), (85, 1.0), (100, 0.5)]

def mut_reroll_loops(amount):
    """Loops between re-rolls for a given MUT amount (0 = never, no mutation)."""
    if amount <= 0.0: return 0.0
    for upto, loops in MUT_REROLL_BANDS:
        if amount <= upto: return loops
    return MUT_REROLL_BANDS[-1][1]

def fold_pitch(n):
    """Keep the pitch class when a note lands outside 0-127 by moving it whole octaves.
    (Clamping would silently turn it into a different note.)"""
    while n > 127: n -= 12
    while n < 0: n += 12
    return n


def get_stochastic_gate_ratio(dur_str, semitone_dist=0, is_phrase_tail=False,
                              tension=0.0, stamina=0.5, entropy=0, mel_macro="Static",
                              prev_gate=0.85):
    """
    v6.0 Sovereign Engine: Multi-dimensional stochastic gate synthesis.
    Duration-scaled Gaussian variance, Markov fatigue sluggishness, 
    Deep Exhalation lung repeller, and vocal phrasing counterpoint.
    """
    # 1. Base mean and duration-scaled standard deviation (Gaussian spread)
    gate_profiles = {
        "1/1":   (0.85, 0.085),  # Long notes: wide expressive spread (65% to 98%)
        "1/2":   (0.88, 0.065),
        "1/4.":  (0.90, 0.050),
        "1/4":   (0.91, 0.045),
        "1/8.":  (0.93, 0.030),
        "1/8":   (0.94, 0.025),
        "1/8T":  (0.95, 0.020),
        "1/16":  (0.95, 0.015),  # Fast notes: tight rhythmic groove
        "1/16T": (0.95, 0.015)
    }
    mu, sigma = gate_profiles.get(dur_str, (0.90, 0.04))

    # 2. Markov Sluggishness (Fatigue drags fingers onto the keys; stamina snaps them off)
    sluggish_bias = tension * (1.0 - (stamina * 0.5)) * 0.08
    mu += sluggish_bias

    # 3. Deep Exhalation Law (Lung repeller: prevents consecutive suffocating tenutos)
    if prev_gate >= 0.93:
        mu -= 0.07

    # 4. Counterpoint & Phrasing Contour
    if 1 <= semitone_dist <= 2:
        mu += 0.04   # Stepwise singing legato slur
    elif semitone_dist >= 7:
        mu -= 0.06   # Wide leap crisp detachment
    if is_phrase_tail:
        mu -= 0.08   # Phrase-tail exhalation breath

    # 5. Macro Modulation
    if mel_macro == "Pedal Point":
        mu += 0.05   # Anchoring tenuto
    elif mel_macro == "Drone Collapse":
        mu -= 0.16   # Chokes gate as the drone decays
    elif mel_macro == "Humanize":
        sigma += 0.025

    # 6. Global Analog Chaos (RC capacitor discharge flutter)
    if entropy > 0:
        ent_factor = entropy / 100.0
        sigma += ent_factor * 0.035
        mu += random.gauss(0.0, ent_factor * 0.03)

    # 7. Sample the Gaussian Gate Distribution
    sampled_gate = random.gauss(mu, sigma)

    # 8. Hardware Protection Clamp (guarantees >= 8ms breath before next step, prevents MIDI hanging)
    return max(0.40, min(0.985, sampled_gate))

# Backwards compatibility alias
get_organic_gate_ratio = get_stochastic_gate_ratio

class ToolTip:
    def __init__(self, widget, text):
        self.widget = widget
        self.text = text
        self.tip_window = None
        self.id = None
        self.widget.bind('<Enter>', self.schedule, add="+")
        self.widget.bind('<Leave>', self.unschedule, add="+")
        self.widget.bind('<ButtonPress>', self.unschedule, add="+")

    def schedule(self, event=None):
        self.unschedule()
        self.id = self.widget.after(500, self.show)

    def unschedule(self, event=None):
        id = self.id
        self.id = None
        if id: self.widget.after_cancel(id)
        self.hide()

    def show(self):
        self.unschedule()
        try:
            self.tip_window = tw = tk.Toplevel(self.widget)
            tw.wm_overrideredirect(True)
            label = tk.Label(tw, text=self.text, justify='left', background=SEPIA_DARK, foreground=FG_COLOR, relief='solid', borderwidth=1, font=FONT_SMALL, padx=6, pady=4, wraplength=350)
            label.pack()
            label.update_idletasks()

            tip_w = label.winfo_reqwidth()
            tip_h = label.winfo_reqheight()
            screen_w = self.widget.winfo_screenwidth()
            screen_h = self.widget.winfo_screenheight()

            # Horizontal placement: flip to left if near right screen edge
            rx = self.widget.winfo_rootx()
            if rx + self.widget.winfo_width() + tip_w > screen_w:
                x = max(0, rx - tip_w - 5)
            else:
                x = rx + 20

            # Vertical placement: flip above if near bottom screen edge
            ry = self.widget.winfo_rooty()
            y = ry + self.widget.winfo_height() + 5
            if y + tip_h > screen_h:
                y = max(0, ry - tip_h - 5)

            tw.wm_geometry(f"+{x}+{y}")
        except Exception:
            pass

    def hide(self):
        tw = self.tip_window
        self.tip_window = None
        if tw: tw.destroy()

class EuclideanGenerator:
    @staticmethod
    def generate(steps, pulses, rotation=0):
        """Generates canonical Bjorklund Euclidean pulse distribution with rotation offset."""
        if steps <= 0: return []
        if pulses <= 0: return [False] * steps
        if pulses >= steps: return [True] * steps
        
        slots = [[True] for _ in range(pulses)] + [[False] for _ in range(steps - pulses)]
        while True:
            last = slots[-1]
            tail_count = 0
            for s in reversed(slots):
                if s == last: tail_count += 1
                else: break
            head_count = len(slots) - tail_count
            if tail_count <= 1 or head_count == 0: break
            num_to_distribute = min(head_count, tail_count)
            new_slots = []
            for i in range(num_to_distribute):
                new_slots.append(slots[i] + slots[len(slots) - num_to_distribute + i])
            new_slots.extend(slots[num_to_distribute:len(slots) - num_to_distribute])
            slots = new_slots
        pattern = [item for sub in slots for item in sub]
        if rotation != 0 and steps > 0:
            rotation = rotation % steps
            pattern = pattern[-rotation:] + pattern[:-rotation]
        return pattern

# --- TRIPLE-A RETRO-FUTURISTIC / CYBERDECK VISUALIZERS ---

class CapsuleVUMeter(tk.Canvas):
    """Segmented LED VU / neon plasma capsule visualizer with peak-hold decay.
    Displays live Brownian Gravity drift (intervals) or Kinetic Inertia fatigue stamina (durations)."""
    def __init__(self, parent, meter_type="gravity", width=28, height=12, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#0c090e", highlightthickness=1, highlightbackground="#2d1d2b", bd=0, **kwargs)
        self.meter_type = meter_type
        self.w = width
        self.h = height
        self.num_segs = 6
        self.cur_val = 0.0
        self.peak_val = 0.0
        self.peak_decay_time = 0.0
        self.seg_items = []
        
        if meter_type == "gravity":
            self.active_colors = [V_AMBER_LOW, "#8c3b1e", V_AMBER_MID, "#d9652a", V_AMBER_HIGH, V_AMBER_PEAK]
            self.peak_color = "#fff2a8"
            self.off_color = "#160e14"
        else:
            self.active_colors = [V_PLASMA_LOW, "#5c2a7a", V_PLASMA_MID, "#b847c2", V_PLASMA_HIGH, V_PLASMA_PEAK]
            self.peak_color = "#c8fff8"
            self.off_color = "#130f1c"
            
        pad_x = 2
        seg_w = (width - (2 * pad_x) - (self.num_segs - 1)) / float(self.num_segs)
        for i in range(self.num_segs):
            x0 = pad_x + i * (seg_w + 1)
            x1 = x0 + seg_w
            y0 = 2
            y1 = height - 2
            rect = self.create_rectangle(x0, y0, x1, y1, fill=self.off_color, outline="", width=0)
            self.seg_items.append(rect)
            
        self.peak_line = self.create_line(pad_x, 1, pad_x, height - 1, fill="", width=1)
        
    def set_value(self, val):
        if val is None: val = 0.0
        try: val = max(0.0, min(100.0, float(val)))
        except (ValueError, TypeError): val = 0.0
        now = time.perf_counter()
        
        if val >= self.peak_val:
            self.peak_val = val
            self.peak_decay_time = now + 0.35
        elif now > self.peak_decay_time:
            self.peak_val = max(val, self.peak_val - 2.8)
            
        if abs(val - self.cur_val) < 0.5 and abs(self.peak_val - getattr(self, '_last_drawn_peak', -1)) < 0.5:
            return
            
        self.cur_val = val
        self._last_drawn_peak = self.peak_val
        
        segs_on = int(round((val / 100.0) * self.num_segs))
        try:
            if segs_on != getattr(self, '_last_segs_on', -1):
                self._last_segs_on = segs_on
                for i in range(self.num_segs):
                    color = self.active_colors[i] if i < segs_on else self.off_color
                    self.itemconfig(self.seg_items[i], fill=color)
                
            if self.peak_val > 4.0:
                pad_x = 2
                avail_w = self.w - (2 * pad_x)
                px = max(pad_x, min(self.w - pad_x, pad_x + (self.peak_val / 100.0) * avail_w))
                self.coords(self.peak_line, px, 1, px, self.h - 1)
                self.itemconfig(self.peak_line, fill=self.peak_color)
            else:
                self.itemconfig(self.peak_line, fill="")
        except tk.TclError: pass
        except Exception: pass


class EuclidOrbitRadar(tk.Canvas):
    """Circular Euclidean Bjorklund Orbit Radar (Interactive). Visualizes pulse constellation,
    rotating real-time sweep hand, center rotation readout, and interactive phase slip."""
    def __init__(self, parent, size=80, **kwargs):
        super().__init__(parent, width=size, height=size, bg="#07040a", highlightthickness=1, highlightbackground="#3a2034", bd=0, cursor="hand2", **kwargs)
        self.size = size
        self.cx = size / 2.0
        self.cy = size / 2.0
        self.r = (size / 2.0) - 8.0
        self.steps = 16
        self.pulses = 4
        self.rot = 0
        self.cur_step = 0
        
        self.on_rot_change = None
        self.on_pulse_change = None
        
        # Triple concentric radar rings
        self.create_oval(self.cx - self.r, self.cy - self.r, self.cx + self.r, self.cy + self.r, outline="#331c2f", width=1.5)
        self.create_oval(self.cx - self.r*0.66, self.cy - self.r*0.66, self.cx + self.r*0.66, self.cy + self.r*0.66, outline="#1f1021", width=1)
        self.create_oval(self.cx - self.r*0.33, self.cy - self.r*0.33, self.cx + self.r*0.33, self.cy + self.r*0.33, outline="#140a16", width=1)
        
        # Crosshair axes
        self.create_line(self.cx - self.r - 2, self.cy, self.cx + self.r + 2, self.cy, fill="#241222", width=1)
        self.create_line(self.cx, self.cy - self.r - 2, self.cx, self.cy + self.r + 2, fill="#241222", width=1)
        
        # 16 Degree tick marks
        for t in range(16):
            ang = -math.pi / 2.0 + (2.0 * math.pi * t) / 16.0
            x1 = self.cx + (self.r - 3) * math.cos(ang)
            y1 = self.cy + (self.r - 3) * math.sin(ang)
            x2 = self.cx + self.r * math.cos(ang)
            y2 = self.cy + self.r * math.sin(ang)
            self.create_line(x1, y1, x2, y2, fill="#42223b", width=1)
            
        self.flash_ring = self.create_oval(self.cx, self.cy, self.cx, self.cy, outline="", width=2)
        self.poly_line = self.create_polygon(0, 0, 0, 0, fill="#260e20", outline="#ff8a4c", width=1.5)
        self.sweep_hand = self.create_line(self.cx, self.cy, self.cx, self.cy - self.r, fill="#ff9a3c", width=1.5)
        self.sweep_tip = self.create_oval(self.cx, self.cy, self.cx, self.cy, fill="#ffffff", outline="#ff9a3c")
        
        # Center hub with rotation text
        self.center_hub = self.create_oval(self.cx - 7, self.cy - 7, self.cx + 7, self.cy + 7, fill="#180a18", outline="#8c3b1e", width=1)
        self.center_txt = self.create_text(self.cx, self.cy, text="R:0", fill="#ffe066", font=('Consolas', 6))
        
        self.node_items = []
        for _ in range(64):
            self.node_items.append(self.create_oval(0, 0, 0, 0, fill="", outline=""))
            
        self.bind("<Button-1>", self._on_click)
        self.bind("<Button-3>", self._on_right_click)
        self.bind("<MouseWheel>", self._on_scroll)
        self.bind("<Button-4>", lambda e: self._handle_scroll(1, e))
        self.bind("<Button-5>", lambda e: self._handle_scroll(-1, e))
        
        self.redraw(16, 4, 0, 0)

    def set_callbacks(self, on_rot=None, on_pulse=None):
        self.on_rot_change = on_rot
        self.on_pulse_change = on_pulse

    def _handle_scroll(self, delta, event):
        if getattr(event, 'state', 0) & 0x0001:  # Shift held -> adjust pulses
            if self.on_pulse_change and self.steps > 0:
                new_p = max(0, min(self.steps, self.pulses + delta))
                self.on_pulse_change(new_p)
        else:  # Normal scroll -> slip rotation
            if self.on_rot_change and self.steps > 0:
                new_r = (self.rot + delta) % self.steps
                self.on_rot_change(new_r)
        self.flash()

    def _on_scroll(self, event):
        delta = 1 if event.delta > 0 else -1
        self._handle_scroll(delta, event)

    def _on_right_click(self, event):
        if self.on_rot_change and self.steps > 0:
            new_r = (self.rot - 1) % self.steps
            self.on_rot_change(new_r)
            self.flash()

    def _on_click(self, event):
        dx = event.x - self.cx
        dy = event.y - self.cy
        dist = math.hypot(dx, dy)
        if self.steps <= 0: return
        if dist <= 10:
            # Click center hub -> advance rotation
            if self.on_rot_change:
                new_r = (self.rot + 1) % self.steps
                self.on_rot_change(new_r)
                self.flash()
        elif 10 < dist <= self.r + 14:
            # Click step on perimeter -> set rotation directly to that step
            ang = math.atan2(dy, dx)
            norm_ang = (ang + math.pi / 2.0) % (2.0 * math.pi)
            clicked_step = int(round((norm_ang / (2.0 * math.pi)) * self.steps)) % self.steps
            if self.on_rot_change:
                self.on_rot_change(clicked_step)
                self.flash()
        
    def redraw(self, steps, pulses, rot, cur_step=0):
        try:
            new_steps = max(1, min(64, int(steps)))
            new_pulses = max(0, min(new_steps, int(pulses)))
            new_rot = int(rot) % new_steps if new_steps > 0 else 0
            new_cur = int(cur_step) % new_steps if new_steps > 0 else 0
        except (ValueError, TypeError): return

        geom_key = (new_steps, new_pulses, new_rot, self.size)
        prev_cur = self.cur_step
        self.steps, self.pulses, self.rot, self.cur_step = new_steps, new_pulses, new_rot, new_cur

        if getattr(self, '_last_geom_key', None) == geom_key and hasattr(self, '_cached_pattern'):
            if prev_cur == new_cur:
                return
            pattern = self._cached_pattern
            try:
                for i in (prev_cur, new_cur):
                    if 0 <= i < self.steps:
                        item = self.node_items[i]
                        angle = -math.pi / 2.0 + (2.0 * math.pi * i) / float(self.steps)
                        x = self.cx + self.r * math.cos(angle)
                        y = self.cy + self.r * math.sin(angle)
                        is_pulse = pattern[i] if i < len(pattern) else False
                        if is_pulse:
                            rad = 4.0 if i == self.cur_step else 3.0
                            color = "#ffffff" if i == self.cur_step else "#ff8a4c"
                            border = "#ff9a3c" if i == self.cur_step else "#8c3b1e"
                        else:
                            rad = 2.5 if i == self.cur_step else 1.5
                            color = "#ff8a4c" if i == self.cur_step else "#261324"
                            border = "#ffffff" if i == self.cur_step else ""
                        self.coords(item, x - rad, y - rad, x + rad, y + rad)
                        self.itemconfig(item, fill=color, outline=border)
                cur_ang = -math.pi / 2.0 + (2.0 * math.pi * self.cur_step) / float(self.steps)
                hx = self.cx + self.r * math.cos(cur_ang)
                hy = self.cy + self.r * math.sin(cur_ang)
                self.coords(self.sweep_hand, self.cx, self.cy, hx, hy)
                self.coords(self.sweep_tip, hx - 2.5, hy - 2.5, hx + 2.5, hy + 2.5)
            except Exception:
                pass
            return

        self._last_geom_key = geom_key
        pattern = EuclideanGenerator.generate(self.steps, self.pulses, self.rot)
        self._cached_pattern = pattern
        active_coords = []
        
        try:
            # Update center hub text
            self.itemconfig(self.center_txt, text=f"R:{self.rot}")
            
            for i in range(len(self.node_items)):
                item = self.node_items[i]
                if i < self.steps:
                    angle = -math.pi / 2.0 + (2.0 * math.pi * i) / float(self.steps)
                    x = self.cx + self.r * math.cos(angle)
                    y = self.cy + self.r * math.sin(angle)
                    is_pulse = pattern[i] if i < len(pattern) else False
                    if is_pulse:
                        active_coords.extend([x, y])
                        rad = 4.0 if i == self.cur_step else 3.0
                        color = "#ffffff" if i == self.cur_step else "#ff8a4c"
                        border = "#ff9a3c" if i == self.cur_step else "#8c3b1e"
                    else:
                        rad = 2.5 if i == self.cur_step else 1.5
                        color = "#ff8a4c" if i == self.cur_step else "#261324"
                        border = "#ffffff" if i == self.cur_step else ""
                    self.coords(item, x - rad, y - rad, x + rad, y + rad)
                    self.itemconfig(item, fill=color, outline=border)
                else:
                    self.coords(item, 0, 0, 0, 0)
                    self.itemconfig(item, fill="", outline="")
                    
            if len(active_coords) >= 6:
                self.coords(self.poly_line, *active_coords)
                self.itemconfig(self.poly_line, fill="#260e20", outline="#ff8a4c")
            elif len(active_coords) >= 4:
                self.coords(self.poly_line, *active_coords)
                self.itemconfig(self.poly_line, fill="", outline="#ff8a4c")
            else:
                self.coords(self.poly_line, 0, 0, 0, 0)
                self.itemconfig(self.poly_line, fill="", outline="")
                
            cur_ang = -math.pi / 2.0 + (2.0 * math.pi * self.cur_step) / float(self.steps)
            hx = self.cx + self.r * math.cos(cur_ang)
            hy = self.cy + self.r * math.sin(cur_ang)
            self.coords(self.sweep_hand, self.cx, self.cy, hx, hy)
            self.coords(self.sweep_tip, hx - 2.5, hy - 2.5, hx + 2.5, hy + 2.5)
        except tk.TclError: pass
        except Exception: pass
        
    def flash(self, vel=100):
        try:
            self.coords(self.flash_ring, self.cx - 6, self.cy - 6, self.cx + 6, self.cy + 6)
            self.itemconfig(self.flash_ring, outline="#ffffff")
            def _decay(step=1):
                if step > 5:
                    try: self.itemconfig(self.flash_ring, outline="")
                    except: pass
                    return
                dr = 7 * step
                try:
                    self.coords(self.flash_ring, self.cx - dr, self.cy - dr, self.cx + dr, self.cy + dr)
                    color = "#ff9a3c" if step == 2 else ("#c85a28" if step == 3 else ("#8c3b20" if step == 4 else "#331822"))
                    self.itemconfig(self.flash_ring, outline=color)
                    self.after(26, lambda: _decay(step + 1))
                except: pass
            _decay()
        except Exception: pass


class EuclidPulseStrip(tk.Canvas):
    """Linear Euclidean step ribbon visualizing Bjorklund pulse distribution, formula, and playback position."""
    def __init__(self, parent, height=38, **kwargs):
        super().__init__(parent, height=height, bg="#0a060c", highlightthickness=1, highlightbackground="#2d1a2b", bd=0, **kwargs)
        self.h = height
        self.w = 320
        self.steps = 16
        self.pulses = 4
        self.rot = 0
        self.cur_step = 0
        self.bind("<Configure>", self._on_resize)
        
    def _on_resize(self, event):
        if event.width > 20 and (event.width != self.w or event.height != self.h):
            self.w = event.width
            self.h = event.height
            self.redraw(self.steps, self.pulses, self.rot, self.cur_step)
            
    def redraw(self, steps, pulses, rot, cur_step=0):
        try:
            new_steps = max(1, min(64, int(steps)))
            new_pulses = max(0, min(new_steps, int(pulses)))
            new_rot = int(rot) % new_steps if new_steps > 0 else 0
            new_cur = int(cur_step) % new_steps if new_steps > 0 else 0

            geom_key = (new_steps, new_pulses, new_rot, self.w, self.h)
            prev_cur = self.cur_step
            self.steps, self.pulses, self.rot, self.cur_step = new_steps, new_pulses, new_rot, new_cur

            pad_l = 8
            pad_r = 8
            avail_w = max(20, self.w - pad_l - pad_r)
            step_w = avail_w / float(self.steps)

            if getattr(self, '_last_geom_key', None) == geom_key and hasattr(self, '_oval_items'):
                if prev_cur == new_cur:
                    return
                pattern = self._cached_pattern
                cx = pad_l + (new_cur + 0.5) * step_w
                self.coords(self._ph_box, cx - step_w*0.45, 16, cx + step_w*0.45, self.h - 2)
                self.coords(self._ph_line, cx, 16, cx, self.h - 2)
                for s in (prev_cur, new_cur):
                    if 0 <= s < len(self._oval_items):
                        is_hit = pattern[s] if s < len(pattern) else False
                        is_cur = (s == new_cur)
                        if is_hit:
                            fill_c = "#ffffff" if is_cur else "#ff8a4c"
                            out_c = "#ff9a3c" if is_cur else "#8c3b1e"
                        else:
                            fill_c = "#ff8a4c" if is_cur else "#1c1020"
                            out_c = "#ffffff" if is_cur else "#2d1a2b"
                        self.itemconfig(self._oval_items[s], fill=fill_c, outline=out_c)
                return

            self._last_geom_key = geom_key
            self.delete("all")
            self._oval_items = []

            # Prominent, highly readable density readout anchored on the right in warm dark orange
            density_pct = (self.pulses / float(self.steps)) * 100.0 if self.steps > 0 else 0.0
            self.create_text(self.w - pad_r, 3, text=f"DENSITY: {density_pct:.0f}%", anchor='ne', fill="#ff8a4c", font=('Consolas', 8))
            
            # Subtle divider line between header readout and step track
            self.create_line(pad_l, 15, self.w - pad_r, 15, fill="#1c0f1e", width=1)
            
            # Compute Bjorklund pulse distribution via unified EuclideanGenerator
            pattern = EuclideanGenerator.generate(self.steps, self.pulses, self.rot)
            self._cached_pattern = pattern
                    
            row_y = self.h - 12
            cur_cx = pad_l + (self.cur_step + 0.5) * step_w
            self._ph_box = self.create_rectangle(cur_cx - step_w*0.45, 16, cur_cx + step_w*0.45, self.h - 2, fill="#321626", outline="#b34722", width=1)
            self._ph_line = self.create_line(cur_cx, 16, cur_cx, self.h - 2, fill="#ff8a4c", width=1)

            for s in range(self.steps):
                cx = pad_l + (s + 0.5) * step_w
                is_hit = pattern[s] if s < len(pattern) else False
                is_cur = (s == self.cur_step)
                rad = 4.0 if is_hit else 2.5
                if is_hit:
                    fill_c = "#ffffff" if is_cur else "#ff8a4c"
                    out_c = "#ff9a3c" if is_cur else "#8c3b1e"
                else:
                    fill_c = "#ff8a4c" if is_cur else "#1c1020"
                    out_c = "#ffffff" if is_cur else "#2d1a2b"
                ov = self.create_oval(cx - rad, row_y - rad, cx + rad, row_y + rad, fill=fill_c, outline=out_c, width=1)
                self._oval_items.append(ov)
        except tk.TclError: pass
        except Exception: pass
        
    def flash(self):
        try:
            f_rect = self.create_rectangle(2, 2, self.w - 2, self.h - 2, fill="", outline="#c85a28", width=1)
            self.after(70, lambda: self.delete(f_rect))
        except Exception: pass


class AksakArchitectureGauge(tk.Canvas):
    """Additive Aksak Cell Architecture Gauge. Displays metric cell compartments (2s and 3s),
    thesis downbeat anchors, and live subdivision progress."""
    def __init__(self, parent, width=500, height=60, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#0d090f", highlightthickness=1, highlightbackground="#3a2034", bd=0, **kwargs)
        self.w = width
        self.h = height
        self.blocks = [2, 2, 2, 3]
        self.cur_step = 0
        self.bind("<Configure>", self._on_resize)
        self.redraw([2, 2, 2, 3], 0)
        
    def _on_resize(self, event):
        if event.width > 20 and (event.width != self.w or event.height != self.h):
            self.w = event.width
            self.h = event.height
            self.redraw(self.blocks, self.cur_step)
        
    def redraw(self, blocks, cur_step=0):
        if not isinstance(blocks, list) or not blocks:
            blocks = [2, 2, 2, 3]
        self.blocks = blocks
        total_steps = max(1, sum(self.blocks))
        try: self.cur_step = int(cur_step) % total_steps
        except: self.cur_step = 0
        
        try:
            self.delete("all")
            pad_x = 2
            avail_w = max(20, self.w - (2 * pad_x))
            
            accum = 0
            active_b_idx = 0
            internal_step = 0
            for idx, b in enumerate(self.blocks):
                if accum <= self.cur_step < accum + b:
                    active_b_idx = idx
                    internal_step = self.cur_step - accum
                    break
                accum += b
                
            cur_x = pad_x
            for idx, b in enumerate(self.blocks):
                bw = (b / float(total_steps)) * avail_w
                is_active_blk = (idx == active_b_idx)
                
                bg_col = "#441838" if is_active_blk else "#120a15"
                border_col = "#ff8a4c" if is_active_blk else "#2d182b"
                border_w = 2.0 if is_active_blk else 1.0
                self.create_rectangle(cur_x, 2, cur_x + bw - 1, self.h - 2, fill=bg_col, outline=border_col, width=border_w)
                
                num_col = "#ff8a4c" if is_active_blk else "#6b3f5a"
                self.create_text(cur_x + bw/2.0, 11, text=str(b), fill=num_col, font=('Consolas', 8))
                
                led_y = self.h - 14
                sub_w = bw / float(b)
                
                # Render subdivisions inside this metric cell
                for s in range(b):
                    sub_cx = cur_x + (s + 0.5) * sub_w
                    is_cur_sub = (is_active_blk and internal_step == s)
                    
                    if s == 0:
                        # Primary Thesis downbeat anchor LED
                        if is_cur_sub:
                            self.create_rectangle(sub_cx - sub_w*0.42, 18, sub_cx + sub_w*0.42, self.h - 4, fill="#5a1e48", outline="#b34722", width=1)
                            self.create_oval(sub_cx - 5, led_y - 5, sub_cx + 5, led_y + 5, fill="#ffffff", outline="#b34722", width=1)
                        else:
                            pip_col = "#ff8a4c" if is_active_blk else "#663344"
                            self.create_oval(sub_cx - 4, led_y - 4, sub_cx + 4, led_y + 4, fill=pip_col, outline="#3a182b", width=1)
                    else:
                        # Arsis secondary pickup dot
                        if is_cur_sub:
                            self.create_rectangle(sub_cx - sub_w*0.42, 16, sub_cx + sub_w*0.42, self.h - 3, fill="#5a1e48", outline="#b34722", width=1)
                            self.create_oval(sub_cx - 4, led_y - 4, sub_cx + 4, led_y + 4, fill="#ff8a4c", outline="#ffffff", width=1)
                        else:
                            dot_col = "#c752d8" if is_active_blk else "#2b1626"
                            self.create_oval(sub_cx - 3, led_y - 3, sub_cx + 3, led_y + 3, fill=dot_col, outline="")
                            
                if is_active_blk:
                    # Subdivision cursor sweep hairline
                    cursor_x = cur_x + (internal_step + 0.5) * sub_w
                    self.create_line(cursor_x, 3, cursor_x, self.h - 3, fill="#ff8a4c", width=1.5)
                    
                cur_x += bw
        except tk.TclError: pass
        except Exception: pass
        
    def flash(self):
        try:
            f_rect = self.create_rectangle(2, 2, self.w - 2, self.h - 2, fill="", outline="#c85a28", width=1)
            self.after(80, lambda: self.delete(f_rect))
        except Exception: pass


class MasterHardwareMeterBridge(tk.Canvas):
    """Large-format real-time 16-channel hardware MIDI output monitor.
    Tracks live Note-On and CC modulation dispatch across MIDI channels 1-16 with ballistic decay."""
    CHANNEL_ROLES = [
        "GM", "HYD", "PLA", "M04", "BD", "BAS",
        "SD", "HHT", "M09", "PIG", "PAN", "M12",
        "M13", "M14", "M15", "MST"
    ]

    def __init__(self, parent, width=480, height=86, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#08040b",
                         highlightthickness=1, highlightbackground="#2d1d2b", bd=0, **kwargs)
        self.w = width
        self.h = height
        self.note_leds = []
        self.cc_leds = []
        self.role_labels = []
        self._last_roles = list(self.CHANNEL_ROLES)
        self._build_ui()

    def _build_ui(self):
        self.delete("all")
        self.note_leds = []
        self.cc_leds = []
        self.role_labels = []

        # Inner cyberdeck bezel frame
        self.create_rectangle(1, 1, self.w - 2, self.h - 2, outline="#1a0f1d", width=1)
        self.create_line(2, self.h - 16, self.w - 2, self.h - 16, fill="#150a17", width=1)
        self.create_text(self.w / 2.0, self.h - 8, text="MASTER 16-CHANNEL MIDI HARDWARE BUS", fill="#5a3d54", font=('Consolas', 6))

        # Left lane indicators
        self.create_text(8, 38, text="NOTE", fill="#8a5c74", font=('Consolas', 6), anchor='w')
        self.create_text(8, 56, text="CC", fill="#3d7285", font=('Consolas', 6), anchor='w')

        margin_left = 32.0
        avail_w = self.w - margin_left - 6.0
        col_w = avail_w / 16.0

        for ch in range(16):
            cx = margin_left + (ch + 0.5) * col_w
            x1 = margin_left + ch * col_w

            # Column dividing line
            if ch > 0:
                self.create_line(x1, 3, x1, self.h - 17, fill="#140a16", width=1)

            # Channel Number (01..16)
            self.create_text(cx, 11, text=f"{ch+1:02d}", fill="#8c7084", font=('Consolas', 7, 'bold'))

            # Channel Role / Category
            role = self._last_roles[ch] if ch < len(self._last_roles) else ""
            r_lbl = self.create_text(cx, 22, text=role, fill="#52394c", font=('Consolas', 6))
            self.role_labels.append(r_lbl)

            # Note-On LED capsule (pill shape)
            pw = max(6.0, (col_w - 6.0) / 2.0)
            n_led = self.create_rectangle(cx - pw, 31, cx + pw, 45, fill="#140a16", outline="#241426", width=1)
            self.note_leds.append(n_led)

            # CC Modulation LED capsule (pill shape)
            c_led = self.create_rectangle(cx - pw, 49, cx + pw, 63, fill="#081216", outline="#10222a", width=1)
            self.cc_leds.append(c_led)

    def resize(self, width, height):
        self.w = max(240, int(width))
        self.h = max(50, int(height))
        self.config(width=self.w, height=self.h)
        self._build_ui()

    def update_traffic(self, note_activity, cc_activity, custom_roles=None):
        now = time.perf_counter()
        decay = 0.18
        try:
            if custom_roles and len(custom_roles) == 16 and custom_roles != self._last_roles:
                self._last_roles = list(custom_roles)
                for ch in range(min(16, len(self.role_labels))):
                    self.itemconfig(self.role_labels[ch], text=custom_roles[ch])
            if not hasattr(self, '_last_n_col') or len(self._last_n_col) != 16:
                self._last_n_col = [None] * 16
                self._last_c_col = [None] * 16
            for ch in range(16):
                dt_note = now - note_activity[ch]
                if dt_note < decay:
                    ratio = 1.0 - (dt_note / decay)
                    r = int(20 + 235 * ratio)
                    g = int(10 + 160 * ratio)
                    b = int(22 + 40 * ratio)
                    n_state = (f"#{r:02x}{g:02x}{b:02x}", "#ffcc66" if ratio > 0.5 else "#381a30")
                else:
                    n_state = ("#140a16", "#241426")
                if self._last_n_col[ch] != n_state:
                    self._last_n_col[ch] = n_state
                    self.itemconfig(self.note_leds[ch], fill=n_state[0], outline=n_state[1])

                dt_cc = now - cc_activity[ch]
                if dt_cc < decay:
                    ratio = 1.0 - (dt_cc / decay)
                    r = int(8 + 50 * ratio)
                    g = int(18 + 180 * ratio)
                    b = int(22 + 225 * ratio)
                    c_state = (f"#{r:02x}{g:02x}{b:02x}", "#64d8cb" if ratio > 0.5 else "#122630")
                else:
                    c_state = ("#081216", "#10222a")
                if self._last_c_col[ch] != c_state:
                    self._last_c_col[ch] = c_state
                    self.itemconfig(self.cc_leds[ch], fill=c_state[0], outline=c_state[1])
        except tk.TclError: pass
        except Exception: pass


class NixieTransportCounter(tk.Canvas):
    """Digital Nixie tube / 7-segment digital display showing BAR : BEAT : STEP and ELAPSED TIME / TEMPO."""
    def __init__(self, parent, width=280, height=86, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#070408", highlightthickness=1, highlightbackground="#3a2435", bd=0, **kwargs)
        self.w = width
        self.h = height
        self._last_glow_state = None
        
        # Outer bezel and inner dividing chamber with beat-glow backdrop
        self.glow_bg = self.create_rectangle(1, 1, width-2, height-2, fill="#070408", outline="#1f1122", width=1)
        self.create_line(8, 44, width-8, 44, fill="#1c0f1e", width=1)
        
        # Column centers for Tier 1 (Position)
        c_bar = int(width * 0.20)
        s_1 = int(width * 0.38)
        c_beat = int(width * 0.54)
        s_2 = int(width * 0.70)
        c_step = int(width * 0.85)
        
        # ROW 1: Labels (clean unbold Consolas 7)
        self.create_text(c_bar, 12, text="BAR", fill="#8c6b84", font=('Consolas', 7))
        self.create_text(c_beat, 12, text="BEAT", fill="#8c6b84", font=('Consolas', 7))
        self.create_text(c_step, 12, text="STEP", fill="#8c6b84", font=('Consolas', 7))
        
        # ROW 1: Ghost segment backdrops (large Consolas 15 bold)
        self.create_text(c_bar, 28, text="888", fill="#241208", font=('Consolas', 15, 'bold'))
        self.create_text(s_1, 28, text=":", fill="#241208", font=('Consolas', 15, 'bold'))
        self.create_text(c_beat, 28, text="88", fill="#241208", font=('Consolas', 15, 'bold'))
        self.create_text(s_2, 28, text=":", fill="#241208", font=('Consolas', 15, 'bold'))
        self.create_text(c_step, 28, text="88", fill="#241208", font=('Consolas', 15, 'bold'))
        
        # ROW 1: Active glowing values (Consolas 15 bold nixie filaments)
        self.val_bar = self.create_text(c_bar, 28, text="001", fill="#ff9a3c", font=('Consolas', 15, 'bold'))
        self.sep_1 = self.create_text(s_1, 28, text=":", fill="#ff9a3c", font=('Consolas', 15, 'bold'))
        self.val_beat = self.create_text(c_beat, 28, text="01", fill="#ff9a3c", font=('Consolas', 15, 'bold'))
        self.sep_2 = self.create_text(s_2, 28, text=":", fill="#ff9a3c", font=('Consolas', 15, 'bold'))
        self.val_step = self.create_text(c_step, 28, text="01", fill="#ff9a3c", font=('Consolas', 15, 'bold'))
        
        # Column centers for Tier 2 (Elapsed Time & Tempo)
        c_time = int(width * 0.30)
        c_tempo = int(width * 0.76)
        
        # ROW 2: Labels
        self.create_text(c_time, 56, text="ELAPSED TIME", fill="#6d5d74", font=('Consolas', 7))
        self.create_text(c_tempo, 56, text="TEMPO / DIV", fill="#6d5d74", font=('Consolas', 7))
        
        # ROW 2: Ghost segment backdrops (Consolas 11 bold)
        self.create_text(c_time, 71, text="88:88.88", fill="#0e1b20", font=('Consolas', 11, 'bold'))
        self.create_text(c_tempo, 71, text="888.8 1x", fill="#0e1b20", font=('Consolas', 11, 'bold'))
        
        # ROW 2: Active glowing values (Consolas 11 bold)
        self.val_time = self.create_text(c_time, 71, text="00:00.00", fill="#64d8cb", font=('Consolas', 11, 'bold'))
        self.val_tempo = self.create_text(c_tempo, 71, text="120.0 1x", fill="#64d8cb", font=('Consolas', 11, 'bold'))
        
    def update_pos(self, current_tick, meter_steps=16, time_div=1, bpm=120.0, running=True):
        try:
            eff_tick = max(0, int(current_tick) // max(1, int(time_div)))
            ticks_per_step = 6
            steps_per_bar = max(1, int(meter_steps))
            ticks_per_bar = steps_per_bar * ticks_per_step
            
            bar = (eff_tick // ticks_per_bar) + 1
            rem_ticks = eff_tick % ticks_per_bar
            beat = (rem_ticks // 24) + 1
            step = ((rem_ticks % 24) // ticks_per_step) + 1
            
            s_bar, s_beat, s_step = f"{bar:03d}", f"{beat:02d}", f"{step:02d}"
            if getattr(self, '_last_s_bar', None) != s_bar:
                self._last_s_bar = s_bar
                self.itemconfig(self.val_bar, text=s_bar)
            if getattr(self, '_last_s_beat', None) != s_beat:
                self._last_s_beat = s_beat
                self.itemconfig(self.val_beat, text=s_beat)
            if getattr(self, '_last_s_step', None) != s_step:
                self._last_s_step = s_step
                self.itemconfig(self.val_step, text=s_step)
            
            # Beat pulse & glow: faint glow with the beat, changing color on the 1
            if running and current_tick > 0:
                beat_tick = eff_tick % 24
                if rem_ticks < 6:
                    glow_state = 'downbeat_1'
                elif rem_ticks < 12:
                    glow_state = 'downbeat_1_decay'
                elif beat_tick < 6:
                    glow_state = 'beat_pulse'
                elif beat_tick < 12:
                    glow_state = 'beat_decay'
                else:
                    glow_state = 'idle'
            else:
                glow_state = 'idle'
            
            if glow_state != self._last_glow_state:
                self._last_glow_state = glow_state
                if glow_state == 'downbeat_1':
                    self.itemconfig(self.glow_bg, fill="#091f24", outline="#257885")
                    self.config(highlightbackground="#257885")
                    for item in (self.val_bar, self.val_beat, self.val_step, self.sep_1, self.sep_2):
                        self.itemconfig(item, fill="#64d8cb")
                elif glow_state == 'downbeat_1_decay':
                    self.itemconfig(self.glow_bg, fill="#081418", outline="#174850")
                    self.config(highlightbackground="#174850")
                    for item in (self.val_bar, self.val_beat, self.val_step, self.sep_1, self.sep_2):
                        self.itemconfig(item, fill="#8fe3da")
                elif glow_state == 'beat_pulse':
                    self.itemconfig(self.glow_bg, fill="#1c0c05", outline="#6e2d12")
                    self.config(highlightbackground="#6e2d12")
                    for item in (self.val_bar, self.val_beat, self.val_step, self.sep_1, self.sep_2):
                        self.itemconfig(item, fill="#ffb366")
                elif glow_state == 'beat_decay':
                    self.itemconfig(self.glow_bg, fill="#100703", outline="#3d190a")
                    self.config(highlightbackground="#3d190a")
                    for item in (self.val_bar, self.val_beat, self.val_step, self.sep_1, self.sep_2):
                        self.itemconfig(item, fill="#ffa044")
                else: # 'idle'
                    self.itemconfig(self.glow_bg, fill="#070408", outline="#1f1122")
                    self.config(highlightbackground="#3a2435")
                    for item in (self.val_bar, self.val_beat, self.val_step, self.sep_1, self.sep_2):
                        self.itemconfig(item, fill="#ff9a3c")

            # Row 2 Elapsed Time & Clock
            try: tempo_f = float(bpm)
            except (ValueError, TypeError): tempo_f = 120.0
            ticks_per_sec = 24.0 * (tempo_f / 60.0)
            elapsed_s = (eff_tick / ticks_per_sec) if ticks_per_sec > 0 else 0.0
            m = int(elapsed_s // 60)
            s = int(elapsed_s % 60)
            cs = int((elapsed_s * 100) % 100)
            div_str = "1/2x" if time_div == 2 else "1x"
            
            s_time = f"{m:02d}:{s:02d}.{cs:02d}"
            s_tempo = f"{tempo_f:5.1f} {div_str}"
            if getattr(self, '_last_s_time', None) != s_time:
                self._last_s_time = s_time
                self.itemconfig(self.val_time, text=s_time)
            if getattr(self, '_last_s_tempo', None) != s_tempo:
                self._last_s_tempo = s_tempo
                self.itemconfig(self.val_tempo, text=s_tempo)
        except tk.TclError: pass
        except Exception: pass


class MauveZoneLogoCanvas(tk.Canvas):
    """Artistic Cyberdeck MAUVE ZONE Animated Logo Canvas.
    Renders an organic bruised purple / mauve / amber chromatic wave flowing across
    intricate ASCII letterforms, responsive to sequencer transport state and mouse interaction."""
    ASCII_ART = [
        "███╗   ███╗ █████╗ ██╗   ██╗██╗   ██╗███████╗    ███████╗ ██████╗ ███╗   ██╗███████╗",
        "████╗ ████║██╔══██╗██║   ██║██║   ██║██╔════╝    ╚══███╔╝██╔═══██╗████╗  ██║██╔════╝",
        "██╔████╔██║███████║██║   ██║██║   ██║█████╗        ███╔╝ ██║   ██║██╔██╗ ██║█████╗  ",
        "██║╚██╔╝██║██╔══██║██║   ██║╚██╗ ██╔╝██╔══╝       ███╔╝  ██║   ██║██║╚██╗██║██╔══╝  ",
        "██║ ╚═╝ ██║██║  ██║╚██████╔╝ ╚████╔╝ ███████╗    ███████╗╚██████╔╝██║ ╚████║███████╗",
        "╚═╝     ╚═╝╚═╝  ╚═╝ ╚═════╝   ╚═══╝  ╚══════╝    ╚══════╝ ╚═════╝ ╚═╝  ╚═══╝╚══════╝"
    ]

    PALETTE = [
        (0.00, "#4a1c47"),
        (0.20, "#732970"),
        (0.38, "#ad4f9f"),
        (0.52, "#ffaa4c"), # Golden Amber / Sepia Peak
        (0.68, "#d968b5"),
        (0.85, "#5f235d"),
        (1.00, "#4a1c47")
    ]

    @staticmethod
    def _interpolate_color(c1, c2, t):
        t = max(0.0, min(1.0, t))
        r1, g1, b1 = int(c1[1:3], 16), int(c1[3:5], 16), int(c1[5:7], 16)
        r2, g2, b2 = int(c2[1:3], 16), int(c2[3:5], 16), int(c2[5:7], 16)
        r = int(r1 + (r2 - r1) * t)
        g = int(g1 + (g2 - g1) * t)
        b = int(b1 + (b2 - b1) * t)
        return f"#{r:02x}{g:02x}{b:02x}"

    @classmethod
    def _get_palette_color(cls, pos):
        pos = pos % 1.0
        for i in range(len(cls.PALETTE) - 1):
            p1, c1 = cls.PALETTE[i]
            p2, c2 = cls.PALETTE[i+1]
            if p1 <= pos <= p2:
                t = (pos - p1) / (p2 - p1)
                return cls._interpolate_color(c1, c2, t)
        return cls.PALETTE[0][1]

    def __init__(self, parent, width=655, height=121, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#0d0811",
                         highlightthickness=1, highlightbackground="#3d1b38", bd=0, cursor="hand2", **kwargs)
        self.w = width
        self.h = height
        self.factor = 1.0
        self.wave_phase = 0.0
        self.is_running = False
        self.ripple_active = False
        self.ripple_center = 0.5
        self.ripple_phase = 0.0
        self.hover_x = -1.0
        self.chunk_size = 2
        self.text_items = []
        self._init_elements()

        self.bind("<Enter>", self._on_enter)
        self.bind("<Leave>", self._on_leave)
        self.bind("<Motion>", self._on_motion)
        self.bind("<Button-1>", self._on_click)

    def resize(self, width, height, factor=1.0):
        self.w = max(240, int(width))
        self.h = max(60, int(height))
        self.factor = factor
        self.config(width=self.w, height=self.h)
        self._init_elements()

    def _init_elements(self):
        self.delete("all")
        self.text_items = []

        # Cybernetic corner brackets
        bw = max(12, int(round(18 * self.factor)))
        bh = max(12, int(round(18 * self.factor)))
        c_edge = "#4a224a"
        self.create_line(4, 4, 4 + bw, 4, fill=c_edge, width=1, tags="chrome")
        self.create_line(4, 4, 4, 4 + bh, fill=c_edge, width=1, tags="chrome")
        self.create_line(self.w - 5, 4, self.w - 5 - bw, 4, fill=c_edge, width=1, tags="chrome")
        self.create_line(self.w - 5, 4, self.w - 5, 4 + bh, fill=c_edge, width=1, tags="chrome")
        self.create_line(4, self.h - 5, 4 + bw, self.h - 5, fill=c_edge, width=1, tags="chrome")
        self.create_line(4, self.h - 5, 4, self.h - 5 - bh, fill=c_edge, width=1, tags="chrome")
        self.create_line(self.w - 5, self.h - 5, self.w - 5 - bw, self.h - 5, fill=c_edge, width=1, tags="chrome")
        self.create_line(self.w - 5, self.h - 5, self.w - 5, self.h - 5 - bh, fill=c_edge, width=1, tags="chrome")

        # Subtitle banner - completely visible across the entire base, zero truncation
        sub_font_size = max(7, int(round(10 * self.factor)))
        sub_font = ("Consolas", sub_font_size)
        sub_text = f"S T O C H A S T I C   C O M P O S E R    v {APP_VERSION} "
        self.sub_tag = self.create_text(max(12, int(round(16 * self.factor))),
                                        self.h - max(10, int(round(14 * self.factor))),
                                        text=sub_text,
                                        fill="#a8829f", font=sub_font, anchor="w", tags="chrome")

        # Monospace font for the logo letterforms
        font_size = max(4, int(round(6 * self.factor)))
        f = tkfont.Font(family="Consolas", size=font_size)
        char_w = f.measure("█")
        line_h = f.metrics("linespace")

        total_cols = len(self.ASCII_ART[0])
        x_start = max(12, int(round(16 * self.factor)))
        y_start = max(10, int(round(13 * self.factor)))

        for row_idx, line in enumerate(self.ASCII_ART):
            y = y_start + row_idx * line_h
            row_chunks = []
            for col_start in range(0, len(line), self.chunk_size):
                chunk = line[col_start:col_start + self.chunk_size]
                if not chunk: continue
                x = x_start + col_start * char_w
                norm_x = (col_start + self.chunk_size / 2.0) / total_cols
                init_color = self._get_palette_color(norm_x)
                tag = self.create_text(x, y, text=chunk, fill=init_color,
                                       font=f, anchor="nw", tags="logo_text")
                row_chunks.append((tag, norm_x))
            self.text_items.append(row_chunks)

    def _on_enter(self, e):
        self.hover_x = e.x / max(1, self.w)

    def _on_leave(self, e):
        self.hover_x = -1.0

    def _on_motion(self, e):
        self.hover_x = e.x / max(1, self.w)

    def _on_click(self, e=None):
        ev_x = getattr(e, 'x', self.w // 2) if e is not None else (self.w // 2)
        self.ripple_center = ev_x / max(1, self.w)
        self.ripple_phase = 0.0
        self.ripple_active = True

    def tick_anim(self, running=False, dt=0.05):
        self.is_running = running

        # The gradient should flow when sequencer is engaged, otherwise it's static.
        if not running and not self.ripple_active and self.hover_x < 0:
            return

        if running:
            speed = 0.22
            self.wave_phase = (self.wave_phase + dt * speed) % 1.0

        if self.ripple_active:
            self.ripple_phase += dt * 1.6
            if self.ripple_phase > 1.2:
                self.ripple_active = False

        for row in self.text_items:
            for tag, norm_x in row:
                pos = (norm_x - self.wave_phase) % 1.0 if running else norm_x

                if self.hover_x >= 0:
                    d_hover = abs(norm_x - self.hover_x)
                    if d_hover < 0.16:
                        pos = (pos + (0.16 - d_hover) * 2.2) % 1.0

                if self.ripple_active:
                    d_rip = abs(norm_x - self.ripple_center)
                    if abs(d_rip - self.ripple_phase) < 0.14:
                        rip_amt = 1.0 - (abs(d_rip - self.ripple_phase) / 0.14)
                        pos = (pos + rip_amt * 0.45) % 1.0

                self.itemconfig(tag, fill=self._get_palette_color(pos))


class ChaosBanner(tk.Canvas):
    """Decorative Cyberdeck Banner for [GLOBAL ANALOG CHAOS INJECTOR].
    Features a dark, bruised mauve & subdued twilight amber chromatic wave.
    Purely decorative?no click or button bindings, adhering strictly to authentic
    Mauve Zone deep bruised plums and dark twilight amber (zero hot pink/magenta)."""
    PALETTE = [
        (0.00, "#1f0a1e"),
        (0.20, "#381336"),
        (0.40, "#541e51"),
        (0.55, "#7a4820"), # Dark subdued warm amber (dark peak, no bright pink)
        (0.70, "#4d1b4a"),
        (0.85, "#331131"),
        (1.00, "#1f0a1e")
    ]

    @staticmethod
    def _interpolate_color(c1, c2, t):
        t = max(0.0, min(1.0, t))
        r1, g1, b1 = int(c1[1:3], 16), int(c1[3:5], 16), int(c1[5:7], 16)
        r2, g2, b2 = int(c2[1:3], 16), int(c2[3:5], 16), int(c2[5:7], 16)
        r = int(r1 + (r2 - r1) * t)
        g = int(g1 + (g2 - g1) * t)
        b = int(b1 + (b2 - b1) * t)
        return f"#{r:02x}{g:02x}{b:02x}"

    @classmethod
    def _get_color(cls, pos):
        pos = pos % 1.0
        for i in range(len(cls.PALETTE) - 1):
            p1, c1 = cls.PALETTE[i]
            p2, c2 = cls.PALETTE[i+1]
            if p1 <= pos <= p2:
                t = (pos - p1) / (p2 - p1)
                return cls._interpolate_color(c1, c2, t)
        return cls.PALETTE[0][1]

    def __init__(self, parent, text="[GLOBAL ANALOG CHAOS INJECTOR]", width=380, height=18, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#0d0811",
                         highlightthickness=1, highlightbackground="#3d1b38", bd=0, **kwargs)
        self.w = width
        self.h = height
        self.text_label = text
        self.phase = 0.0
        self.num_slices = 32

        self._draw_banner()

    def resize(self, width, height):
        self.w = max(100, int(width))
        self.h = max(14, int(height))
        self.config(width=self.w, height=self.h)
        self._draw_banner()

    def tick_anim(self, dt=0.05):
        speed = 0.12 # slow, dignified organic flow
        self.phase = (self.phase + dt * speed) % 1.0
        if not hasattr(self, '_slice_items') or len(self._slice_items) != self.num_slices:
            self._draw_banner()
            return
        for i, rect_id in enumerate(self._slice_items):
            slice_pos = (i / float(self.num_slices) - self.phase) % 1.0
            col = self._get_color(slice_pos)
            self.itemconfig(rect_id, fill=col)

    def _draw_banner(self):
        self.delete("all")
        self._slice_items = []
        dx = self.w / float(self.num_slices)

        for i in range(self.num_slices):
            x1 = int(round(i * dx))
            x2 = int(round((i + 1) * dx)) + 1
            slice_pos = (i / float(self.num_slices) - self.phase) % 1.0
            col = self._get_color(slice_pos)
            rect_id = self.create_rectangle(x1, 0, x2, self.h, fill=col, outline="")
            self._slice_items.append(rect_id)

        # Sleek dark cybernetic border
        self.create_rectangle(0, 0, self.w - 1, self.h - 1, outline="#3d1838", width=1)

        # Subtle corner brackets
        cw = 6
        self.create_line(1, 1, 1 + cw, 1, fill="#5a2355", width=1)
        self.create_line(1, 1, 1, 1 + cw, fill="#5a2355", width=1)
        self.create_line(self.w - 2, 1, self.w - 2 - cw, 1, fill="#5a2355", width=1)
        self.create_line(self.w - 2, 1, self.w - 2, 1 + cw, fill="#5a2355", width=1)

        # Centered monospace label
        self.create_text(self.w // 2, self.h // 2, text=self.text_label, fill="#d6b8d2", font=("Consolas", 8, "bold"))


class HarmonicVectorScope(tk.Canvas):
    """Retro Lissajous / Constellation / Waveform / Spectrum Harmonic Vector Scope (Interactive).
    Visualizes active pitch constellations, time-domain acoustic waveforms, Lissajous phase orbits,
    and 12-band chroma spectrum energy across active voices with phosphor persistence.
    Left-click or right-click to select modes or sleep."""
    NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

    def __init__(self, parent, width=420, height=88, **kwargs):
        super().__init__(parent, width=width, height=height, bg="#060309",
                         highlightthickness=1, highlightbackground="#3a2034", bd=0, cursor="hand2", **kwargs)
        self.w = width
        self.h = height
        self.cx = width / 2.0
        self.cy = height / 2.0
        self.r = min(self.cx, self.cy) - 8.0
        self.mode = "DUAL"
        self.last_update_time = time.perf_counter()
        self.spectrum_levels = [0.0] * 12
        self.spectrum_peaks = [0.0] * 12
        self.spectrum_peak_times = [0.0] * 12

        self._build_static_graticules()
        self._build_dynamic_elements()

        self.bind("<Button-1>", self._handle_click)
        self.bind("<Button-3>", self._show_mode_menu)

    def _build_static_graticules(self):
        self.delete("graticule")
        for gx in range(24, int(self.w), 36):
            self.create_line(gx, 0, gx, self.h, fill="#120914", width=1, tags="graticule")
        for gy in range(14, int(self.h), 20):
            self.create_line(0, gy, self.w, gy, fill="#120914", width=1, tags="graticule")

        self.create_oval(self.cx - self.r, self.cy - self.r, self.cx + self.r, self.cy + self.r, outline="#241226", width=1, tags="graticule")
        self.create_oval(self.cx - self.r*0.66, self.cy - self.r*0.66, self.cx + self.r*0.66, self.cy + self.r*0.66, outline="#180b1a", width=1, tags="graticule")
        self.create_line(self.cx - self.r - 4, self.cy, self.cx + self.r + 4, self.cy, fill="#1e0e20", width=1, tags="graticule")
        self.create_line(self.cx, self.cy - self.r - 4, self.cx, self.cy + self.r + 4, fill="#1e0e20", width=1, tags="graticule")

        for pc in range(12):
            ang = -math.pi / 2.0 + (2.0 * math.pi * pc) / 12.0
            x1 = self.cx + (self.r - 3) * math.cos(ang)
            y1 = self.cy + (self.r - 3) * math.sin(ang)
            x2 = self.cx + self.r * math.cos(ang)
            y2 = self.cy + self.r * math.sin(ang)
            self.create_line(x1, y1, x2, y2, fill="#42203b", width=1, tags="graticule")
            if pc in [0, 3, 5, 7, 10]:
                tx = self.cx + (self.r + 6) * math.cos(ang)
                ty = self.cy + (self.r + 6) * math.sin(ang)
                self.create_text(tx, ty, text=self.NOTE_NAMES[pc], fill="#4d3248", font=('Consolas', 5), tags="graticule")

    def _build_dynamic_elements(self):
        self.trail_line = self.create_line(self.cx, self.cy, self.cx, self.cy, fill="#8c3294", width=1.5, smooth=True)
        self.trace_line = self.create_line(self.cx, self.cy, self.cx, self.cy, fill="#ffaa33", width=2, smooth=True)
        self.poly_line = self.create_polygon(0, 0, 0, 0, fill="#260e22", outline="#c752d8", width=1.5)

        self.node_pool = [self.create_oval(0, 0, 0, 0, fill="#ffe066", outline="#ffffff", width=1) for _ in range(12)]
        self.node_labels = [self.create_text(0, 0, text="", fill="#ffe066", font=('Consolas', 6, 'bold')) for _ in range(12)]

        self.spectrum_bars = [self.create_rectangle(0, 0, 0, 0, fill="#8c3b1e", outline="") for _ in range(12)]
        self.spectrum_pips = [self.create_line(0, 0, 0, 0, fill="#ffea75", width=2) for _ in range(12)]
        self.spectrum_labels = [self.create_text(0, 0, text=self.NOTE_NAMES[i], fill="#5a3d54", font=('Consolas', 6)) for i in range(12)]

        self.chord_text = self.create_text(8, self.h - 8, text="", anchor="sw", fill="#ff9a3c", font=('Consolas', 7))
        self.mode_tag = self.create_text(8, 8, text="VECTOR OSCILLOSCOPE // HARMONIC CONSTELLATION [DUAL]", anchor="nw", fill="#705068", font=('Consolas', 6))

    def _handle_click(self, event):
        if self.mode == "OFF":
            self.set_mode("WAVEFORM")
        else:
            self._show_mode_menu(event)

    def _show_mode_menu(self, event):
        menu = tk.Menu(self, tearoff=0, bg="#100814", fg="#f0d0e0", activebackground="#4a2245", activeforeground="#ffffff", font=('Consolas', 9))
        modes = [
            ("CRT Time-Domain Waveform", "WAVEFORM"),
            ("XY Lissajous Phase Orbit", "LISSAJOUS"),
            ("Chroma Harmonic Constellation", "CONSTELLATION"),
            ("12-Band Chroma Spectrum Analyzer", "SPECTRUM"),
            ("Dual Hybrid (Constellation + Beam)", "DUAL"),
            ("Display Sleep / Off", "OFF")
        ]
        for label, m_key in modes:
            prefix = "✔  " if self.mode == m_key else "    "
            menu.add_command(label=f"{prefix}{label}", command=lambda k=m_key: self.set_mode(k))
        try: menu.tk_popup(event.x_root, event.y_root)
        except Exception: pass

    def set_mode(self, new_mode):
        self.mode = new_mode
        tags = {
            "WAVEFORM": "CRT OSCILLOSCOPE // TIME-DOMAIN [WAVEFORM]",
            "LISSAJOUS": "VECTOR OSCILLOSCOPE // XY PHASE SPACE [LISSAJOUS]",
            "CONSTELLATION": "VECTOR OSCILLOSCOPE // CHROMA POLAR [CONSTELLATION]",
            "SPECTRUM": "VECTOR OSCILLOSCOPE // CHROMA SPECTRUM [12-BAND]",
            "DUAL": "VECTOR OSCILLOSCOPE // HARMONIC CONSTELLATION [DUAL]",
            "OFF": "CRT OSCILLOSCOPE // DISPLAY SLEEP [OFF]"
        }
        self.itemconfig(self.mode_tag, text=tags.get(new_mode, "VECTOR OSCILLOSCOPE"))
        self._hide_all()
        if new_mode == "OFF":
            self.itemconfig(self.chord_text, text="CRT POWER: STANDBY // CLICK TO WAKE")

    def _hide_all(self):
        self.coords(self.trace_line, 0, 0, 0, 0)
        self.coords(self.trail_line, 0, 0, 0, 0)
        self.coords(self.poly_line, 0, 0, 0, 0)
        for i in range(12):
            self.coords(self.node_pool[i], 0, 0, 0, 0)
            self.coords(self.node_labels[i], 0, 0)
            self.coords(self.spectrum_bars[i], 0, 0, 0, 0)
            self.coords(self.spectrum_pips[i], 0, 0, 0, 0)
            self.coords(self.spectrum_labels[i], 0, 0)

    def resize(self, width, height):
        self.w = max(180, int(width))
        self.h = max(60, int(height))
        self.cx = self.w / 2.0
        self.cy = self.h / 2.0
        self.r = min(self.cx, self.cy) - 8.0
        self.config(width=self.w, height=self.h)
        self._build_static_graticules()
        self.coords(self.mode_tag, 8, 8)
        self.coords(self.chord_text, 8, self.h - 8)

    @staticmethod
    def _identify_chord(pitches):
        if not pitches: return "Standby"
        if len(pitches) == 1: return "Single Note"
        pcs = sorted(list({p % 12 for p in pitches}))
        if len(pcs) == 1: return "Octave Unison"
        CHORD_PATTERNS = {
            (0, 4, 7): "Maj Triad", (0, 3, 7): "Min Triad", (0, 3, 6): "Dim Triad", (0, 4, 8): "Aug Triad",
            (0, 4, 7, 10): "Dom 7th", (0, 4, 7, 11): "Maj 7th", (0, 3, 7, 10): "Min 7th", (0, 3, 6, 9): "Dim 7th",
            (0, 3, 6, 10): "Half-Dim 7th", (0, 5, 7): "Sus4", (0, 2, 7): "Sus2",
            (0, 2, 4, 7): "Maj Add9", (0, 2, 3, 7): "Min Add9", (0, 5, 7, 10): "7Sus4",
            (0, 2, 4, 7, 11): "Maj 9th", (0, 2, 3, 7, 10): "Min 9th", (0, 2, 4, 7, 10): "Dom 9th",
            (0, 1, 4, 7, 10): "7(b9)", (0, 3, 4, 7, 10): "7(#9)",
            (0, 4, 7, 9): "Maj 6th", (0, 3, 7, 9): "Min 6th", (0, 2, 4, 7, 9): "6/9",
            (0, 4, 6, 10): "7(b5)", (0, 4, 8, 10): "Aug 7th", (0, 4, 8, 11): "Maj7(#5)",
            (0, 3, 7, 11): "Min/Maj7", (0, 2, 5, 7): "Sus2/4", (0, 5, 7, 11): "Maj7Sus4",
            (0, 2, 5, 7, 10): "11th", (0, 2, 7, 9): "Quartal Stack",
            (0, 7): "Open 5th", (0, 6): "Tritone", (0, 4): "Maj 3rd", (0, 3): "Min 3rd", (0, 5): "Perf 4th"
        }
        for root in pcs:
            shifted = tuple(sorted([(p - root) % 12 for p in pcs]))
            if shifted in CHORD_PATTERNS:
                root_name = HarmonicVectorScope.NOTE_NAMES[root]
                return f"{root_name} {CHORD_PATTERNS[shifted]}"
        return f"{len(pcs)}-Tone Chord"

    def update_scope(self, sounding_notes):
        if self.mode == "OFF": return
        now = time.perf_counter()
        dt = max(0.001, min(0.1, now - self.last_update_time))
        self.last_update_time = now

        pitches = sorted(list({n for chan, n in sounding_notes}))[:12] if sounding_notes else []

        if pitches:
            chord_str = ' · '.join([f"{self.NOTE_NAMES[p % 12]}{(p // 12) - 1}" for p in pitches[:6]])
            chord_desc = self._identify_chord(pitches)
        else:
            chord_str = ""
            chord_desc = "STANDBY // SCANNING"

        if self.mode == "WAVEFORM":

            if pitches:
                sig_text = f"SIGNAL: [ {chord_str} ] ({chord_desc})"
                if getattr(self, '_last_chord_sig', None) != sig_text:
                    self._last_chord_sig = sig_text
                    self.itemconfig(self.chord_text, text=sig_text)
                pts_main, pts_trail = [], []
                steps = 64
                span_w = self.w - 48.0
                for s in range(steps):
                    x = 24.0 + (s / float(steps - 1)) * span_w
                    t = (s / float(steps - 1)) * 4.0 * math.pi
                    y = 0.0
                    for idx, p in enumerate(pitches[:5]):
                        hf = ((p % 12) + 1) * 0.75
                        y += math.sin(hf * t + now * 5.0 + idx * 0.5)
                    y /= math.sqrt(len(pitches[:5]))
                    y_px = self.cy - y * (self.r * 0.82)
                    pts_main.extend([x, y_px])
                    pts_trail.extend([x, y_px + math.sin(t + now * 2.0) * 1.5])
                self.coords(self.trace_line, *pts_main)
                self.itemconfig(self.trace_line, fill="#ffaa33")
                self.coords(self.trail_line, *pts_trail)
                self.itemconfig(self.trail_line, fill="#8c3294")
            else:
                self.itemconfig(self.chord_text, text="STANDBY // CRT SWEEP BASELINE")
                pts_main, pts_trail = [], []
                steps = 48
                span_w = self.w - 48.0
                for s in range(steps):
                    x = 24.0 + (s / float(steps - 1)) * span_w
                    t = (s / float(steps - 1)) * 2.0 * math.pi
                    y_px = self.cy - math.sin(t + now * 2.5) * 2.0
                    pts_main.extend([x, y_px])
                    pts_trail.extend([x, y_px * 0.99])
                self.coords(self.trace_line, *pts_main)
                self.itemconfig(self.trace_line, fill="#ff8a4c")
                self.coords(self.trail_line, *pts_trail)
                self.itemconfig(self.trail_line, fill="#4a1f38")

        elif self.mode == "LISSAJOUS":

            pts_main, pts_trail = [], []
            steps = 50
            span_x = (self.w / 2.0) - 24.0
            span_y = self.r * 0.88
            if pitches:
                self.itemconfig(self.chord_text, text=f"ORBITAL: [ {chord_str} ] ({chord_desc})")
                p1 = pitches[0]
                p2 = pitches[1] if len(pitches) > 1 else pitches[0] + 7
                f1 = (p1 % 12) + 1
                f2 = (p2 % 12) + 1
                for s in range(steps):
                    t = (s / float(steps)) * 2.0 * math.pi
                    lx = math.sin(f1 * t + now * 2.5)
                    ly = math.cos(f2 * t + now * 2.5 + 0.4)
                    if len(pitches) > 2:
                        lx += 0.25 * math.sin(((pitches[2] % 12) + 1) * t)
                        ly += 0.25 * math.cos(((pitches[-1] % 12) + 1) * t)
                        lx /= 1.25; ly /= 1.25
                    px = self.cx + span_x * lx
                    py = self.cy + span_y * ly
                    pts_main.extend([px, py])
                    pts_trail.extend([self.cx + (span_x * 0.95) * lx, self.cy + (span_y * 0.95) * ly])
                self.coords(self.trace_line, *pts_main)
                self.itemconfig(self.trace_line, fill="#ffe066")
                self.coords(self.trail_line, *pts_trail)
                self.itemconfig(self.trail_line, fill="#9a3284")
            else:
                self.itemconfig(self.chord_text, text="STANDBY // ORBITAL SWEEP")
                for s in range(steps):
                    t = (s / float(steps)) * 2.0 * math.pi
                    lx = math.sin(2.0 * t + now * 1.5) * math.cos(t)
                    ly = math.sin(3.0 * t + now * 1.5) * 0.8
                    pts_main.extend([self.cx + span_x * lx, self.cy + span_y * ly])
                    pts_trail.extend([self.cx + span_x * 0.95 * lx, self.cy + span_y * 0.95 * ly])
                self.coords(self.trace_line, *pts_main)
                self.itemconfig(self.trace_line, fill="#ff8a4c")
                self.coords(self.trail_line, *pts_trail)
                self.itemconfig(self.trail_line, fill="#4a1f38")

        elif self.mode in ("CONSTELLATION", "DUAL"):
            for i in range(12):
                self.coords(self.spectrum_bars[i], 0, 0, 0, 0)
                self.coords(self.spectrum_pips[i], 0, 0, 0, 0)
                self.coords(self.spectrum_labels[i], 0, 0)

            if pitches:
                self.itemconfig(self.chord_text, text=f"CHROMA: [ {chord_str} ] ({chord_desc})")
                coords = []
                for i in range(12):
                    if i < len(pitches):
                        p = pitches[i]
                        pc = p % 12
                        ang = -math.pi / 2.0 + (2.0 * math.pi * pc) / 12.0
                        rad = 12.0 + (self.r - 18.0) * max(0.1, min(1.0, (p - 24) / 60.0))
                        nx = self.cx + rad * math.cos(ang)
                        ny = self.cy + rad * math.sin(ang)
                        coords.extend([nx, ny])
                        r_pip = 3.5
                        self.coords(self.node_pool[i], nx - r_pip, ny - r_pip, nx + r_pip, ny + r_pip)
                        self.itemconfig(self.node_pool[i], fill="#ffe066", outline="#ffffff")
                        self.coords(self.node_labels[i], nx + 7, ny)
                        self.itemconfig(self.node_labels[i], text=f"{self.NOTE_NAMES[pc]}{(p // 12) - 1}")
                    else:
                        self.coords(self.node_pool[i], 0, 0, 0, 0)
                        self.coords(self.node_labels[i], 0, 0)
                if len(coords) >= 6:
                    self.coords(self.poly_line, *coords)
                    self.itemconfig(self.poly_line, fill="#2a0f28", outline="#d95fe6")
                elif len(coords) >= 4:
                    self.coords(self.poly_line, *coords)
                    self.itemconfig(self.poly_line, fill="", outline="#d95fe6")
                else:
                    self.coords(self.poly_line, 0, 0, 0, 0)
            else:
                self.itemconfig(self.chord_text, text="STANDBY // SCANNING RETICLE")
                self.coords(self.poly_line, 0, 0, 0, 0)
                for i in range(12):
                    self.coords(self.node_pool[i], 0, 0, 0, 0)
                    self.coords(self.node_labels[i], 0, 0)

            if self.mode == "DUAL":
                pts_main, pts_trail = [], []
                steps = 40
                span_x = (self.w / 2.0) - 20.0
                span_y = self.r * 0.82
                for s in range(steps):
                    t = (s / float(steps)) * 2.0 * math.pi
                    if pitches:
                        lx, ly = 0.0, 0.0
                        for idx, p in enumerate(pitches[:4]):
                            freq = (p % 12) + 1
                            lx += math.sin(freq * t + now * 3.0) / float(len(pitches[:4]))
                            ly += math.cos((freq + 3) * t + now * 3.0) / float(len(pitches[:4]))
                    else:
                        lx = math.sin(2.0 * t + now * 1.5) * math.cos(t)
                        ly = math.sin(3.0 * t + now * 1.5) * 0.8
                    px = self.cx + span_x * lx
                    py = self.cy + span_y * ly
                    pts_main.extend([px, py])
                    pts_trail.extend([self.cx + span_x * 0.95 * lx, self.cy + span_y * 0.95 * ly])
                self.coords(self.trace_line, *pts_main)
                self.itemconfig(self.trace_line, fill="#ffe066")
                self.coords(self.trail_line, *pts_trail)
                self.itemconfig(self.trail_line, fill="#8c3294")
            else:
                self.coords(self.trace_line, 0, 0, 0, 0)
                self.coords(self.trail_line, 0, 0, 0, 0)

        elif self.mode == "SPECTRUM":
            self.coords(self.trace_line, 0, 0, 0, 0)
            self.coords(self.trail_line, 0, 0, 0, 0)
            self.coords(self.poly_line, 0, 0, 0, 0)
            for i in range(12):
                self.coords(self.node_pool[i], 0, 0, 0, 0)
                self.coords(self.node_labels[i], 0, 0)

            active_pcs = {p % 12 for p in pitches}
            self.itemconfig(self.chord_text, text=f"SPECTRUM: [ {chord_str} ] ({len(active_pcs)} Active Pitch Classes)" if pitches else "STANDBY // ZERO CHROMA ENERGY")

            margin_left = 32.0
            avail_w = self.w - margin_left - 8.0
            col_w = avail_w / 12.0
            bar_w = max(6.0, col_w * 0.65)
            max_h = self.h - 38.0
            y_base = self.h - 18.0

            for pc in range(12):
                cx = margin_left + (pc + 0.5) * col_w
                target = 1.0 if pc in active_pcs else 0.0
                if target > self.spectrum_levels[pc]:
                    self.spectrum_levels[pc] = target
                else:
                    self.spectrum_levels[pc] = max(0.0, self.spectrum_levels[pc] - dt * 2.8)

                lvl = self.spectrum_levels[pc]
                if lvl >= self.spectrum_peaks[pc]:
                    self.spectrum_peaks[pc] = lvl
                    self.spectrum_peak_times[pc] = now
                elif now - self.spectrum_peak_times[pc] > 0.35:
                    self.spectrum_peaks[pc] = max(0.0, self.spectrum_peaks[pc] - dt * 1.8)

                bh = lvl * max_h
                y_top = y_base - bh
                self.coords(self.spectrum_bars[pc], cx - bar_w/2.0, y_top, cx + bar_w/2.0, y_base)
                if lvl > 0.1:
                    self.itemconfig(self.spectrum_bars[pc], fill="#ffaa33", outline="#ffe066")
                else:
                    self.itemconfig(self.spectrum_bars[pc], fill="#160a18", outline="#241226")

                yp = y_base - self.spectrum_peaks[pc] * max_h
                self.coords(self.spectrum_pips[pc], cx - bar_w/2.0, yp, cx + bar_w/2.0, yp)
                self.itemconfig(self.spectrum_pips[pc], fill="#ffe066" if self.spectrum_peaks[pc] > 0.05 else "#241226")

                self.coords(self.spectrum_labels[pc], cx, self.h - 8)
                self.itemconfig(self.spectrum_labels[pc], fill="#ffaa33" if lvl > 0.1 else "#5a3d54")


class ScrollableTargetPopup(tk.Toplevel):
    """Dynamic, searchable, mouse-wheel scrollable cyberdeck popup selector for LFO destinations."""
    def __init__(self, master_btn, target_var, target_groups, on_select=None):
        prev_popup = getattr(master_btn, '_active_popup', None)
        if prev_popup is not None:
            try: prev_popup.destroy()
            except Exception: pass
        super().__init__(master_btn)
        master_btn._active_popup = self
        self.overrideredirect(True)
        self.target_var = target_var
        self.on_select = on_select
        self.config(bg="#140b17", highlightthickness=1, highlightbackground=SEPIA_ACTIVE, bd=0)
        
        try:
            bx = master_btn.winfo_rootx()
            by = master_btn.winfo_rooty() + master_btn.winfo_height() + 2
            screen_h = self.winfo_screenheight()
            if by + 260 > screen_h:
                by = max(10, master_btn.winfo_rooty() - 264)
            self.geometry(f"204x260+{bx}+{by}")
        except Exception:
            self.geometry("204x260")
            
        s_frame = tk.Frame(self, bg="#140b17", padx=4, pady=4)
        s_frame.pack(fill='x')
        
        self.search_var = tk.StringVar()
        self.search_entry = tk.Entry(s_frame, textvariable=self.search_var, bg=INPUT_BG, fg=INPUT_FG, insertbackground=SEPIA_ACTIVE, font=FONT_SMALL, relief='sunken', bd=1)
        self.search_entry.pack(fill='x', padx=2, pady=2)
        self.search_entry.focus_set()
        
        list_frame = tk.Frame(self, bg="#140b17")
        list_frame.pack(fill='both', expand=True, padx=4, pady=(0, 4))
        
        self.scrollbar = tk.Scrollbar(list_frame, orient="vertical", bg=INPUT_BG, troughcolor="#0e0710", width=10)
        self.scrollbar.pack(side='right', fill='y')
        
        self.listbox = tk.Listbox(
            list_frame,
            yscrollcommand=self.scrollbar.set,
            bg=INPUT_BG,
            fg=INPUT_FG,
            selectbackground=SEPIA_ACTIVE,
            selectforeground=LED_OFF,
            font=FONT_SMALL,
            relief='flat',
            bd=0,
            highlightthickness=0,
            activestyle='none'
        )
        self.listbox.pack(side='left', fill='both', expand=True)
        self.scrollbar.config(command=self.listbox.yview)
        
        self.all_items = []
        for grp_name, opts in target_groups:
            self.all_items.append((True, grp_name))
            for opt in opts:
                self.all_items.append((False, opt))
                
        self.visible_items = []
        self._populate("")
        
        self.search_var.trace_add("write", lambda *args: self._populate(self.search_var.get()))
        self.listbox.bind("<Button-1>", self._on_click)
        self.listbox.bind("<Double-Button-1>", self._on_double_click)
        self.listbox.bind("<Return>", self._on_enter)
        self.search_entry.bind("<Return>", self._on_enter)
        self.search_entry.bind("<Down>", lambda e: self.listbox.focus_set())
        self.bind("<Escape>", lambda e: self.destroy())
        self.bind("<FocusOut>", self._on_focus_out)
        
        def _on_wheel(event):
            delta = -1 if event.delta > 0 else 1
            self.listbox.yview_scroll(delta * 2, "units")
            return "break"
        self.listbox.bind("<MouseWheel>", _on_wheel)
        self.bind("<MouseWheel>", _on_wheel)
        self.search_entry.bind("<MouseWheel>", _on_wheel)
        
    def _populate(self, filter_text):
        query = filter_text.strip().upper()
        self.listbox.delete(0, 'end')
        self.visible_items = []
        
        for is_header, text in self.all_items:
            if is_header:
                if not query:
                    self.listbox.insert('end', f"── {text} ──")
                    self.listbox.itemconfig('end', fg="#6b4c64")
                    self.visible_items.append((True, text))
            else:
                if not query or query in text.upper():
                    self.listbox.insert('end', f"  {text}")
                    if text == self.target_var.get():
                        self.listbox.itemconfig('end', fg=SEPIA_ACTIVE)
                    self.visible_items.append((False, text))
                    
    def _on_click(self, event):
        idx = self.listbox.nearest(event.y)
        if 0 <= idx < len(self.visible_items):
            is_header, text = self.visible_items[idx]
            if not is_header:
                self._choose(text)
                
    def _on_double_click(self, event):
        self._on_click(event)
        
    def _on_enter(self, event):
        sel = self.listbox.curselection()
        if sel:
            idx = sel[0]
            if 0 <= idx < len(self.visible_items):
                is_header, text = self.visible_items[idx]
                if not is_header:
                    self._choose(text)
                    
    def _choose(self, val):
        self.target_var.set(val)
        if self.on_select:
            try: self.on_select(val)
            except Exception: pass
        self.destroy()
        
    def _on_focus_out(self, event):
        def _check_focus():
            try:
                if not self.winfo_exists(): return
                focus_w = self.focus_get()
                if focus_w not in (self, self.search_entry, self.listbox, self.scrollbar):
                    self.destroy()
            except Exception:
                try: self.destroy()
                except Exception: pass
        try:
            self.after(60, _check_focus)
        except Exception:
            self.destroy()

# ---------------------------------------------------------

# LFO cycle length in beats (quarter notes) for each RATE setting.
MOD_RATE_BEATS = {
    "64/1": 256.0, "32/1": 128.0, "16/1": 64.0, "8/1": 32.0, "4/1": 16.0, "2/1": 8.0,
    "1/1": 4.0, "1/2": 2.0, "1/4": 1.0, "1/8": 0.5, "1/16": 0.25, "1/32": 0.125
}
# Mod targets that are edge-triggered (one action per LFO pulse) instead of continuously scaled.
TRIGGER_PARAMS = ('ACT', 'LCK', 'ROT', 'RND')
# Where LCK on/off and memory recalls land: "STEP" = next 16th (instant rolling-window freeze), "BEAT" = next quarter note, "LOOP" = next loop start.
LOCK_QUANT = "STEP"
# Where an M-slot recall (button, ROT/RND) lands: "STEP" = the next 16th note, jumping straight into the new
# phrase at the same position in the loop (instant, in time, works M -> M while playing); "BEAT" or "LOOP"
# wait for the next beat / the new phrase's first step.
RECALL_QUANT = "STEP"

class SequencerEngine:
    def __init__(self, channels, get_settings_callback):
        self.channels = channels
        self.channel_map = {ch.name: ch for ch in channels}
        self.get_settings = get_settings_callback
        
        self.running = False
        self.thread_main = None
        self.thread_mod = None
        self.thread_midi_in = None
        self.thread_scheduler = None
        
        self.outport = None
        self.inport = None
        self.midi_lock = threading.Lock()
        
        self.current_tick = 0
        self.next_due = {}
        self.pending_phase_reset = False
        self.turing_buffers = {ch.name: [None] * 384 for ch in channels if ch.channel_type in ['melodic', 'polyphonic']}
        self.history_buffers = {ch.name: [None] * 384 for ch in channels if ch.channel_type in ['melodic', 'polyphonic']}
        self.lock_start_ticks = {ch.name: 0 for ch in channels}
        self.lock_anchor_ticks = {ch.name: 0 for ch in channels}
        self.last_locked_state = {ch.name: False for ch in channels}
        
        self.memory_slots = {ch.name: {i: None for i in range(1, 11)} for ch in channels if ch.channel_type in ['melodic', 'polyphonic']}
        
        self.mod_states = {ch.name: {'target': 0.0, 'current': 0.0, 'phase': 0.0, 'last_eval_phase': 0.0, 'last_time': time.perf_counter()} for ch in channels if ch.channel_type == 'modulation'}
        self.last_sent_cc = {ch.name: -1 for ch in channels if ch.channel_type == 'modulation'}
        self.mod_scope_data = {ch.name: ('Sine', 0.0, 0.0, False) for ch in channels if ch.channel_type == 'modulation'}
        
        self.mod_matrix = {}
        self.toggle_state = {}     # {target_ch: {'ACT': bool, 'LCK': bool}} - flipped once per LFO pulse
        self.trigger_gate = {}     # {(mod_ch, slot): last gate level} for rising-edge detection
        self.force_lock = {}       # {ch: lock_len} - recall lock held until the UI catches up
        self.pending_recall = {}   # {ch: slot} - recall waiting for the next loop boundary
        self.playing_mem = {}      # {ch: slot} - M slot whose phrase is looping right now
        self.mutation_active = {}  # {ch: {amount, seed, gen, last_reroll}}
        self.heard_buf = {}        # {ch: {ring_index: event}} the phrase exactly as last played (incl. live mutation)
        self._mem_ui_last = {}
        self.eff_lock = {}         # {ch: (is_locked, lock_len_steps)} resolved every tick
        self._rand_cache = {}
        self.mod_seed = random.random()
        self.cached_settings = None
        self.midi_events = []
        self.ui_events = deque()
        self.ext_bpm = 115.0
        self.last_clock_time = time.perf_counter()
        self.sounding = set()      # {(chan, note)} currently held, so HALT can release exactly these
        self.midi_channel_activity = [0.0] * 16
        self.midi_cc_activity = [0.0] * 16
        self.last_error = ""
        self.last_prog_tick = -1
        self.perc_playback_pos = {}
        self.last_sent_cc = {ch.name: -1 for ch in self.channels if ch.channel_type == 'modulation'}
        self.tension_buffer = {}

    @property
    def tempo(self):
        try:
            if self.cached_settings and 'tempo' in self.cached_settings:
                return float(self.cached_settings['tempo'])
        except Exception: pass
        return 120.0

    def _reset_transport_state(self):
        """Per-run bookkeeping that must not leak from one run into the next."""
        self.prog_step = -1
        self.last_prog_tick = -1
        self.mutation_active = {}
        self.heard_buf = {}   # {ch: {ring_index: event}} the phrase exactly as last played (incl. live mutation)
        self.brownian_state = {}
        self.tension_buffer = {}
        self.midi_channel_activity = [0.0] * 16
        self.midi_cc_activity = [0.0] * 16
        self.perc_playback_pos = {}
        if hasattr(self, 'history_buffers'):
            for ch_name in self.history_buffers:
                self.history_buffers[ch_name] = [None] * 384
        if hasattr(self, 'ui_events'):
            self.ui_events.clear()
        
        self.prog_dir = 1
        self.prog_pedal_flag = False
        self.prog_outer_idx = 0

        # Safely wipe all tracker attributes so a fresh start guarantees immediate sequence execution
        prefixes = (
            'last_mem_tick_', 'seq_head_', 'last_seq_active_', 'seq_pending_start_',
            'last_perc_seq_tick_', 'last_perc_seq_step_', 'last_mem_mode_', 'mem_pending_start_',
            'mem_history_', 'active_mem_', 'last_act_', 'active_perc_mode_',
            'perc_phase_anchor_', 'add_meter_override_', 'eucl_override_',
            'last_rest_', 'last_vel_', 'last_ths_vel_', 'last_ars_vel_', '_has_history_',
            'manual_lck_', 'last_int_', 'last_dir_', 'current_octave_', 'last_pitch_', 'last_leap_', 'last_chord_',
            'mod_phase_offset_', 'repeat_count_', 'prog_dir', 'prog_pedal_flag', 'prog_outer_idx'
        )
        for k in list(self.__dict__.keys()):
            if any(k.startswith(p) for p in prefixes):
                delattr(self, k)

    def _supervise(self, fn, name):
        """Run a worker loop; if it raises, log it and restart it, so one bad value can't silently kill the transport."""
        while self.running:
            try:
                fn()
                return
            except Exception:
                log_exc(f"thread:{name}")
                time.sleep(0.05)

    def start(self, port_name, inport_name):
        if self.running: return
        self.last_error = ""
        try: self.outport = mido.open_output(port_name)
        except Exception as e:
            self.outport = None
            self.last_error = f"Could not open MIDI output '{port_name}': {e}"
            log.error(self.last_error); return
        self.inport = None
        try: self.inport = mido.open_input(inport_name) if inport_name and inport_name != "No Input Found" else None
        except Exception as e: log.warning("Input Fault: %s", e)

        self.running = True
        self.current_tick = 0
        self.start_time = time.perf_counter()
        self.last_tick_time = time.perf_counter()
        self._reset_transport_state()
        self.sounding = set()
        self.toggle_state = {}
        self.trigger_gate = {}
        self.force_lock = {}
        self.pending_recall = {}
        self.mutation_active = {}
        self.heard_buf = {}   # {ch: {ring_index: event}} the phrase exactly as last played (incl. live mutation)
        self.eff_lock = {}
        self.lock_anchor_ticks = {ch.name: 0 for ch in self.channels}
        self.mod_seed = random.random()
        self.next_due = {}
        self.midi_events = []
        if isinstance(getattr(self, 'ui_events', None), deque):
            self.ui_events.clear()
        else:
            self.ui_events = deque()
        self.mod_matrix = {}
        self.perc_playback_pos = {}
        
        self.mod_states = {ch.name: {'target': 0.0, 'current': 0.0, 'phase': 0.0, 'last_eval_phase': 0.0, 'last_time': time.perf_counter()} for ch in self.channels if ch.channel_type == 'modulation'}
        self.mod_scope_data = {ch.name: ('Sine', 0.0, 0.0, False) for ch in self.channels if ch.channel_type == 'modulation'}
        
        if self.outport and self.cached_settings and self.cached_settings.get('sync_mode', 'INT') == 'INT':
            try:
                with self.midi_lock: self.outport.send(mido.Message('start'))
            except Exception: pass
        
        self.thread_main = threading.Thread(target=self._supervise, args=(self._run_loop, 'clock'), daemon=True)
        self.thread_mod = threading.Thread(target=self._supervise, args=(self._mod_loop, 'mod'), daemon=True)
        self.thread_scheduler = threading.Thread(target=self._supervise, args=(self._scheduler_loop, 'scheduler'), daemon=True)
        self.thread_main.start()
        self.thread_mod.start()
        self.thread_scheduler.start()
        
        if self.inport:
            self.thread_midi_in = threading.Thread(target=self._supervise, args=(self._midi_in_loop, 'midi_in'), daemon=True)
            self.thread_midi_in.start()

    def stop(self):
        if not self.running: return
        self.running = False
        if self.thread_main: self.thread_main.join(timeout=1.0)
        if self.thread_mod: self.thread_mod.join(timeout=1.0)
        if self.thread_scheduler: self.thread_scheduler.join(timeout=1.0)
        if self.thread_midi_in: self.thread_midi_in.join(timeout=1.0)
        self.toggle_state = {}
        self.trigger_gate = {}
        self.perc_playback_pos = {}
        
        port, self.outport = self.outport, None
        if port:
            with self.midi_lock:
                def _send(msg):
                    try: port.send(msg)
                    except Exception: pass
                # Release every note that is still sounding: CC 123 alone is ignored by some hardware.
                for chan, note in list(self.sounding):
                    _send(mido.Message('note_off', note=note, velocity=0, channel=chan))
                self.sounding.clear()
                self.midi_events = []
                _send(mido.Message('stop'))
                for i in range(16):
                    _send(mido.Message('control_change', control=123, value=0, channel=i))
                    _send(mido.Message('control_change', control=120, value=0, channel=i))
            try: port.close()
            except Exception: pass
        if self.inport:
            try: self.inport.close()
            except Exception: pass
            self.inport = None

    def _quant_ticks(self, lock_len_steps, kind='lock'):
        """Size (in half-time adjusted ticks) of the grid that lock / unlock (kind='lock') or recall snap to."""
        mode = RECALL_QUANT if kind == 'recall' else LOCK_QUANT
        if mode == "BEAT": return 24
        if mode == "STEP": return 6
        return max(1, int(lock_len_steps)) * 6

    def trigger_memory_recall(self, ch_name, slot):
        """Queue a recall. The engine applies it on the next RECALL_QUANT grid line (default: next 16th)."""
        if not self.memory_slots.get(ch_name, {}).get(slot): return
        self.pending_recall[ch_name] = slot
        setattr(self, f'active_mem_{ch_name}', slot)

    @staticmethod
    def _copy_event(ev):
        if not ev: return None
        res = {
            'phrase': [dict(p) for p in ev.get('phrase', [])],
            'base_note': ev.get('base_note'),
            'vel': ev.get('vel')
        }
        if 'chosen_dur' in ev and ev['chosen_dur'] is not None:
            res['chosen_dur'] = ev['chosen_dur']
        if 'root_offset' in ev and ev['root_offset'] is not None:
            res['root_offset'] = ev['root_offset']
        return res

    def snapshot_rolling_phrase(self, ch_name, lock_len_steps, eff_tick):
        """Flatten and freeze the last lock_len_steps of unlocked history into a normalized
        [0 .. 383] loop buffer (with start_tick = 0), preserving exact rhythmic spacing,
        sustain windows, and micro-timing nuances non-destructively."""
        L = max(1, min(64, int(lock_len_steps))) * 6
        hist = self.history_buffers.get(ch_name)
        if not hist or not any(hist):
            hist = self.turing_buffers.get(ch_name) or ([None] * 384)

        slice_buf = [None] * L
        tick_now = max(0, int(eff_tick))
        start_k = max(0, tick_now - L)
        end_k = max(L, tick_now) if tick_now < L else tick_now

        # Non-destructively copy the exact heard events in the L-tick window
        for k in range(start_k, end_k):
            ev = hist[k % 384]
            if ev is not None and ev.get('phrase'):
                idx = k % L
                slice_buf[idx] = self._copy_event(ev)

        # Carry-in of sustained notes: only for polyphonic pads so we prevent silent loop holes
        # without injecting ghost notes into monophonic lead/bass lines.
        ch_type = getattr(self.channel_map.get(ch_name), 'channel_type', None)
        if ch_type == 'polyphonic' and slice_buf[0] is None and any(hist):
            dur_ticks_rev = {"1/1": 96, "1/2": 48, "1/4.": 36, "1/4": 24, "1/8.": 18, "1/8": 12, "1/8T": 8, "1/16": 6, "1/16T": 4}
            for back in range(1, 97):
                k = start_k - back
                if k < 0: break
                ev = hist[k % 384]
                if ev is not None and ev.get('phrase'):
                    dur_str = ev.get('chosen_dur', '1/16')
                    note_dur_ticks = dur_ticks_rev.get(dur_str, 6)
                    if k + note_dur_ticks > start_k:
                        slice_buf[0] = self._copy_event(ev)
                    break

        # Fallback: if the L-tick window has no triggers at all,
        # pull the most recent trigger from the 384-tick history anchored to step 0
        if not any(slice_buf) and any(hist):
            for back in range(1, 385):
                k = tick_now - back
                if k < 0: break
                ev = hist[k % 384]
                if ev is not None and ev.get('phrase'):
                    slice_buf[0] = self._copy_event(ev)
                    break

        # Tile the normalized L-tick loop across all 384 ticks so start_tick is always 0
        # and widening LEN while locked seamlessly extends the loop instead of hitting silence.
        return [self._copy_event(slice_buf[i % L]) for i in range(384)]

    def capture_heard_phrase(self, ch_name, lock_len_steps, buf):
        """The loop exactly as it was just played (including any live mutation), step by step, ready to save
        to an M slot as a clean normalized phrase (start_tick = 0). Steps not played since the lock engaged
        fall back to the stored phrase."""
        heard = dict(self.heard_buf.get(ch_name, {}))
        L = max(1, min(64, int(lock_len_steps))) * 6
        start = self.lock_start_ticks.get(ch_name, 0)
        slice_buf = [None] * L
        for i in range(L):
            idx = (start + i) % 384
            ev = heard.get(idx, buf[idx])
            if ev and ev.get('phrase'):
                slice_buf[i] = self._copy_event(ev)
        return [self._copy_event(slice_buf[i % L]) for i in range(384)]

    def _apply_memory_recall(self, ch_name, slot, eff_tick):
        mem = self.memory_slots.get(ch_name, {}).get(slot)
        if not mem: return
        
        # Flawless Legato Phase Alignment: normalize recalled phrase to start_tick = 0 and tile across 384 ticks
        lock_len = max(1, min(64, int(mem.get('lock_len', 32))))
        L = lock_len * 6
        start = int(mem.get('start_tick', 0))
        src_buf = mem.get('buffer') or ([None] * 384)
        slice_buf = [self._copy_event(src_buf[(start + i) % 384]) for i in range(L)]

        self.cached_settings['channels'][ch_name]['locked'] = True
        setattr(self, f"manual_lck_{ch_name}", True)
        self.lock_start_ticks[ch_name] = 0
        self.last_locked_state[ch_name] = True
        self.force_lock[ch_name] = lock_len
        self.turing_buffers[ch_name] = [self._copy_event(slice_buf[i % L]) for i in range(384)]
        self.playing_mem[ch_name] = slot
        self.heard_buf.pop(ch_name, None)
        
        # Non-Destructive Transition Hand-Off:
        # Purge future unplayed Note-ON events for this channel, but preserve scheduled Note-OFFs
        # for actively sounding voices so they conclude their natural envelope release without abrupt mid-air truncation.
        midi_chan = self.cached_settings['channels'][ch_name]['midi_chan'] - 1
        with self.midi_lock:
            active_notes = {n for (c, n) in self.sounding if c == midi_chan}
            self.midi_events = [
                ev for ev in self.midi_events
                if ev.get('ch_name') != ch_name or (ev.get('type') == 'off' and ev.get('note') in active_notes)
            ]
        
        self.ui_events.append(('update_local_var', ch_name, 'lock_len', lock_len))
        self.ui_events.append(('update_local_var', ch_name, 'locked', True))

    def _execute_mem_action(self, ch_name, action):
        slots = self.memory_slots.get(ch_name, {})
        valid_slots = sorted(k for k, v in slots.items() if v is not None)
        if not valid_slots: return
        
        active_slot = getattr(self, f'active_mem_{ch_name}', None)
        
        if action == 'ROT':
            if active_slot in valid_slots:
                idx = valid_slots.index(active_slot)
                next_slot = valid_slots[(idx + 1) % len(valid_slots)]
            else:
                next_slot = valid_slots[0]
        elif action == 'RND':
            history = list(getattr(self, f'mem_history_{ch_name}', []))
            choices = [s for s in valid_slots if s != active_slot] if (len(valid_slots) > 1 and active_slot in valid_slots) else list(valid_slots)
            weights = []
            for s in choices:
                # Recency-weighted Markov penalty: suppress recently visited slots so the bank is explored organically
                w = 1.0
                for age, prev_s in enumerate(reversed(history)):
                    if prev_s == s:
                        w *= (0.20 + 0.15 * min(4, age))
                        break
                if active_slot is not None:
                    # Subtle proximity bias so neighboring slots connect naturally
                    w *= 1.0 / (1.0 + 0.12 * abs(s - active_slot))
                weights.append(max(0.05, w))
            next_slot = random.choices(choices, weights=weights, k=1)[0]
            history.append(next_slot)
            if len(history) > 8:
                history = history[-8:]
            setattr(self, f'mem_history_{ch_name}', history)
                
        self.trigger_memory_recall(ch_name, next_slot)

    @staticmethod
    def _stochastic_step_deviation(head, num_steps, mut_amount, rng=None):
        """Boltzmann distance-weighted step selection: low MUT favors adjacent neighbor slips,
        while high MUT raises temperature for wider timeline leaps."""
        if num_steps <= 1: return head
        r = rng if rng is not None else random
        choices = [i for i in range(num_steps) if i != head]
        tau = 0.6 + 3.4 * max(0.0, min(1.0, mut_amount / 100.0))
        weights = []
        for i in choices:
            dist = min(abs(i - head), num_steps - abs(i - head))
            weights.append(math.exp(-dist / tau))
        return r.choices(choices, weights=weights, k=1)[0]

    @staticmethod
    def _stochastic_drift_s(drift_ms, rng=None):
        """Half-Gaussian pocket timing drift (seconds): clusters organically near the beat
        while allowing natural analog dispersion up to drift_ms."""
        if drift_ms <= 0: return 0.0
        r = rng if rng is not None else random
        ms = min(float(drift_ms), abs(r.gauss(0.0, float(drift_ms) * 0.45)))
        return ms / 1000.0

    def _advance_step_sequence(self, ch_name, steps, mut_amount=0.0):
        valid_steps = [(i, s) for i, s in enumerate(steps) if s is not None]
        if not valid_steps: return
        
        # The invisible linear playhead always advances cleanly
        head = getattr(self, f'seq_head_{ch_name}', -1)
        head = (head + 1) % len(valid_steps)
        setattr(self, f'seq_head_{ch_name}', head)
        
        eff_head = head
        
        # Non-Destructive Timeline Mutation:
        # At 100 MUT, there is a 75% chance the sequencer deviates using a Boltzmann distance distribution.
        if mut_amount > 0 and len(valid_steps) > 1:
            deviation_chance = (mut_amount / 100.0) * 0.75
            if random.random() < deviation_chance:
                eff_head = self._stochastic_step_deviation(head, len(valid_steps), mut_amount)
        
        phys_idx, target_m = valid_steps[eff_head]
        self.trigger_memory_recall(ch_name, target_m)
        
        # The visual UI tracks the actual deviated step so you can see the mutation
        self.ui_events.append(('seq_step_active', ch_name, phys_idx + 1))

    def _scheduler_loop(self):
        fails = 0
        while self.running:
            now = time.perf_counter()
            to_execute = []
            
            with self.midi_lock:
                for ev in self.midi_events:
                    if ev['time'] <= now:
                        to_execute.append(ev)
                self.midi_events = [ev for ev in self.midi_events if ev['time'] > now]

            to_execute.sort(key=lambda x: (x['time'], {'off': 0, 'cc': 1, 'on': 2}.get(x.get('type'), 1)))

            for ev in to_execute:
                if not self.running: break
                port = self.outport
                if not port: continue
                try:
                    chan = max(0, min(15, int(ev['chan'])))
                    with self.midi_lock:
                        if ev['type'] == 'on':
                            note = max(0, min(127, int(ev['note'])))
                            port.send(mido.Message('note_on', note=note, velocity=max(0, min(127, int(ev['vel']))), channel=chan))
                            self.sounding.add((chan, note))
                            self.midi_channel_activity[chan] = now
                        elif ev['type'] == 'off':
                            note = max(0, min(127, int(ev['note'])))
                            port.send(mido.Message('note_off', note=note, velocity=0, channel=chan))
                            self.sounding.discard((chan, note))
                        elif ev['type'] == 'cc':
                            port.send(mido.Message('control_change', control=max(0, min(127, int(ev['cc']))), value=max(0, min(127, int(ev['val']))), channel=chan))
                            self.midi_cc_activity[chan] = now
                    fails = 0
                except Exception:
                    fails += 1
                    log_exc('midi_send')
                    if fails == 25:
                        self.ui_events.append(('engine_fault', "The MIDI output stopped accepting data (device unplugged or port closed?). The transport was halted."))

            time.sleep(0.001)

    def _midi_in_loop(self):
        while self.running and self.inport:
            for msg in self.inport.iter_pending():
                # Fix the deadlock: Instantly abort if HALT was clicked
                if not self.running: break
                
                settings = self.cached_settings
                if not settings: continue
                
                if msg.type == 'clock' and settings.get('sync_mode', 'INT') == 'EXT':
                    now = time.perf_counter()
                    
                    # Sliding Window Low-Pass Filter (Calculates BPM flawlessly across exactly 1 beat)
                    if not hasattr(self, '_clk_history'): self._clk_history = []
                    self._clk_history.append(now)
                    
                    if len(self._clk_history) > 25:
                        self._clk_history.pop(0)
                        
                    if len(self._clk_history) == 25:
                        dt_total = self._clk_history[-1] - self._clk_history[0]
                        if dt_total > 0.05:
                            meas_bpm = 60.0 / dt_total
                            if 20.0 <= meas_bpm <= 400.0:
                                self.ext_bpm = (self.ext_bpm * 0.8) + (meas_bpm * 0.2)

                    if self.current_tick % 6 == 0:
                        time_div = 2 if settings.get('half_time') else 1
                        is_downbeat = (self.current_tick % (settings.get('master_phrase', 16) * 6 * time_div) == 0)
                        self.ui_events.append(('master_flash', is_downbeat))
                        
                    self.last_tick_time = now
                    try: self._process_tick(settings, self.current_tick, now)
                    except Exception: log_exc('process_tick')
                    
                    self.current_tick += 1
                    
                # Support both hard restarts (start) and paused un-mutes (continue)
                elif msg.type in ('start', 'continue') and settings.get('sync_mode', 'INT') == 'EXT':
                    if msg.type == 'start':
                        self.current_tick = 0
                        self.next_due = {}
                        self.trigger_gate = {}
                        self.toggle_state = {}
                        self.pending_recall = {}
                        self._reset_transport_state()
                    self._clk_history = []
            time.sleep(0.002)

    def _mod_loop(self):
        while self.running:
            settings = self.cached_settings
            if not settings:
                time.sleep(0.01)
                continue
                
            actual_tempo = self.ext_bpm if settings.get('sync_mode', 'INT') == 'EXT' else settings['tempo']
            time_div = 2 if settings.get('half_time') else 1
            new_matrix = {} 
                
            now = time.perf_counter()
            for ch in self.channels:
                if ch.channel_type != 'modulation': continue
                ch_data = settings['channels'][ch.name]
                
                state = self.mod_states[ch.name]
                state['last_time'] = now
                
                # Check cross-mod ACT toggle if any
                act_gate = 1.0 if self.toggle_state.get(ch.name, {}).get('ACT') else 0.0
                is_enabled = ch_data.get('enabled', False) ^ bool(act_gate > 0.5)

                min_v, max_v = ch_data.get('min_val', 0), ch_data.get('max_val', 127)
                pol = ch_data.get('polarity', 'UNI')
                raw_dep = ch_data.get('depth', 100) + self.mod_matrix.get(ch.name, {}).get('DP', 0.0)
                dep = max(0.0, min(100.0, raw_dep)) / 100.0
                wave = ch_data.get('waveform', "Sine")
                rate_str = ch_data.get('rate', '1/4')
                phs = float(ch_data.get('phase_offset', 0) or 0)
                
                rate_beats = MOD_RATE_BEATS.get(rate_str, 1.0)
                # Phase comes from transport tick count + phase offset (re-anchored on PHASE RESET)
                reset_anchor = float(getattr(self, f"mod_phase_offset_{ch.name}", 0.0) or 0.0)
                pos = max(0.0, self._transport_pos(actual_tempo, time_div) - reset_anchor)
                cycle_idx, phase = self._mod_cycle_pos(rate_str, pos, phs)
                last_cycle = state.get('last_cycle')
                phase_wrapped = last_cycle is not None and cycle_idx != last_cycle
                state['last_cycle'] = cycle_idx
                cycle_seconds = rate_beats * (60.0 / max(1.0, actual_tempo)) * time_div
                v_raw = self._mod_wave(ch.name, wave, cycle_idx, phase, cycle_seconds)

                # Store live scope frame for real-time oscilloscope
                self.mod_scope_data[ch.name] = (wave, phase, v_raw, is_enabled)

                if not is_enabled: continue

                if phase_wrapped:
                    self.ui_events.append(('flash', ch.name))
                self.ui_events.append(('mod_led', ch.name, v_raw))

                targets = [
                    (1, ch_data.get('t1_act', "ON"), ch_data.get('mod_target_1', 'OFF'), ch_data.get('t1_amt', 100)),
                    (2, ch_data.get('t2_act', "ON"), ch_data.get('mod_target_2', 'OFF'), ch_data.get('t2_amt', 100)),
                    (3, ch_data.get('t3_act', "ON"), ch_data.get('mod_target_3', 'OFF'), ch_data.get('t3_amt', 100))
                ]
                
                for slot_idx, act, mod_target, slot_amt in targets:
                    act_str = str(act).upper()
                    if act_str in ["FALSE", "0", "OFF"] or mod_target == "OFF": 
                        continue
                    try: t_amt = float(slot_amt) / 100.0
                    except (TypeError, ValueError): t_amt = 1.0
                    if act_str == "INV": t_amt = -t_amt
                    if t_amt == 0.0: continue
                        
                    if mod_target == 'EXT CC':
                        span = (max_v - min_v) * dep * abs(t_amt)
                        eff_v_raw = (1.0 - v_raw) if t_amt < 0 else v_raw
                        if pol == "UNI": v = min_v + (eff_v_raw * span)
                        else: v = ((max_v + min_v) / 2.0) + ((eff_v_raw - 0.5) * span)
                            
                        final_val = int(max(0, min(127, v)))
                        
                        if final_val != self.last_sent_cc[ch.name]:
                            self.last_sent_cc[ch.name] = final_val
                            with self.midi_lock:
                                self.midi_events.append({'time': time.perf_counter(), 'type': 'cc', 'cc': ch_data.get('cc_num', 74), 'val': final_val, 'chan': ch_data.get('midi_chan', 1) - 1})
                    else:
                        tgt_ch, param = mod_target.rsplit(' ', 1)
                        if param in TRIGGER_PARAMS: continue   # handled tick-exact in _update_mod_triggers
                        if tgt_ch not in new_matrix: new_matrix[tgt_ch] = {}
                        if param not in new_matrix[tgt_ch]: new_matrix[tgt_ch][param] = 0.0
                        
                        osc = v_raw if pol == "UNI" else (v_raw - 0.5)
                        mod_amount = osc * dep * t_amt
                        
                        range_max = 100
                        if param in ['V.MIN', 'V.MAX']: range_max = 127
                        elif param == 'PLS': range_max = 64
                        elif param in ['LCK', 'ROT', 'RND', 'ACT']: range_max = 1
                        elif param == 'MUT': range_max = 100
                        elif param == 'DP': range_max = 100
                        
                        new_matrix[tgt_ch][param] += mod_amount * range_max
            
            self.mod_matrix = new_matrix
            time.sleep(0.01)

    def _transport_pos(self, actual_tempo, time_div):
        """Transport position in (half-time adjusted) ticks, interpolated between clock ticks."""
        spt = (60.0 / max(1.0, actual_tempo)) / 24.0
        frac = max(0.0, min(1.0, (time.perf_counter() - self.last_tick_time) / spt))
        return max(0.0, (self.current_tick - 1) + frac) / time_div

    @staticmethod
    def _mod_cycle_pos(rate_str, pos_ticks, phase_offset_deg=0.0):
        cycle_ticks = 24.0 * MOD_RATE_BEATS.get(rate_str, 1.0)
        x = (pos_ticks / cycle_ticks) + (float(phase_offset_deg or 0.0) / 360.0)
        idx = int(math.floor(x))
        return idx, x - idx

    def _cycle_rand(self, ch_name, idx):
        """Deterministic random value per LFO cycle, so both threads agree and it stays phase-locked."""
        key = (ch_name, idx)
        v = self._rand_cache.get(key)
        if v is None:
            if len(self._rand_cache) > 256: self._rand_cache.clear()
            v = random.Random(f"{self.mod_seed}:{ch_name}:{idx}").random()
            self._rand_cache[key] = v
        return v

    def _mod_wave(self, ch_name, wave, cycle_idx, phase, cycle_seconds):
        if wave == "Sine": return 0.5 + 0.5 * math.sin(phase * 2 * math.pi)
        if wave == "Triangle": return phase * 2.0 if phase < 0.5 else 2.0 - (phase * 2.0)
        if wave == "Saw Up": return phase
        if wave == "Saw Down": return 1.0 - phase
        if wave == "Pulse": return 1.0 if phase < 0.5 else 0.0
        if wave == "Random": return self._cycle_rand(ch_name, cycle_idx)
        if wave == "SlewRand":
            prev = self._cycle_rand(ch_name, cycle_idx - 1)
            tgt = self._cycle_rand(ch_name, cycle_idx)
            return prev + (tgt - prev) * (1.0 - math.exp(-(phase * cycle_seconds) / 0.2))
        if wave == "S&H":
            step = int(phase * 8)
            return self._cycle_rand(ch_name, cycle_idx * 16 + step)
        if wave == "ExpDecay":
            decay = math.exp(-5.0 * phase)
            return (decay - 0.006738) / (1.0 - 0.006738)
        if wave == "Chaos":
            t = cycle_idx + phase
            val = 0.5 + 0.26 * math.sin(phase * 2 * math.pi) + \
                  0.15 * math.sin(t * 10.166407) + \
                  0.09 * math.cos(t * 15.168928)
            return max(0.0, min(1.0, val))
        return 0.0

    def _update_mod_triggers(self, settings, tick_counter, time_div, actual_tempo):
        """One action per LFO pulse (rising edge) for ACT / LCK toggles and ROT / RND recalls,
        evaluated exactly on the tick grid so it lines up with the downbeat."""
        pos = tick_counter / float(time_div)
        targeted, seen = set(), set()
        for mch in self.channels:
            if mch.channel_type != 'modulation': continue
            d = settings['channels'][mch.name]
            act_gate = 1.0 if self.toggle_state.get(mch.name, {}).get('ACT') else 0.0
            if not (d.get('enabled') ^ bool(act_gate > 0.5)): continue
            rate_str = d.get('rate', '1/4')
            phs = float(d.get('phase_offset', 0) or 0)
            reset_anchor = float(getattr(self, f"mod_phase_offset_{mch.name}", 0.0) or 0.0)
            eff_pos = max(0.0, pos - reset_anchor)
            cycle_idx, phase = self._mod_cycle_pos(rate_str, eff_pos, phs)
            cycle_seconds = MOD_RATE_BEATS.get(rate_str, 1.0) * (60.0 / max(1.0, actual_tempo)) * time_div
            v_raw = self._mod_wave(mch.name, d.get('waveform', 'Sine'), cycle_idx, phase, cycle_seconds)
            raw_dep = d.get('depth', 100) + self.mod_matrix.get(mch.name, {}).get('DP', 0.0)
            dep = max(0.0, min(100.0, raw_dep)) / 100.0
            for slot in (1, 2, 3):
                act = str(d.get(f't{slot}_act', 'ON')).upper()
                target = d.get(f'mod_target_{slot}', 'OFF')
                if act in ('FALSE', '0', 'OFF') or target in ('OFF', 'EXT CC') or ' ' not in target: continue
                tgt_ch, param = target.rsplit(' ', 1)
                if param not in TRIGGER_PARAMS: continue
                try: t_amt = float(d.get(f't{slot}_amt', 100)) / 100.0
                except (TypeError, ValueError): t_amt = 1.0
                if act == 'INV': t_amt = -t_amt
                if t_amt == 0.0: continue
                
                targeted.add((tgt_ch, param))
                eff_mod = v_raw * dep * t_amt
                gate = eff_mod >= 0.5 if t_amt >= 0 else (v_raw * dep * abs(t_amt)) < 0.5
                key = (mch.name, slot)
                seen.add(key)
                prev = self.trigger_gate.get(key, False)
                self.trigger_gate[key] = gate
                if gate and not prev:
                    if param in ('ACT', 'LCK'):
                        tog = self.toggle_state.setdefault(tgt_ch, {})
                        tog[param] = not tog.get(param, False)
                    else:
                        self._execute_mem_action(tgt_ch, param)
        for k in list(self.trigger_gate):
            if k not in seen: del self.trigger_gate[k]
        # If nothing drives a toggle any more, fall back to the manual button state.
        for tgt_ch, tog in self.toggle_state.items():
            for param in list(tog):
                if tog[param] and (tgt_ch, param) not in targeted: tog[param] = False

    def _run_loop(self):
        next_time = time.perf_counter()
        clock_fails = 0
        while self.running:
            settings = self.cached_settings
            if not settings:
                time.sleep(0.01)
                continue
                
            if settings.get('sync_mode', 'INT') == 'INT':
                seconds_per_clock = (60.0 / settings['tempo']) / 24.0
                port = self.outport
                if port:
                    try:
                        with self.midi_lock: port.send(mido.Message('clock'))
                        clock_fails = 0
                    except Exception:
                        clock_fails += 1
                        log_exc('clock_send')
                        if clock_fails == 48:
                            self.ui_events.append(('engine_fault', "The MIDI output stopped accepting data (device unplugged or port closed?). The transport was halted."))

                if self.current_tick % 6 == 0:
                        time_div = 2 if settings.get('half_time') else 1
                        is_downbeat = (self.current_tick % (settings.get('master_phrase', 16) * 6 * time_div) == 0)
                        self.ui_events.append(('master_flash', is_downbeat))

                tick_anchor = next_time
                self.last_tick_time = tick_anchor
                try: self._process_tick(settings, self.current_tick, tick_anchor)
                except Exception: log_exc('process_tick')
                
                self.current_tick += 1

                next_time += seconds_per_clock
                while True:
                    rem = next_time - time.perf_counter()
                    if rem <= 0: break
                    if rem > 0.002: time.sleep(rem - 0.002)
                    else: time.sleep(0)
                now_after = time.perf_counter()
                if now_after - next_time > 0.050: next_time = now_after
            else:
                time.sleep(0.01)

    def _mutate_playback_event(self, ch_name, buffer, read_index, mutation, scale_intervals, tempo, mutation_seed=0, macro_state="Static", note_probs=None, lock_len_ticks=96, time_div=1, drift_ms=0):
        """Create a musical, deterministic variation without editing the source buffer.
        
        Uses full-loop context for melodic contour preservation, empirical duration pooling,
        dynamic velocity hierarchy, targeted attrition (Rests), and inter-step gap-filling.
        """
        try:
            amount = max(0.0, min(100.0, float(mutation))) / 100.0
        except (TypeError, ValueError):
            amount = 0.0
            
        if amount <= 0.0 or not buffer:
            return buffer[read_index % len(buffer)] if buffer else None

        buf_len = len(buffer)
        L = max(6, min(buf_len, int(lock_len_ticks or 96)))
        idx_in_buf = read_index % buf_len
        source_event = buffer[idx_in_buf]
        if source_event is None or not source_event.get('phrase'):
            return source_event

        # Deterministic RNG locked to this phrase cycle
        channel_hash = sum((i + 1) * ord(c) for i, c in enumerate(ch_name))
        seed = (int(mutation_seed or 0) * 1000003 + channel_hash * 9176 + idx_in_buf * 7919 + 481)
        rng = random.Random(seed)
        
        scale = sorted(set(int(x) % 12 for x in (scale_intervals or [0, 2, 3, 5, 7, 9, 10])))
        if not scale:
            scale = [0, 2, 3, 5, 7, 9, 10]

        # Extract active intervallic weights for pitch substitution
        weighted_pcs = []
        if isinstance(note_probs, dict):
            for raw_interval, raw_weight in note_probs.items():
                try:
                    pc, weight = int(raw_interval) % 12, max(0.0, float(raw_weight))
                except (TypeError, ValueError):
                    continue
                if weight > 0 and pc in scale:
                    weighted_pcs.append((pc, weight))
        if not weighted_pcs:
            weighted_pcs = [(pc, 1.0) for pc in scale]

        event = {
            'base_note': source_event.get('base_note'),
            'vel': source_event.get('vel'),
            'chosen_dur': source_event.get('chosen_dur'),
            'root_offset': source_event.get('root_offset'),
            'phrase': []
        }
        phrase = source_event.get('phrase', [])
        if not phrase:
            return event
            
        # Build empirically weighted Duration Pool across the entire locked phrase to preserve rhythmic DNA
        dur_counts = {}
        for k in range(L):
            ev_k = buffer[k % buf_len]
            if ev_k and ev_k.get('phrase'):
                for item in ev_k['phrase']:
                    d = round(float(item.get('dur', 0.25)), 4)
                    if d > 0.05:
                        dur_counts[d] = dur_counts.get(d, 0) + 1
        if not dur_counts:
            for item in phrase:
                d = round(float(item.get('dur', 0.25)), 4)
                if d > 0.05:
                    dur_counts[d] = dur_counts.get(d, 0) + 1
        if not dur_counts:
            dur_counts = {0.25: 1}
        dur_pool = list(dur_counts.keys())
        dur_base_weights = [float(dur_counts[d]) for d in dur_pool]
            
        # Degradation Parameters
        pitch_chance = amount * 0.75
        rest_chance = max(0.0, (amount - 0.4) * 1.2)
        rest_chance = min(0.60, rest_chance) # Hard cap attrition at 60% so it never completely mutes
        # Respect zero-drift lock: only inject additional mutation timing slop when channel drift/entropy or Micro-Drift is active
        eff_drift_allowance = float(drift_ms or 0) + (35.0 if macro_state == "Micro-Drift" else 0.0)
        mut_drift_s = 0.0 if eff_drift_allowance <= 0.0 else min(0.050, amount * (eff_drift_allowance / 100.0) * 0.050)

        # Find the preceding pitch in the loop so melodic contour works across steps
        prev_pitch = None
        for back in range(1, L):
            prev_ev = buffer[(idx_in_buf - back) % L]
            if prev_ev and prev_ev.get('phrase'):
                prev_pitch = int(prev_ev['phrase'][-1].get('note_offset', 0))
                break

        new_phrase = []
        base_vel = event.get('vel', 100)
        
        # 1. Modify Existing Notes (Dynamics, Attrition, Pitch)
        for item in phrase:
            if rng.random() < rest_chance:
                continue # Rhythmic attrition (void creation)
                
            new_item = dict(item)
            current_pitch = int(new_item.get('note_offset', 0))
            vel_mod = int(new_item.get('vel_mod', 0))
            abs_vel = max(1, min(127, base_vel + vel_mod))
            
            # Dynamic Hierarchy (Anchors vs Ghosts) via Truncated Gaussian
            if abs_vel > 95:
                vel_swing = int(10 * amount) # Protect the strong thesis downbeats
            else:
                vel_swing = int(40 * amount) # Expressive swings on weak arsis ghost notes
            if vel_swing > 0:
                gauss_delta = int(round(rng.gauss(0.0, max(1.0, vel_swing * 0.45))))
                new_item['vel_mod'] = vel_mod + max(-vel_swing, min(vel_swing, gauss_delta))
            else:
                new_item['vel_mod'] = vel_mod
            
            # Melodic Contour & Distance-Weighted Pitch Swap
            if rng.random() < pitch_chance:
                options = []
                tau_pitch = 2.5 + 6.0 * amount
                for pc, weight in weighted_pcs:
                    for octave in range(-1, 2):
                        target = current_pitch - (current_pitch % 12) + pc + (12 * octave)
                        
                        dist = target - current_pitch
                        if abs(dist) > 12 or dist == 0:
                            continue # Keep inside a tight register relative to original
                            
                        # Boltzmann pitch-proximity weight scaled by MUT temperature
                        proximity = weight * math.exp(-abs(dist) / tau_pitch)
                        if prev_pitch is not None:
                            old_dir = current_pitch - prev_pitch
                            new_dir = target - prev_pitch
                            if (old_dir > 0 and new_dir > 0) or (old_dir < 0 and new_dir < 0) or old_dir == 0:
                                proximity *= 2.0 # Reward moving in the same melodic direction
                            else:
                                proximity *= 0.3 # Penalize breaking the contour
                        options.append((target, proximity))
                        
                if options:
                    pitches, weights = zip(*options)
                    chosen_pitch = int(rng.choices(pitches, weights=weights, k=1)[0])
                    if chosen_pitch != current_pitch:
                        new_item['note_offset'] = chosen_pitch
                        new_item.pop('chord_notes', None)
                        new_item.pop('played_ints', None)
                    
            # Apply internal analog pocket slop up to 50ms via truncated Gaussian
            if mut_drift_s > 0:
                drift_delta = max(-mut_drift_s, min(mut_drift_s, rng.gauss(0.0, mut_drift_s * 0.45)))
                new_item['start_offset'] = max(0.0, new_item['start_offset'] + drift_delta)
            
            prev_pitch = new_item['note_offset']
            new_phrase.append(new_item)

        # 2. Inject Rhythmic Fills (Gap Hunting across both sub-events and the next loop step)
        if amount > 0.50 and new_phrase:
            inject_chance = (amount - 0.50) * 1.5 # Scales up to 75% at max mutation
            final_phrase = []
            new_phrase.sort(key=lambda x: x.get('start_offset', 0))
            spt = ((60.0 / max(1.0, float(tempo or 120.0))) / 24.0) * max(1, int(time_div or 1))
            
            for i in range(len(new_phrase)):
                final_phrase.append(new_phrase[i])
                current_end = new_phrase[i]['start_offset'] + new_phrase[i]['dur']
                next_start = None
                if i < len(new_phrase) - 1:
                    next_start = new_phrase[i + 1]['start_offset']
                else:
                    # Look ahead in the loop buffer to find the gap to the next scheduled step
                    for fwd in range(1, L):
                        next_ev = buffer[(idx_in_buf + fwd) % L]
                        if next_ev and next_ev.get('phrase'):
                            next_start = (fwd * spt) + float(next_ev['phrase'][0].get('start_offset', 0.0))
                            break
                if next_start is not None:
                    gap = next_start - current_end
                    if gap > 0.08 and rng.random() < inject_chance: # Only fill actual audible voids
                        # Weight durations by empirical frequency and how cleanly they fit the gap
                        fit_weights = [
                            bw * (1.5 if d <= gap else 0.5 / (1.0 + (d - gap)))
                            for d, bw in zip(dur_pool, dur_base_weights)
                        ]
                        chosen_dur = rng.choices(dur_pool, weights=fit_weights, k=1)[0]
                        actual_dur = min(chosen_dur, gap - 0.01) # Truncate to fit gap perfectly
                        
                        if actual_dur > 0.04: # Ensure it doesn't become a tiny audio click
                            pitches, weights = zip(*weighted_pcs)
                            pc = rng.choices(pitches, weights=weights, k=1)[0]
                            anchor_pitch = new_phrase[i]['note_offset']
                            oct_base = anchor_pitch - (anchor_pitch % 12)
                            fill_vel_mod = max(-35, min(-5, int(round(rng.gauss(-18.0, 6.0)))))
                            
                            final_phrase.append({
                                'note_offset': oct_base + pc,
                                'start_offset': current_end + 0.005,
                                'dur': actual_dur,
                                'vel_mod': fill_vel_mod # Injected notes are naturally softer (Gaussian centered at -18)
                            })
            event['phrase'] = final_phrase
        else:
            event['phrase'] = new_phrase
            
        return event

    def request_phase_reset(self):
        self.pending_phase_reset = True
        if not self.running:
            for ch in self.channels:
                if ch.channel_type == 'percussion':
                    setattr(self, f"perc_phase_anchor_{ch.name}", 0)
                    setattr(self, f"seq_head_{ch.name}", -1)
                    setattr(self, f"last_perc_seq_step_{ch.name}", -1)
                elif ch.channel_type in ['melodic', 'polyphonic']:
                    self.next_due[ch.name] = 0
                    setattr(self, f"seq_head_{ch.name}", -1)
                    setattr(self, f"last_mem_tick_{ch.name}", -1)
                elif ch.channel_type == 'modulation':
                    setattr(self, f"mod_phase_offset_{ch.name}", 0)
            self.pending_phase_reset = False
            self.ui_events.append(('phase_reset_complete', None))

    def _build_polyphonic_voicing(self, ch_name, base_note, n_off, scale_intervals, chord_type, min_o, max_o, root_offset):
        """Construct a voice-led polyphonic chord voicing across inversions and allowed octave bounds.
        Supports 'Triad', '7th', 'Sus4', 'Add9', and 'Open 5th' while minimizing voice movement
        and rewarding common-tone retention across both generative and locked/recalled playback."""
        poly_scale = sorted(set(x for x in (scale_intervals or [0, 3, 5, 7, 10]) if x < 12)) or [0, 3, 5, 7, 10]
        min_o, max_o = min(int(min_o), int(max_o)), max(int(min_o), int(max_o))
        idx = min(range(len(poly_scale)), key=lambda i: abs(poly_scale[i] - (n_off % 12)))

        def deg_pc(step_offset):
            q, r = divmod(idx + step_offset, len(poly_scale))
            return poly_scale[r] + 12 * q

        ctype = str(chord_type or "Triad")
        if ctype == "7th":
            raw_pcs = [deg_pc(0), deg_pc(2), deg_pc(4), deg_pc(6)]
        elif ctype == "Sus4":
            raw_pcs = [deg_pc(0), deg_pc(3), deg_pc(4)]
        elif ctype == "Add9":
            raw_pcs = [deg_pc(0), deg_pc(2), deg_pc(4), deg_pc(1) + 12]
        elif ctype == "Open 5th":
            raw_pcs = [deg_pc(0), deg_pc(4), deg_pc(0) + 12]
        else:
            raw_pcs = [deg_pc(0), deg_pc(2), deg_pc(4)]

        chord_pcs = [pc % 12 for pc in raw_pcs]
        num_voices = len(chord_pcs)

        voicings = []
        for inv in range(num_voices):
            rotated = chord_pcs[inv:] + [pc + 12 for pc in chord_pcs[:inv]]
            for k in range(1, len(rotated)):
                while rotated[k] <= rotated[k - 1]:
                    rotated[k] += 12
            base_pc = rotated[0]
            rel_intervals = [p - base_pc for p in rotated]
            for o in range(min_o, max_o + 1):
                base_midi = 12 * (o + 1) + root_offset + (base_pc % 12)
                c_candidate = sorted([base_midi + rel for rel in rel_intervals])
                if all(0 <= n <= 127 for n in c_candidate):
                    voicings.append(c_candidate)

        prev_chord = getattr(self, f"last_chord_{ch_name}", None)
        if voicings:
            if prev_chord and len(prev_chord) == num_voices:
                scored_v = []
                for v in voicings:
                    disp = sum(abs(v[k] - prev_chord[k]) for k in range(num_voices))
                    common_count = sum(1 for n in v if n in prev_chord)
                    outer_leap = abs(v[-1] - prev_chord[-1]) + abs(v[0] - prev_chord[0])
                    score = disp + (outer_leap * 0.25) - (common_count * 4.5)
                    scored_v.append((v, score))
                scored_v.sort(key=lambda x: x[1])
                chosen_chord = scored_v[0][0]
            else:
                target_oct = max(min_o, min(max_o, (base_note // 12) - 1))
                mid_voicings = [v for v in voicings if any((target_oct + 1) * 12 <= n < (target_oct + 3) * 12 for n in v)]
                chosen_chord = mid_voicings[0] if mid_voicings else voicings[len(voicings) // 2]

            setattr(self, f"last_chord_{ch_name}", chosen_chord)
            played_ints = [12 if (n - root_offset) % 12 == 0 and n != root_offset else ((n - root_offset) % 12) for n in chosen_chord]
            return chosen_chord, played_ints

        fallback_note = fold_pitch(base_note + n_off)
        return [fallback_note], [12 if n_off == 12 else (n_off % 12)]

    def _process_tick(self, settings, tick_counter, tick_time=None):
        global GLOBAL_PHYSICS_STATE
        tick_now = tick_time if tick_time is not None else time.perf_counter()
        scale_intervals = SCALES.get(settings['global_scale'], [0, 3, 5, 7, 10])
        root_offset = ROOT_NOTES.index(settings['root_note']) if settings.get('root_note') in ROOT_NOTES else 0
        actual_tempo = self.ext_bpm if settings.get('sync_mode', 'INT') == 'EXT' else settings['tempo']
        master_phrase = max(1, settings['master_phrase'])
        
        time_div = 2 if settings.get('half_time') else 1
        
        if not hasattr(self, 'last_time_div'):
            self.last_time_div = time_div
        if time_div != self.last_time_div:
            for ch_name in self.next_due:
                self.next_due[ch_name] = 0
            self.last_time_div = time_div

        eff_tick = tick_counter // time_div

        phrase_ticks = master_phrase * 6
        if getattr(self, 'pending_phase_reset', False):
            if eff_tick % phrase_ticks == 0 or not self.running:
                self.pending_phase_reset = False
                for ch in self.channels:
                    if ch.channel_type == 'percussion':
                        current_step_16th = (eff_tick // 12) * 2
                        setattr(self, f"perc_phase_anchor_{ch.name}", current_step_16th)
                        setattr(self, f"seq_head_{ch.name}", -1)
                        setattr(self, f"last_perc_seq_step_{ch.name}", -1)
                    elif ch.channel_type in ['melodic', 'polyphonic']:
                        if not self.eff_lock.get(ch.name, (False, 16))[0]:
                            self.next_due[ch.name] = eff_tick
                        setattr(self, f"seq_head_{ch.name}", -1)
                        setattr(self, f"last_mem_tick_{ch.name}", -1)
                    elif ch.channel_type == 'modulation':
                        setattr(self, f"mod_phase_offset_{ch.name}", eff_tick)
                self.ui_events.append(('phase_reset_complete', None))

        self._update_mod_triggers(settings, tick_counter, time_div, actual_tempo)
        
        rate_mult = settings.get('prog_rate', 4)
        ticks_per_change = master_phrase * 6 * rate_mult
        
        if (eff_tick == 0 or eff_tick % ticks_per_change == 0) and eff_tick != getattr(self, 'last_prog_tick', -1):
            self.last_prog_tick = eff_tick
            prog_slots = settings.get('progression', [])
            active_slots = [p for p in prog_slots if p in ROOT_NOTES]
            if active_slots:
                motion_mode = settings.get('root_motion', 'Linear Loop (1->2->3->4)')
                n_slots = len(active_slots)
                if not hasattr(self, 'prog_dir'): self.prog_dir = 1
                if not hasattr(self, 'prog_pedal_flag'): self.prog_pedal_flag = False
                if not hasattr(self, 'prog_outer_idx'): self.prog_outer_idx = 0

                if n_slots <= 1:
                    self.prog_step = 0
                elif motion_mode.startswith('Pendulum'):
                    # Ping-pong traversal (0 -> 1 -> 2 -> 1 -> 0)
                    next_s = self.prog_step + self.prog_dir
                    if next_s >= n_slots:
                        self.prog_dir = -1
                        next_s = max(0, n_slots - 2)
                    elif next_s < 0:
                        self.prog_dir = 1
                        next_s = min(n_slots - 1, 1)
                    self.prog_step = max(0, min(n_slots - 1, next_s))
                elif motion_mode.startswith('Tonic Anchor'):
                    # Alternates home root (Slot 0) between outer excursions: 0 -> 1 -> 0 -> 2 -> 0 -> 3...
                    if self.prog_step == -1:
                        self.prog_step = 0
                        self.prog_pedal_flag = False
                    elif self.prog_pedal_flag:
                        self.prog_step = 0
                        self.prog_pedal_flag = False
                    else:
                        self.prog_outer_idx = (self.prog_outer_idx % (n_slots - 1)) + 1
                        self.prog_step = self.prog_outer_idx
                        self.prog_pedal_flag = True
                elif motion_mode.startswith('Brownian'):
                    # Stochastic walk with momentum: stay (15%), step back (25%), step forward (60%)
                    step_delta = random.choices([-1, 0, 1], weights=[0.25, 0.15, 0.60])[0]
                    self.prog_step = (self.prog_step + step_delta) % n_slots
                elif motion_mode.startswith('Turnaround Snap'):
                    # On downbeat of master phrase, snap to Slot 0; otherwise step forward
                    pos_in_ph = eff_tick % (master_phrase * 6)
                    if pos_in_ph == 0 and eff_tick > 0:
                        self.prog_step = 0
                    else:
                        self.prog_step = (self.prog_step + 1) % n_slots
                elif motion_mode.startswith('Chaos Shuffle'):
                    # Stochastic leap to any other active slot
                    candidates = [i for i in range(n_slots) if i != self.prog_step]
                    self.prog_step = random.choice(candidates) if candidates else 0
                else:
                    self.prog_step = (self.prog_step + 1) % n_slots

                new_root = active_slots[self.prog_step]
                self.ui_events.append(('set_root', new_root))
                settings['root_note'] = new_root
                root_offset = ROOT_NOTES.index(new_root)
                
            if eff_tick > 0:
                perc_macro_list = ["Static", "Void", "Evolve", "Drive", "Stutter", "Ghost", "Swarm", "Disintegration"]
                mel_macro_list = ["Static", "Humanize", "Octave Drop", "Octave Leap", "Grace Notes", "Echo", "Tremolo", "Pedal Point", "Drone Collapse", "Micro-Drift"]
                
                for ch in self.channels:
                    ch_d = settings['channels'][ch.name]
                    if ch_d.get('macro_auto'):
                        # Read from the channel's custom selected pool, fallback to defaults if empty
                        if ch.channel_type == 'percussion': 
                            mac_list = ch_d.get('macro_pool', perc_macro_list)
                        elif ch.channel_type in ['melodic', 'polyphonic']: 
                            mac_list = ch_d.get('macro_pool', mel_macro_list)
                        else: continue
                        
                        if not mac_list: 
                            mac_list = ["Static"]
                            
                        curr = ch_d.get('macro_state', "Static")
                        next_mac = mac_list[(mac_list.index(curr) + 1) % len(mac_list)] if curr in mac_list else mac_list[0]
                        self.ui_events.append(('update_local_var', ch.name, 'macro_state', next_mac))
                        ch_d['macro_state'] = next_mac

        for ch in self.channels:
            try:
                if ch.channel_type in ['melodic', 'polyphonic']:
                    ch_d = settings['channels'][ch.name]
                
                    # --- AUTO MEMORY SEQUENCER (ROT, RND, & SEQ) ---
                    mode = ch_d.get('mem_seq_mode', 'OFF')
                    seq_active = ch_d.get('seq_active', False)
                
                    was_active = getattr(self, f'last_seq_active_{ch.name}', False)
                    last_mode = getattr(self, f'last_mem_mode_{ch.name}', 'OFF')
                    transport_start = ((seq_active or mode != 'OFF') and eff_tick == 0)

                    if seq_active and not was_active:
                        setattr(self, f'seq_head_{ch.name}', -1)
                        setattr(self, f'mem_pending_start_{ch.name}', True)
                    elif mode != 'OFF' and mode != last_mode:
                        setattr(self, f'mem_pending_start_{ch.name}', True)
                    elif not seq_active and mode == 'OFF':
                        setattr(self, f'mem_pending_start_{ch.name}', False)

                    setattr(self, f'last_seq_active_{ch.name}', seq_active)
                    setattr(self, f'last_mem_mode_{ch.name}', mode)

                    if mode != 'OFF' or seq_active:
                        rate_str = ch_d.get('mem_seq_rate', '1x METER')
                        mult_map = {"1/4x METER": 0.25, "1/2x METER": 0.5, "1x METER": 1.0, "2x METER": 2.0, "4x METER": 4.0, "8x METER": 8.0}
                        mult = mult_map.get(rate_str, 1.0)
                        ticks_per_change = max(6, int(master_phrase * 6 * mult))
                        is_downbeat = (eff_tick % (master_phrase * 6) == 0)
                        pending_start = getattr(self, f'mem_pending_start_{ch.name}', False)

                        advance_triggered = False
                        if (pending_start and (is_downbeat or transport_start)) or (transport_start and getattr(self, f'last_mem_tick_{ch.name}', -1) != 0):
                            advance_triggered = True
                            setattr(self, f'mem_pending_start_{ch.name}', False)
                            if seq_active and transport_start:
                                setattr(self, f'seq_head_{ch.name}', -1)
                            setattr(self, f'last_mem_tick_{ch.name}', eff_tick)
                        elif not pending_start and eff_tick > 0 and eff_tick % ticks_per_change == 0 and eff_tick != getattr(self, f'last_mem_tick_{ch.name}', -1):
                            advance_triggered = True
                            setattr(self, f'last_mem_tick_{ch.name}', eff_tick)

                        if advance_triggered:
                            if seq_active:
                                mut_val = max(0.0, min(100.0, float(ch_d.get('mutation', 0) or 0) + self.mod_matrix.get(ch.name, {}).get('MUT', 0.0)))
                                self._advance_step_sequence(ch.name, ch_d.get('seq_steps', []), mut_val)
                            else:
                                self._execute_mem_action(ch.name, mode)
                        
                    # --- LOCK STATE (resolved every tick, even while ACT is off) ---
                    # LCK engages on the next 16th-note step (LOCK_QUANT = "STEP"), immediately snapshotting and
                    # flattening the rolling history window so the generator cannot overwrite what was just heard.
                    on_step = (tick_counter % time_div == 0)
                    pend = self.pending_recall.get(ch.name)
                    if pend is not None:
                        mem = self.memory_slots.get(ch.name, {}).get(pend)
                        if mem is None:
                            self.pending_recall.pop(ch.name, None)
                        elif on_step and eff_tick % self._quant_ticks(mem['lock_len'], 'recall') == 0:
                            self.pending_recall.pop(ch.name, None)
                            self._apply_memory_recall(ch.name, pend, eff_tick)
                
                    base_lck = ch_d.get('locked', False)
                    lock_len_eff = ch_d.get('lock_len', 32)
                    force = self.force_lock.get(ch.name)
                    if force:
                        # A memory recall locked this channel; the UI vars lag the engine by up to ~30 ms.
                        if base_lck and lock_len_eff == force: self.force_lock[ch.name] = None
                        else: base_lck, lock_len_eff = True, force
                    # Separate manual LCK state from LFO modulation
                    manual_req = bool(base_lck)
                    manual_now = getattr(self, f"manual_lck_{ch.name}", False)
                    mod_lck = bool(self.toggle_state.get(ch.name, {}).get('LCK', False))

                    phrase_ticks = master_phrase * 6

                    # Manual LCK Quantization:
                    # - Engaging (True): captures on the next 16th-note step boundary (instant snapshot).
                    # - Releasing (False): waits until the next master-phrase "1" (eff_tick % phrase_ticks == 0).
                    if manual_req != manual_now:
                        if manual_req:
                            if on_step and eff_tick % self._quant_ticks(lock_len_eff) == 0:
                                manual_now = True
                        else:
                            if on_step and eff_tick % phrase_ticks == 0:
                                manual_now = False
                        setattr(self, f"manual_lck_{ch.name}", manual_now)

                    # Effective lock request: manual state XOR LFO modulation
                    requested = manual_now ^ mod_lck
                    lock_len_eff = max(1, min(64, int(lock_len_eff)))   # phrase memory = 384 ticks = 64 steps
                    is_locked = self.last_locked_state.get(ch.name, False)
                    can_lock = True
                    lock_len_ticks = lock_len_eff * 6
                    hist_buf = self.history_buffers.get(ch.name, [])
                    if requested:
                        if not any(hist_buf) and not any(self.turing_buffers[ch.name]):
                            can_lock = False
                        elif eff_tick < lock_len_ticks and not getattr(self, f'_has_history_{ch.name}', False):
                            can_lock = False
                    if eff_tick >= lock_len_ticks:
                        setattr(self, f'_has_history_{ch.name}', True)

                    if requested != is_locked and on_step and eff_tick % self._quant_ticks(lock_len_eff) == 0 and can_lock:
                        if requested:
                            # Flatten and freeze the last lock_len_eff steps of heard history into a normalized [0..383] loop
                            self.turing_buffers[ch.name] = self.snapshot_rolling_phrase(ch.name, lock_len_eff, eff_tick)
                            self.lock_start_ticks[ch.name] = 0
                        else:
                            self.next_due[ch.name] = eff_tick   # generator resumes on the phrase boundary (the 1!)
                            self.tension_buffer[ch.name] = 0.0   # fresh stamina hand-off on release
                            setattr(self, f"last_rest_{ch.name}", False)
                            # Inherit the last pitch and register from the locked loop for continuous voice leading
                            buf = self.turing_buffers.get(ch.name) or []
                            if buf:
                                for back_k in range(1, lock_len_ticks + 1):
                                    ev_k = buf[(eff_tick - back_k) % 384]
                                    if ev_k and ev_k.get('phrase'):
                                        base_n = ev_k.get('base_note')
                                        n_off = ev_k['phrase'][-1].get('note_offset', 0)
                                        if base_n is not None:
                                            full_pitch = base_n + n_off
                                            setattr(self, f"last_pitch_{ch.name}", full_pitch)
                                            setattr(self, f"last_int_{ch.name}", n_off % 12)
                                            setattr(self, f"current_octave_{ch.name}", max(0, min(8, ((full_pitch - root_offset) // 12) - 1)))
                                            setattr(self, f"repeat_count_{ch.name}", 0)
                                        break
                            midi_chan = ch_d.get('midi_chan', 1) - 1
                            with self.midi_lock:
                                active_notes = {n for (c, n) in self.sounding if c == midi_chan}
                                self.midi_events = [
                                    ev for ev in self.midi_events
                                    if ev.get('ch_name') != ch.name or (ev.get('type') == 'off' and ev.get('note') in active_notes)
                                ]
                        is_locked = requested
                        self.last_locked_state[ch.name] = is_locked
                        self.playing_mem.pop(ch.name, None)     # a plain LCK on/off is no longer an M phrase
                        self.heard_buf.pop(ch.name, None)
                    self.eff_lock[ch.name] = (is_locked, lock_len_eff)
                
                    # M slot indicator: steady border while its phrase loops, blink on each loop start
                    play = self.playing_mem.get(ch.name)
                    if play is not None and self.memory_slots.get(ch.name, {}).get(play) is None:
                        self.playing_mem.pop(ch.name, None); play = None
                    mem_ui = (play, self.pending_recall.get(ch.name))
                    if self._mem_ui_last.get(ch.name) != mem_ui:
                        self._mem_ui_last[ch.name] = mem_ui
                        self.ui_events.append(('mem_state', ch.name, mem_ui[0], mem_ui[1]))
                    if play is not None and is_locked and on_step and eff_tick % (lock_len_eff * 6) == 0:
                        self.ui_events.append(('mem_flash', ch.name, play))

                ch_data = settings['channels'][ch.name]
                if ch.channel_type == 'modulation': continue
            
                global_entropy = settings.get('entropy', 0)
            
                mod_drift = self.mod_matrix.get(ch.name, {}).get('DRF', 0.0)
                mod_rest = self.mod_matrix.get(ch.name, {}).get('RST%', 0.0)
                mod_act = 1.0 if self.toggle_state.get(ch.name, {}).get('ACT') else 0.0
            
                drift_ms = max(0, min(100, int(ch_data.get('drift', 0) + mod_drift) + global_entropy))
                rest_prob = max(0, min(100, int(ch_data.get('rest_prob', 0) + mod_rest) + int(global_entropy * 0.8)))
            
                # XOR Digital Logic Gate for ACT
                base_act = ch_data.get('enabled', False)
                requested_act = bool(base_act) ^ bool(mod_act > 0.5)
                is_active = requested_act
            
                # Percussion ACT Quantization (manual button only): turning ACT on waits for the next master-phrase "1",
                # turning it off is instant. LFO-pulse toggles are applied immediately, so fast pulses still gate the drums.
                if ch.channel_type == 'percussion':
                    on_step = (tick_counter % time_div == 0)
                    manual_now = getattr(self, f"last_act_{ch.name}", False)
                    manual_req = bool(base_act)
                    if manual_req != manual_now:
                        if manual_req:
                            if on_step and eff_tick % (master_phrase * 6) == 0:
                                manual_now = True
                        else:
                            manual_now = False
                    setattr(self, f"last_act_{ch.name}", manual_now)
                    is_active = manual_now ^ bool(mod_act > 0.5)

                if not is_active:
                    if ch.channel_type in ['melodic', 'polyphonic']:
                        # A locked phrase (LCK or a recalled M slot) must survive ACT going off,
                        # so only the live rolling history is cleared.
                        if not self.eff_lock.get(ch.name, (False, 32))[0]:
                            self.turing_buffers[ch.name][eff_tick % 384] = None
                            self.history_buffers[ch.name][eff_tick % 384] = None
                            self.next_due[ch.name] = 0
                    continue
                
                if tick_counter % time_div != 0: continue
                
                midi_chan = ch_data['midi_chan'] - 1

                if ch.channel_type == 'percussion':
                    cycle_tick = eff_tick % 12
                    mod_swg = self.mod_matrix.get(ch.name, {}).get('SWG', 0.0)
                    swing_val = max(0, min(100, int(ch_data.get('swing', 0) + mod_swg)))
                    swing_ticks = int((swing_val / 100.0) * 4) 
                
                    is_downbeat = (cycle_tick == 0)
                    is_offbeat = (cycle_tick == (6 + swing_ticks))
                    if not (is_downbeat or is_offbeat): continue
                
                    current_step_16th = (eff_tick // 12) * 2 + (1 if is_offbeat else 0)
                
                    # Percussion Engine Quantization: Wait for the next "1" (evaluated on logical 16th step so SWG% works seamlessly on odd meters too)
                    is_phrase_downbeat = (current_step_16th % master_phrase == 0)
                    requested_mode = ch_data.get('perc_mode', 'EUCLID')
                    active_mode = getattr(self, f"active_perc_mode_{ch.name}", requested_mode)
                
                    if requested_mode != active_mode:
                        if is_phrase_downbeat:
                            active_mode = requested_mode
                            # Anchor phase so the new pattern physically starts on its first step
                            setattr(self, f"perc_phase_anchor_{ch.name}", current_step_16th)
                        
                    setattr(self, f"active_perc_mode_{ch.name}", active_mode)
                    perc_mode = active_mode
                
                    seq_active = ch_data.get('seq_active', False)
                    was_active = getattr(self, f'last_seq_active_{ch.name}', False)
                    transport_start = (seq_active and current_step_16th == 0)
                
                    # Arm the sequence if it was just engaged
                    if seq_active and not was_active:
                        setattr(self, f'seq_pending_start_{ch.name}', True)
                    setattr(self, f'last_seq_active_{ch.name}', seq_active)

                    if seq_active and (perc_mode == 'ADDITIVE' or perc_mode == 'EUCLID'):
                        rate_str = ch_data.get('mem_seq_rate', '1x METER')
                        mult_map = {"1/4x METER": 0.25, "1/2x METER": 0.5, "1x METER": 1.0, "2x METER": 2.0, "4x METER": 4.0, "8x METER": 8.0}
                        mult = mult_map.get(rate_str, 1.0)
                        steps_per_change = max(1, int(round(master_phrase * mult)))
                    
                        pending_start = getattr(self, f'seq_pending_start_{ch.name}', False)
                    
                        advance_triggered = False
                    
                        # 1. Force immediate start on phrase downbeat or a fresh transport playback
                        if pending_start and (is_phrase_downbeat or transport_start):
                            advance_triggered = True
                            setattr(self, f'seq_pending_start_{ch.name}', False)
                            setattr(self, f'seq_head_{ch.name}', -1) 
                            setattr(self, f'last_perc_seq_tick_{ch.name}', eff_tick)
                            setattr(self, f'last_perc_seq_step_{ch.name}', current_step_16th)
                        
                        # 2. Standard grid progression (evaluated in logical 16th steps so SWG% never skips odd-meter boundaries)
                        elif not pending_start and current_step_16th > 0 and current_step_16th % steps_per_change == 0 and current_step_16th != getattr(self, f'last_perc_seq_step_{ch.name}', -1):
                            advance_triggered = True
                            setattr(self, f'last_perc_seq_tick_{ch.name}', eff_tick)
                            setattr(self, f'last_perc_seq_step_{ch.name}', current_step_16th)
                        
                        if advance_triggered:
                            mut_val = max(0.0, min(100.0, float(ch_data.get('mutation', 0) or 0) + self.mod_matrix.get(ch.name, {}).get('MUT', 0.0)))
                            steps = ch_data.get('eucl_seq_steps', []) if perc_mode == 'EUCLID' else ch_data.get('add_seq_steps', [])
                            valid_steps = [(i, s) for i, s in enumerate(steps) if s is not None and str(s).strip() != ""]
                        
                            if valid_steps:
                                head = getattr(self, f'seq_head_{ch.name}', -1)
                                head = (head + 1) % len(valid_steps)
                                setattr(self, f'seq_head_{ch.name}', head)
                            
                                eff_head = head
                                if mut_val > 0 and len(valid_steps) > 1:
                                    deviation_chance = (mut_val / 100.0) * 0.75
                                    if random.random() < deviation_chance:
                                        eff_head = self._stochastic_step_deviation(head, len(valid_steps), mut_val)
                            
                                phys_idx, target_val = valid_steps[eff_head]
                            
                                if perc_mode == 'ADDITIVE':
                                    setattr(self, f"add_meter_override_{ch.name}", target_val)
                                    self.ui_events.append(('update_local_var', ch.name, 'add_meter', target_val))
                                elif perc_mode == 'EUCLID':
                                    setattr(self, f"eucl_override_{ch.name}", target_val)
                                    try:
                                        s, p, r = map(int, str(target_val).split(':'))
                                        self.ui_events.append(('update_local_var', ch.name, 'eucl_steps', s))
                                        self.ui_events.append(('update_local_var', ch.name, 'eucl_pulses', p))
                                        self.ui_events.append(('update_local_var', ch.name, 'eucl_rot', r))
                                    except Exception: pass

                                self.ui_events.append(('seq_step_active', ch.name, phys_idx + 1))
                                setattr(self, f"perc_phase_anchor_{ch.name}", current_step_16th)
                    else:
                        if not seq_active:
                            setattr(self, f"add_meter_override_{ch.name}", None)
                            setattr(self, f"eucl_override_{ch.name}", None)
                            setattr(self, f'seq_pending_start_{ch.name}', False)

                    # Determine active meter
                    meter_override = getattr(self, f"add_meter_override_{ch.name}", None)
                    active_add_meter = meter_override if meter_override else ch_data.get('add_meter', "Zeibekiko / Aksak (2-2-2-3) [9]")
                
                    anchor = getattr(self, f"perc_phase_anchor_{ch.name}", 0)
                    eff_step_16th = current_step_16th - anchor
                
                    fire_note = False
                    final_vel = 0
                
                    macro = ch_data.get('macro_state', 'Static')
                    bar_count = (current_step_16th // master_phrase)
                
                    if macro == "Void" and bar_count % 4 == 3: continue 

                    if perc_mode == 'EUCLID':
                        eucl_over = getattr(self, f"eucl_override_{ch.name}", None)
                        if eucl_over and ":" in str(eucl_over):
                            try:
                                s, p, r = map(int, str(eucl_over).split(':'))
                                steps_eff = max(1, s)
                                pulses_eff = p
                                rot_eff = r
                            except Exception:
                                steps_eff = max(1, ch_data.get('eucl_steps', 16))
                                pulses_eff = ch_data.get('eucl_pulses', 4)
                                rot_eff = ch_data.get('eucl_rot', 0)
                        else:
                            steps_eff = max(1, ch_data.get('eucl_steps', 16))
                            pulses_eff = ch_data.get('eucl_pulses', 4)
                            rot_eff = ch_data.get('eucl_rot', 0)

                        mod_pls = self.mod_matrix.get(ch.name, {}).get('PLS', 0.0)
                        pulses = max(0, min(steps_eff, int(pulses_eff + mod_pls)))
                    
                        if macro == "Evolve": pulses = min(steps_eff, pulses + ((bar_count % 4) * 2))
                        elif macro == "Drive" and bar_count % 8 == 7: pulses = steps_eff

                        cur_e_step = eff_step_16th % steps_eff
                        self.perc_playback_pos[ch.name] = ('EUCLID', cur_e_step, steps_eff, pulses, rot_eff)

                        pattern = EuclideanGenerator.generate(steps_eff, pulses, rot_eff)
                        if pattern[eff_step_16th % max(1, len(pattern))]:
                            was_rest = getattr(self, f"last_rest_{ch.name}", False)
                            struct_mod = 0.7 if is_downbeat else 1.2
                            markov_mod = 0.5 if was_rest else 1.0
                        
                            if random.random() >= ((rest_prob / 100.0) * struct_mod * markov_mod):
                                setattr(self, f"last_rest_{ch.name}", False)
                                mod_vmin = self.mod_matrix.get(ch.name, {}).get('V.MIN', 0.0)
                                mod_vmax = self.mod_matrix.get(ch.name, {}).get('V.MAX', 0.0)
                                v_min_eff = max(1, min(127, int(ch_data.get('v_min', 80) + mod_vmin)))
                                v_max_eff = max(1, min(127, int(ch_data.get('v_max', 127) + mod_vmax)))
                                v_min_eff, v_max_eff = min(v_min_eff, v_max_eff), max(v_min_eff, v_max_eff)
                            
                                mu = (v_min_eff + v_max_eff) / 2.0
                                sigma = max(1, (v_max_eff - v_min_eff) / 6.0)
                                gauss_vel = int(random.gauss(mu, sigma))
                                prev_vel = getattr(self, f"last_vel_{ch.name}", gauss_vel)
                                final_vel = max(v_min_eff, min(v_max_eff, prev_vel + max(-10, min(10, gauss_vel - prev_vel))))

                                # Roger Linn MPC Dynamic Swing Pocket: offbeats relax dynamically into the pocket
                                if is_offbeat and swing_val > 0:
                                    swing_pocket = int(round(- (swing_val * 0.18) + random.gauss(0.0, 1.5)))
                                    final_vel = max(1, min(127, final_vel + swing_pocket))

                                # GLOBAL ANALOG CHAOS INJECTOR: Dual-layer power-rail sag & micro-grit
                                if global_entropy > 0:
                                    ent_f = global_entropy / 100.0
                                    prev_w = getattr(self, f"ent_w_{ch.name}", 0.0)
                                    new_w = (prev_w * 0.88) + (random.gauss(0.0, 1.0) * 0.12)
                                    setattr(self, f"ent_w_{ch.name}", new_w)
                                    macro_drift = new_w * (ent_f * 22.0)
                                    micro_spike = random.gauss(0.0, 1.0) * (ent_f * 12.0)
                                    final_vel = max(1, min(127, int(round(final_vel + macro_drift + micro_spike))))

                                setattr(self, f"last_vel_{ch.name}", final_vel)
                                fire_note = True
                            else:
                                setattr(self, f"last_rest_{ch.name}", True)
                            
                    elif perc_mode == 'ADDITIVE':
                        meter_str = resolve_additive_meter(active_add_meter)
                        blocks = ADDITIVE_METERS.get(meter_str, [2, 2, 2, 3])
                        total_phrase_steps = max(1, sum(blocks))
                        cycle_pos = eff_step_16th % total_phrase_steps
                        self.perc_playback_pos[ch.name] = ('ADDITIVE', cycle_pos, total_phrase_steps, blocks)
                    
                        ths_center = max(1, min(127, int(ch_data.get('ths_v', 127))))
                        ars_center = max(1, min(127, int(ch_data.get('ars_v', 55))))
                    
                        if macro == "Drive" and bar_count % 8 == 7:
                            # Drive forces a machine-gun roll on every step with subtle Gaussian micro-dynamics
                            if random.random() >= (rest_prob / 100.0):
                                gauss_vel = int(round(random.gauss(ths_center, 4.0)))
                                prev_vel = getattr(self, f"last_ths_vel_{ch.name}", gauss_vel)
                                final_vel = max(1, min(127, prev_vel + max(-6, min(6, gauss_vel - prev_vel))))
                                setattr(self, f"last_ths_vel_{ch.name}", final_vel)
                                fire_note = True
                        else:
                            cycle_pos = eff_step_16th % total_phrase_steps
                        
                            is_thesis = False
                            block_offset = 0
                            block_len = blocks[0] if blocks else 2
                            accumulated = 0
                            for b in blocks:
                                if cycle_pos == accumulated:
                                    is_thesis = True
                                    block_offset = 0
                                    block_len = b
                                    break
                                elif accumulated < cycle_pos < accumulated + b:
                                    block_offset = cycle_pos - accumulated
                                    block_len = b
                                    break
                                accumulated += b
                            
                            was_rest = getattr(self, f"last_rest_{ch.name}", False)
                            markov_mod = 0.5 if was_rest else 1.0
                        
                            if is_thesis:
                                # Primary cycle downbeat is protected against total dropout (50% floor at 100% RST)
                                struct_mod = 0.7 if cycle_pos == 0 else 0.85
                                if random.random() >= ((rest_prob / 100.0) * struct_mod * markov_mod):
                                    setattr(self, f"last_rest_{ch.name}", False)
                                    accent_bias = 4.0 if cycle_pos == 0 else -2.0
                                    gauss_vel = int(round(random.gauss(ths_center + accent_bias, 5.0)))
                                    prev_vel = getattr(self, f"last_ths_vel_{ch.name}", gauss_vel)
                                    low_b = max(1, ths_center - 14)
                                    high_b = min(127, ths_center + 10)
                                    final_vel = max(low_b, min(high_b, prev_vel + max(-7, min(7, gauss_vel - prev_vel))))

                                    # GLOBAL ANALOG CHAOS INJECTOR (Thesis Downbeat Dynamic Turbulence)
                                    if global_entropy > 0:
                                        ent_f = global_entropy / 100.0
                                        prev_w = getattr(self, f"ent_w_{ch.name}", 0.0)
                                        new_w = (prev_w * 0.88) + (random.gauss(0.0, 1.0) * 0.12)
                                        setattr(self, f"ent_w_{ch.name}", new_w)
                                        macro_drift = new_w * (ent_f * 22.0)
                                        micro_spike = random.gauss(0.0, 1.0) * (ent_f * 12.0)
                                        final_vel = max(1, min(127, int(round(final_vel + macro_drift + micro_spike))))

                                    setattr(self, f"last_ths_vel_{ch.name}", final_vel)
                                    fire_note = True
                                else:
                                    setattr(self, f"last_rest_{ch.name}", True)
                            else:
                                a_rst = max(0, min(100, int(ch_data.get('ars_rst', 50))))
                                # Final pickup sub-step of a 3-step block slightly more likely to articulate
                                ars_struct = 0.85 if (block_len >= 3 and block_offset == block_len - 1) else 1.05
                                if random.random() >= ((a_rst / 100.0) * ars_struct) and random.random() >= ((rest_prob / 100.0) * markov_mod):
                                    setattr(self, f"last_rest_{ch.name}", False)
                                    contour_bias = 3.0 if (block_len >= 3 and block_offset == block_len - 1) else -2.0
                                    gauss_vel = int(round(random.gauss(ars_center + contour_bias, 6.0)))
                                    prev_vel = getattr(self, f"last_ars_vel_{ch.name}", gauss_vel)
                                    low_b = max(1, ars_center - 16)
                                    high_b = min(127, ars_center + 16)
                                    final_vel = max(low_b, min(high_b, prev_vel + max(-8, min(8, gauss_vel - prev_vel))))

                                    # Roger Linn MPC Dynamic Swing Pocket on Arsis sub-steps
                                    if is_offbeat and swing_val > 0:
                                        swing_pocket = int(round(- (swing_val * 0.18) + random.gauss(0.0, 1.5)))
                                        final_vel = max(1, min(127, final_vel + swing_pocket))

                                    # GLOBAL ANALOG CHAOS INJECTOR (Arsis Sub-step Dynamic Turbulence)
                                    if global_entropy > 0:
                                        ent_f = global_entropy / 100.0
                                        prev_w = getattr(self, f"ent_w_{ch.name}", 0.0)
                                        new_w = (prev_w * 0.88) + (random.gauss(0.0, 1.0) * 0.12)
                                        setattr(self, f"ent_w_{ch.name}", new_w)
                                        macro_drift = new_w * (ent_f * 22.0)
                                        micro_spike = random.gauss(0.0, 1.0) * (ent_f * 12.0)
                                        final_vel = max(1, min(127, int(round(final_vel + macro_drift + micro_spike))))

                                    setattr(self, f"last_ars_vel_{ch.name}", final_vel)
                                    fire_note = True
                                else:
                                    setattr(self, f"last_rest_{ch.name}", True)

                    if macro == "Ghost" and fire_note:
                        ghost_touch = max(0.25, min(0.50, random.gauss(0.38, 0.05)))
                        final_vel = int(round(final_vel * ghost_touch))

                    if macro == "Stutter" and bar_count % 4 == 3 and (current_step_16th % master_phrase) >= (master_phrase - 2):
                        fire_note = True
                        final_vel = ch_data.get('v_max', 127) if perc_mode == 'EUCLID' else ch_data.get('ths_v', 127)

                    if macro == "Swarm" and not fire_note:
                        if random.random() < 0.25:
                            fire_note = True
                            final_vel = int((ch_data.get('v_max', 127) if perc_mode == 'EUCLID' else ch_data.get('ths_v', 127)) * 0.3)
                        
                    if macro == "Disintegration":
                        if random.random() < 0.35: fire_note = False
                        drift_ms = min(100, drift_ms + 40)

                    if fire_note:
                        note = {"BD": 35, "SD": 38, "HHT": 42}.get(ch.name, 36)
                        start_time = tick_now + self._stochastic_drift_s(drift_ms)
                        end_time = start_time + 0.02
                        with self.midi_lock:
                            for ev in self.midi_events:
                                if ev.get('ch_name') == ch.name and ev['type'] == 'off' and ev['time'] >= start_time:
                                    ev['time'] = max(start_time - 0.002, ev.get('on_time', 0.0) + 0.001)
                                
                            self.midi_events.append({'time': start_time, 'type': 'on', 'note': note, 'vel': final_vel, 'chan': midi_chan, 'ch_name': ch.name})
                            self.midi_events.append({'time': end_time, 'type': 'off', 'note': note, 'chan': midi_chan, 'ch_name': ch.name, 'on_time': start_time})
                        self.ui_events.append(('flash', ch.name))

                elif ch.channel_type in ['melodic', 'polyphonic']:
                    is_locked, lock_len_steps = self.eff_lock.get(ch.name, (False, 32))
                    buffer = self.turing_buffers[ch.name]
                
                    if is_locked:
                        lock_len_ticks = lock_len_steps * 6
                        start_tick = self.lock_start_ticks.get(ch.name, 0)
                    
                        # Strict master downbeat synchronization: loop_idx is phase-locked to the master metric grid
                        loop_idx = eff_tick % lock_len_ticks
                        read_index = (start_tick + loop_idx) % 384
                        mutation_scale = scale_intervals
                        active_slot = self.playing_mem.get(ch.name)
                        if active_slot is not None:
                            active_memory = self.memory_slots.get(ch.name, {}).get(active_slot)
                            if active_memory and active_memory.get('scale_intervals'):
                                mutation_scale = active_memory['scale_intervals']
                        requested_amount = max(0.0, min(100.0, float(ch_data.get('mutation', 0) or 0) + self.mod_matrix.get(ch.name, {}).get('MUT', 0.0)))
                        requested_seed = int(ch_data.get('mutation_seed', 0) or 0)
                        state = self.mutation_active.get(ch.name)
                        if state is None:
                            state = {
                                'amount': requested_amount, 'seed': requested_seed,
                                'gen': 0, 'last_reroll': eff_tick
                            }
                            self.mutation_active[ch.name] = state
                        if requested_seed != state.get('seed', 0):
                            state['seed'] = requested_seed
                            state['gen'] = 0
                            state['last_reroll'] = eff_tick
                        state['amount'] = requested_amount
                        # Auto re-roll: stronger MUT settings roll a fresh variation more often,
                        # always aligned to the loop grid.
                        period = mut_reroll_loops(requested_amount)
                        if period:
                            grid = max(6, int(lock_len_ticks * min(1.0, period)))
                            if eff_tick % grid == 0:
                                last = state.get('last_reroll')
                                if last is None:
                                    state['last_reroll'] = eff_tick
                                elif eff_tick - last >= int(lock_len_ticks * period):
                                    state['gen'] = state.get('gen', 0) + 1
                                    state['last_reroll'] = eff_tick
                        eff_seed = (int(state.get('seed', requested_seed)) * 1000003 + state.get('gen', 0) * 7919 + 17) & 0x7fffffff
                        state['eff_seed'] = eff_seed
                        active_amount = requested_amount
                        event = self._mutate_playback_event(
                            ch.name, buffer, read_index, active_amount,
                            mutation_scale, actual_tempo, eff_seed,
                            ch_data.get('macro_state', 'Static'), ch_data.get('note_probs', {}),
                            lock_len_ticks=lock_len_ticks, time_div=time_div, drift_ms=drift_ms
                        )
                        self.heard_buf.setdefault(ch.name, {})[read_index] = event   # remember exactly what is played, for M capture
                        self.history_buffers[ch.name][eff_tick % 384] = self._copy_event(event) if event and event.get('phrase') else None
                    
                        if event and event.get('phrase'):
                            # Transpose locked / recalled phrase to the current live ROOT / PROG while preserving recorded octave.
                            # All performance macros (Humanize, Octave Drop/Leap, Pedal Point, Drone Collapse, Grace/Echo/Tremolo)
                            # and micro-timing drift were already flattened into the phrase at capture time, so locked playback
                            # replays the exact captured nuances without re-rolling random changes unless MUT > 0.
                            eff_base_note = ((int(event['base_note']) // 12) * 12) + root_offset
                            eff_base_vel = int(event['vel'])
                            min_o_lck, max_o_lck = ch_data.get('min_oct', 2), ch_data.get('max_oct', 5)

                            played_intervals = []
                            for ev_idx, ev in enumerate(event['phrase']):
                                n_off = ev['note_offset']
                                notes_to_play = []
                            
                                if ch.channel_type == 'polyphonic':
                                    frozen_chord = ev.get('chord_notes')
                                    rec_root = event.get('root_offset', root_offset)
                                    if frozen_chord:
                                        root_shift = ((root_offset - rec_root + 6) % 12) - 6
                                        lo, hi = 12 * (min_o_lck + 1), 12 * (max_o_lck + 2) - 1
                                        c_notes = [n + root_shift for n in frozen_chord]
                                        while c_notes and min(c_notes) < lo:
                                            c_notes = [n + 12 for n in c_notes]
                                        while c_notes and max(c_notes) > hi:
                                            c_notes = [n - 12 for n in c_notes]
                                        c_notes = sorted(set(max(0, min(127, n)) for n in c_notes))
                                        c_ints = [12 if (n - root_offset) % 12 == 0 and n != root_offset else ((n - root_offset) % 12) for n in c_notes]
                                        setattr(self, f"last_chord_{ch.name}", list(c_notes))
                                    else:
                                        c_notes, c_ints = self._build_polyphonic_voicing(
                                            ch.name, eff_base_note, n_off, mutation_scale,
                                            ch_data.get('chord_type', 'Triad'), min_o_lck, max_o_lck, root_offset
                                        )
                                    notes_to_play.extend(c_notes)
                                    played_intervals.extend(c_ints)
                                else:
                                    rec_root = event.get('root_offset', root_offset)
                                    root_shift = ((root_offset - rec_root + 6) % 12) - 6
                                    lo, hi = 12 * (min_o_lck + 1), 12 * (max_o_lck + 2) - 1
                                    rec_pitch = int(event['base_note']) + n_off + root_shift
                                    while rec_pitch < lo:
                                        rec_pitch += 12
                                    while rec_pitch > hi:
                                        rec_pitch -= 12
                                    target_pitch = fold_pitch(rec_pitch)
                                    notes_to_play.append(target_pitch)
                                    int_offset = (target_pitch - root_offset) % 12
                                    played_intervals.append(12 if int_offset == 0 and target_pitch != root_offset else int_offset)
                                
                                start_time = tick_now + max(0.0, float(ev['start_offset']))
                                end_time = start_time + float(ev['dur'])
                                ev_vel = max(1, min(127, eff_base_vel + int(ev['vel_mod'])))
                            
                                with self.midi_lock:
                                    if ch.channel_type == 'melodic' and ev_idx == 0:
                                        # Clean monophonic legato transition across loop wrap-arounds
                                        for q_ev in self.midi_events:
                                            if q_ev.get('ch_name') == ch.name and q_ev.get('type') == 'off' and q_ev['time'] >= start_time:
                                                q_ev['time'] = max(start_time - 0.004, q_ev.get('on_time', 0.0) + 0.001)
                                    for n in notes_to_play:
                                        for q_ev in self.midi_events:
                                            if q_ev.get('ch_name') == ch.name and q_ev.get('note') == n and q_ev.get('type') == 'off' and q_ev['time'] >= start_time:
                                                q_ev['time'] = max(start_time - 0.004, q_ev.get('on_time', 0.0) + 0.001)
                                        self.midi_events.append({'time': start_time, 'type': 'on', 'note': n, 'vel': ev_vel, 'chan': midi_chan, 'ch_name': ch.name})
                                        self.midi_events.append({'time': end_time, 'type': 'off', 'note': n, 'chan': midi_chan, 'ch_name': ch.name, 'on_time': start_time})
                                             
                            played_dur = event.get('chosen_dur')
                            if not played_dur and event.get('phrase'):
                                ev_dur_s = event['phrase'][0].get('dur', 0.25)
                                beat_s = (60.0 / max(1.0, actual_tempo)) * time_div
                                ev_ticks = round((ev_dur_s / max(0.001, beat_s)) * 24)
                                dur_ticks_rev = {96: "1/1", 48: "1/2", 36: "1/4.", 24: "1/4", 18: "1/8.", 12: "1/8", 8: "1/8T", 6: "1/16", 4: "1/16T"}
                                closest_tick = min(dur_ticks_rev.keys(), key=lambda t: abs(t - ev_ticks))
                                played_dur = dur_ticks_rev.get(closest_tick, "1/16")
                        
                            self.ui_events.append(('flash', ch.name, played_intervals, played_dur))
                        continue

                    buffer[eff_tick % 384] = None
                    self.history_buffers[ch.name][eff_tick % 384] = None

                    # Check next due boundary before running generator physics
                    due = self.next_due.get(ch.name, 0)
                    if due == 0:
                        phrase_ticks = master_phrase * 6
                        due = eff_tick if eff_tick % phrase_ticks == 0 else eff_tick + (phrase_ticks - (eff_tick % phrase_ticks))
                        self.next_due[ch.name] = due

                    if eff_tick < due:
                        continue
                
                    # --- 1. THE BROWNIAN GRAVITY ENGINE (Event-Driven Pitch Drift) ---
                    if not hasattr(self, 'brownian_state'): self.brownian_state = {}
                    b_state = self.brownian_state.setdefault(ch.name, {})
                
                    note_probs = ch_data['note_probs']
                    allowed = set(scale_intervals) | {12}
                
                    grv_mod = self.mod_matrix.get(ch.name, {}).get('GRV', 0.0)
                    grv_val = max(0, min(100, int(ch_data.get('gravity', 100) + grv_mod)))
                    max_dev = 100.0 - grv_val  # Leash radius (0 to 100)
                
                    eff_active_notes = []
                    for inter, base_w in note_probs.items():
                        if inter not in allowed: continue
                    
                        if max_dev <= 0.0:
                            new_w = float(base_w)
                        else:
                            # Execute Independent Random Walk within the Gravity Leash (stepped once per event)
                            current_w = b_state.get(inter, base_w)
                            step = random.gauss(0, 2.5) 
                            new_w = current_w + step
                        
                            low_bound = max(0.0, base_w - max_dev)
                            high_bound = min(100.0, base_w + max_dev)
                            if new_w > high_bound: new_w = high_bound - min(max_dev, abs(step))
                            elif new_w < low_bound: new_w = low_bound + min(max_dev, abs(step))
                            new_w = max(low_bound, min(high_bound, new_w))
                        
                            b_state[inter] = new_w
                    
                        if new_w > 0 or base_w > 0: # Ensure valid faders aren't lost to floating point zero
                            eff_active_notes.append((inter, new_w))

                    # --- SAFE THREAD EXPORT (GRAVITY) ---
                    if 'GLOBAL_PHYSICS_STATE' not in globals(): GLOBAL_PHYSICS_STATE = {}
                    if ch.name not in GLOBAL_PHYSICS_STATE: GLOBAL_PHYSICS_STATE[ch.name] = {'notes': {}, 'durs': {}}
                    GLOBAL_PHYSICS_STATE[ch.name]['notes'] = {inter: w for inter, w in eff_active_notes}

                    if not eff_active_notes:
                        eff_active_notes = [(0, 1.0)]
                
                    # --- 2. THE INERTIA MARKOV ENGINE (Time & Fatigue) ---
                    if not hasattr(self, 'tension_buffer'): self.tension_buffer = {}
                    tension = self.tension_buffer.setdefault(ch.name, 0.0)
                
                    int_mod = self.mod_matrix.get(ch.name, {}).get('INT', 0.0)
                    int_val = max(0, min(100, int(ch_data.get('inertia', 50) + int_mod)))
                    stamina = int_val / 100.0 # 0.0 (exhausted sludge) to 1.0 (infinite arpeggiator)
                
                    dur_probs = ch_data['duration_probs']
                    dur_keys = list(dur_probs.keys())
                    dur_weights = [dur_probs[k] for k in dur_keys]
                
                    # Kinetic effort map (-1.0 = deep recovery, 1.0 = maximum exertion)
                    dur_effort = {"1/1": -1.0, "1/2": -0.8, "1/4": -0.2, "1/4.": -0.1, 
                                  "1/8": 0.5, "1/8.": 0.4, "1/8T": 0.6, 
                                  "1/16": 1.0, "1/16T": 1.0}
                              
                    eff_dur_weights = []
                    for dur, base_w in zip(dur_keys, dur_weights):
                        if base_w <= 0:
                            eff_dur_weights.append(0) # Absolute Zero Fader Rule
                            continue
                        
                        effort = dur_effort.get(dur, 0.0)
                        if effort > 0:
                            # High tension suppresses fast notes (mitigated by stamina)
                            suppression = tension * (1.0 - stamina) * 0.95
                            mult = max(0.05, 1.0 - suppression)
                        else:
                            # High tension massively amplifies long recovery notes
                            mult = 1.0 + (tension * 3.0)
                        
                        eff_dur_weights.append(base_w * mult)

                    # --- SAFE THREAD EXPORT (INERTIA) ---
                    if 'GLOBAL_PHYSICS_STATE' not in globals(): GLOBAL_PHYSICS_STATE = {}
                    if ch.name not in GLOBAL_PHYSICS_STATE: GLOBAL_PHYSICS_STATE[ch.name] = {'notes': {}, 'durs': {}}
                    GLOBAL_PHYSICS_STATE[ch.name]['durs'] = {dur: w for dur, w in zip(dur_keys, eff_dur_weights)}
                
                    if sum(eff_dur_weights) <= 0:
                        self.next_due[ch.name] = 0
                        continue

                    chosen_dur = random.choices(dur_keys, weights=eff_dur_weights, k=1)[0]
                    chosen_effort = dur_effort.get(chosen_dur, 0.0)
                
                    # Resolve the Markov Tension State
                    if chosen_effort > 0:
                        tension += chosen_effort * 0.22 * (1.0 - stamina) # Builds exhaustion mitigated by stamina
                    else:
                        tension += chosen_effort * 0.50 # Heavy drones clear exhaustion rapidly
                    
                    tension = max(0.0, min(1.0, tension))
                    self.tension_buffer[ch.name] = tension

                    # Structural Rests & Fatigue
                    was_rest = getattr(self, f"last_rest_{ch.name}", False)
                    # True bar downbeat (Beat 1 of measure: 24 ticks * 4 beats = 96 ticks in 4/4)
                    is_downbeat = (eff_tick % 96 == 0)
                
                    # Fader respect: if rest_prob == 0, eff_rest_prob is strictly 0.0 (zero forced rests)
                    eff_rest_prob = 0.0
                    if rest_prob > 0:
                        fatigue_mult = 1.0 + (tension * (1.0 - stamina) * 1.5)
                        eff_rest_prob = min(100.0, rest_prob * fatigue_mult)

                    is_rest = False
                    if eff_rest_prob >= 100.0:
                        is_rest = True  # Strict 100% silence
                    elif eff_rest_prob > 0.0:
                        struct_mod = 0.2 if is_downbeat else 1.2
                        markov_mod = 0.1 if was_rest else 1.0
                        # Smoothly blend modifiers toward 1.0 as eff_rest_prob approaches 100
                        p = eff_rest_prob / 100.0
                        eff_mod = 1.0 + ((struct_mod * markov_mod) - 1.0) * (1.0 - p)
                        is_rest = (random.random() < (p * eff_mod))

                    if is_rest:
                        setattr(self, f"last_rest_{ch.name}", True)
                        # A rest acts as a breath, bleeding off tension
                        self.tension_buffer[ch.name] = max(0.0, tension - 0.15)
                    
                        dur_ticks_map = {"1/1": 96, "1/2": 48, "1/4": 24, "1/4.": 36, "1/8": 12, "1/8.": 18, "1/8T": 8, "1/16": 6, "1/16T": 4}
                        dur_ticks = dur_ticks_map.get(chosen_dur, 12)
                        new_due = due + dur_ticks
                        if dur_ticks % 6 == 0 and new_due % 6 != 0: new_due += (6 - (new_due % 6))
                        self.next_due[ch.name] = new_due
                        continue
                    
                    setattr(self, f"last_rest_{ch.name}", False)

                    # --- PHASE 2: UNIFIED ABSOLUTE PITCH SPACE, HARMONIC GRAVITY & LAW OF RECOVERY ---
                    mel_macro = ch_data.get('macro_state', 'Static')
                    intervals, weights = zip(*eff_active_notes)
                    prev_pitch = getattr(self, f"last_pitch_{ch.name}", None)
                    prev_dir = getattr(self, f"last_dir_{ch.name}", 0)
                    prev_leap = getattr(self, f"last_leap_{ch.name}", False)
                    repeat_cnt = int(getattr(self, f"repeat_count_{ch.name}", 0) or 0)

                    min_o, max_o = min(int(ch_data['min_oct']), int(ch_data['max_oct'])), max(int(ch_data['min_oct']), int(ch_data['max_oct']))
                    lo_p = 12 * (min_o + 1)
                    hi_p = 12 * (max_o + 1) + 11

                    # Build deduplicated absolute pitch pool strictly bounded within [lo_p, hi_p]
                    # Softens multi-octave fader multiplication and prevents double-weighting (Edit A)
                    pool = {}
                    for inter, w in eff_active_notes:
                        if w <= 0: continue
                        p = lo_p + ((root_offset + inter - lo_p) % 12)
                        copies = max(1, (hi_p - p) // 12 + 1)
                        norm_w = w / (copies ** 0.5)
                        while p <= hi_p:
                            if p not in pool:
                                pool[p] = (inter, norm_w)
                            else:
                                prev_inter, prev_w = pool[p]
                                best_inter = inter if norm_w > prev_w else prev_inter
                                pool[p] = (best_inter, prev_w + norm_w)
                            p += 12

                    if not pool:
                        fallback_p = max(lo_p, min(hi_p, 12 * (min_o + 1) + root_offset))
                        pool[fallback_p] = (0, 1.0)

                    phrase_ticks = master_phrase * 6
                    pos_in_phrase = eff_tick % phrase_ticks
                    is_phrase_start = (pos_in_phrase == 0)
                    is_turnaround = (phrase_ticks >= 48 and pos_in_phrase >= phrase_ticks - 24)

                    if prev_pitch is None:
                        # Initial note: center in register steered by kinetic effort, drawn strictly from pool
                        curr_oct = min_o + int(round((max_o - min_o) * max(0.0, min(1.0, (chosen_effort + 1.0) / 2.0))))
                        target_pitch = 12 * (curr_oct + 1) + root_offset
                        pool_items = list(pool.items())
                        init_scores = [it[1][1] * math.exp(-abs(it[0] - target_pitch) / 6.0) for it in pool_items]
                        if sum(init_scores) > 0:
                            chosen_idx = random.choices(range(len(pool_items)), weights=init_scores, k=1)[0]
                        else:
                            chosen_idx = random.choices(range(len(pool_items)), weights=[it[1][1] for it in pool_items], k=1)[0]
                        chosen_pitch = pool_items[chosen_idx][0]
                        chosen_int = pool_items[chosen_idx][1][0]
                        octave = max(0, min(8, (chosen_pitch // 12) - 1))
                        semitone_dist = 0
                        mel_delta = 0
                        setattr(self, f"last_dir_{ch.name}", 0)
                        setattr(self, f"last_leap_{ch.name}", False)
                        setattr(self, f"repeat_count_{ch.name}", 0)
                    else:
                        # Adaptive Boltzmann temperature: widens when few intervals are active or kinetic/Brownian freedom is high
                        active_pc_count = len(set(inter % 12 for inter, w in eff_active_notes if w > 0))
                        tau = 4.2 + (max(0.0, chosen_effort) * 1.4) + ((max_dev / 100.0) * 1.8)
                        if active_pc_count <= 3:
                            tau += 2.5

                        curr_oct = max(0, min(8, (prev_pitch // 12) - 1))
                        candidates = []
                        for cand_p, (inter, w) in pool.items():
                            cand_oct = max(0, min(8, (cand_p // 12) - 1))
                            delta = cand_p - prev_pitch
                            dist = abs(delta)

                            # 1. Distance proximity: Master Stochastic Distribution
                            distro_mode = settings.get('distro', 'Boltzmann (Organic)')
                            if distro_mode.startswith('Gaussian'):
                                sigma_d = max(1.8, tau * 0.75)
                                prox = math.exp(-(dist ** 2) / (2.0 * (sigma_d ** 2)))
                                if inter % 12 in (0, 7): prox *= 1.40
                            elif distro_mode.startswith('Cauchy'):
                                gamma_d = max(1.4, tau * 0.55)
                                prox = 1.0 / (1.0 + (dist / gamma_d) ** 2)
                                if dist >= 7: prox *= 1.35
                            elif distro_mode.startswith('1/f Pink'):
                                prox = 1.0 / (max(0.2, dist + 0.8) ** 1.15)
                                if dist in (0, 7, 12): prox *= 1.25
                            elif distro_mode.startswith('Weibull'):
                                lambda_d = max(3.0, tau * 1.1)
                                prox = ((dist / lambda_d) ** 0.85) * math.exp(-((dist / lambda_d) ** 1.85)) if dist > 0 else 0.12
                            elif distro_mode.startswith('Tension'):
                                if is_turnaround:
                                    sigma_t = 2.2
                                    prox = math.exp(-(dist ** 2) / (2.0 * (sigma_t ** 2)))
                                    if inter % 12 in (0, 7): prox *= 1.85
                                else:
                                    prox = math.exp(-dist / (tau * 1.35))
                                    if inter % 12 in (1, 2, 6, 8, 10, 11): prox *= 1.35
                            else:
                                prox = math.exp(-dist / tau)

                            # 2. Register affinity: only penalize octave boundary crossings for skips/leaps (dist > 2)
                            if dist > 2:
                                d_oct = abs(cand_oct - curr_oct)
                                if d_oct == 0:
                                    prox *= 1.0
                                elif d_oct == 1:
                                    # Neutral kinetic mobility allows fluid bidirectional runs without ceiling trapping
                                    prox *= 0.68 * (1.0 + abs(chosen_effort) * 0.25)
                                else:
                                    prox *= 0.18 / d_oct

                            # 2b. Wall reflection (Ceiling / Floor Bounce from Edit B)
                            if prev_pitch - lo_p < 3 and delta > 0:
                                prox *= 1.30
                            elif hi_p - prev_pitch < 3 and delta < 0:
                                prox *= 1.30

                            # 3. Harmonic resonance & Consecutive Repetition Damper
                            if dist == 7: prox *= 1.35
                            elif dist == 12: prox *= 1.30
                            elif dist == 0:
                                if mel_macro in ["Pedal Point", "Drone Collapse"] or active_pc_count <= 1:
                                    prox *= 1.25
                                else:
                                    unison_dur_factors = {
                                        "1/1":   0.15,
                                        "1/2":   0.30,
                                        "1/4.":  0.42,
                                        "1/4":   0.48,
                                        "1/8.":  0.60,
                                        "1/8":   0.65,
                                        "1/8T":  0.68,
                                        "1/16":  0.72,
                                        "1/16T": 0.72
                                    }
                                    dur_unison_mult = unison_dur_factors.get(chosen_dur, 0.65)
                                    prox *= dur_unison_mult * (0.30 ** min(4, repeat_cnt))

                            # 4. Metric Harmonic Gravity (Phrase Downbeat Anchoring & Turnaround Tendency)
                            pc = inter % 12
                            if is_phrase_start:
                                if pc in (0, 7): prox *= 1.30
                                elif pc in (3, 4): prox *= 1.15
                            elif is_turnaround:
                                if pc in (2, 5, 9, 10, 11): prox *= 1.25

                            # 5. Classical Melodic Phrasing Rules & Law of Recovery:
                            cand_dir = 1 if delta > 0 else (-1 if delta < 0 else 0)
                            if prev_leap:
                                # After a wide leap (>= 5 semitones), melody breathes and resolves in reverse by step
                                if cand_dir == -prev_dir and 1 <= dist <= 4:
                                    prox *= 1.65
                                elif cand_dir == prev_dir and dist >= 5:
                                    prox *= 0.35 # Discourage leaping repeatedly in the same direction
                            else:
                                # Small step continuation: reward smooth arched scale runs
                                if cand_dir == prev_dir and 1 <= dist <= 3:
                                    prox *= 1.35
                                elif cand_dir == -prev_dir and 1 <= dist <= 3:
                                    prox *= 1.15 # Natural melodic wave crest/trough

                            candidates.append((cand_p, cand_oct, inter, w * prox))

                        if candidates:
                            c_pitches, c_octs, c_ints, c_scores = zip(*candidates)
                            if sum(c_scores) > 0:
                                chosen_idx = random.choices(range(len(candidates)), weights=c_scores, k=1)[0]
                                chosen_pitch, octave, chosen_int, _ = candidates[chosen_idx]
                            else:
                                pool_items = list(pool.items())
                                chosen_idx = random.choices(range(len(pool_items)), weights=[it[1][1] for it in pool_items], k=1)[0]
                                chosen_pitch = pool_items[chosen_idx][0]
                                chosen_int = pool_items[chosen_idx][1][0]
                                octave = max(0, min(8, (chosen_pitch // 12) - 1))
                        else:
                            pool_items = list(pool.items())
                            chosen_idx = random.choices(range(len(pool_items)), weights=[it[1][1] for it in pool_items], k=1)[0]
                            chosen_pitch = pool_items[chosen_idx][0]
                            chosen_int = pool_items[chosen_idx][1][0]
                            octave = max(0, min(8, (chosen_pitch // 12) - 1))

                        mel_delta = chosen_pitch - prev_pitch
                        semitone_dist = abs(mel_delta)
                        new_dir = 1 if mel_delta > 0 else (-1 if mel_delta < 0 else prev_dir)
                        setattr(self, f"last_dir_{ch.name}", new_dir)
                        setattr(self, f"last_leap_{ch.name}", semitone_dist >= 5)
                        setattr(self, f"repeat_count_{ch.name}", (repeat_cnt + 1) if semitone_dist == 0 else 0)

                    setattr(self, f"last_pitch_{ch.name}", chosen_pitch)
                    setattr(self, f"current_octave_{ch.name}", octave)
                    setattr(self, f"last_int_{ch.name}", chosen_int)

                    base_note = chosen_pitch - chosen_int
                
                    mod_vmin = self.mod_matrix.get(ch.name, {}).get('V.MIN', 0.0)
                    mod_vmax = self.mod_matrix.get(ch.name, {}).get('V.MAX', 0.0)
                    v_min_eff = max(1, min(127, int(ch_data.get('v_min', 65) + mod_vmin)))
                    v_max_eff = max(1, min(127, int(ch_data.get('v_max', 115) + mod_vmax)))
                    v_min_eff, v_max_eff = min(v_min_eff, v_max_eff), max(v_min_eff, v_max_eff)
                    v_span = max(0, v_max_eff - v_min_eff)
                
                    # Shift Gaussian velocity mean using kinetic effort + human contour & metric phrasing
                    mu = (v_min_eff + v_max_eff) / 2.0
                    mu += chosen_effort * (v_span * 0.30)
                    contour_vel_bias = 0.0
                    if mel_delta > 0:
                        contour_vel_bias = min(0.10, (semitone_dist / 12.0) * 0.10) * v_span
                    elif prev_leap and 1 <= semitone_dist <= 3:
                        contour_vel_bias = -0.07 * v_span  # Soften post-leap recovery step like a human singer
                    metric_vel_bias = (0.06 * v_span) if is_phrase_start else ((-0.04 * v_span) if (eff_tick % 12 != 0) else 0.0)
                    mu += contour_vel_bias + metric_vel_bias

                    # Adapt dynamics and velocity contour by master stochastic distribution
                    distro_mode = settings.get('distro', 'Boltzmann (Organic)')
                    if distro_mode.startswith('Gaussian'):
                        sigma = max(1.0, v_span / 8.0) # Tight, focused punch
                    elif distro_mode.startswith('Cauchy') and semitone_dist >= 7:
                        mu += 0.08 * v_span # Expressive accent on Xenakis leaps
                        sigma = max(1.0, v_span / 5.5)
                    elif distro_mode.startswith('Tension') and is_turnaround:
                        mu += 0.12 * v_span # Dramatic energy swell on turnaround
                        sigma = max(1.0, v_span / 5.0)
                    else:
                        sigma = max(1.0, v_span / 6.0) 

                    gauss_vel = int(random.gauss(mu, sigma))
                
                    prev_vel = getattr(self, f"last_vel_{ch.name}", gauss_vel)
                    max_walk = max(6, int(8 + abs(contour_vel_bias) * 0.5))
                    walk_step = max(-max_walk, min(max_walk, gauss_vel - prev_vel))
                    vel = max(v_min_eff, min(v_max_eff, prev_vel + walk_step))

                    # GLOBAL ANALOG CHAOS INJECTOR: Melodic & Polyphonic Power-Rail Sag & Micro-Grit
                    if global_entropy > 0:
                        ent_f = global_entropy / 100.0
                        prev_w = getattr(self, f"ent_w_{ch.name}", 0.0)
                        new_w = (prev_w * 0.88) + (random.gauss(0.0, 1.0) * 0.12)
                        setattr(self, f"ent_w_{ch.name}", new_w)
                        macro_drift = new_w * (ent_f * 24.0)
                        micro_spike = random.gauss(0.0, 1.0) * (ent_f * 13.0)
                        vel = max(1, min(127, int(round(vel + macro_drift + micro_spike))))

                    setattr(self, f"last_vel_{ch.name}", vel)
                
                    # Schedule next step with synchronized metric due & duration
                    dur_ticks_map = {"1/1": 96, "1/2": 48, "1/4": 24, "1/4.": 36, "1/8": 12, "1/8.": 18, "1/8T": 8, "1/16": 6, "1/16T": 4}
                    dur_ticks = dur_ticks_map.get(chosen_dur, 12)
                    new_due = due + dur_ticks
                    if dur_ticks % 6 == 0 and new_due % 6 != 0: new_due += (6 - (new_due % 6))
                    self.next_due[ch.name] = new_due

                    # Synchronize sounding duration with actual metric step span & multi-dimensional stochastic phrasing gate
                    actual_step_ticks = new_due - due
                    step_duration_s = (actual_step_ticks / 24.0) * (60.0 / actual_tempo) * time_div
                    is_phrase_tail = ((new_due % phrase_ticks == 0) or (due // phrase_ticks != new_due // phrase_ticks))
                    prev_gate = getattr(self, f"last_gate_{ch.name}", 0.85)
                    gate_ratio = get_stochastic_gate_ratio(
                        chosen_dur, semitone_dist=semitone_dist, is_phrase_tail=is_phrase_tail,
                        tension=tension, stamina=stamina, entropy=global_entropy,
                        mel_macro=mel_macro, prev_gate=prev_gate
                    )
                    setattr(self, f"last_gate_{ch.name}", gate_ratio)
                    # Hardware protection: guarantee at least an 8ms breath before the next step for analog envelope resets
                    length_s = max(0.035, min(step_duration_s - 0.008, step_duration_s * gate_ratio))
                
                    # Execute basic Macros
                    mel_macro = ch_data.get('macro_state', 'Static')
                    if mel_macro == "Humanize":
                        vel = min(127, max(1, vel + int(round(max(-15.0, min(15.0, random.gauss(0.0, 6.0)))))))
                        drift_ms += int(round(max(0.0, min(25.0, random.gauss(8.0, 5.0)))))
                    elif mel_macro in ("Octave Drop", "Octave Leap") and random.random() < 0.20:
                        shift = -12 if mel_macro == "Octave Drop" else 12
                        if not (lo_p <= base_note + chosen_int + shift <= hi_p):
                            shift = -shift                       # reflect instead of escaping the range
                        if lo_p <= base_note + chosen_int + shift <= hi_p:
                            base_note += shift
                            setattr(self, f"last_pitch_{ch.name}", base_note + chosen_int)
                            setattr(self, f"current_octave_{ch.name}", max(0, min(8, ((base_note + chosen_int) // 12) - 1)))
                    elif mel_macro == "Pedal Point" and eff_tick % 12 != 0:
                        chosen_int = 0
                        pedal_oct = max(min_o, min(max_o, (chosen_pitch // 12) - 1))
                        pedal_p = 12 * (pedal_oct + 1) + root_offset
                        while pedal_p > hi_p: pedal_p -= 12
                        while pedal_p < lo_p: pedal_p += 12
                        base_note = pedal_p
                        pedal_dip = int(round(max(8, min(28, random.gauss(18.0, 4.5)))))
                        vel = max(1, vel - pedal_dip)
                        setattr(self, f"last_pitch_{ch.name}", base_note)
                        setattr(self, f"current_octave_{ch.name}", max(0, min(8, (base_note // 12) - 1)))
                        setattr(self, f"last_int_{ch.name}", 0)
                    elif mel_macro == "Drone Collapse":
                        chosen_int = 0
                        drone_oct = max(min_o, min(max_o, (chosen_pitch // 12) - 1))
                        drone_p = 12 * (drone_oct + 1) + root_offset
                        while drone_p > hi_p: drone_p -= 12
                        while drone_p < lo_p: drone_p += 12
                        base_note = drone_p
                        drone_dip = int(round(max(6, min(24, random.gauss(14.0, 4.0)))))
                        vel = max(1, vel - drone_dip)
                        setattr(self, f"last_pitch_{ch.name}", base_note)
                        setattr(self, f"current_octave_{ch.name}", max(0, min(8, (base_note // 12) - 1)))
                        setattr(self, f"last_int_{ch.name}", 0)
                    elif mel_macro == "Micro-Drift":
                        drift_ms = min(100, drift_ms + 45)

                    # --- PHRASE INJECTOR ---
                    phrase_events = []
                    inject = False
                
                    if mel_macro == "Grace Notes" and random.random() < 0.25:
                        inject = True
                        idx = min(range(len(scale_intervals)), key=lambda i: abs(scale_intervals[i] - (chosen_int % 12))) if scale_intervals else 0
                        q, r = divmod(idx + 1, len(scale_intervals))
                        grace_off = scale_intervals[r] + (12 * q) + ((chosen_int // 12) * 12)
                    
                        # Organic human flam: variable dynamic touch and duration
                        grace_v_dip = int(round(max(-32, min(-8, random.gauss(-20.0, 5.0)))))
                        grace_dur = max(0.035, min(0.065, random.gauss(0.048, 0.007)))
                        phrase_events.append({'note_offset': grace_off, 'start_offset': 0.0, 'dur': grace_dur, 'vel_mod': grace_v_dip})
                        phrase_events.append({'note_offset': chosen_int, 'start_offset': grace_dur + 0.01, 'dur': max(0.04, length_s - (grace_dur + 0.01)), 'vel_mod': 0})
                    
                    elif mel_macro == "Echo" and random.random() < 0.25:
                        inject = True
                        echo_step = ((60.0 / actual_tempo) / 4.0) * time_div   # 16th-note step (half-time aware)
                        num_echos = max(2, min(8, int((length_s * 0.85) / max(0.05, echo_step))))
                        for i in range(num_echos):
                            decay_pct = i / max(1, num_echos - 1)
                            # Analog BBD / Tape delay flutter: exponential curve + tape saturation flutter
                            tape_flutter = random.gauss(0.0, 3.5) if i > 0 else 0.0
                            v_drop = int(round(16 + (decay_pct ** 0.85) * 46 + tape_flutter)) if i > 0 else 0
                            echo_dur = min(echo_step * 0.75, max(0.04, length_s - (i * echo_step)))
                            phrase_events.append({
                                'note_offset': chosen_int,
                                'start_offset': i * echo_step,
                                'dur': echo_dur,
                                'vel_mod': -v_drop
                            })
                        
                    elif mel_macro == "Tremolo" and length_s >= 0.25 and random.random() < 0.25:
                        inject = True
                        if length_s >= 0.75 * time_div:
                            trem_step = ((60.0 / actual_tempo) / 4.0) * time_div  # 16th-note pulsation on long notes
                        else:
                            trem_step = ((60.0 / actual_tempo) / 8.0) * time_div  # 32nd-note pulsation on faster notes
                        num_trems = max(2, min(12, int(length_s / trem_step)))
                        for i in range(num_trems):
                            # Organic wrist tremolo: alternating strong and soft pulses with natural variance
                            if i % 2 == 0:
                                v_mod = int(round(max(-5, min(6, random.gauss(0.0, 2.5)))))
                            else:
                                v_mod = int(round(max(-28, min(-10, random.gauss(-18.0, 4.0)))))
                            pulse_dur = max(0.035, trem_step * 0.70)
                            phrase_events.append({
                                'note_offset': chosen_int,
                                'start_offset': i * trem_step,
                                'dur': pulse_dur,
                                'vel_mod': v_mod
                            })
                        
                    if not inject:
                        phrase_events.append({'note_offset': chosen_int, 'start_offset': 0.0, 'dur': length_s, 'vel_mod': 0})

                    # Bake the exact heard micro-timing drift into phrase_events so LCK and M freeze the true groove
                    step_drift_s = self._stochastic_drift_s(drift_ms)
                    for ev in phrase_events:
                        ev['start_offset'] = max(0.0, float(ev['start_offset']) + step_drift_s)
                        if ch.channel_type == 'polyphonic':
                            c_notes, c_ints = self._build_polyphonic_voicing(
                                ch.name, base_note, ev['note_offset'], scale_intervals,
                                ch_data.get('chord_type', 'Triad'), min_o, max_o, root_offset
                            )
                            ev['chord_notes'] = list(c_notes)
                            ev['played_ints'] = list(c_ints)

                    recorded_ev = {
                        'phrase': [dict(p) for p in phrase_events],
                        'base_note': base_note,
                        'vel': vel,
                        'chosen_dur': chosen_dur,
                        'root_offset': root_offset
                    }
                    buffer[eff_tick % 384] = recorded_ev
                    self.history_buffers[ch.name][eff_tick % 384] = self._copy_event(recorded_ev)

                    played_intervals = []
                    for ev_idx, ev in enumerate(phrase_events):
                        n_off = ev['note_offset']
                        notes_to_play = []
                    
                        if ch.channel_type == 'polyphonic':
                            notes_to_play.extend(ev.get('chord_notes', []))
                            played_intervals.extend(ev.get('played_ints', []))
                        else:
                            notes_to_play.append(fold_pitch(base_note + n_off))
                            played_intervals.append(12 if n_off == 12 else (n_off % 12))
                        
                        start_time = tick_now + ev['start_offset']
                        end_time = start_time + ev['dur']
                        ev_vel = max(1, min(127, vel + ev['vel_mod']))
                    
                        with self.midi_lock:
                            if ch.channel_type == 'melodic' and ev_idx == 0:
                                for q_ev in self.midi_events:
                                    if q_ev.get('ch_name') == ch.name and q_ev.get('type') == 'off' and q_ev['time'] >= start_time:
                                        q_ev['time'] = max(start_time - 0.004, q_ev.get('on_time', 0.0) + 0.001)
                            for n in notes_to_play:
                                for q_ev in self.midi_events:
                                    if q_ev.get('ch_name') == ch.name and q_ev.get('note') == n and q_ev.get('type') == 'off' and q_ev['time'] >= start_time:
                                        q_ev['time'] = max(start_time - 0.004, q_ev.get('on_time', 0.0) + 0.001)
                                    
                                self.midi_events.append({'time': start_time, 'type': 'on', 'note': n, 'vel': ev_vel, 'chan': midi_chan, 'ch_name': ch.name})
                                self.midi_events.append({'time': end_time, 'type': 'off', 'note': n, 'chan': midi_chan, 'ch_name': ch.name, 'on_time': start_time})
                
                    self.ui_events.append(('flash', ch.name, played_intervals, chosen_dur))
            except Exception:
                log_exc(f'tick:{ch.name}')

class ChannelView(tk.Frame):
    def __init__(self, parent, name, channel_type, mem_callback=None):
        super().__init__(parent, bg=PANEL_COLOR, highlightbackground=ACCENT_BRUISED, highlightcolor=ACCENT_BRUISED, highlightthickness=2)
        self.name = name
        self.channel_type = channel_type
        self.mem_callback = mem_callback
        self.vars = {}
        self.base_vars = {}
        self.is_modulating = False
        self._update_callbacks = [] 
        self._interval_cbs = []
        self.note_col_frames = {}
        self._inter_flash_tokens = {}
        self.dur_col_frames = {}
        self._dur_flash_tokens = {}
        self._interval_scales = []
        self._duration_scales = []
        self.mutation_seed = random.SystemRandom().randrange(1, 2**31 - 1)
        self.mod_badge_labels = {}
        
        self._expanded = True
        self.grid_columnconfigure(0, weight=1)
        self.header_frame = tk.Frame(self, bg=PANEL_COLOR)
        self.header_frame.grid(row=0, column=0, sticky='ew')
        
        self.body_frame = tk.Frame(self, bg=PANEL_COLOR)
        self.body_frame.grid(row=1, column=0, sticky='nsew')
        
        self.create_widgets()

    def is_expanded(self):
        if not hasattr(self, 'body_frame'): return False
        return getattr(self, '_expanded', self.body_frame.winfo_manager() == 'grid')

    def collapse(self):
        if hasattr(self, 'body_frame') and self.is_expanded():
            self._expanded = False
            self.body_frame.grid_remove()
            self.toggle_btn.config(text="[+]")
            if getattr(self, '_physics_after_id', None) is not None:
                try: self.after_cancel(self._physics_after_id)
                except Exception: pass
                self._physics_after_id = None

    def expand(self):
        if hasattr(self, 'body_frame') and not self.is_expanded():
            self._expanded = True
            self.body_frame.grid(row=1, column=0, sticky='nsew')
            self.toggle_btn.config(text="[-]")
            if getattr(self, '_physics_after_id', None) is not None:
                try: self.after_cancel(self._physics_after_id)
                except Exception: pass
                self._physics_after_id = None
            if self.channel_type in ['melodic', 'polyphonic']:
                self.update_physics_visuals()

    def toggle_collapse(self, event=None):
        top = self.winfo_toplevel()
        if hasattr(top, 'toggle_channel_view'):
            top.toggle_channel_view(self)
        else:
            if self.is_expanded():
                self.collapse()
            else:
                self.expand()
            if hasattr(top, 'ui_frame'):
                top.ui_frame.update_idletasks()
            if hasattr(top, '_sync_canvas_window'):
                top._sync_canvas_window()


    def _init_mod_scope(self, parent):
        self.scope_canvas = tk.Canvas(parent, width=74, height=36, bg="#131014",
                                      highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.scope_canvas.pack(side='top', padx=(2, 2), pady=(1, 2))
        ToolTip(self.scope_canvas, "Mini-Oscilloscope. Visualizes real-time LFO waveform geometry. The glowing dot tracks live cycle phase and output voltage.")
        self._scope_wave = None
        self._scope_line = None
        self._scope_dot = self.scope_canvas.create_oval(-10, -10, -10, -10, fill=SEPIA_ACTIVE, outline="#ff9977")
        self.draw_scope_curve(self.vars.get('waveform', tk.StringVar(value='Sine')).get())

    def draw_scope_curve(self, wave):
        if not hasattr(self, 'scope_canvas'): return
        self._scope_wave = wave
        w, h = 74, 36
        pad_x, pad_y = 3, 3
        usable_w = w - 2 * pad_x
        usable_h = h - 2 * pad_y
        pts = []
        steps = 36
        for i in range(steps + 1):
            p = i / float(steps)
            x = pad_x + p * usable_w
            if wave == "Sine": y_val = 0.5 + 0.5 * math.sin(p * 2 * math.pi)
            elif wave == "Triangle": y_val = p * 2.0 if p < 0.5 else 2.0 - (p * 2.0)
            elif wave == "Saw Up": y_val = p
            elif wave == "Saw Down": y_val = 1.0 - p
            elif wave == "Pulse": y_val = 1.0 if p < 0.5 else 0.0
            elif wave == "Random":
                y_val = 0.5 + 0.35 * math.sin(p * 2 * math.pi * 1.5)
            elif wave == "SlewRand":
                y_val = 0.5 + 0.35 * math.sin(p * 2 * math.pi * 1.5) + 0.15 * math.cos(p * 2 * math.pi * 3.0)
            elif wave == "S&H":
                step = int(p * 8)
                hash_v = ((step * 9301 + 49297) % 233280) / 233280.0
                y_val = hash_v
            elif wave == "ExpDecay":
                decay = math.exp(-5.0 * p)
                y_val = (decay - 0.006738) / (1.0 - 0.006738)
            elif wave == "Chaos":
                y_val = 0.5 + 0.26 * math.sin(p * 2 * math.pi) + 0.15 * math.sin(p * 10.166) + 0.09 * math.cos(p * 15.169)
            else:
                y_val = 0.5
            y_val = max(0.0, min(1.0, y_val))
            y = (h - pad_y) - (y_val * usable_h)
            pts.extend([x, y])

        is_smooth = wave in ("Sine", "ExpDecay", "Chaos", "SlewRand")
        if self._scope_line is None:
            self._scope_line = self.scope_canvas.create_line(*pts, fill="#6e4f6a", width=1.5, smooth=is_smooth)
            self.scope_canvas.tag_lower(self._scope_line)
        else:
            self.scope_canvas.coords(self._scope_line, *pts)
            self.scope_canvas.itemconfig(self._scope_line, smooth=is_smooth)

    def update_scope(self, wave, phase, val, is_active=True):
        if not hasattr(self, 'scope_canvas'): return
        if not self.is_expanded(): return
        if wave != getattr(self, '_scope_wave', None):
            self.draw_scope_curve(wave)
        w, h = 74, 36
        pad_x, pad_y = 3, 3
        cx = pad_x + max(0.0, min(1.0, phase)) * (w - 2 * pad_x)
        cy = (h - pad_y) - max(0.0, min(1.0, val)) * (h - 2 * pad_y)
        state_key = (cx, cy, bool(is_active))
        if getattr(self, '_last_scope_state', None) == state_key:
            return
        self._last_scope_state = state_key
        dot_color = SEPIA_ACTIVE if is_active else "#555555"
        dot_outline = "#ff9977" if is_active else "#777777"
        try:
            self.scope_canvas.coords(self._scope_dot, cx - 3, cy - 3, cx + 3, cy + 3)
            if getattr(self, '_last_scope_act', None) != bool(is_active):
                self._last_scope_act = bool(is_active)
                self.scope_canvas.itemconfig(self._scope_dot, fill=dot_color, outline=dot_outline)
        except tk.TclError: pass

    def _on_var_user_change(self, name):
        if not getattr(self, 'is_modulating', False):
            try: self.base_vars[name] = self.vars[name].get()
            except: pass

    def apply_mod_visuals(self, ch_mods):
        if not ch_mods and not getattr(self, '_had_active_mods', False):
            return
        self._had_active_mods = bool(ch_mods)
        self.is_modulating = True
        v_map = {
            'RST%': 'rest_prob', 'SWG': 'swing', 'DRF': 'drift',
            'V.MIN': 'v_min', 'V.MAX': 'v_max', 'PLS': 'eucl_pulses',
            'LCK': 'locked', 'ACT': 'enabled', 'MUT': 'mutation',
            'GRV': 'gravity', 'INT': 'inertia'
        }
        
        needs_redraw = False
        
        for param, var_name in v_map.items():
            if var_name not in self.vars or var_name not in self.base_vars: continue
            
            base_val = self.base_vars[var_name]
            if param in ch_mods:
                offset = ch_mods[param]
                if param in ['LCK', 'ACT']:
                    # XOR visual redraw logic: perfectly mimics the engine's toggling gate
                    final_val = bool(base_val) ^ bool(offset > 0.5)
                else:
                    final_val = base_val + offset
                    if var_name in ['rest_prob', 'swing', 'drift', 'mutation', 'gravity', 'inertia']:
                        final_val = max(0, min(100, int(round(final_val))))
                    elif var_name in ['v_min', 'v_max']:
                        final_val = max(1, min(127, int(round(final_val))))
                    elif var_name == 'eucl_pulses':
                        try: max_p = self.vars['eucl_steps'].get()
                        except: max_p = 16
                        final_val = max(0, min(max_p, int(round(final_val))))
                        
                try:
                    if self.vars[var_name].get() != final_val:
                        self.vars[var_name].set(final_val)
                        needs_redraw = True
                except tk.TclError: pass
                except Exception: log_exc("apply_mod_visuals_mod")
            else:
                try:
                    if self.vars[var_name].get() != base_val:
                        self.vars[var_name].set(base_val)
                        needs_redraw = True
                except tk.TclError: pass
                except Exception: log_exc("apply_mod_visuals_base")
                
        # Reverse-modulation visual badging on modulated parameter labels (dirty-checked to avoid Win32 HWND invalidation)
        for param, lbl in getattr(self, 'mod_badge_labels', {}).items():
            try:
                is_badged = (param in ch_mods and abs(ch_mods[param]) > 0.001)
                if getattr(lbl, '_is_mod_badged', False) != is_badged:
                    lbl._is_mod_badged = is_badged
                    base_txt = getattr(lbl, '_base_text', None)
                    if base_txt is None:
                        base_txt = lbl.cget('text')
                        lbl._base_text = base_txt
                    base_fg = getattr(lbl, '_base_fg', None)
                    if base_fg is None:
                        base_fg = lbl.cget('fg')
                        lbl._base_fg = base_fg
                    if is_badged:
                        lbl.config(fg=SEPIA_ACTIVE, text=f"~{base_txt.lstrip('~')}")
                    else:
                        lbl.config(fg=base_fg, text=base_txt)
            except Exception: pass

        if needs_redraw:
            for cb in self._update_callbacks:
                try: cb()
                except Exception: pass
                
        self.is_modulating = False

    def update_mem_btn_color(self, slot, has_data, slot_data=None):
        if hasattr(self, 'mem_btns') and slot in self.mem_btns:
            btn = self.mem_btns[slot]
            if has_data:
                detail_info = ""
                if slot_data and isinstance(slot_data, dict):
                    buf = slot_data.get('buffer', [])
                    lock_len = slot_data.get('lock_len', 32)
                    active_cnt = sum(1 for ev in buf if ev is not None)
                    detail_info = f" ({active_cnt} notes, {lock_len} stp)"
                btn.config(text=f"{slot}", bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                ToolTip(btn, f"M{slot}{detail_info}\n\n• L-CLICK: Recalls stored phrase.\n• R-CLICK: Deletes slot.\n• If a top Step box is armed, assigns this M-slot to the Step sequence.")
            else:
                btn.config(text=f"{slot}", bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                ToolTip(btn, f"M{slot}\n\n• L-CLICK: Snapshots phrase if empty, recalls if populated.\n• R-CLICK: Deletes.\n• If a top Step box is armed, assigns this M-slot to the Step sequence.")

    def set_mem_state(self, playing, pending):
        """Border on the M slot that is looping (cream) or queued for the next loop start (red)."""
        self._mem_playing = playing
        for slot, btn in getattr(self, 'mem_btns', {}).items():
            c = MEM_PLAY_BORDER if slot == playing else (LED_ON if slot == pending else PANEL_COLOR)
            try: btn.config(highlightbackground=c)
            except Exception: pass

    def flash_mem(self, slot):
        btn = getattr(self, 'mem_btns', {}).get(slot)
        if not btn: return
        def _restore():
            try:
                self.update_mem_btn_color(slot, True)
                btn.config(highlightbackground=MEM_PLAY_BORDER if getattr(self, '_mem_playing', None) == slot else PANEL_COLOR)
            except Exception: pass
        try:
            btn.config(bg=MEM_FLASH, highlightbackground=MEM_FLASH)
            self.after(140, _restore)
        except Exception: pass

    def rebuild_intervals(self, scale_name):
        if self.channel_type not in ['melodic', 'polyphonic']: return
        self._probs_dirty = True
        
        for cb in self._interval_cbs:
            if cb in self._update_callbacks: self._update_callbacks.remove(cb)
        self._interval_cbs = []
        self._interval_scales = []
        for widget in self.note_frame.winfo_children():
            widget.destroy()
            
        # Reset the live readout references so we don't try to update dead Tkinter widgets
        self.note_eff_labels = {} 
        self.note_col_frames = {}
            
        grid_inner = tk.Frame(self.note_frame, bg=PANEL_COLOR)
        grid_inner.pack(fill='x', expand=True, padx=2, pady=4)
        
        scale_intervals = SCALES.get(scale_name, [0, 3, 5, 7, 10]).copy()
        if 12 not in scale_intervals: scale_intervals.append(12)
        
        for i, interval in enumerate(scale_intervals):
            subf = tk.Frame(grid_inner, bg=PANEL_COLOR, highlightthickness=1, highlightbackground=PANEL_COLOR)
            subf.grid(row=0, column=i, padx=2, sticky='nsew')
            grid_inner.columnconfigure(i, weight=1)
            
            lbl_title = tk.Label(subf, text=INTERVAL_NAMES.get(interval, str(interval)), bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_title.pack()
            
            var = self.vars['note_probs'][interval]
            sc = tk.Scale(subf, from_=100, to=0, orient='vertical', variable=var, length=SLIDER_LEN, sliderlength=12, width=14, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            sc.pack(pady=2)
            self._interval_scales.append(sc)
            
            lbl = tk.Label(subf, text=str(int(var.get())), bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3, anchor='center')
            lbl.pack()
            
            sc.configure(command=lambda val, l=lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(sc, lbl, var, 0, 100)
            _cb = lambda v=var, l=lbl: l.config(text=str(int(float(v.get()))))
            self._update_callbacks.append(_cb)
            self._interval_cbs.append(_cb)
            
            # --- LIVE PHYSICS CAPSULE VU METER ---
            eff_meter = CapsuleVUMeter(subf, meter_type="gravity", width=28, height=12)
            eff_meter.pack(pady=(2, 1))
            self.note_eff_labels[interval] = eff_meter
            self.note_col_frames[interval] = (subf, lbl_title)
            ToolTip(eff_meter, f"Live Effective Weight for {INTERVAL_NAMES.get(interval, str(interval))}. Segmented LED capsule meter displaying live Brownian Gravity (GRV) drift with ballistic peak-hold decay.")
            # --------------------------------------

            
            ToolTip(sc, f"Probability weight for generating the {INTERVAL_NAMES.get(interval)} interval relative to the Root note. Higher values mean this interval is chosen more frequently during stochastic generation. Only intervals actively mapped to the Global Scale mathematically trigger.")

    def update_led_brightness(self, val):
        r1, g1, b1 = 10, 7, 10
        r2, g2, b2 = 212, 61, 30
        nr = int(r1 + (r2 - r1) * val)
        ng = int(g1 + (g2 - g1) * val)
        nb = int(b1 + (b2 - b1) * val)
        color = f"#{nr:02x}{ng:02x}{nb:02x}"
        try:
            if hasattr(self, 'led_canvas') and hasattr(self, 'led_circle'):
                self.led_canvas.itemconfig(self.led_circle, fill=color)
        except tk.TclError: pass
        except Exception: log_exc("update_led_brightness")

    def toggle_lock_state(self):
        new_val = not self.vars['locked'].get()
        self.base_vars['locked'] = new_val
        self.vars['locked'].set(new_val)
        if not new_val:
            self.vars['mem_seq_mode'].set("OFF")
        for cb in self._update_callbacks:
            try: cb()
            except Exception: pass

    def create_widgets(self):
        default_routing = {
            "BD": 5, "SD": 7, "HHT": 8, 
            "Bass": 6, "Plasma": 3, "Panharmonium": 11, 
            "Pigments": 10, "Hydrasynth": 2
        }
        fallback_chan = 10 if self.channel_type == 'percussion' else 1
        self.vars['midi_chan'] = tk.IntVar(value=default_routing.get(self.name, fallback_chan))

        self.header_row1 = tk.Frame(self.header_frame, bg="#130e15", highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.header_row1.pack(fill='x', padx=1, pady=(1, 1))
        self.header_row1.grid_columnconfigure(0, weight=1, uniform='hdr_r1')
        self.header_row1.grid_columnconfigure(1, weight=0)
        self.header_row1.grid_columnconfigure(2, weight=1, uniform='hdr_r1')

        row1_left = tk.Frame(self.header_row1, bg="#130e15")
        row1_left.grid(row=0, column=0, sticky='w')
        self.row1_left = row1_left

        row1_center = tk.Frame(self.header_row1, bg="#130e15")
        row1_center.grid(row=0, column=1)
        self.row1_center = row1_center

        row1_right = tk.Frame(self.header_row1, bg="#130e15")
        row1_right.grid(row=0, column=2, sticky='e')
        self.row1_right = row1_right
        
        self.toggle_btn = tk.Label(row1_left, text="[-]", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN, relief='raised', bd=1, cursor="hand2", padx=3, pady=1)
        self.toggle_btn.pack(side='left', padx=(1, 4))
        self.toggle_btn.bind("<Button-1>", self.toggle_collapse)
        ToolTip(self.toggle_btn, "Collapse / Expand module view. Collapsing conceals visualizers and sequencer lanes to save screen space and suspend physics polling.")

        if self.channel_type == 'percussion':
            name_fg = "#ffaa4c"
        elif self.channel_type == 'modulation':
            name_fg = "#64d8cb"
        else:
            name_fg = "#f0e6d2"
        name_plate = tk.Frame(row1_center, bg="#0d0710", relief='sunken', bd=1)
        name_plate.pack(side='left', padx=2)
        name_lbl = tk.Label(name_plate, text=f"[{self.name.upper()}]", bg="#0d0710", fg=name_fg, font=FONT_BOLD, padx=6, pady=1)
        name_lbl.pack(side='left')

        self.vars['enabled'] = tk.BooleanVar(value=False)
        self.base_vars['enabled'] = False
        
        act_btn = tk.Label(row1_left, text="ACT", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_BOLD, relief='raised', bd=1, cursor="hand2", width=7, pady=1)
        act_btn.pack(side='left', padx=(2, 4))
        self.act_btn = act_btn
        
        def _update_act_visual(*args):
            v = self.vars['enabled'].get()
            if v:
                act_btn.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                self.config(highlightbackground=SEPIA_ACTIVE, highlightcolor=SEPIA_ACTIVE)
            else:
                act_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                self.config(highlightbackground=ACCENT_BRUISED, highlightcolor=ACCENT_BRUISED)
                
        def _toggle_act(event=None):
            new_val = not self.vars['enabled'].get()
            self.base_vars['enabled'] = new_val
            self.vars['enabled'].set(new_val)
            _update_act_visual()
            
        act_btn.bind("<Button-1>", _toggle_act)
        self._update_callbacks.append(_update_act_visual)
        ToolTip(act_btn, "Channel Arm / Mute Button. Click to activate. When disabled, this channel instantly stops computing and transmitting MIDI data. Used to manually drop elements in and out live on stage. XOR Logic Gate applies: an LFO pulse from the Mod Matrix will logically toggle this button exactly as if you clicked it.")
        
        self.led_canvas = tk.Canvas(row1_left, width=16, height=16, highlightthickness=0, bg="#130e15")
        self.led_canvas.pack(side='left', padx=(2, 2))
        self.led_circle = self.led_canvas.create_oval(2, 2, 14, 14, fill=LED_OFF, outline=ACCENT_BRUISED)
        ToolTip(self.led_canvas, "Channel Activity LED. Flashes bright orange on active MIDI note triggers and glows dynamically with incoming LFO modulation voltage.")

        if self.channel_type == 'modulation':
            lbl_dp = tk.Label(row1_right, text="DP:", bg="#130e15", fg=FG_COLOR, font=FONT_SMALL)
            lbl_dp.pack(side='left', padx=(4, 2))
            self.vars['depth'] = tk.IntVar(value=100)
            sp_dep = tk.Spinbox(row1_right, from_=0, to=100, width=3, textvariable=self.vars['depth'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_dep.pack(side='left', padx=(2, 2))
            ToolTip(sp_dep, "Modulation Depth (0-100%). Master attenuator percentage for all targets driven by this LFO.")

            mod_top = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            mod_top.pack(fill='x', padx=6, pady=2)

            lbl_ch = tk.Label(mod_top, text="CH:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN)
            lbl_ch.pack(side='left', padx=(0, 2))
            self.lbl_ch = lbl_ch
            sp_ch = tk.Spinbox(mod_top, from_=1, to=16, width=3, textvariable=self.vars['midi_chan'],
                               bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN,
                               relief='sunken', bd=1, insertbackground=FG_COLOR,
                               disabledbackground="#140f16", disabledforeground="#6e626c")
            sp_ch.pack(side='left', padx=(0, 4))
            self.sp_ch = sp_ch
            ToolTip(sp_ch, "MIDI Output Hardware Target (1-16).")

            lbl_phs = tk.Label(mod_top, text="PHS:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_phs.pack(side='left', padx=(4, 1))
            self.vars['phase_offset'] = tk.IntVar(value=0)
            sp_phs = tk.Spinbox(mod_top, from_=0, to=360, increment=15, width=3, textvariable=self.vars['phase_offset'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_phs.pack(side='left', padx=1)
            ToolTip(sp_phs, "LFO Phase Offset (0°–360°). Shifts the cycle start relative to transport downbeats. Offset multiple MOD channels (e.g. 0°, 90°, 180°, 270°) for quadrature modulation or polyrhythmic phasing.")
            def _on_phs_change(*args):
                try:
                    deg = self.vars['phase_offset'].get()
                    p = (deg % 360) / 360.0
                    self.update_scope(self.vars['waveform'].get(), p, 0.5, False)
                except Exception: pass
            self.vars['phase_offset'].trace_add('write', _on_phs_change)
            
            lbl_rt = tk.Label(mod_top, text="RT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_rt.pack(side='left', padx=(4, 1))
            self.vars['rate'] = tk.StringVar(value="1/4")
            rt_menu = tk.OptionMenu(mod_top, self.vars['rate'], "64/1", "32/1", "16/1", "8/1", "4/1", "2/1", "1/1", "1/2", "1/4", "1/8", "1/16", "1/32")
            rt_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=4)
            rt_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
            rt_menu.pack(side='left', padx=1)
            ToolTip(rt_menu, "LFO Rate. Strictly synchronized to the global clock. '1/4' means one full waveform cycle spans exactly one quarter-note beat. '64/1' takes a massive 64 quarter-notes to complete one extremely slow, evolving ambient sweep.")

            lbl_wav = tk.Label(mod_top, text="WAV:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_wav.pack(side='left', padx=(4, 1))
            self.vars['waveform'] = tk.StringVar(value="Sine")
            wave_options = ["Sine", "Triangle", "Saw Up", "Saw Down", "Pulse", "Random", "SlewRand", "S&H", "ExpDecay", "Chaos"]
            def _on_wave_select(val):
                self.base_vars['waveform'] = val
                self.draw_scope_curve(val)
            w_menu = tk.OptionMenu(mod_top, self.vars['waveform'], *wave_options, command=_on_wave_select)
            w_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=8)
            w_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
            w_menu.pack(side='left', padx=1)
            ToolTip(w_menu, "LFO Waveform Shape. Defines the exact geometric path of the modulation: Sine, Triangle, Saw Up/Down, Pulse, Random, SlewRand (analog drift), S&H (8 stepped sample & hold levels), ExpDecay (percussive envelope plunge), Chaos (incommensurate non-linear attractor).")

            mod_container = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            mod_container.pack(fill='both', expand=True, padx=4, pady=2)

            body_left = tk.Frame(mod_container, bg=PANEL_COLOR)
            body_left.pack(side='left', fill='y', padx=(2, 6))

            self._init_mod_scope(body_left)

            row_l1 = tk.Frame(body_left, bg=PANEL_COLOR)
            row_l1.pack(fill='x', pady=(2, 1))
            tk.Label(row_l1, text="POL:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left')
            self.vars['polarity'] = tk.StringVar(value="UNI")
            p_menu = tk.OptionMenu(row_l1, self.vars['polarity'], "UNI", "BI")
            p_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=3)
            p_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
            p_menu.pack(side='left', padx=1)
            ToolTip(p_menu, "LFO Polarity. 'UNI' (Unipolar) sweeps the value strictly upwards from base value. 'BI' (Bipolar) sweeps symmetrically above and below center.")

            row_l2 = tk.Frame(body_left, bg=PANEL_COLOR)
            row_l2.pack(fill='x', pady=1)
            tk.Label(row_l2, text="MI:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left')
            self.vars['min_val'] = tk.IntVar(value=0)
            sp_min = tk.Spinbox(row_l2, from_=0, to=127, width=3, textvariable=self.vars['min_val'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_min.pack(side='left', padx=1)
            ToolTip(sp_min, "Minimum Mathematical Boundary (0-127). The lowest absolute floor value permitted.")

            tk.Label(row_l2, text="MX:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 0))
            self.vars['max_val'] = tk.IntVar(value=127)
            sp_max = tk.Spinbox(row_l2, from_=0, to=127, width=3, textvariable=self.vars['max_val'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_max.pack(side='left')
            ToolTip(sp_max, "Maximum Mathematical Boundary (0-127). The absolute ceiling permitted.")

            body_right = tk.Frame(mod_container, bg=PANEL_COLOR)
            body_right.pack(side='left', fill='both', expand=True)

            # Group destinations by instrument and category so the MOD menu is easy to scan.
            perc_names = ["BD", "SD", "HHT"]
            mel_names = ["Bass", "Plasma", "GM", "Panharmonium", "Pigments", "Hydrasynth"]
            mod_names = [f"MOD {i}" for i in range(1, 11)]
            target_groups = [("GLOBAL", ["OFF", "EXT CC"])]
            for n in perc_names:
                target_groups.append((f"DRUMS · {n}", [
                    f"{n} ACT", f"{n} MUT", f"{n} RST%", f"{n} PLS", f"{n} SWG",
                    f"{n} DRF", f"{n} V.MIN", f"{n} V.MAX"
                ]))
            for n in mel_names:
                target_groups.append((f"MELODIC · {n}", [
                    f"{n} ACT", f"{n} LCK", f"{n} MUT", f"{n} RST%", f"{n} DRF",
                    f"{n} GRV", f"{n} INT", f"{n} V.MIN", f"{n} V.MAX", f"{n} ROT", f"{n} RND"
                ]))
            for n in mod_names:
                if n != self.name:
                    target_groups.append((f"MOD · {n}", [f"{n} DP", f"{n} ACT"]))

            all_flat_options = []
            for _, opts in target_groups:
                all_flat_options.extend(opts)

            def make_target_menu(parent, variable, width=9):
                btn = tk.Label(parent, textvariable=variable, bg=INPUT_BG, fg=INPUT_FG, font=FONT_SMALL,
                               relief='sunken', bd=1, width=width, anchor='center', cursor="hand2")
                               
                def _update_btn_color(*args):
                    cur = str(variable.get())
                    if cur == "OFF":
                        btn.config(fg="#6e5b6b", bg=INPUT_BG)
                    elif cur == "EXT CC":
                        btn.config(fg="#38bdf8", bg="#0a141a")
                    else:
                        btn.config(fg=SEPIA_ACTIVE, bg="#1a0f1d")
                variable.trace_add("write", _update_btn_color)
                _update_btn_color()
                
                # Direct mouse wheel scrolling on the target button!
                def _on_wheel(event):
                    cur = variable.get()
                    try: idx = all_flat_options.index(cur)
                    except ValueError: idx = 0
                    delta = -1 if event.delta > 0 else 1
                    new_idx = max(0, min(len(all_flat_options) - 1, idx + delta))
                    variable.set(all_flat_options[new_idx])
                    return "break"
                btn.bind("<MouseWheel>", _on_wheel)
                btn.bind("<Button-4>", lambda e: _on_wheel(type('obj', (object,), {'delta': 120})))
                btn.bind("<Button-5>", lambda e: _on_wheel(type('obj', (object,), {'delta': -120})))
                
                # Left-click opens searchable, mouse-wheel scrollable popup
                def _open_popup(event=None):
                    ScrollableTargetPopup(btn, variable, target_groups)
                btn.bind("<Button-1>", _open_popup)
                
                # Right-click opens organized cascading submenu
                def _open_cascade(event):
                    casc = tk.Menu(btn, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                    casc.add_command(label="OFF", command=lambda: variable.set("OFF"))
                    casc.add_command(label="EXT CC", command=lambda: variable.set("EXT CC"))
                    casc.add_separator()
                    
                    drums_menu = tk.Menu(casc, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                    for n in perc_names:
                        sub = tk.Menu(drums_menu, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                        for opt in [f"{n} ACT", f"{n} MUT", f"{n} RST%", f"{n} PLS", f"{n} SWG", f"{n} DRF", f"{n} V.MIN", f"{n} V.MAX"]:
                            sub.add_command(label=opt, command=lambda v=opt: variable.set(v))
                        drums_menu.add_cascade(label=n, menu=sub)
                    casc.add_cascade(label="DRUMS ►", menu=drums_menu)
                    
                    mel_menu = tk.Menu(casc, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                    for n in mel_names:
                        sub = tk.Menu(mel_menu, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                        for opt in [f"{n} ACT", f"{n} LCK", f"{n} MUT", f"{n} RST%", f"{n} DRF", f"{n} GRV", f"{n} INT", f"{n} V.MIN", f"{n} V.MAX", f"{n} ROT", f"{n} RND"]:
                            sub.add_command(label=opt, command=lambda v=opt: variable.set(v))
                        mel_menu.add_cascade(label=n, menu=sub)
                    casc.add_cascade(label="MELODIC ►", menu=mel_menu)
                    
                    mod_menu = tk.Menu(casc, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                    for n in mod_names:
                        if n != self.name:
                            sub = tk.Menu(mod_menu, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                            for opt in [f"{n} DP", f"{n} ACT"]:
                                sub.add_command(label=opt, command=lambda v=opt: variable.set(v))
                            mod_menu.add_cascade(label=n, menu=sub)
                    casc.add_cascade(label="MODULATION ►", menu=mod_menu)
                    
                    try: casc.tk_popup(event.x_root, event.y_root)
                    except Exception: pass
                btn.bind("<Button-3>", _open_cascade)
                
                return btn

            def make_toggle(parent, var_name, text):
                self.vars[var_name] = tk.StringVar(value="ON")
                self.base_vars[var_name] = "ON"
                lbl = tk.Label(parent, text=f" {text.strip()} ", bg=SEPIA_ACTIVE, fg=LED_OFF, font=FONT_SMALL, relief='solid', bd=1, cursor="hand2")
                lbl.pack(side='left', padx=(0, 2))
                ToolTip(lbl, f"Modulation Target Polarity ({text.strip()}). Left-click to cycle: ON (Active), INV (Inverted), or OFF (Bypassed / muted target).")
                
                def update_visual(*args):
                    val = str(self.vars[var_name].get()).upper()
                    base_label = text.strip()
                    if val in ["TRUE", "1", "ON"]:
                        lbl.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='solid', text=f" {base_label} ")
                    elif val == "INV":
                        lbl.config(bg=ACCENT_BRUISED, fg=FG_COLOR, relief='solid', text=f"-{base_label} ")
                    else:
                        lbl.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='flat', text=f" {base_label} ")
                
                def toggle(event=None):
                    val = str(self.vars[var_name].get()).upper()
                    if val in ["TRUE", "1", "ON"]: new_val = "INV"
                    elif val == "INV": new_val = "OFF"
                    else: new_val = "ON"
                    self.base_vars[var_name] = new_val
                    self.vars[var_name].set(new_val)
                    update_visual()
                    
                lbl.bind("<Button-1>", toggle)
                self._update_callbacks.append(update_visual)
                return lbl

            # Destination Strip 1 (T1)
            r1 = tk.Frame(body_right, bg=PANEL_COLOR)
            r1.pack(fill='x', pady=1)
            make_toggle(r1, 't1_act', " T1 ")
            self.vars['mod_target_1'] = tk.StringVar(value="OFF")
            m1 = make_target_menu(r1, self.vars['mod_target_1'])
            m1.pack(side='left', padx=1)
            ToolTip(m1, "LFO Target 1 Destination. Route this LFO to drums, melodic channels, other MOD LFOs, or EXT CC.")

            tk.Label(r1, text="AMT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 0))
            self.vars['t1_amt'] = tk.IntVar(value=100)
            sp_amt1 = tk.Spinbox(r1, from_=-100, to=100, increment=5, width=4, textvariable=self.vars['t1_amt'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_amt1.pack(side='left', padx=1)
            ToolTip(sp_amt1, "Target 1 Amount (-100% to +100%). Fine-tunes depth for Target 1 independently. Negative values invert the wave.")

            tk.Label(r1, text="CC:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 0))
            self.vars['cc_num'] = tk.IntVar(value=74)
            sp_cc = tk.Spinbox(r1, from_=0, to=127, width=3, textvariable=self.vars['cc_num'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_cc.pack(side='left')
            ToolTip(sp_cc, "External MIDI CC Number (0-127). Transmits hardware CC continuous controller data when target is set to 'EXT CC'.")

            # Destination Strip 2 (T2)
            r2 = tk.Frame(body_right, bg=PANEL_COLOR)
            r2.pack(fill='x', pady=1)
            make_toggle(r2, 't2_act', " T2 ")
            self.vars['mod_target_2'] = tk.StringVar(value="OFF")
            m2 = make_target_menu(r2, self.vars['mod_target_2'])
            m2.pack(side='left', padx=1)
            ToolTip(m2, "LFO Target 2 Destination. Route this LFO to a second concurrent destination.")

            tk.Label(r2, text="AMT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 0))
            self.vars['t2_amt'] = tk.IntVar(value=100)
            sp_amt2 = tk.Spinbox(r2, from_=-100, to=100, increment=5, width=4, textvariable=self.vars['t2_amt'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_amt2.pack(side='left', padx=1)
            ToolTip(sp_amt2, "Target 2 Amount (-100% to +100%). Independent bipolar modulation depth for Target 2.")

            # Destination Strip 3 (T3)
            r3 = tk.Frame(body_right, bg=PANEL_COLOR)
            r3.pack(fill='x', pady=1)
            make_toggle(r3, 't3_act', " T3 ")
            self.vars['mod_target_3'] = tk.StringVar(value="OFF")
            m3 = make_target_menu(r3, self.vars['mod_target_3'])
            m3.pack(side='left', padx=1)
            ToolTip(m3, "LFO Target 3 Destination. Route this LFO to a third concurrent destination.")

            tk.Label(r3, text="AMT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 0))
            self.vars['t3_amt'] = tk.IntVar(value=100)
            sp_amt3 = tk.Spinbox(r3, from_=-100, to=100, increment=5, width=4, textvariable=self.vars['t3_amt'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
            sp_amt3.pack(side='left', padx=1)
            ToolTip(sp_amt3, "Target 3 Amount (-100% to +100%). Independent bipolar modulation depth for Target 3.")

            self.mod_target_btns = {'t1': m1, 't2': m2, 't3': m3}
            self._update_callbacks.append(lambda: self.draw_scope_curve(self.vars['waveform'].get()))


        elif self.channel_type == 'percussion':
            # Sequencer state and visual updater
            if 'seq_active' not in self.vars: self.vars['seq_active'] = tk.BooleanVar(value=False)
            
            def _update_perc_seq_visual():
                is_seq = self.vars['seq_active'].get()
                bg_col = SEPIA_ACTIVE if is_seq else PANEL_COLOR
                fg_col = LED_OFF if is_seq else FG_COLOR
                rel = 'sunken' if is_seq else 'raised'
                if hasattr(self, 'e_seq_btn'):
                    self.e_seq_btn.config(bg=bg_col, fg=fg_col, relief=rel)
                if hasattr(self, 'add_seq_btn'):
                    self.add_seq_btn.config(bg=bg_col, fg=fg_col, relief=rel)
                if hasattr(self, 'seq_btn') and self.seq_btn not in (getattr(self, 'e_seq_btn', None), getattr(self, 'add_seq_btn', None)):
                    self.seq_btn.config(bg=bg_col, fg=fg_col, relief=rel)
            self._update_perc_seq_visual = _update_perc_seq_visual

            def _toggle_perc_seq(event=None):
                new_val = not self.vars['seq_active'].get()
                self.vars['seq_active'].set(new_val)
                _update_perc_seq_visual()
                if new_val:
                    if self.vars.get('perc_mode') and self.vars['perc_mode'].get() == "EUCLID":
                        if 'eucl_preset' in self.vars:
                            self.vars['eucl_preset'].set("Custom / Manual")
                else:
                    for i, b in getattr(self, 'step_btns', {}).items(): b.config(highlightbackground=PANEL_COLOR)
                    for i, b in getattr(self, 'e_step_btns', {}).items(): b.config(highlightbackground=PANEL_COLOR)

            # Row 2 (MACRO dropdown, AUTO btn, RST% slider, MUT slider)
            header_row2 = tk.Frame(self.header_frame, bg=PANEL_COLOR)
            header_row2.pack(fill='x', padx=1, pady=1)
            header_row2.grid_columnconfigure(0, weight=0)
            header_row2.grid_columnconfigure(1, weight=1, uniform='hdr_sliders')
            header_row2.grid_columnconfigure(2, weight=1, uniform='hdr_sliders')

            macro_frame = tk.Frame(header_row2, bg=PANEL_COLOR)
            macro_frame.grid(row=0, column=0, sticky='w', padx=(0, 2))

            PERC_MACROS = ["Static", "Void", "Evolve", "Drive", "Stutter", "Ghost", "Swarm", "Disintegration"]
            self.macro_pool = list(PERC_MACROS)
            self.vars['macro_state'] = tk.StringVar(value="Static")

            tk.Label(macro_frame, text="MACRO:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(1, 1))

            macro_lbl = tk.Label(macro_frame, text="Static", bg=INPUT_BG, fg=INPUT_FG, font=FONT_SMALL, width=11, anchor='w', relief='sunken', bd=1, cursor="hand2")
            macro_lbl.pack(side='left', padx=1)

            def _update_perc_macro_lbl(*args):
                macro_lbl.config(text=self.vars['macro_state'].get())
            self.vars['macro_state'].trace_add('write', _update_perc_macro_lbl)

            def _show_perc_macro_menu(event):
                def _popup(ev_x, ev_y):
                    menu = tk.Menu(self, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                    is_auto = self.vars['macro_auto'].get()
                    for idx, mac in enumerate(PERC_MACROS):
                        def make_handler(m=mac, x=ev_x, y=ev_y):
                            def handler():
                                if self.vars['macro_auto'].get():
                                    if m in self.macro_pool:
                                        if len(self.macro_pool) > 1: self.macro_pool.remove(m)
                                    else:
                                        self.macro_pool.append(m)
                                        self.macro_pool.sort(key=lambda x: PERC_MACROS.index(x))
                                    try: menu.destroy()
                                    except Exception: pass
                                    _popup(x, y)
                                else:
                                    self.vars['macro_state'].set(m)
                            return handler
                        menu.add_command(label=mac, command=make_handler())
                        if is_auto and mac in self.macro_pool:
                            menu.entryconfig(idx, background=ACCENT_BRUISED, foreground=FG_COLOR)
                        elif not is_auto and mac == self.vars['macro_state'].get():
                            menu.entryconfig(idx, background=ACCENT_BRUISED, foreground=FG_COLOR)
                    try: menu.tk_popup(ev_x, ev_y)
                    except Exception: pass
                _popup(event.x_root, event.y_root)
            macro_lbl.bind("<Button-1>", _show_perc_macro_menu)
            ToolTip(macro_lbl, "Percussion performance macro. Left-click to select (Static, Void, Evolve, Drive, Stutter, Ghost, Swarm, Disintegration). If AUTO is enabled, the menu acts as a multi-select filter to build your rotation pool.")

            self.vars['macro_auto'] = tk.BooleanVar(value=False)
            self.base_vars['macro_auto'] = False
            auto_btn = tk.Label(macro_frame, text="AUTO", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2", padx=2, pady=1)
            auto_btn.pack(side='left', padx=1)

            def _update_perc_auto_visual(*args):
                if self.vars['macro_auto'].get():
                    auto_btn.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                else:
                    auto_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')

            def _toggle_perc_auto(event=None):
                new_val = not self.vars['macro_auto'].get()
                self.base_vars['macro_auto'] = new_val
                self.vars['macro_auto'].set(new_val)
                _update_perc_auto_visual()

            auto_btn.bind("<Button-1>", _toggle_perc_auto)
            self.vars['macro_auto'].trace_add('write', _update_perc_auto_visual)
            self._update_callbacks.append(_update_perc_auto_visual)
            ToolTip(auto_btn, "Toggle AUTO macro rotation. Left-click to engage. If enabled, the macro menu acts as a multi-select pool to cycle through.")

            # RST% slider container
            rst_frame = tk.Frame(header_row2, bg=PANEL_COLOR)
            rst_frame.grid(row=0, column=1, sticky='ew', padx=2)

            lbl_rst = tk.Label(rst_frame, text="RST%:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_rst.pack(side='left', padx=(1, 1))
            self.mod_badge_labels['RST%'] = lbl_rst
            self.vars['rest_prob'] = tk.IntVar(value=0)
            rst_lbl = tk.Label(rst_frame, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            rst_lbl.pack(side='right', padx=1)
            rst_scale = tk.Scale(rst_frame, from_=0, to=100, orient='horizontal', variable=self.vars['rest_prob'], length=30, sliderlength=10, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            rst_scale.pack(side='left', fill='x', expand=True, padx=1)
            rst_scale.configure(command=lambda val, l=rst_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(rst_scale, rst_lbl, self.vars['rest_prob'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['rest_prob'], l=rst_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(rst_scale, "Rest Probability. Determines the percentage chance (0-100) that the engine will deliberately drop or skip a note that it was supposed to play.")

            # MUT slider container
            mut_frame = tk.Frame(header_row2, bg=PANEL_COLOR)
            mut_frame.grid(row=0, column=2, sticky='ew', padx=2)

            lbl_mut = tk.Label(mut_frame, text="MUT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_mut.pack(side='left', padx=(1, 1))
            self.mod_badge_labels['MUT'] = lbl_mut
            self.vars['mutation'] = tk.IntVar(value=0)
            mut_lbl = tk.Label(mut_frame, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            mut_lbl.pack(side='right', padx=1)
            mut_scale = tk.Scale(mut_frame, from_=0, to=100, orient='horizontal', variable=self.vars['mutation'], length=30, sliderlength=10, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            mut_scale.pack(side='left', fill='x', expand=True, padx=1)
            mut_scale.configure(command=lambda val, l=mut_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(mut_scale, mut_lbl, self.vars['mutation'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['mutation'], l=mut_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(mut_scale, "Percussion Mutation Intensity (0-100). Higher values introduce Boltzmann distance step deviations, pulse count drift, and phase slips during sequence playback.")

            # --- BODY_FRAME: TIMING CONTROLS ---
            timing_frame = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            timing_frame.pack(fill='x', padx=6, pady=2)

            lbl_ch = tk.Label(timing_frame, text="CH:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN)
            lbl_ch.pack(side='left', padx=(0, 2))
            self.lbl_ch = lbl_ch
            sp_ch = tk.Spinbox(timing_frame, from_=1, to=16, width=3, textvariable=self.vars['midi_chan'],
                               bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN,
                               relief='sunken', bd=1, insertbackground=FG_COLOR,
                               disabledbackground="#140f16", disabledforeground="#6e626c")
            sp_ch.pack(side='left', padx=(0, 6))
            self.sp_ch = sp_ch
            ToolTip(sp_ch, "MIDI Output Hardware Target (1-16).")
            
            swg_f = tk.Frame(timing_frame, bg=PANEL_COLOR)
            swg_f.pack(side='left', fill='x', expand=True, padx=(0,4))
            lbl_swg = tk.Label(swg_f, text="SWG%:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_swg.pack(side='left')
            self.mod_badge_labels['SWG'] = lbl_swg
            self.vars['swing'] = tk.IntVar(value=0)
            swg_lbl = tk.Label(swg_f, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            swg_lbl.pack(side='right')
            swg_scale = tk.Scale(swg_f, from_=0, to=100, orient='horizontal', variable=self.vars['swing'], sliderlength=12, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            swg_scale.pack(side='left', fill='x', expand=True, padx=2)
            swg_scale.configure(command=lambda val, l=swg_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(swg_scale, swg_lbl, self.vars['swing'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['swing'], l=swg_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(swg_scale, "MPC-Style Swing percentage. Delays the even-numbered 16th notes to create a classic shuffled groove. Applies to both Euclidean and Additive percussion.")

            drf_f = tk.Frame(timing_frame, bg=PANEL_COLOR)
            drf_f.pack(side='left', fill='x', expand=True, padx=(4,0))
            lbl_drf = tk.Label(drf_f, text="DRF:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_drf.pack(side='left')
            self.mod_badge_labels['DRF'] = lbl_drf
            self.vars['drift'] = tk.IntVar(value=0)
            drf_lbl = tk.Label(drf_f, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            drf_lbl.pack(side='right')
            drf_scale = tk.Scale(drf_f, from_=0, to=100, orient='horizontal', variable=self.vars['drift'], sliderlength=12, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            drf_scale.pack(side='left', fill='x', expand=True, padx=2)
            drf_scale.configure(command=lambda val, l=drf_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(drf_scale, drf_lbl, self.vars['drift'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['drift'], l=drf_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(drf_scale, "Analog Slop. Actively injects Gaussian microsecond timing delays into every percussion trigger.")

            # Unified Percussion Header Frame (2-Row Grid: Visualizers + Primary Controls)
            self.perc_header_frame = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            self.perc_header_frame.pack(fill='x', padx=6, pady=(6, 4))
            
            # Row 0, Col 0: Engine Selection Buttons
            eng_sel_frame = tk.Frame(self.perc_header_frame, bg=PANEL_COLOR)
            eng_sel_frame.grid(row=0, column=0, sticky='w', padx=(0, 6))
            
            tk.Label(eng_sel_frame, text="ENGINE:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left')
            self.vars['perc_mode'] = tk.StringVar(value="EUCLID")
            
            btn_euclid = tk.Label(eng_sel_frame, text=" EUCLID ", bg=SEPIA_ACTIVE, fg=LED_OFF, font=FONT_MAIN, width=10, pady=2, relief='sunken', bd=2, cursor="hand2")
            btn_euclid.pack(side='left', padx=(6, 2))
            ToolTip(btn_euclid, "Euclidean Generator Mode. Distributes active pulses evenly across a fixed step timeline using Bjorklund's algorithm. Perfect for 4/4 kicks, African/Cuban bell patterns, dense polyrhythmic hi-hats, and electronic grooves.")
            
            btn_additive = tk.Label(eng_sel_frame, text=" ADDITIVE ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN, width=10, pady=2, relief='raised', bd=2, cursor="hand2")
            btn_additive.pack(side='left', padx=2)
            ToolTip(btn_additive, "Additive / Aksak Generator Mode. Constructs asymmetric meters from combined 2-step and 3-step rhythmic cells. Ideal for traditional Greek, Balkan, and Anatolian odd meters (5/8, 7/8, 9/8, 11/8, etc.).")
            
            # Row 0, Col 1: Euclid Step Strip
            self.eucl_pulse_strip = EuclidPulseStrip(self.perc_header_frame, height=44)
            self.eucl_pulse_strip.grid(row=0, column=1, sticky='ew', padx=(0, 6))
            ToolTip(self.eucl_pulse_strip, "Euclidean Bjorklund Step Strip. Real-time linear step chaser visualizing pulse distribution and active playhead position across the rhythmic cycle.")

            # Row 0, Col 1-2 (Additive Mode): Aksak Architecture Gauge
            self.aksak_gauge = AksakArchitectureGauge(self.perc_header_frame, width=500, height=60)
            ToolTip(self.aksak_gauge, "Additive Aksak Cell Architecture Gauge. Displays metric cell compartments (2s and 3s), thesis downbeat anchors, and live subdivision progress.")

            # Rows 0-1, Col 2: Enlarged Interactive Euclid Orbit Radar (96x96 px)
            self.eucl_radar = EuclidOrbitRadar(self.perc_header_frame, size=96)
            self.eucl_radar.grid(row=0, column=2, rowspan=2, sticky='nsew', padx=(2, 0))
            self.eucl_radar.set_callbacks(
                on_rot=lambda new_r: self.vars['eucl_rot'].set(new_r),
                on_pulse=lambda new_p: self.vars['eucl_pulses'].set(new_p)
            )
            ToolTip(self.eucl_radar, "Euclidean Bjorklund Orbit Radar (Interactive). Click any step node to snap rotation phase; click center to advance; scroll mouse wheel to shift ROT; Shift+scroll to change PLS pulse count.")

            # --- SHARED PERCUSSION SEQUENCE VARIABLES ---
            if 'mem_seq_rate' not in self.vars: self.vars['mem_seq_rate'] = tk.StringVar(value="1x METER")
            if not hasattr(self, 'add_seq_steps'): self.add_seq_steps = {i: None for i in range(1, 11)}
            if not hasattr(self, 'eucl_seq_steps'): self.eucl_seq_steps = {i: None for i in range(1, 11)}

            # Row 1, Col 0-1: Euclid Primary Controls (STP, PLS, ROT, V.MIN, V.MAX)
            self.eucl_ctrl_row = tk.Frame(self.perc_header_frame, bg=PANEL_COLOR)
            self.eucl_ctrl_row.grid(row=1, column=0, columnspan=2, sticky='w', pady=(3, 1))

            tk.Label(self.eucl_ctrl_row, text="STP:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN).pack(side='left', padx=(4, 2))
            self.vars['eucl_steps'] = tk.IntVar(value=16)
            sp_stp = tk.Spinbox(self.eucl_ctrl_row, from_=1, to=64, width=3, textvariable=self.vars['eucl_steps'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_stp.pack(side='left', padx=2)
            ToolTip(sp_stp, "Euclidean Sequence Length (1 to 64 steps). Defines the total number of 16th-note slots in the rhythm cycle.")
            
            lbl_pls = tk.Label(self.eucl_ctrl_row, text="PLS:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN)
            lbl_pls.pack(side='left', padx=(8, 2))
            self.mod_badge_labels['PLS'] = lbl_pls
            self.vars['eucl_pulses'] = tk.IntVar(value=4)
            sp_pls = tk.Spinbox(self.eucl_ctrl_row, from_=0, to=64, width=3, textvariable=self.vars['eucl_pulses'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_pls.pack(side='left', padx=2)
            ToolTip(sp_pls, "Euclidean Pulse Count (0 to 64 pulses). Number of active drum hits distributed evenly across the step length (e.g. 4 pulses in 16 steps = four-on-the-floor; 5 in 16 = Cuban cinquillo). Modulatable via LFO.")
            
            tk.Label(self.eucl_ctrl_row, text="ROT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN).pack(side='left', padx=(8, 2))
            self.vars['eucl_rot'] = tk.IntVar(value=0)
            sp_rot = tk.Spinbox(self.eucl_ctrl_row, from_=0, to=64, width=3, textvariable=self.vars['eucl_rot'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_rot.pack(side='left', padx=2)
            ToolTip(sp_rot, "Euclidean Phase Rotation (0 to 64 steps). Shifts the entire generated rhythm forwards or backwards in time, changing which hit falls on the downbeat.")

            lbl_evmin = tk.Label(self.eucl_ctrl_row, text="V.MIN:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN)
            lbl_evmin.pack(side='left', padx=(8, 2))
            self.mod_badge_labels['V.MIN'] = lbl_evmin
            self.vars['v_min'] = tk.IntVar(value=80)
            sp_evmin = tk.Spinbox(self.eucl_ctrl_row, from_=1, to=127, width=3, textvariable=self.vars['v_min'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_evmin.pack(side='left', padx=2)
            ToolTip(sp_evmin, "Velocity Output Floor (1-127). The minimum velocity generated for hits on this percussion channel. Combined with V.MAX to create a dynamic human velocity spread.")
            
            lbl_evmax = tk.Label(self.eucl_ctrl_row, text="V.MAX:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN)
            lbl_evmax.pack(side='left', padx=(8, 2))
            self.mod_badge_labels['V.MAX'] = lbl_evmax
            self.vars['v_max'] = tk.IntVar(value=127)
            sp_evmax = tk.Spinbox(self.eucl_ctrl_row, from_=1, to=127, width=3, textvariable=self.vars['v_max'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_evmax.pack(side='left', padx=2)
            ToolTip(sp_evmax, "Velocity Output Ceiling (1-127). The maximum velocity generated for hits on this percussion channel.")

            def _update_radar(*args):
                try:
                    s = self.vars['eucl_steps'].get()
                    p = self.vars['eucl_pulses'].get()
                    r = self.vars['eucl_rot'].get()
                    cur = getattr(self, '_last_perc_cur_step', 0) or 0
                    if hasattr(self, 'eucl_radar'):
                        self.eucl_radar.redraw(s, p, r, cur)
                    if hasattr(self, 'eucl_pulse_strip'):
                        self.eucl_pulse_strip.redraw(s, p, r, cur)
                except Exception: pass
            self.vars['eucl_steps'].trace_add('write', _update_radar)
            self.vars['eucl_pulses'].trace_add('write', _update_radar)
            self.vars['eucl_rot'].trace_add('write', _update_radar)
            _update_radar()

            self.perc_header_frame.columnconfigure(1, weight=1)

            # --- EUCLIDEAN DOWNSTAIRS CONTAINER ---
            self.eucl_container = tk.Frame(self.body_frame, bg=PANEL_COLOR)

            eucl_row3 = tk.Frame(self.eucl_container, bg=PANEL_COLOR)
            eucl_row3.pack(fill='x', pady=(4, 3))

            def make_euclid_menu(parent, variable, width=34):
                menu_button = tk.OptionMenu(parent, variable, "Custom / Manual")
                menu = menu_button["menu"]
                menu.delete(0, "end")
                for group_idx, (group_name, options) in enumerate(EUCLID_GROUPS):
                    if group_idx > 0: menu.add_separator()
                    menu.add_command(label=f"── {group_name} ──", state="disabled")
                    for option in options:
                        menu.add_command(label=option, command=lambda value=option, v=variable: v.set(value))
                menu_button.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, highlightthickness=1, font=FONT_SMALL, bd=1, width=width, height=1, pady=1)
                menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                return menu_button

            self.vars['eucl_preset'] = tk.StringVar(value="Custom / Manual")
            epreset_menu = make_euclid_menu(eucl_row3, self.vars['eucl_preset'], width=34)
            epreset_menu.pack(side='left', padx=(0, 8))
            ToolTip(epreset_menu, "Curated Euclidean Rhythmic Presets. Library of mathematically authentic global and electronic grooves categorized by genre. Selecting a preset updates STP, PLS, and ROT.")

            def _on_eucl_preset(*args):
                val = self.vars['eucl_preset'].get()
                if '(' in val and ')' in val:
                    try:
                        inner = val.split('(')[-1].strip(')')
                        s, p, r = map(int, inner.split(':'))
                        self.vars['eucl_steps'].set(s)
                        self.vars['eucl_pulses'].set(p)
                        self.vars['eucl_rot'].set(r)
                    except: pass
            self.vars['eucl_preset'].trace_add('write', _on_eucl_preset)

            e_seq_ctrl = tk.Frame(eucl_row3, bg=PANEL_COLOR)
            e_seq_ctrl.pack(side='left', padx=(0, 0))

            def _stoch_fill_eucl(event=None):
                if not hasattr(self, 'e_step_btns') or not self.e_step_btns: return
                groups = EUCLID_GROUPS[1:]
                group_weights = []
                for g_name, _ in groups:
                    w = 1.0
                    if self.name == "BD" and ("SPARSE" in g_name or "INDUSTRIAL" in g_name): w = 2.4
                    elif self.name == "SD" and ("COMPLEX" in g_name or "INDUSTRIAL" in g_name or "FRINGES" in g_name): w = 2.2
                    elif self.name == "HHT" and ("BUSY" in g_name or "COMPLEX" in g_name or "FRINGES" in g_name): w = 2.4
                    group_weights.append(w)
                base_group = random.choices(groups, weights=group_weights, k=1)[0][1]

                parsed_candidates = []
                for opt in base_group:
                    try:
                        code = opt.split('(')[-1].strip(')')
                        s, p, r = map(int, code.split(':'))
                        parsed_candidates.append((code, max(1, s), p, r, p / float(max(1, s))))
                    except Exception:
                        pass
                if not parsed_candidates:
                    return

                prev_density = parsed_candidates[len(parsed_candidates) // 2][4]

                for i in range(1, 11):
                    is_turnaround = i in (4, 8, 10)
                    target_density = min(1.0, prev_density + (0.15 if is_turnaround else 0.0))
                    c_weights = [math.exp(-abs(c[4] - target_density) / 0.22) for c in parsed_candidates]
                    code, s, p, r, dens = random.choices(parsed_candidates, weights=c_weights, k=1)[0]
                    prev_density = dens

                    mut_prob = 0.45 if is_turnaround else 0.22
                    if random.random() < mut_prob:
                        dp = int(round(max(-2.0, min(2.0, random.gauss(0.5 if is_turnaround else 0.0, 1.1)))))
                        if dp == 0: dp = 1 if is_turnaround else -1
                        p = max(1, min(s, p + dp))
                        dr = random.choices([0, 1, -1, 2], weights=[0.40, 0.30, 0.20, 0.10], k=1)[0]
                        r = (r + dr) % s
                        val = f"{s}:{p}:{r}"
                        prev_density = p / float(max(1, s))
                    else:
                        val = code

                    self.eucl_seq_steps[i] = val
                    self.e_step_btns[i].config(text=val)
                    ToolTip(self.e_step_btns[i], f"Step {i}: {val} (Stochastic)")
            
            e_stoch_btn = tk.Label(e_seq_ctrl, text=" ۞ ", bg=INPUT_BG, fg=SEPIA_ACTIVE, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2")
            e_stoch_btn.pack(side='left', padx=(0, 8))
            e_stoch_btn.bind("<Button-1>", _stoch_fill_eucl)
            ToolTip(e_stoch_btn, "Stochastic Injection. Populates the sequence chain using a 1st-order Markov density walk and Gaussian parameter mutations.")

            tk.Label(e_seq_ctrl, text="AUTO SEQ RATE:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 2))
            emrate_menu = tk.OptionMenu(e_seq_ctrl, self.vars['mem_seq_rate'], "1/4x METER", "1/2x METER", "1x METER", "2x METER", "4x METER", "8x METER")
            emrate_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, highlightthickness=1, font=FONT_SMALL, bd=1, width=9)
            emrate_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
            emrate_menu.pack(side='left', padx=(0, 0))
            ToolTip(emrate_menu, "Euclidean Sequence Rate. How many master-phrase meters pass between advancing to the next step in the Euclidean sequence timeline.")

            self.e_seq_btn = tk.Label(e_seq_ctrl, text="SEQ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2", width=5, pady=1)
            self.e_seq_btn.pack(side='left', padx=(6, 0))
            self.e_seq_btn.bind("<Button-1>", _toggle_perc_seq)
            self.seq_btn = self.e_seq_btn
            ToolTip(self.e_seq_btn, "Timeline Sequencer. Activates the 10-step arrangement chain.")

            eucl_row4 = tk.Frame(self.eucl_container, bg=PANEL_COLOR)
            eucl_row4.pack(fill='x', pady=(0, 6))

            e_seq_f = tk.Frame(eucl_row4, bg=PANEL_COLOR)
            e_seq_f.pack(side='left', padx=(0, 0))
            
            e_steps_lbl = tk.Label(e_seq_f, text="STEPS", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=6, height=1, relief='flat')
            e_steps_lbl.pack(side='left', padx=(0, 6))
            self.e_step_btns = {}

            def _show_eucl_menu(event, idx):
                if self.vars['seq_active'].get(): return
                menu = tk.Menu(self, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                current_val = self.eucl_seq_steps.get(idx)
                menu_idx = 0

                def _capture():
                    s, p, r = self.vars['eucl_steps'].get(), self.vars['eucl_pulses'].get(), self.vars['eucl_rot'].get()
                    val = f"{s}:{p}:{r}"
                    self.eucl_seq_steps[idx] = val
                    self.e_step_btns[idx].config(text=val)
                    ToolTip(self.e_step_btns[idx], f"Step {idx}: {val}")
                menu.add_command(label="[ Capture Live ]", command=_capture)
                menu_idx += 1
                
                def _type_custom():
                    btn = self.e_step_btns[idx]
                    entry = tk.Entry(btn, justify="center", font=FONT_SMALL, bg=INPUT_BG, fg=INPUT_FG, insertbackground=INPUT_FG, bd=0, highlightthickness=0)
                    entry.place(x=0, y=0, relwidth=1, relheight=1)
                    cv = btn.cget("text")
                    entry.insert(0, cv if cv else "ST:PL:RT")
                    entry.focus_set()
                    entry.select_range(0, "end")
                    
                    def _commit(e=None):
                        val = entry.get().strip()
                        if val:
                            try:
                                parts = val.split(':')
                                if len(parts) != 3: raise ValueError
                                s = max(1, min(64, int(parts[0])))
                                p = max(0, min(s, int(parts[1])))
                                r = max(0, min(s, int(parts[2])))
                                clean_val = f"{s}:{p}:{r}"
                                self.eucl_seq_steps[idx] = clean_val
                                btn.config(text=clean_val)
                                ToolTip(btn, f"Step {idx}: {clean_val}")
                            except Exception: pass
                        else:
                            self.eucl_seq_steps[idx] = None
                            btn.config(text="")
                            ToolTip(btn, f"Step {idx}: Empty")
                        try: entry.destroy()
                        except: pass
                        
                    entry.bind("<Return>", _commit)
                    entry.bind("<FocusOut>", _commit)
                    entry.bind("<Escape>", lambda e: entry.destroy())
                menu.add_command(label="[ Manual Entry ]", command=_type_custom)
                menu_idx += 1
                menu.add_separator()
                menu_idx += 1
                
                for group_idx, (group_name, options) in enumerate(EUCLID_GROUPS):
                    if group_idx > 0: 
                        menu.add_separator()
                        menu_idx += 1
                    menu.add_command(label=f"── {group_name} ──", state="disabled")
                    menu_idx += 1
                    for option in options:
                        if "Custom" in option: continue
                        try: inner = option.split('(')[-1].strip(')')
                        except: inner = option
                            
                        def select(opt=option, val=inner):
                            self.eucl_seq_steps[idx] = val
                            self.e_step_btns[idx].config(text=val)
                            ToolTip(self.e_step_btns[idx], f"Step {idx}: {opt}")
                        menu.add_command(label=option, command=select)
                        if current_val == inner:
                            menu.entryconfig(menu_idx, background=SEPIA_ACTIVE, foreground=LED_OFF)
                        menu_idx += 1
                        
                menu.tk_popup(event.x_root, event.y_root)

            def _e_step_rclick(idx):
                self.eucl_seq_steps[idx] = None
                self.e_step_btns[idx].config(text="")
                ToolTip(self.e_step_btns[idx], f"Step {idx}: Empty")

            for i in range(1, 11):
                btn = tk.Label(e_seq_f, text="", bg=INPUT_BG, fg=INPUT_FG, font=('Consolas', 8), width=8, height=1, relief='sunken', cursor="hand2", highlightbackground=PANEL_COLOR, highlightthickness=2, bd=1)
                btn.pack(side='left', padx=2)
                btn.bind("<Button-1>", lambda e, idx=i: _show_eucl_menu(e, idx))
                btn.bind("<Button-3>", lambda e, idx=i: _e_step_rclick(idx))
                self.e_step_btns[i] = btn
                ToolTip(btn, f"Step {i}: Empty. Left-click for options.")

            # --- ADDITIVE UI ---
            self.add_container = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            self.add_ctrl_row = tk.Frame(self.perc_header_frame, bg=PANEL_COLOR)
            add_row1 = self.add_ctrl_row
            
            tk.Label(add_row1, text="THS.V:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN).pack(side='left', padx=(4, 0))
            self.vars['ths_v'] = tk.IntVar(value=127)
            sp_ths = tk.Spinbox(add_row1, from_=1, to=127, width=3, textvariable=self.vars['ths_v'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_ths.pack(side='left', padx=2)
            ToolTip(sp_ths, "Thesis Velocity (1-127).")
            
            tk.Label(add_row1, text="ARS.V:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN).pack(side='left', padx=(4, 0))
            self.vars['ars_v'] = tk.IntVar(value=55)
            sp_ars = tk.Spinbox(add_row1, from_=1, to=127, width=3, textvariable=self.vars['ars_v'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_MAIN, relief='sunken', bd=1)
            sp_ars.pack(side='left', padx=2)
            ToolTip(sp_ars, "Arsis Velocity (1-127).")
            
            tk.Label(add_row1, text="A.RST%:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN).pack(side='left', padx=(6, 0))
            self.vars['ars_rst'] = tk.IntVar(value=50)
            a_rst_lbl = tk.Label(add_row1, text="50", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_MAIN, width=3)
            a_rst_lbl.pack(side='right')
            a_rst_scale = tk.Scale(add_row1, from_=0, to=100, orient='horizontal', variable=self.vars['ars_rst'], sliderlength=12, width=14, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            a_rst_scale.pack(side='left', fill='x', expand=True, padx=2)
            a_rst_scale.configure(command=lambda val, l=a_rst_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(a_rst_scale, a_rst_lbl, self.vars['ars_rst'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['ars_rst'], l=a_rst_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(a_rst_scale, "Arsis Rest Probability (0-100%).")

            add_row2 = tk.Frame(self.add_container, bg=PANEL_COLOR)
            add_row2.pack(fill='x', pady=(4, 3))

            def make_additive_menu(parent, variable, width=34):
                menu_button = tk.OptionMenu(parent, variable, "Four-on-the-Floor (4-4-4-4) [16]")
                menu = menu_button["menu"]
                menu.delete(0, "end")
                for group_idx, (group_name, options) in enumerate(ADDITIVE_GROUPS):
                    if group_idx > 0: menu.add_separator()
                    menu.add_command(label=f"── {group_name} ──", state="disabled")
                    for option in options:
                        menu.add_command(label=option, command=lambda value=option, v=variable: v.set(value))
                menu_button.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=width, height=1, pady=1)
                menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                return menu_button
            
            self.vars['add_meter'] = tk.StringVar(value="Four-on-the-Floor (4-4-4-4) [16]")
            meter_menu = make_additive_menu(add_row2, self.vars['add_meter'], width=34)
            meter_menu.pack(side='left', padx=(0, 8))
            ToolTip(meter_menu, "Curated Additive / Asymmetric Meter Library.")

            def _on_add_meter_change(*args):
                if hasattr(self, 'aksak_gauge'):
                    try:
                        blocks = self._get_active_aksak_blocks()
                        cur = getattr(self, '_last_perc_cur_step', 0) or 0
                        self.aksak_gauge.redraw(blocks, cur)
                    except Exception: pass
            self.vars['add_meter'].trace_add('write', _on_add_meter_change)
            _on_add_meter_change()

            seq_controls_f = tk.Frame(add_row2, bg=PANEL_COLOR)
            seq_controls_f.pack(side='left', padx=(0, 0))

            def _stoch_fill_add(event=None):
                if not hasattr(self, 'step_btns') or not self.step_btns: return
                cur_meter = self.vars.get('add_meter').get() if 'add_meter' in self.vars else ""
                p_weights = [2.5 if cur_meter in g_opts else 1.0 for _, g_opts in ADDITIVE_GROUPS]
                p_idx = random.choices(range(len(ADDITIVE_GROUPS)), weights=p_weights, k=1)[0]
                s_weights = [0.2 if idx == p_idx else math.exp(-abs(idx - p_idx) / 2.0) for idx in range(len(ADDITIVE_GROUPS))]
                s_idx = random.choices(range(len(ADDITIVE_GROUPS)), weights=s_weights, k=1)[0]
                primary_opts = ADDITIVE_GROUPS[p_idx][1]
                secondary_opts = ADDITIVE_GROUPS[s_idx][1]

                def _meter_stats(m_str):
                    blocks = ADDITIVE_METERS.get(resolve_additive_meter(m_str), [2, 2, 2, 3])
                    return sum(blocks), len(blocks)

                prev_len, prev_blocks = _meter_stats(cur_meter if cur_meter else primary_opts[0])
                in_secondary = False

                for i in range(1, 11):
                    is_turnaround = i in (4, 8, 10)
                    if is_turnaround:
                        in_secondary = (random.random() < 0.55)
                    else:
                        in_secondary = (random.random() < (0.35 if in_secondary else 0.15))
                    pool = secondary_opts if in_secondary else primary_opts

                    m_weights = []
                    for cand in pool:
                        c_len, c_blk = _meter_stats(cand)
                        dist = abs(c_len - prev_len) * 0.6 + abs(c_blk - prev_blocks) * 1.1
                        m_weights.append(math.exp(-dist / (3.5 if is_turnaround else 2.2)))
                    val = random.choices(pool, weights=m_weights, k=1)[0]
                    prev_len, prev_blocks = _meter_stats(val)

                    self.add_seq_steps[i] = val
                    steps = self._format_additive_step_display(val)
                    self.step_btns[i].config(text=steps)
                    ToolTip(self.step_btns[i], f"Step {i}: {val} (Stochastic)")

            a_stoch_btn = tk.Label(seq_controls_f, text=" ۞ ", bg=INPUT_BG, fg=SEPIA_ACTIVE, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2")
            a_stoch_btn.pack(side='left', padx=(0, 8))
            a_stoch_btn.bind("<Button-1>", _stoch_fill_add)
            ToolTip(a_stoch_btn, "Stochastic Injection.")

            tk.Label(seq_controls_f, text="AUTO SEQ RATE:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2, 2))
            mrate_menu = tk.OptionMenu(seq_controls_f, self.vars['mem_seq_rate'], "1/4x METER", "1/2x METER", "1x METER", "2x METER", "4x METER", "8x METER")
            mrate_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=9)
            mrate_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
            mrate_menu.pack(side='left', padx=(0, 0))
            ToolTip(mrate_menu, "Additive Sequence Rate.")

            self.add_seq_btn = tk.Label(seq_controls_f, text="SEQ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2", width=5, pady=1)
            self.add_seq_btn.pack(side='left', padx=(6, 0))
            self.add_seq_btn.bind("<Button-1>", _toggle_perc_seq)
            ToolTip(self.add_seq_btn, "Timeline Sequencer. Activates the 10-step arrangement chain.")

            add_row3 = tk.Frame(self.add_container, bg=PANEL_COLOR)
            add_row3.pack(fill='x', pady=(0, 6))

            self.perc_seq_f = tk.Frame(add_row3, bg=PANEL_COLOR)
            self.perc_seq_f.pack(side='left', padx=(0, 0))

            perc_steps_lbl = tk.Label(self.perc_seq_f, text="STEPS", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=6, height=1, relief='flat')
            perc_steps_lbl.pack(side='left', padx=(0, 6))
            self.step_btns = {}

            def show_additive_menu(event, idx):
                if self.vars['seq_active'].get(): return
                menu = tk.Menu(self, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                current_val = self.add_seq_steps.get(idx)
                menu_idx = 0
                for group_idx, (group_name, options) in enumerate(ADDITIVE_GROUPS):
                    if group_idx > 0: 
                        menu.add_separator()
                        menu_idx += 1
                    menu.add_command(label=f"── {group_name} ──", state="disabled")
                    menu_idx += 1
                    for option in options:
                        def select(opt=option):
                            self.add_seq_steps[idx] = opt
                            steps = self._format_additive_step_display(opt)
                            self.step_btns[idx].config(text=steps)
                            ToolTip(self.step_btns[idx], f"Step {idx}: {opt}")
                        menu.add_command(label=option, command=select)
                        if current_val == option:
                            menu.entryconfig(menu_idx, background=SEPIA_ACTIVE, foreground=LED_OFF)
                        menu_idx += 1
                menu.tk_popup(event.x_root, event.y_root)

            def _perc_step_rclick(idx):
                self.add_seq_steps[idx] = None
                self.step_btns[idx].config(text="", highlightbackground=PANEL_COLOR)
                ToolTip(self.step_btns[idx], f"Step {idx}: Empty.")

            for i in range(1, 11):
                s_btn = tk.Label(self.perc_seq_f, text="", bg=INPUT_BG, fg=INPUT_FG, font=('Consolas', 8), width=8, height=1, relief='sunken', cursor="hand2", highlightbackground=PANEL_COLOR, highlightthickness=2, bd=1)
                s_btn.pack(side='left', padx=2)
                s_btn.bind("<Button-1>", lambda e, idx=i: show_additive_menu(e, idx))
                s_btn.bind("<Button-3>", lambda e, idx=i: _perc_step_rclick(idx))
                self.step_btns[i] = s_btn
                ToolTip(s_btn, f"Step {i}: Empty. Left-click to assign.")

            def _swap_perc_ui(*args):
                mode = self.vars['perc_mode'].get()
                if getattr(self, '_perc_ui_mode', None) == mode: return
                self._perc_ui_mode = mode
                
                # Auto-kill SEQ on engine switch to prevent UI/Engine desync
                if self.vars.get('seq_active') and self.vars['seq_active'].get():
                    self.vars['seq_active'].set(False)
                    if hasattr(self, '_update_perc_seq_visual'):
                        self._update_perc_seq_visual()
                    elif hasattr(self, 'seq_btn'):
                        self.seq_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                    for i, b in getattr(self, 'step_btns', {}).items(): 
                        b.config(highlightbackground=PANEL_COLOR)
                    for i, b in getattr(self, 'e_step_btns', {}).items(): 
                        b.config(highlightbackground=PANEL_COLOR)

                if mode == "EUCLID":
                    btn_euclid.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                    btn_additive.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                    if hasattr(self, 'aksak_gauge'):
                        self.aksak_gauge.grid_remove()
                    if hasattr(self, 'add_ctrl_row'):
                        self.add_ctrl_row.grid_remove()
                        
                    if hasattr(self, 'eucl_pulse_strip'):
                        self.eucl_pulse_strip.grid(row=0, column=1, sticky='ew', padx=(0, 6))
                    if hasattr(self, 'eucl_radar'):
                        self.eucl_radar.grid(row=0, column=2, rowspan=2, sticky='nsew', padx=(2, 0))
                    if hasattr(self, 'eucl_ctrl_row'):
                        self.eucl_ctrl_row.grid(row=1, column=0, columnspan=2, sticky='w', pady=(3, 1))
                        _update_radar()
                        
                    self.add_container.pack_forget()
                    self.eucl_container.pack(in_=self.body_frame, fill='x', padx=6, after=self.perc_header_frame)
                else:
                    btn_additive.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                    btn_euclid.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                    if hasattr(self, 'eucl_pulse_strip'):
                        self.eucl_pulse_strip.grid_remove()
                    if hasattr(self, 'eucl_radar'):
                        self.eucl_radar.grid_remove()
                    if hasattr(self, 'eucl_ctrl_row'):
                        self.eucl_ctrl_row.grid_remove()
                        
                    if hasattr(self, 'aksak_gauge'):
                        self.aksak_gauge.grid(row=0, column=1, columnspan=2, sticky='nsew', padx=(0, 0))
                        try:
                            blocks = self._get_active_aksak_blocks()
                            cur = getattr(self, '_last_perc_cur_step', 0) or 0
                            self.aksak_gauge.redraw(blocks, cur)
                        except Exception: pass
                    if hasattr(self, 'add_ctrl_row'):
                        self.add_ctrl_row.grid(row=1, column=0, columnspan=3, sticky='ew', pady=(3, 1))
                        
                    self._last_perc_cur_step = None
                    self.eucl_container.pack_forget()
                    self.add_container.pack(in_=self.body_frame, fill='x', padx=6, after=self.perc_header_frame)

            def _set_perc_mode_clean(target_mode):
                if self.vars['perc_mode'].get() == target_mode:
                    return
                top = self.winfo_toplevel()
                has_trans = hasattr(top, '_begin_toggle_transition') and hasattr(top, '_finish_toggle_transition')
                if has_trans:
                    top._begin_toggle_transition()
                try:
                    self.vars['perc_mode'].set(target_mode)
                finally:
                    if has_trans:
                        top._finish_toggle_transition()

            btn_euclid.bind("<Button-1>", lambda e: _set_perc_mode_clean("EUCLID"))
            btn_additive.bind("<Button-1>", lambda e: _set_perc_mode_clean("ADDITIVE"))
            self.vars['perc_mode'].trace_add('write', _swap_perc_ui)
            self._update_callbacks.append(_swap_perc_ui)
            _swap_perc_ui() # initialize layout immediately


        elif self.channel_type in ['melodic', 'polyphonic']:
            # Melodic sequencer and lock state variables
            if 'locked' not in self.vars: self.vars['locked'] = tk.BooleanVar(value=False)
            self.base_vars['locked'] = False
            self.vars['mem_seq_mode'] = tk.StringVar(value="OFF")
            if 'seq_active' not in self.vars: self.vars['seq_active'] = tk.BooleanVar(value=False)

            # Row 2 (MACRO dropdown, AUTO btn, RST% slider, MUT slider)
            header_row2 = tk.Frame(self.header_frame, bg=PANEL_COLOR)
            header_row2.pack(fill='x', padx=1, pady=1)
            header_row2.grid_columnconfigure(0, weight=0)
            header_row2.grid_columnconfigure(1, weight=1, uniform='hdr_sliders')
            header_row2.grid_columnconfigure(2, weight=1, uniform='hdr_sliders')

            macro_frame = tk.Frame(header_row2, bg=PANEL_COLOR)
            macro_frame.grid(row=0, column=0, sticky='w', padx=(0, 2))

            tk.Label(macro_frame, text="MACRO:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(1, 1))

            MEL_MACROS = ["Static", "Humanize", "Octave Drop", "Octave Leap", "Grace Notes", "Echo", "Tremolo", "Pedal Point", "Drone Collapse", "Micro-Drift"]
            self.macro_pool = list(MEL_MACROS)
            self.vars['macro_state'] = tk.StringVar(value="Static")

            mel_macro_lbl = tk.Label(macro_frame, text="Static", bg=INPUT_BG, fg=INPUT_FG, font=FONT_SMALL, width=12, anchor='w', relief='sunken', bd=1, cursor="hand2")
            mel_macro_lbl.pack(side='left', padx=1)

            def _update_mel_macro_lbl(*args):
                mel_macro_lbl.config(text=self.vars['macro_state'].get())
            self.vars['macro_state'].trace_add('write', _update_mel_macro_lbl)

            def _show_mel_macro_menu(event):
                def _popup(ev_x, ev_y):
                    menu = tk.Menu(self, tearoff=0, bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
                    is_auto = self.vars['macro_auto'].get()
                    for idx, mac in enumerate(MEL_MACROS):
                        def make_handler(m=mac, x=ev_x, y=ev_y):
                            def handler():
                                if self.vars['macro_auto'].get():
                                    if m in self.macro_pool:
                                        if len(self.macro_pool) > 1: self.macro_pool.remove(m)
                                    else:
                                        self.macro_pool.append(m)
                                        self.macro_pool.sort(key=lambda x: MEL_MACROS.index(x))
                                    try: menu.destroy()
                                    except Exception: pass
                                    _popup(x, y)
                                else:
                                    self.vars['macro_state'].set(m)
                            return handler
                        menu.add_command(label=mac, command=make_handler())
                        if is_auto and mac in self.macro_pool:
                            menu.entryconfig(idx, background=ACCENT_BRUISED, foreground=FG_COLOR)
                        elif not is_auto and mac == self.vars['macro_state'].get():
                            menu.entryconfig(idx, background=ACCENT_BRUISED, foreground=FG_COLOR)
                    try: menu.tk_popup(ev_x, ev_y)
                    except Exception: pass
                _popup(event.x_root, event.y_root)

            mel_macro_lbl.bind("<Button-1>", _show_mel_macro_menu)
            ToolTip(mel_macro_lbl, "Melodic performance macro. Left-click to select. If AUTO is enabled, the menu acts as a multi-select filter to build your rotation pool.")

            self.vars['macro_auto'] = tk.BooleanVar(value=False)
            self.base_vars['macro_auto'] = False
            auto_btn = tk.Label(macro_frame, text="AUTO", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2", padx=2, pady=1)
            auto_btn.pack(side='left', padx=1)

            def _update_mel_auto_visual(*args):
                if self.vars['macro_auto'].get():
                    auto_btn.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                else:
                    auto_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')

            def _toggle_mel_auto(event=None):
                new_val = not self.vars['macro_auto'].get()
                self.base_vars['macro_auto'] = new_val
                self.vars['macro_auto'].set(new_val)
                _update_mel_auto_visual()

            auto_btn.bind("<Button-1>", _toggle_mel_auto)
            self.vars['macro_auto'].trace_add('write', _update_mel_auto_visual)
            self._update_callbacks.append(_update_mel_auto_visual)
            ToolTip(auto_btn, "Toggle AUTO macro rotation. Left-click to engage. If enabled, the macro menu acts as a multi-select pool to cycle through.")

            # RST% slider container
            rst_frame = tk.Frame(header_row2, bg=PANEL_COLOR)
            rst_frame.grid(row=0, column=1, sticky='ew', padx=2)

            lbl_rst = tk.Label(rst_frame, text="RST%:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_rst.pack(side='left', padx=(1, 1))
            self.mod_badge_labels['RST%'] = lbl_rst
            self.vars['rest_prob'] = tk.IntVar(value=0)
            rst_lbl = tk.Label(rst_frame, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            rst_lbl.pack(side='right', padx=1)
            rst_scale = tk.Scale(rst_frame, from_=0, to=100, orient='horizontal', variable=self.vars['rest_prob'], length=30, sliderlength=10, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            rst_scale.pack(side='left', fill='x', expand=True, padx=1)
            rst_scale.configure(command=lambda val, l=rst_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(rst_scale, rst_lbl, self.vars['rest_prob'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['rest_prob'], l=rst_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(rst_scale, "Rest Probability. Determines the percentage chance (0-100) that the engine will deliberately drop or skip a note.")

            # MUT slider container
            mut_frame = tk.Frame(header_row2, bg=PANEL_COLOR)
            mut_frame.grid(row=0, column=2, sticky='ew', padx=2)

            lbl_mut = tk.Label(mut_frame, text="MUT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_mut.pack(side='left', padx=(1, 1))
            self.mod_badge_labels['MUT'] = lbl_mut
            self.vars['mutation'] = tk.IntVar(value=0)
            mutation_lbl = tk.Label(mut_frame, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            mutation_lbl.pack(side='right', padx=1)
            mutation_scale = tk.Scale(mut_frame, from_=0, to=100, orient='horizontal', variable=self.vars['mutation'], length=30, sliderlength=10, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            mutation_scale.pack(side='left', fill='x', expand=True, padx=1)
            mutation_scale.configure(command=lambda val, l=mutation_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(mutation_scale, mutation_lbl, self.vars['mutation'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['mutation'], l=mutation_lbl: l.config(text=str(int(float(v.get())))))
            def _new_mutation_realization(_event=None):
                self.mutation_seed = random.SystemRandom().randrange(1, 2**31 - 1)
            mutation_scale._mauve_on_release = _new_mutation_realization
            mutation_scale._mauve_on_value_commit = _new_mutation_realization
            ToolTip(mutation_scale, "NON-DESTRUCTIVE MUTATION for locked (LCK or M) playback. 0 is an exact bypass. As it rises, notes drop into rests, shift to neighbouring scale tones and gain short articulation, always on the existing grid. It re-rolls into a fresh variation every 4 loops at low settings, speeding up to every half loop near the top, and a change latches at the next loop start. The stored phrase is never altered: to keep what you hear, press an empty M slot while it plays and that exact variation becomes a new clean phrase.")

            # --- MICRO VIEW (body_frame) ---
            mel_container = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            mel_container.pack(fill='x', padx=6, pady=(2, 2))

            self.vars['note_probs'] = {i: tk.DoubleVar(value=60 if i in [0, 7, 12] else 25) for i in range(13)}
            
            # --- LEFT COLUMN (Protected from Rebuild Wipes) ---
            left_col = tk.Frame(mel_container, bg=PANEL_COLOR)
            left_col.pack(side='left', fill='both', expand=True, padx=(0, 4))
            
            grv_f = tk.Frame(left_col, bg=PANEL_COLOR)
            grv_f.pack(fill='x', padx=4, pady=2)
            lbl_grv = tk.Label(grv_f, text="GRV:", bg=PANEL_COLOR, fg=SEPIA_ACTIVE, font=FONT_MAIN)
            lbl_grv.pack(side='left')
            self.mod_badge_labels['GRV'] = lbl_grv
            self.vars['gravity'] = tk.IntVar(value=100)
            grv_lbl = tk.Label(grv_f, text="100", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            grv_lbl.pack(side='right')
            grv_scale = tk.Scale(grv_f, from_=0, to=100, orient='horizontal', variable=self.vars['gravity'], sliderlength=12, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            grv_scale.pack(side='left', fill='x', expand=True, padx=4)
            grv_scale.configure(command=lambda val, l=grv_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(grv_scale, grv_lbl, self.vars['gravity'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['gravity'], l=grv_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(grv_scale, "Gravity Attractor. 100 locks pitches perfectly to your faders. Lowering GRV loosens the mathematical leash, allowing individual pitch probabilities to drift independently via Brownian motion. At 0, the faders are completely ignored and the harmonic structure boils.")

            self.note_frame = tk.LabelFrame(left_col, text=" Intervallic Weights ", bg=PANEL_COLOR, fg=FG_COLOR, highlightbackground=ACCENT_BRUISED, font=FONT_SMALL)
            self.note_frame.pack(fill='both', expand=True)
            self.rebuild_intervals("Natural Minor (Aeolian)")

            # --- RIGHT COLUMN (Durations & Inertia) ---
            durations = ["1/1", "1/2", "1/4", "1/4.", "1/8", "1/8.", "1/8T", "1/16", "1/16T"]
            self.vars['duration_probs'] = {}
            
            right_col = tk.Frame(mel_container, bg=PANEL_COLOR)
            right_col.pack(side='right', fill='both', expand=True, padx=(4, 0))

            int_f = tk.Frame(right_col, bg=PANEL_COLOR)
            int_f.pack(fill='x', padx=4, pady=2)
            lbl_int = tk.Label(int_f, text="INT:", bg=PANEL_COLOR, fg=SEPIA_ACTIVE, font=FONT_MAIN)
            lbl_int.pack(side='left')
            self.mod_badge_labels['INT'] = lbl_int
            self.vars['inertia'] = tk.IntVar(value=50)
            int_lbl = tk.Label(int_f, text="50", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            int_lbl.pack(side='right')
            int_scale = tk.Scale(int_f, from_=0, to=100, orient='horizontal', variable=self.vars['inertia'], sliderlength=12, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            int_scale.pack(side='left', fill='x', expand=True, padx=4)
            int_scale.configure(command=lambda val, l=int_lbl: l.config(text=str(int(float(val)))))
            make_scale_value_editable(int_scale, int_lbl, self.vars['inertia'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['inertia'], l=int_lbl: l.config(text=str(int(float(v.get())))))
            ToolTip(int_scale, "Kinetic Inertia (Stamina). Introduces a 1st-Order Markov Chain fatigue buffer. Fast notes build tension; slow drones clear it. 100 = infinite stamina (arpeggiator). 50 = human momentum (requires breathing). 0 = exhausted sludge. Fast notes pull the sequence louder and higher; drones resolve soft and low.")

            dur_frame = tk.LabelFrame(right_col, text=" Duration Weights ", bg=PANEL_COLOR, fg=FG_COLOR, highlightbackground=ACCENT_BRUISED, font=FONT_SMALL)
            dur_frame.pack(fill='both', expand=True)

            dur_inner = tk.Frame(dur_frame, bg=PANEL_COLOR)
            dur_inner.pack(fill='x', expand=True, padx=2, pady=4)
            
            self.dur_eff_labels = {} # Store references to the live readouts
            self.dur_col_frames = {} # dur -> (subf, lbl_title)
            self._duration_scales = []
            for i, dur in enumerate(durations):
                subf = tk.Frame(dur_inner, bg=PANEL_COLOR, highlightthickness=1, highlightbackground=PANEL_COLOR)
                subf.grid(row=0, column=i, padx=2, sticky='nsew')
                dur_inner.columnconfigure(i, weight=1)
                lbl_title = tk.Label(subf, text=dur, bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
                lbl_title.pack()
                var = tk.DoubleVar(value=50 if dur in ["1/8", "1/16"] else 0)
                self.vars['duration_probs'][dur] = var
                sc = tk.Scale(subf, from_=100, to=0, orient='vertical', variable=var, length=SLIDER_LEN, sliderlength=12, width=14, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
                sc.pack(pady=2)
                self._duration_scales.append(sc)
                
                # Base Fader Label
                lbl = tk.Label(subf, text=str(int(var.get())), bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
                lbl.pack()
                sc.configure(command=lambda val, l=lbl: l.config(text=str(int(float(val)))))
                make_scale_value_editable(sc, lbl, var, 0, 100)
                
                # Live Physics Capsule VU Meter (Kinetic Inertia Stamina)
                eff_meter = CapsuleVUMeter(subf, meter_type="inertia", width=28, height=12)
                eff_meter.pack(pady=(2, 1))
                self.dur_eff_labels[dur] = eff_meter
                self.dur_col_frames[dur] = (subf, lbl_title)
                ToolTip(eff_meter, f"Live Effective Weight for {dur}. Segmented LED capsule meter displaying Kinetic Inertia Markov stamina (INT) with ballistic peak-hold decay.")
                ToolTip(sc, f"Probability weight for holding the note open for a {dur} physical subdivision. Higher values make the engine favor this length. For example, spiking 1/16 guarantees extremely rapid staccato plucks, while spiking 1/1 forces massive, evolving cinematic drones that bridge across measures.")

            ctrl_row1 = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            ctrl_row1.pack(fill='x', padx=6, pady=(2, 1))
            
            lbl_ch = tk.Label(ctrl_row1, text="CH:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_ch.pack(side='left')
            self.lbl_ch = lbl_ch
            sp_ch = tk.Spinbox(ctrl_row1, from_=1, to=16, width=2, textvariable=self.vars['midi_chan'],
                               bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL,
                               relief='sunken', bd=1,
                               disabledbackground="#140f16", disabledforeground="#6e626c")
            sp_ch.pack(side='left', padx=2)
            self.sp_ch = sp_ch
            ToolTip(sp_ch, "MIDI Output Hardware Target Channel (1-16).")

            lbl_oct = tk.Label(ctrl_row1, text="OCT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_oct.pack(side='left', padx=(4, 0))
            self.vars['min_oct'] = tk.IntVar(value=2)
            sp_oct_min = tk.Spinbox(ctrl_row1, from_=0, to=6, width=2, textvariable=self.vars['min_oct'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, relief='sunken', bd=1)
            sp_oct_min.pack(side='left', padx=2)
            ToolTip(sp_oct_min, "Lowest Octave Boundary limit. The generative engine is physically blocked from generating pitches below this octave multiplier. Use C1-C2 to enforce deep hardware basslines.")
            
            self.vars['max_oct'] = tk.IntVar(value=4)
            sp_oct_max = tk.Spinbox(ctrl_row1, from_=0, to=6, width=2, textvariable=self.vars['max_oct'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, relief='sunken', bd=1)
            sp_oct_max.pack(side='left', padx=2)
            ToolTip(sp_oct_max, "Highest Octave Boundary limit. The generative engine is physically blocked from generating pitches above this octave multiplier. When MIN and MAX are identical, the melody is entirely constrained to one strict octave.")

            if self.channel_type == 'polyphonic':
                self.vars['chord_type'] = tk.StringVar(value="Triad")
                chord_menu = tk.OptionMenu(ctrl_row1, self.vars['chord_type'], "Triad", "7th", "Sus4", "Add9", "Open 5th")
                chord_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, highlightbackground=ACCENT_BRUISED, width=5, font=FONT_SMALL, relief='sunken', bd=1)
                chord_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, font=FONT_SMALL)
                chord_menu.pack(side='left', padx=(6,2))
                ToolTip(chord_menu, "Polyphonic Voicing Architecture. Dictates how the channel constructs voice-led chords with smooth inversions and common-tone retention: 'Triad' (1-3-5), '7th' (1-3-5-7), 'Sus4' (1-4-5), 'Add9' (1-3-5-9), or 'Open 5th' (1-5-8).")

            drf_f2 = tk.Frame(ctrl_row1, bg=PANEL_COLOR)
            drf_f2.pack(side='left', fill='x', expand=True, padx=(8,0))
            lbl_drf2 = tk.Label(drf_f2, text="DRF:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_drf2.pack(side='left')
            self.mod_badge_labels['DRF'] = lbl_drf2
            self.vars['drift'] = tk.IntVar(value=0)
            drf_lbl2 = tk.Label(drf_f2, text="0", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=3)
            drf_lbl2.pack(side='right')
            drf_scale2 = tk.Scale(drf_f2, from_=0, to=100, orient='horizontal', variable=self.vars['drift'], sliderlength=12, width=12, bg=PANEL_COLOR, fg=FG_COLOR, highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
            drf_scale2.pack(side='left', fill='x', expand=True, padx=2)
            drf_scale2.configure(command=lambda val, l=drf_lbl2: l.config(text=str(int(float(val)))))
            make_scale_value_editable(drf_scale2, drf_lbl2, self.vars['drift'], 0, 100)
            self._update_callbacks.append(lambda v=self.vars['drift'], l=drf_lbl2: l.config(text=str(int(float(v.get())))))
            ToolTip(drf_scale2, "Analog Slop / Pocket Drift. Actively injects half-Gaussian microsecond timing delays (up to 100ms) into every generated note trigger. Clustered organically near the pocket edge with natural dispersion to break away from rigid DAW grids without erratic jitter.")

            ctrl_row2 = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            ctrl_row2.pack(fill='x', padx=6, pady=(1, 1))

            lbl_vmin = tk.Label(ctrl_row2, text="V.MIN:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_vmin.pack(side='left')
            self.mod_badge_labels['V.MIN'] = lbl_vmin
            self.vars['v_min'] = tk.IntVar(value=65)
            sp_vmin = tk.Spinbox(ctrl_row2, from_=1, to=127, width=3, textvariable=self.vars['v_min'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, relief='sunken', bd=1)
            sp_vmin.pack(side='left', padx=2)
            ToolTip(sp_vmin, "Velocity Output Minimum. Every melodic note generated by this channel will calculate a randomized human velocity no lower than this exact limit. Ensures soft ghost notes don't disappear completely in the mix.")
            
            lbl_vmax = tk.Label(ctrl_row2, text="V.MAX:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
            lbl_vmax.pack(side='left', padx=(4,0))
            self.mod_badge_labels['V.MAX'] = lbl_vmax
            self.vars['v_max'] = tk.IntVar(value=115)
            sp_vmax = tk.Spinbox(ctrl_row2, from_=1, to=127, width=3, textvariable=self.vars['v_max'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, relief='sunken', bd=1)
            sp_vmax.pack(side='left', padx=2)
            ToolTip(sp_vmax, "Velocity Output Maximum. Every melodic note generated by this channel will calculate a randomized human velocity no higher than this absolute ceiling limit. Prevents harsh dynamics from striking synth filter limits.")

            # --- The Arranger Step Boxes (Right Symmetrical Block with LCK & SEQ) ---
            self.seq_f = tk.Frame(ctrl_row2, bg=PANEL_COLOR)
            self.seq_f.pack(side='right', padx=(4, 0))

            # LCK and SEQ buttons next to STEPS, same width (width 6), with breathing padding
            self.lck_btn = tk.Label(self.seq_f, text=" LCK ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2", width=6, pady=2)
            self.lck_btn.pack(side='left', padx=(0, 4))
            
            def _update_lck_visual(*args):
                if self.vars['locked'].get(): self.lck_btn.config(bg=SEPIA_ACTIVE, fg=LED_OFF, relief='sunken')
                else: self.lck_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                
            def _toggle_lck(event=None):
                new_val = not self.vars['locked'].get()
                self.base_vars['locked'] = new_val
                self.vars['locked'].set(new_val)
                if not new_val:
                    self.vars['mem_seq_mode'].set("OFF")
                    _update_mem_seq_visual()
                _update_lck_visual()

            self.lck_btn.bind("<Button-1>", _toggle_lck)
            self._update_callbacks.append(_update_lck_visual)
            ToolTip(self.lck_btn, "Turing Memory Lock. Freezes the channel's recent history into a loop of LEN steps (up to 64). Instantly captures the previous LEN steps that just played and repeats them from the first step without generating new notes. Click again to release; the loop continues tightly until the next master-phrase downbeat (the 1), where the generator resumes in perfect sync. An LFO pulse routed to LCK flips it once per pulse. The stored loop is never changed by MUT.")

            self.seq_btn = tk.Label(self.seq_f, text=" SEQ ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, relief='raised', bd=1, cursor="hand2", width=6, pady=2)
            self.seq_btn.pack(side='left', padx=(0, 6))

            def _toggle_seq(event=None):
                new_val = not self.vars['seq_active'].get()
                self.vars['seq_active'].set(new_val)
                self.seq_btn.config(bg=SEPIA_ACTIVE if new_val else PANEL_COLOR, fg=LED_OFF if new_val else FG_COLOR, relief='sunken' if new_val else 'raised')
                if new_val:
                    self.vars['mem_seq_mode'].set("OFF")
                    _update_mem_seq_visual()
                    if self.armed_step is not None:
                        self.step_btns[self.armed_step].config(highlightbackground=PANEL_COLOR)
                        self.armed_step = None
                else:
                    for i, b in getattr(self, 'step_btns', {}).items():
                        b.config(highlightbackground=PANEL_COLOR)

            self.seq_btn.bind("<Button-1>", _toggle_seq)
            ToolTip(self.seq_btn, "Chain Sequencer. Activates the timeline.")

            step_spacer = tk.Label(self.seq_f, text="STEPS", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=6, height=1, relief='flat', bd=1, pady=2)
            step_spacer.pack(side='left', padx=(0, 4))
            ToolTip(step_spacer, "Arrangement Step Track (10 steps). Armed step assigns the selected memory phrase slot.")

            self.step_btns = {}
            self._seq_steps_dirty = True
            self.armed_step = None

            def _step_click(idx):
                if self.armed_step == idx:
                    self.step_btns[idx].config(highlightbackground=PANEL_COLOR)
                    self.armed_step = None
                else:
                    if self.armed_step is not None:
                        self.step_btns[self.armed_step].config(highlightbackground=PANEL_COLOR)
                    self.armed_step = idx
                    self.step_btns[idx].config(highlightbackground=FG_COLOR)

            def _step_rclick(idx):
                self._seq_steps_dirty = True
                self.step_btns[idx].config(text="", highlightbackground=PANEL_COLOR)
                if self.armed_step == idx:
                    self.armed_step = None

            for i in range(1, 11):
                s_btn = tk.Label(self.seq_f, text="", bg=INPUT_BG, fg=INPUT_FG, font=FONT_SMALL, width=4, height=1, relief='sunken', cursor="hand2", highlightbackground=PANEL_COLOR, highlightthickness=2, bd=1, pady=2)
                s_btn.pack(side='left', padx=2)
                s_btn.bind("<Button-1>", lambda e, idx=i: _step_click(idx))
                s_btn.bind("<Button-3>", lambda e, idx=i: _step_rclick(idx))
                self.step_btns[i] = s_btn
                ToolTip(s_btn, f"Step {i}: Empty. Left-click to arm this step, then left-click any M-slot (M1–M10) below to assign it. Right-click to clear.")

            # --- ROW 3: Memory Routing ---
            ctrl_row3 = tk.Frame(self.body_frame, bg=PANEL_COLOR)
            ctrl_row3.pack(fill='x', padx=6, pady=(1, 2))

            rot_btn = tk.Label(ctrl_row3, text=" ROT ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, height=1, relief='raised', bd=1, cursor="hand2", width=5, pady=2)
            rot_btn.pack(side='left', padx=(2, 2))
            
            rnd_btn = tk.Label(ctrl_row3, text=" RND ", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, height=1, relief='raised', bd=1, cursor="hand2", width=5, pady=2)
            rnd_btn.pack(side='left', padx=(2, 6))
            ToolTip(rot_btn, "Auto-Rotation. Steps through the populated M slots in order (M1 to M10), changing slot once per AUTO SEQ RATE. Each switch lands on the next step and keeps the loop position, and forces LCK on. Turns the SEQ chain off. An LFO pulse routed to ROT advances one slot per pulse.")
            ToolTip(rnd_btn, "Auto-Random. Jumps to a random populated M slot once per AUTO SEQ RATE. Each switch lands on the next step and keeps the loop position, and forces LCK on. Turns the SEQ chain off. An LFO pulse routed to RND picks a new slot per pulse.")
            
            tk.Label(ctrl_row3, text="LEN:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(2,0))
            self.vars['lock_len'] = tk.IntVar(value=32)
            len_spin = tk.Spinbox(ctrl_row3, from_=1, to=64, width=3, textvariable=self.vars['lock_len'], bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, relief='sunken', bd=1)
            len_spin.pack(side='left')
            ToolTip(len_spin, "Loop length in steps (1 to 64; 64 is the whole phrase memory). Set it to your meter (for example 9 or 14) to loop an asymmetrical phrase without cutting its tail. The channel must have played at least this many steps before you lock, or the loop is silent.")
            
            tk.Label(ctrl_row3, text="RATE:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL).pack(side='left', padx=(6, 0))
            self.vars['mem_seq_rate'] = tk.StringVar(value="1x METER")
            mrate_menu = tk.OptionMenu(ctrl_row3, self.vars['mem_seq_rate'], "1/4x METER", "1/2x METER", "1x METER", "2x METER", "4x METER", "8x METER")
            mrate_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=9, padx=2, pady=0)
            mrate_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
            mrate_menu.pack(side='left', padx=1)
            ToolTip(mrate_menu, "How many master-phrase meters pass between slot changes for ROT, RND and the SEQ chain. 1x METER changes every bar; 1/4x METER changes every beat.")

            # --- ROW 3: The M-Slots (Right Symmetrical Block) ---
            self.m_f = tk.Frame(ctrl_row3, bg=PANEL_COLOR)
            self.m_f.pack(side='right', padx=(4, 0))

            spacer = tk.Label(self.m_f, text="MEMORY", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=6, height=1, relief='flat', bd=1, pady=2)
            spacer.pack(side='left', padx=(0, 4))
            ToolTip(spacer, "Turing Memory Bank. 10 phrase snapshot registers (M1 to M10). Left-click an empty slot while playing to capture the current phrase. Left-click a stored slot to recall it. Right-click to delete.")

            self.mem_btns = {}

            def _m_click(slot, btn_type="left"):
                if btn_type == "left" and self.armed_step is not None:
                    if self.vars['seq_active'].get(): return
                    self._seq_steps_dirty = True
                    self.step_btns[self.armed_step].config(text=str(slot), highlightbackground=PANEL_COLOR)
                    self.armed_step = None
                else:
                    if self.mem_callback: self.mem_callback(self.name, slot, btn_type)

            for i in range(1, 11):
                m_btn = tk.Label(self.m_f, text=f"{i}", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=4, height=1, relief='raised', bd=1, cursor="hand2", highlightthickness=2, highlightbackground=PANEL_COLOR, pady=2)
                m_btn.pack(side='left', padx=2)
                m_btn.bind("<Button-1>", lambda e, s=i: _m_click(s, "left"))
                m_btn.bind("<Button-3>", lambda e, s=i: _m_click(s, "right"))
                self.mem_btns[i] = m_btn
                ToolTip(m_btn, f"M{i}\n\n• L-CLICK: Snapshots phrase if empty, recalls if populated.\n• R-CLICK: Deletes.\n• If a top Step box is armed, L-CLICK assigns this M-slot to the Step sequence.")

            def _update_mem_seq_visual(*args):
                mode = self.vars['mem_seq_mode'].get()
                rot_btn.config(bg=SEPIA_ACTIVE if mode == "ROT" else PANEL_COLOR, fg=LED_OFF if mode == "ROT" else FG_COLOR, relief='sunken' if mode == "ROT" else 'raised')
                rnd_btn.config(bg=SEPIA_ACTIVE if mode == "RND" else PANEL_COLOR, fg=LED_OFF if mode == "RND" else FG_COLOR, relief='sunken' if mode == "RND" else 'raised')

            def _toggle_rot(event=None):
                new_val = "OFF" if self.vars['mem_seq_mode'].get() == "ROT" else "ROT"
                self.vars['mem_seq_mode'].set(new_val)
                if new_val == "ROT" and self.vars['seq_active'].get():
                    self.vars['seq_active'].set(False)
                    self.seq_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                    for i, b in self.step_btns.items(): b.config(highlightbackground=PANEL_COLOR)
                _update_mem_seq_visual()
                
            def _toggle_rnd(event=None):
                new_val = "OFF" if self.vars['mem_seq_mode'].get() == "RND" else "RND"
                self.vars['mem_seq_mode'].set(new_val)
                if new_val == "RND" and self.vars['seq_active'].get():
                    self.vars['seq_active'].set(False)
                    self.seq_btn.config(bg=PANEL_COLOR, fg=FG_COLOR, relief='raised')
                    for i, b in self.step_btns.items(): b.config(highlightbackground=PANEL_COLOR)
                _update_mem_seq_visual()
                
            rot_btn.bind("<Button-1>", _toggle_rot)
            rnd_btn.bind("<Button-1>", _toggle_rnd)
            self._update_callbacks.append(_update_mem_seq_visual)
        # Shadow State binding to capture user actions (including dict vars so get_settings is zero-Tcl-call!)
        self._probs_dirty = True
        for name, var in self.vars.items():
            if isinstance(var, dict):
                for sub_k, sub_var in var.items():
                    try:
                        sub_var.trace_add('write', lambda *args: setattr(self, '_probs_dirty', True))
                    except Exception: pass
                continue
            try:
                self.base_vars[name] = var.get()
                def make_tracer(n=name):
                    return lambda *args: self._on_var_user_change(n)
                var.trace_add('write', make_tracer())
            except Exception: pass

        if self.channel_type in ['melodic', 'polyphonic']:
            self.update_physics_visuals()

    def _get_active_aksak_blocks(self):
        m_str = self.vars.get('add_meter').get() if 'add_meter' in self.vars else "Four-on-the-Floor (4-4-4-4) [16]"
        m_resolved = resolve_additive_meter(m_str)
        return ADDITIVE_METERS.get(m_resolved, [2, 2, 2, 3])

    def flash_led(self, intervals=None, dur=None):
        def _flash_safe():
            try:
                self.led_canvas.itemconfig(self.led_circle, fill=LED_ON)
                self.after(50, lambda: self.led_canvas.itemconfig(self.led_circle, fill=LED_OFF))
            except Exception: pass
            if hasattr(self, 'eucl_radar'):
                try: self.eucl_radar.flash()
                except Exception: pass
            if hasattr(self, 'eucl_pulse_strip'):
                try: self.eucl_pulse_strip.flash()
                except Exception: pass
            if hasattr(self, 'aksak_gauge'):
                try: self.aksak_gauge.flash()
                except Exception: pass
            if intervals and hasattr(self, 'flash_intervals'):
                try: self.flash_intervals(intervals)
                except Exception: pass
            if dur and hasattr(self, 'flash_duration'):
                try: self.flash_duration(dur)
                except Exception: pass
        self.after(0, _flash_safe)

    def flash_intervals(self, intervals):
        if not hasattr(self, 'note_col_frames') or not self.note_col_frames:
            return
        if not hasattr(self, '_inter_flash_tokens'):
            self._inter_flash_tokens = {}
            
        for inter in intervals:
            target = inter
            if target not in self.note_col_frames and (inter % 12) in self.note_col_frames:
                target = inter % 12
            if target not in self.note_col_frames:
                continue
                
            subf, lbl = self.note_col_frames[target]
            token = self._inter_flash_tokens.get(target, 0) + 1
            self._inter_flash_tokens[target] = token
            
            # Instant peak glow: thin radiant orange border (#ff9a3c) + illuminated gold text (#ffe066)
            try:
                subf.config(highlightbackground='#ff9a3c')
                lbl.config(fg='#ffe066')
            except Exception: pass
            
            # Step 1: Amber decay (80 ms)
            def _step1(tok=token, s=subf, tgt=target):
                try:
                    if self._inter_flash_tokens.get(tgt) == tok:
                        s.config(highlightbackground='#c85a28')
                except Exception: pass
            self.after(80, _step1)
            
            # Step 2: Deep amber ember (150 ms)
            def _step2(tok=token, s=subf, l=lbl, tgt=target):
                try:
                    if self._inter_flash_tokens.get(tgt) == tok:
                        s.config(highlightbackground='#5e2d1d')
                        l.config(fg=FG_COLOR)
                except Exception: pass
            self.after(150, _step2)
            
            # Step 3: Full restore to panel background (220 ms)
            def _restore(tok=token, s=subf, l=lbl, tgt=target):
                try:
                    if self._inter_flash_tokens.get(tgt) == tok:
                        s.config(highlightbackground=PANEL_COLOR)
                        l.config(fg=FG_COLOR)
                except Exception: pass
            self.after(220, _restore)

    def flash_duration(self, dur):
        if not hasattr(self, 'dur_col_frames') or not self.dur_col_frames:
            return
        if not hasattr(self, '_dur_flash_tokens'):
            self._dur_flash_tokens = {}
            
        target = dur
        if target not in self.dur_col_frames:
            return
            
        subf, lbl = self.dur_col_frames[target]
        token = self._dur_flash_tokens.get(target, 0) + 1
        self._dur_flash_tokens[target] = token
        
        # Instant peak glow: thin radiant electric violet border (#e05fe6) + electric cyan duration label (#64d8cb)
        try:
            subf.config(highlightbackground='#e05fe6')
            lbl.config(fg='#64d8cb')
        except Exception: pass
        
        # Step 1: Rich plasma violet decay (80 ms)
        def _step1(tok=token, s=subf, tgt=target):
            try:
                if self._dur_flash_tokens.get(tgt) == tok:
                    s.config(highlightbackground='#8c3fa8')
            except Exception: pass
        self.after(80, _step1)
        
        # Step 2: Deep bruised violet ember (150 ms)
        def _step2(tok=token, s=subf, l=lbl, tgt=target):
            try:
                if self._dur_flash_tokens.get(tgt) == tok:
                    s.config(highlightbackground='#331e42')
                    l.config(fg=FG_COLOR)
            except Exception: pass
        self.after(150, _step2)
        
        # Step 3: Full restore to panel background (220 ms)
        def _restore(tok=token, s=subf, l=lbl, tgt=target):
            try:
                if self._dur_flash_tokens.get(tgt) == tok:
                    s.config(highlightbackground=PANEL_COLOR)
                    l.config(fg=FG_COLOR)
            except Exception: pass
        self.after(220, _restore)

    def set_active_seq_step(self, step_idx):
        self._last_active_seq_step = getattr(self, '_active_seq_step_idx', None)
        self._active_seq_step_idx = step_idx
        
        # Step chaser with active highlight and decay trail
        if hasattr(self, 'step_btns'):
            for i, btn in self.step_btns.items():
                if i == step_idx:
                    btn.config(highlightbackground='#ff8a4c', highlightthickness=2, fg='#ffe066')
                elif i == self._last_active_seq_step:
                    btn.config(highlightbackground='#5c2a38', highlightthickness=2, fg=INPUT_FG)
                else:
                    btn.config(highlightbackground=PANEL_COLOR, highlightthickness=2, fg=INPUT_FG)
                    
        if hasattr(self, 'e_step_btns'):
            for i, btn in self.e_step_btns.items():
                if i == step_idx:
                    btn.config(highlightbackground='#ff8a4c', highlightthickness=2, fg='#ffe066')
                elif i == self._last_active_seq_step:
                    btn.config(highlightbackground='#5c2a38', highlightthickness=2, fg=INPUT_FG)
                else:
                    btn.config(highlightbackground=PANEL_COLOR, highlightthickness=2, fg=INPUT_FG)

    def update_euclid_playback(self, cur_step, steps=None, pulses=None, rot=None):
        try:
            s = int(steps) if steps is not None else self.vars['eucl_steps'].get()
            p = int(pulses) if pulses is not None else self.vars['eucl_pulses'].get()
            r = int(rot) if rot is not None else self.vars['eucl_rot'].get()
            if hasattr(self, 'eucl_radar'):
                self.eucl_radar.redraw(s, p, r, cur_step)
            if hasattr(self, 'eucl_pulse_strip'):
                self.eucl_pulse_strip.redraw(s, p, r, cur_step)
        except Exception: pass

    def update_additive_playback(self, cur_step, blocks=None):
        try:
            if hasattr(self, 'aksak_gauge'):
                active_blocks = blocks if isinstance(blocks, list) else self._get_active_aksak_blocks()
                self.aksak_gauge.redraw(active_blocks, cur_step)
        except Exception: pass

    def flash_seq_step(self, slot):
        btn = getattr(self, 'step_btns', {}).get(slot)
        e_btn = getattr(self, 'e_step_btns', {}).get(slot)
        def _restore():
            try: 
                if btn: btn.config(bg=INPUT_BG)
                if e_btn: e_btn.config(bg=INPUT_BG)
            except Exception: pass
        try:
            if btn: btn.config(bg='#ffe066')
            if e_btn: e_btn.config(bg='#ffe066')
            self.after(140, _restore)
        except Exception: pass

    @staticmethod
    def _format_additive_step_display(val):
        if not val:
            return ""
        s = str(val).strip()
        try:
            if '(' in s and ')' in s:
                raw = s.split('(')[1].split(')')[0]
            else:
                raw = s
            if len(raw) <= 8:
                return raw
            compact = raw.replace('-', '')
            if len(compact) <= 8:
                return compact
            if '[' in s and ']' in s:
                total = s.split('[')[1].split(']')[0]
                name = s.split('(')[0].strip()[:4].upper()
                return f"{total}·{name}"
            return compact[:8]
        except Exception:
            return s[:8]
    
    def get_settings(self, current_cache=None):
        if getattr(self, '_probs_dirty', True) or not hasattr(self, '_cached_note_probs'):
            self._probs_dirty = False
            if 'note_probs' in self.vars:
                np = {}
                for interval, var in self.vars['note_probs'].items():
                    try: np[interval] = var.get()
                    except tk.TclError: np[interval] = current_cache['note_probs'][interval] if current_cache and 'note_probs' in current_cache else 0.0
                self._cached_note_probs = np
            if 'duration_probs' in self.vars:
                dp = {}
                for dur, var in self.vars['duration_probs'].items():
                    try: dp[dur] = var.get()
                    except tk.TclError: dp[dur] = current_cache['duration_probs'][dur] if current_cache and 'duration_probs' in current_cache else 0.0
                self._cached_dur_probs = dp

        res = {}
        for k, v in self.vars.items():
            if k == 'note_probs':
                res[k] = dict(getattr(self, '_cached_note_probs', {}))
            elif k == 'duration_probs':
                res[k] = dict(getattr(self, '_cached_dur_probs', {}))
            else:
                try: res[k] = self.base_vars.get(k, v.get())
                except tk.TclError: res[k] = current_cache[k] if current_cache and k in current_cache else 0
        if hasattr(self, 'macro_pool'):
            res['macro_pool'] = self.macro_pool
        if 'midi_chan' in res: res['midi_chan'] = max(1, min(16, res['midi_chan']))
        if 'mutation' in self.vars: res['mutation_seed'] = self.mutation_seed
        if hasattr(self, 'add_seq_steps') and hasattr(self, 'eucl_seq_steps'):
            res['add_seq_steps'] = [self.add_seq_steps[i] for i in range(1, 11)]
            res['eucl_seq_steps'] = [self.eucl_seq_steps[i] for i in range(1, 11)]
        elif hasattr(self, 'step_btns'):
            if getattr(self, '_seq_steps_dirty', True) or not hasattr(self, '_cached_seq_steps'):
                self._seq_steps_dirty = False
                self._cached_seq_steps = [int(self.step_btns[i].cget("text")) if self.step_btns[i].cget("text").isdigit() else None for i in range(1, 11)]
            res['seq_steps'] = list(self._cached_seq_steps)
        return res

    def set_settings(self, data):
        self.is_modulating = True
        self._probs_dirty = True
        self._seq_steps_dirty = True
        
        if 'macro_pool' in data and hasattr(self, 'macro_pool'):
            self.macro_pool = data['macro_pool']

        if 'mutation_seed' in data:
            self.mutation_seed = data['mutation_seed']
            
        if 'seq_active' in data:
            is_seq = data['seq_active']
            if hasattr(self, '_update_perc_seq_visual'):
                self._update_perc_seq_visual()
            else:
                if hasattr(self, 'seq_btn'):
                    self.seq_btn.config(bg=SEPIA_ACTIVE if is_seq else PANEL_COLOR, fg=LED_OFF if is_seq else FG_COLOR, relief='sunken' if is_seq else 'raised')
                if hasattr(self, 'e_seq_btn'):
                    self.e_seq_btn.config(bg=SEPIA_ACTIVE if is_seq else PANEL_COLOR, fg=LED_OFF if is_seq else FG_COLOR, relief='sunken' if is_seq else 'raised')
                if hasattr(self, 'add_seq_btn'):
                    self.add_seq_btn.config(bg=SEPIA_ACTIVE if is_seq else PANEL_COLOR, fg=LED_OFF if is_seq else FG_COLOR, relief='sunken' if is_seq else 'raised')
            
        if 'add_seq_steps' in data and hasattr(self, 'add_seq_steps'):
            for i, val in enumerate(data['add_seq_steps']):
                idx = i + 1
                self.add_seq_steps[idx] = val
                str_val = str(val).strip() if val is not None else ""
                if hasattr(self, 'step_btns'):
                    if str_val:
                        steps = self._format_additive_step_display(str_val)
                        self.step_btns[idx].config(text=steps)
                        ToolTip(self.step_btns[idx], f"Step {idx}: {val}")
                    else:
                        self.step_btns[idx].config(text="")

        if 'eucl_seq_steps' in data and hasattr(self, 'eucl_seq_steps'):
            for i, val in enumerate(data['eucl_seq_steps']):
                idx = i + 1
                self.eucl_seq_steps[idx] = val
                str_val = str(val).strip() if val is not None else ""
                if hasattr(self, 'e_step_btns'):
                    if str_val:
                        self.e_step_btns[idx].config(text=str_val)
                        ToolTip(self.e_step_btns[idx], f"Step {idx}: {val}")
                    else:
                        self.e_step_btns[idx].config(text="")

        if 'seq_steps' in data and hasattr(self, 'step_btns') and not hasattr(self, 'add_seq_steps'):
            for i, val in enumerate(data['seq_steps']):
                idx = i + 1
                if idx in self.step_btns:
                    if val is not None and str(val).strip().isdigit():
                        self.step_btns[idx].config(text=str(int(val)), highlightbackground=PANEL_COLOR)
                    else:
                        self.step_btns[idx].config(text="", highlightbackground=PANEL_COLOR)
            self._seq_steps_dirty = True
            self.armed_step = None
            
        for k, v in data.items():
            if k == 'mod_target' and 'mod_target_1' in self.vars:
                self.vars['mod_target_1'].set(v)
                self.base_vars['mod_target_1'] = v
                continue

            if k in self.vars:
                if isinstance(self.vars[k], dict):
                    for sub_k, sub_v in v.items():
                        if k == 'note_probs':
                            try:
                                key_cast = int(sub_k)
                                if key_cast in self.vars[k]: self.vars[k][key_cast].set(sub_v)
                            except Exception: pass
                        else:
                            if sub_k in self.vars[k]: self.vars[k][sub_k].set(sub_v)
                else:
                    try:
                        if k in ['t1_act', 't2_act', 't3_act']:
                            v_str = str(v).upper()
                            if v_str in ["TRUE", "1"]: v = "ON"
                            elif v_str in ["FALSE", "0"]: v = "OFF"
                        if k == 'add_meter': v = resolve_additive_meter(v)
                        self.base_vars[k] = v
                        self.vars[k].set(v)
                        if k == 'enabled':
                            c = SEPIA_ACTIVE if v else ACCENT_BRUISED
                            self.config(highlightbackground=c, highlightcolor=c)
                    except Exception: pass
        
        for cb in self._update_callbacks:
            try: cb()
            except Exception: pass
        self.is_modulating = False

    def update_physics_visuals(self):
        """Safely pulls live physics data from the global thread bridge and updates the UI readouts."""
        if not hasattr(self, 'body_frame') or not self.is_expanded(): return
        self._physics_after_id = None
        try:
            top = getattr(self, '_top_app', None)
            if top is None:
                self._top_app = top = self.winfo_toplevel()
            if getattr(top, '_is_toggling', False) or (hasattr(top, 'state') and top.state() == 'iconic'):
                self._physics_after_id = self.after(200, self.update_physics_visuals)
                return
            if hasattr(top, 'engine') and not top.engine.running:
                if not getattr(self, '_physics_halt_cleaned', False):
                    self._physics_halt_cleaned = True
                    if hasattr(self, 'note_eff_labels'):
                        for lbl in self.note_eff_labels.values():
                            if hasattr(lbl, 'set_value'): lbl.set_value(0.0)
                    if hasattr(self, 'dur_eff_labels'):
                        for lbl in self.dur_eff_labels.values():
                            if hasattr(lbl, 'set_value'): lbl.set_value(0.0)
                self._physics_after_id = self.after(150, self.update_physics_visuals)
                return
            self._physics_halt_cleaned = False
        except Exception: pass
        if 'GLOBAL_PHYSICS_STATE' in globals() and self.name in GLOBAL_PHYSICS_STATE:
            live_state = GLOBAL_PHYSICS_STATE[self.name]
            
            # Update Gravity (Intervals)
            if hasattr(self, 'note_eff_labels'):
                for inter, lbl in self.note_eff_labels.items():
                    live_val = live_state['notes'].get(inter, None)
                    if live_val is not None:
                        if hasattr(lbl, 'set_value'):
                            lbl.set_value(live_val)
                        else:
                            current_text = f"[{int(live_val):^3}]"
                            if lbl.cget("text") != current_text:
                                lbl.config(text=current_text)
                            
            # Update Inertia (Durations)
            if hasattr(self, 'dur_eff_labels'):
                for dur, lbl in self.dur_eff_labels.items():
                    live_val = live_state['durs'].get(dur, None)
                    if live_val is not None:
                        if hasattr(lbl, 'set_value'):
                            lbl.set_value(live_val)
                        else:
                            current_text = f"[{int(live_val):^3}]"
                            if lbl.cget("text") != current_text:
                                lbl.config(text=current_text)
                            
        # Loop at butter-smooth 20 FPS (50ms)
        self._physics_after_id = self.after(50, self.update_physics_visuals) 

    def set_midi_chan_editable(self, editable):
        """Enable or grey out the MIDI hardware channel selector depending on transport state.
        When running, channel spinboxes are locked and visually greyed out to prevent mid-sequence drift."""
        if not hasattr(self, 'sp_ch'):
            return
        if editable:
            try:
                self.sp_ch.config(
                    state='normal',
                    bg=INPUT_BG,
                    fg=INPUT_FG,
                    buttonbackground=ACCENT_BRUISED
                )
                if hasattr(self, 'lbl_ch'):
                    self.lbl_ch.config(fg=FG_COLOR)
                ToolTip(self.sp_ch, "MIDI Output Hardware Target Channel (1-16).")
            except Exception:
                pass
        else:
            try:
                ch_val = self.vars.get('midi_chan', tk.IntVar(value=1)).get()
                self.sp_ch.config(
                    state='disabled',
                    disabledbackground="#140f16",
                    disabledforeground="#6e626c",
                    buttonbackground="#221424"
                )
                if hasattr(self, 'lbl_ch'):
                    self.lbl_ch.config(fg="#6e626c")
                ToolTip(self.sp_ch, f"MIDI Hardware Channel ({ch_val}). Locked while sequencer is running.")
            except Exception:
                pass

class Application(tk.Tk):
    def __init__(self):
        if sys.platform == 'win32':
            try:
                import ctypes
                myappid = f"MauveZone.StochasticComposer.v{APP_VERSION}"
                ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
            except Exception:
                pass

        super().__init__()
        self._init_fonts()
        self.title(f"Mauve Zone - Stochastic Composer v{APP_VERSION} [{APP_CODENAME}]")
        try:
            base_dir = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
            ico_path = os.path.join(base_dir, 'mauve_zone.ico')
            if os.path.exists(ico_path):
                self.iconbitmap(default=ico_path)
                try:
                    from PIL import Image, ImageTk
                    self._app_icon_img = ImageTk.PhotoImage(file=ico_path)
                    self.iconphoto(True, self._app_icon_img)
                except Exception:
                    pass
        except Exception:
            pass
        try: self.state('zoomed')
        except tk.TclError:
            try: self.attributes('-zoomed', True)
            except tk.TclError: pass
        self.minsize(640, 480)
        self.configure(bg=BG_GRAD_BOT)

        main_container = tk.Frame(self, bg=BG_GRAD_BOT)
        main_container.pack(fill='both', expand=True)
        main_container.grid_rowconfigure(0, weight=1)
        main_container.grid_columnconfigure(0, weight=1)

        self.canvas = tk.Canvas(main_container, highlightthickness=0, bd=0, bg=BG_GRAD_BOT)
        self.v_scroll = tk.Scrollbar(main_container, orient="vertical", command=self.canvas.yview,
                                     bg=HEADER_BG, troughcolor=BG_GRAD_BOT, activebackground=ACCENT_BRUISED,
                                     highlightthickness=0, bd=0, width=12)
        self.h_scroll = tk.Scrollbar(main_container, orient="horizontal", command=self.canvas.xview,
                                     bg=HEADER_BG, troughcolor=BG_GRAD_BOT, activebackground=ACCENT_BRUISED,
                                     highlightthickness=0, bd=0, width=12)
        self.canvas.configure(yscrollcommand=self.v_scroll.set, xscrollcommand=self.h_scroll.set)
        self.canvas.grid(row=0, column=0, sticky="nsew")

        self.ui_frame = tk.Frame(self.canvas, bg=BG_GRAD_BOT)
        self.canvas_window = self.canvas.create_window((0, 0), window=self.ui_frame, anchor="nw")

        def _configure_ui_frame(event):
            self._sync_canvas_window()
        self.ui_frame.bind("<Configure>", _configure_ui_frame)

        def _on_mousewheel(event):
            is_shift = bool(event.state & 0x0001) if hasattr(event, 'state') else False
            if is_shift:
                if self.ui_frame.winfo_reqwidth() <= self.canvas.winfo_width():
                    return
                delta = event.delta
                scroll = -1 if (abs(delta) < 120 and delta > 0) else (1 if abs(delta) < 120 else int(-1 * (delta / 120)))
                self.canvas.xview_scroll(scroll, "units")
            else:
                if self.ui_frame.winfo_reqheight() <= self.canvas.winfo_height():
                    return
                delta = event.delta
                scroll = -1 if (abs(delta) < 120 and delta > 0) else (1 if abs(delta) < 120 else int(-1 * (delta / 120)))
                self.canvas.yview_scroll(scroll, "units")

        def _on_shift_mousewheel(event):
            if self.ui_frame.winfo_reqwidth() <= self.canvas.winfo_width():
                return
            delta = event.delta
            scroll = -1 if (abs(delta) < 120 and delta > 0) else (1 if abs(delta) < 120 else int(-1 * (delta / 120)))
            self.canvas.xview_scroll(scroll, "units")

        self.canvas.bind_all("<MouseWheel>", _on_mousewheel)
        self.canvas.bind_all("<Shift-MouseWheel>", _on_shift_mousewheel)
        for seq, cmd in [
            ("<Shift-Button-4>", lambda e: self.canvas.xview_scroll(-1, "units") if self.ui_frame.winfo_reqwidth() > self.canvas.winfo_width() else None),
            ("<Shift-Button-5>", lambda e: self.canvas.xview_scroll(1, "units") if self.ui_frame.winfo_reqwidth() > self.canvas.winfo_width() else None),
            ("<Button-6>", lambda e: self.canvas.xview_scroll(-1, "units") if self.ui_frame.winfo_reqwidth() > self.canvas.winfo_width() else None),
            ("<Button-7>", lambda e: self.canvas.xview_scroll(1, "units") if self.ui_frame.winfo_reqwidth() > self.canvas.winfo_width() else None)
        ]:
            try: self.canvas.bind_all(seq, cmd)
            except tk.TclError: pass

        self._grad_timer_id = None
        self._is_toggling = False
        self._base_col_w = 1054
        self._base_mod_w = 626
        self._base_master_w = 3186

        def _do_draw_gradient():
            self._grad_timer_id = None
            w = max(self.canvas.winfo_width(), 4500)
            h = max(self.canvas.winfo_height(), 3500)
            if w <= getattr(self, '_last_grad_w', 0) and h <= getattr(self, '_last_grad_h', 0): return
            self._last_grad_w, self._last_grad_h = w, h
            self.canvas.delete("gradient")
            step = max(1, h // 100)
            r1, g1, b1 = int(BG_GRAD_TOP[1:3], 16), int(BG_GRAD_TOP[3:5], 16), int(BG_GRAD_TOP[5:7], 16)
            r2, g2, b2 = int(BG_GRAD_BOT[1:3], 16), int(BG_GRAD_BOT[3:5], 16), int(BG_GRAD_BOT[5:7], 16)
            for i in range(0, h, step):
                ratio = i / h
                nr = int(r1 + (r2 - r1) * ratio)
                ng = int(g1 + (g2 - g1) * ratio)
                nb = int(b1 + (b2 - b1) * ratio)
                color = f"#{nr:02x}{ng:02x}{nb:02x}"
                self.canvas.create_rectangle(0, i, w, i+step, fill=color, outline="", tags="gradient")
            self.canvas.tag_lower("gradient")

        def _draw_gradient(event=None):
            if not getattr(self, '_suspend_sync', False):
                self._sync_canvas_window()
            timer_holder = self.master if getattr(self, 'master', None) is not None else self
            if getattr(self, '_grad_timer_id', None) is not None:
                try: timer_holder.after_cancel(self._grad_timer_id)
                except Exception: pass
            self._grad_timer_id = timer_holder.after(75, _do_draw_gradient)

        _do_draw_gradient()

        self.canvas.bind("<Configure>", _draw_gradient)

        self.master_frame = tk.Frame(self.ui_frame, bg=BG_GRAD_BOT)
        self.master_frame.pack(side='top', fill='x', padx=12, pady=(2, 1))

        # --- GLOBAL SECTION HEADER (Standardized Cyberdeck Header Frame) ---
        self.header_global = tk.Frame(self.master_frame, bg=HEADER_BG, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.header_global.pack(side='top', fill='x', pady=(0, 1))

        tk.Label(self.header_global, text=" /// ⚙ GLOBAL ENGINE CONFIGURATION /// ", bg=HEADER_BG, fg="#ff8a4c", font=FONT_HDR_TITLE).pack(side='left', padx=4, pady=0)
        self.global_toggle_btn = tk.Button(self.header_global, text="[ ▲ COMPRESS ]", command=self.toggle_global_engine,
                                           bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                                           font=FONT_HDR_BTN, relief='flat', bd=1, padx=4, pady=0, cursor="hand2")
        self.global_toggle_btn.pack(side='left', padx=2, pady=0)
        ToolTip(self.global_toggle_btn, "Toggle Global Configuration Controls (UNFOLD / COMPRESS).")
        self.btn_unfold_global = self.global_toggle_btn
        self.btn_compress_global = self.global_toggle_btn

        # --- GLOBAL HEADER FRAME (Permanently visible transport bar) ---
        self.global_header_frame = tk.Frame(self.master_frame, bg=HEADER_BG, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.global_header_frame.pack(side='top', fill='x', pady=(0, 2))
        self.global_header_frame.grid_columnconfigure(0, weight=1, uniform='hdr_wings')
        self.global_header_frame.grid_columnconfigure(1, weight=0)
        self.global_header_frame.grid_columnconfigure(2, weight=1, uniform='hdr_wings')

        # 1. Left Wing (Mauve Zone Logo)
        hdr_left = tk.Frame(self.global_header_frame, bg=HEADER_BG)
        hdr_left.grid(row=0, column=0, sticky='w')

        self.logo_frame = tk.Frame(hdr_left, bg=HEADER_BG)
        self.logo_frame.pack(side='left', fill='y', padx=(8, 12), pady=2)

        self.logo_canvas = MauveZoneLogoCanvas(self.logo_frame, width=655, height=121)
        self.logo_canvas.pack(anchor='w')
        ToolTip(self.logo_canvas, "MAUVE ZONE System Core (Interactive). Chromatic bruised purple / warm amber tide washes dynamically across letterforms during playback. Left-click to pulse an energetic ripple.")

        # 2. Center Wing (Master Transport Control Cluster: [ENGAGE] [Nixie Transport Counter] [LOAD/SAVE/INIT])
        hdr_center = tk.Frame(self.global_header_frame, bg=HEADER_BG)
        hdr_center.grid(row=0, column=1)

        # Equal-width and equal-height flanks guarantee pixel-perfect mathematical centering of Nixie Counter with Meter Bridge below
        # and full visibility of all 3 file buttons (LOAD, SAVE, INIT) without truncation
        self._base_flank_w = 115
        self._base_flank_h = 121
        self.hdr_left_flank = tk.Frame(hdr_center, bg=HEADER_BG, width=self._base_flank_w, height=self._base_flank_h)
        self.hdr_left_flank.pack_propagate(False)
        self.hdr_left_flank.pack(side='left', fill='both', padx=(4, 6), pady=2)

        self.start_btn = tk.Button(self.hdr_left_flank, text="ENGAGE", command=self.toggle_sequencer,
                                   bg=ACCENT_BRUISED, fg=FG_COLOR, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF,
                                   font=FONT_BOLD, relief='flat')
        self.start_btn.pack(fill='both', expand=True)
        ToolTip(self.start_btn, "Master Transport Control. Initiates or violently halts the core multi-threaded execution loop and the live MIDI output pipeline.")

        self.nixie_counter = NixieTransportCounter(hdr_center, width=280, height=86)
        self.nixie_counter.pack(side='left', padx=6, pady=2)
        ToolTip(self.nixie_counter, "Digital Nixie Transport Counter. Dual-tier vacuum fluorescent display showing live BAR : BEAT : STEP and ELAPSED TIME / TEMPO.")

        self.hdr_right_flank = tk.Frame(hdr_center, bg=HEADER_BG, width=self._base_flank_w, height=self._base_flank_h)
        self.hdr_right_flank.pack_propagate(False)
        self.hdr_right_flank.pack(side='left', fill='both', padx=(6, 4), pady=2)

        self.file_btns_frame = tk.Frame(self.hdr_right_flank, bg=HEADER_BG)
        self.file_btns_frame.pack(fill='both', expand=True)

        self.load_btn = tk.Button(self.file_btns_frame, text="LOAD", command=self.load_state,
                                  bg=INPUT_BG, fg=FG_COLOR, activebackground=FG_COLOR, activeforeground=BG_GRAD_BOT,
                                  font=FONT_SMALL, relief='flat', padx=6, pady=1)
        self.load_btn.pack(side='top', fill='both', expand=True, pady=1)
        ToolTip(self.load_btn, "Recall completely serialized sequencer arrangements, intervals, and captured memory buffers from a saved JSON file.")

        self.save_btn = tk.Button(self.file_btns_frame, text="SAVE", command=self.save_state,
                                  bg=INPUT_BG, fg=FG_COLOR, activebackground=FG_COLOR, activeforeground=BG_GRAD_BOT,
                                  font=FONT_SMALL, relief='flat', padx=6, pady=1)
        self.save_btn.pack(side='top', fill='both', expand=True, pady=1)
        ToolTip(self.save_btn, "Serialize the exact state of every parameter, array, and active memory slot across the entire machine into a portable JSON file on your hard drive.")

        self.init_btn = tk.Button(self.file_btns_frame, text="INIT", command=self.init_state,
                                  bg=INPUT_BG, fg=FG_COLOR, activebackground=FG_COLOR, activeforeground=BG_GRAD_BOT,
                                  font=FONT_SMALL, relief='flat', padx=6, pady=1)
        self.init_btn.pack(side='top', fill='both', expand=True, pady=1)
        ToolTip(self.init_btn, "Factory Master Reset. Restores the entire composer, all 25 channels, probability matrices, scales, and memory slots back to original clean startup state.")

        # 3. Right Wing (Sync & Routing Block: SYNC, BPM, 1/2 TIME, METER, Downbeat LED, PORT IN, PORT OUT)
        hdr_right = tk.Frame(self.global_header_frame, bg=HEADER_BG)
        hdr_right.grid(row=0, column=2, sticky='e')

        self.sync_routing_frame = tk.Frame(hdr_right, bg=HEADER_BG)
        self.sync_routing_frame.pack(side='right', fill='y', padx=(6, 10), pady=2)
        self.sync_routing_frame.grid_columnconfigure(0, weight=1)

        # Row 0: SYNC, BPM, 1/2 TIME, METER (+ Downbeat LED)
        row0_frame = tk.Frame(self.sync_routing_frame, bg=HEADER_BG)
        row0_frame.grid(row=0, column=0, sticky='ew', pady=(1, 2))

        lbl_sync = tk.Label(row0_frame, text="SYNC:", bg=HEADER_BG, fg=FG_COLOR, font=FONT_SMALL)
        lbl_sync.pack(side='left', padx=(2, 2))
        self.sync_var = tk.StringVar(value="INT")
        sync_menu = tk.OptionMenu(row0_frame, self.sync_var, "INT", "EXT")
        sync_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=3, padx=2, pady=0)
        sync_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
        sync_menu.pack(side='left', padx=(0, 6))
        ToolTip(sync_menu, "Master Clock Synchronization. 'INT' uses the internal Python timer to generate precise clock pulses. 'EXT' configures the engine to listen for incoming MIDI Realtime Clock (F8) and physical Start/Stop transport commands from external hardware (like an Octatrack or DAW).")

        lbl_tempo = tk.Label(row0_frame, text="BPM:", bg=HEADER_BG, fg=FG_COLOR, font=FONT_SMALL)
        lbl_tempo.pack(side='left', padx=(4, 2))
        self.tempo_var = tk.IntVar(value=115)
        self.sp_tempo = tk.Spinbox(row0_frame, from_=40, to=240, width=5, textvariable=self.tempo_var,
                                   bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED,
                                   disabledbackground=PANEL_COLOR, disabledforeground=SEPIA_ACTIVE,
                                   font=FONT_SMALL, bd=1)
        self.sp_tempo.pack(side='left', padx=(0, 6))
        ToolTip(self.sp_tempo, "Internal Tempo Configuration. Dictates the absolute baseline Beats Per Minute of the sequencer grid. This is completely overridden when SYNC is set to 'EXT'.")

        def _on_sync_change(*args):
            if self.sync_var.get() == "EXT":
                self.sp_tempo.config(state="disabled")
            else:
                self.sp_tempo.config(state="normal")
        self.sync_var.trace_add("write", _on_sync_change)
        _on_sync_change()

        self.half_time_var = tk.BooleanVar(value=False)
        ht_cb = tk.Checkbutton(row0_frame, text="1/2 TIME", variable=self.half_time_var, bg=HEADER_BG, fg=FG_COLOR, selectcolor=INPUT_BG, activebackground=HEADER_BG, activeforeground=FG_COLOR, font=FONT_SMALL)
        ht_cb.pack(side='left', padx=(4, 6))
        ToolTip(ht_cb, "Global Clock Divider. When engaged, this cuts the sequencer's structural time resolution directly in half, slowing generative notes from 16ths to 8ths. LFOs and master grid progression mathematically maintain their relative timing.")

        lbl_phrase = tk.Label(row0_frame, text="METER:", bg=HEADER_BG, fg=FG_COLOR, font=FONT_SMALL)
        lbl_phrase.pack(side='left', padx=(4, 2))
        self.phrase_var = tk.IntVar(value=16)
        sp_phrase = tk.Spinbox(row0_frame, from_=1, to=128, width=4, textvariable=self.phrase_var, bg=INPUT_BG, fg=INPUT_FG, buttonbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1)
        sp_phrase.pack(side='left', padx=(0, 4))
        ToolTip(sp_phrase, "Structural Master Phrase Length. This sets the invisible boundary line for all macro and chord math, measured strictly in 16th-note steps. 16 steps equals exactly one 4/4 bar. Every time this counter loops, the Global Progression advances.")

        self.master_led_canvas = tk.Canvas(row0_frame, width=20, height=20, highlightthickness=0, bg=HEADER_BG)
        self.master_led_canvas.pack(side='left', padx=(4, 2))
        self.master_led_circle = self.master_led_canvas.create_oval(3, 3, 17, 17, fill=LED_OFF, outline=ACCENT_BRUISED)
        ToolTip(self.master_led_canvas, "Master Phrase & Downbeat Flash Indicator. Pulses bright orange/gold on every primary phrase downbeat (the '1' of METER) and flashes softly on sub-beats.")

        # Row 1: PORT IN (stretched to match total width of Row 0)
        ports = mido.get_output_names()
        inports = mido.get_input_names()

        row1_frame = tk.Frame(self.sync_routing_frame, bg=HEADER_BG)
        row1_frame.grid(row=1, column=0, sticky='ew', pady=(1, 2))

        lbl_in = tk.Label(row1_frame, text="PORT IN:", bg=HEADER_BG, fg=FG_COLOR, font=FONT_SMALL, width=10, anchor='w')
        lbl_in.pack(side='left', padx=(2, 2))
        self.inport_var = tk.StringVar(value=inports[0] if inports else "No Input Found")
        inport_menu = tk.OptionMenu(row1_frame, self.inport_var, *(inports if inports else ["No Input Found"]))
        inport_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, highlightthickness=1, font=FONT_SMALL, bd=1, width=22, padx=2, pady=0)
        inport_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, font=FONT_SMALL)
        inport_menu.pack(side='left', fill='x', expand=True, padx=(2, 2))
        ToolTip(inport_menu, "MIDI Input Hardware Device. The specific physical or virtual port the engine watches to receive External Clock pulses, and Start/Stop transport commands.")

        # Row 2: PORT OUT (stretched to match total width of Row 0)
        row2_frame = tk.Frame(self.sync_routing_frame, bg=HEADER_BG)
        row2_frame.grid(row=2, column=0, sticky='ew', pady=(1, 2))

        lbl_out = tk.Label(row2_frame, text="PORT OUT:", bg=HEADER_BG, fg=FG_COLOR, font=FONT_SMALL, width=10, anchor='w')
        lbl_out.pack(side='left', padx=(2, 2))
        self.port_var = tk.StringVar(value=ports[0] if ports else "No Output Found")
        port_menu = tk.OptionMenu(row2_frame, self.port_var, *(ports if ports else ["No Output Found"]))
        port_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, highlightthickness=1, font=FONT_SMALL, bd=1, width=22, padx=2, pady=0)
        port_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, font=FONT_SMALL)
        port_menu.pack(side='left', fill='x', expand=True, padx=(2, 2))
        ToolTip(port_menu, "MIDI Output Hardware Device. The master physical or virtual port where the engine routes all generated Pitch, Velocity, Gates, and CC LFO Modulation data. Required to drive your hardware synthesizers.")

        self.port_menu, self.inport_menu = port_menu, inport_menu
        # Auto-refresh MIDI ports dynamically on click/post
        inport_menu.bind("<Button-1>", lambda e: self.refresh_ports(), add="+")
        port_menu.bind("<Button-1>", lambda e: self.refresh_ports(), add="+")
        inport_menu["menu"].config(postcommand=self.refresh_ports)
        port_menu["menu"].config(postcommand=self.refresh_ports)
        self.transport_frame = self.global_header_frame

        # --- GLOBAL BODY FRAME (Toggled deep-configuration widgets) ---
        self.global_body_frame = tk.Frame(self.master_frame, bg=PANEL_COLOR, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.global_body_frame.pack(side='top', fill='x', padx=0, pady=(1, 2))
        self.global_body_frame.grid_columnconfigure(0, weight=1, uniform='body_wings')
        self.global_body_frame.grid_columnconfigure(1, weight=0)
        self.global_body_frame.grid_columnconfigure(2, weight=1, uniform='body_wings')

        # -------------------------------------------------------------------------
        # 1. Left Wing: Harmonic Oscilloscope + Left System Controls (UI Zoom & Refresh Ports)
        # -------------------------------------------------------------------------
        body_left = tk.Frame(self.global_body_frame, bg=PANEL_COLOR)
        body_left.grid(row=0, column=0, sticky='w', padx=(8, 4), pady=3)

        # Vector Scope: sized to match the Mauve Zone logo above in all UI zooms
        self.vector_scope = HarmonicVectorScope(body_left, width=655, height=121)
        self.vector_scope.pack(side='left', padx=(0, 8), pady=2)
        ToolTip(self.vector_scope, "Retro CRT Harmonic Vector Scope (Interactive). Left-click or right-click to switch modes: Waveform, Lissajous, Constellation, 12-Band Spectrum, Dual, or Power Standby.")

        # Left Control Panel: UI ZOOM + REFRESH MIDI PORTS directly underneath
        left_ctrl = tk.Frame(body_left, bg=PANEL_COLOR, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        left_ctrl.pack(side='left', fill='y', padx=(0, 4), pady=2)

        zoom_row = tk.Frame(left_ctrl, bg=PANEL_COLOR)
        zoom_row.pack(side='top', fill='x', padx=6, pady=(6, 4))
        lbl_zoom = tk.Label(zoom_row, text="UI ZOOM:", bg=PANEL_COLOR, fg="#8c6b84", font=FONT_SMALL)
        lbl_zoom.pack(side='left', padx=(0, 4))
        self.zoom_var = tk.StringVar(value="100%")
        zoom_menu = tk.OptionMenu(zoom_row, self.zoom_var, "75%", "100%", "125%", "150%", command=self.apply_ui_scale)
        zoom_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG,
                         highlightthickness=1, highlightbackground=ACCENT_BRUISED, font=FONT_SMALL, bd=1, width=4, padx=2, pady=0)
        zoom_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
        zoom_menu.pack(side='left')
        ToolTip(zoom_menu, "Global UI Scaling factor. Resizes fonts, visualizers, and sequencer canvases to breathe across ultra-wide or high-DPI displays.")

        # PHASE RESET button: Gracefully synchronizes all channels, Turing loops, Aksak meters, and LFOs to the next 1
        self.phase_reset_btn = tk.Button(left_ctrl, text="PHASE RESET", command=self.request_phase_reset,
                                         bg=INPUT_BG, fg=FG_COLOR, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF,
                                         font=FONT_SMALL, relief='raised', bd=1, padx=6, pady=2, cursor="hand2")
        self.phase_reset_btn.pack(side='top', fill='x', padx=6, pady=(3, 3))
        ToolTip(self.phase_reset_btn, "Graceful Master Phase Reset. Synchronizes all channel clocks, Turing memory buffers, Euclidean/Aksak phase anchors, and LFO cycles to the upcoming phrase downbeat (the 1) without clipping actively sounding voices.")

        # Cosmic Mutation button: Randomize all controls (preserving MIDI channels, LCK, SEQ, and M-slots)
        self.randomize_btn = tk.Button(left_ctrl, text="COSMIC MUTATION", command=self.randomize_all_controls,
                                       bg=INPUT_BG, fg=FG_COLOR, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF,
                                       font=FONT_SMALL, relief='raised', bd=1, padx=6, pady=2, cursor="hand2")
        self.randomize_btn.pack(side='top', fill='x', padx=6, pady=(2, 4))
        ToolTip(self.randomize_btn, "Stochastic Cosmic Mutation. Intelligently randomizes all musical parameters across the composer (scales, root notes, chord progression arrays, probability faders, intervallic weights, human feel inertia, velocity boundaries, and performance macros) while strictly preserving hardware MIDI channels, Turing locks, Arranger timelines, and M1–M10 memory slots.")

        # -------------------------------------------------------------------------
        # 2. Center Wing: Large-Format 16-Channel Hardware MIDI Monitor + Expanded ENTROPY Fader
        # -------------------------------------------------------------------------
        body_center = tk.Frame(self.global_body_frame, bg=PANEL_COLOR)
        body_center.grid(row=0, column=1, padx=4, pady=3)

        self.meter_bridge = MasterHardwareMeterBridge(body_center, width=480, height=86)
        self.meter_bridge.pack(side='top', padx=4, pady=2)
        ToolTip(self.meter_bridge, "Master 16-Channel MIDI Hardware Meter Bridge. Large-format real-time monitor displaying active Note-On (amber/green) and CC modulation (cyan) transmissions across physical and virtual MIDI channels 1-16.")

        # Large tactile ENTROPY% Chaos Injector expanded to match meter bridge width (480px)
        self.ent_container = tk.Frame(body_center, bg=PANEL_COLOR, width=480)
        self.ent_container.pack(side='top', fill='x', padx=4, pady=(2, 0))

        ent_title_frame = tk.Frame(self.ent_container, bg=PANEL_COLOR)
        ent_title_frame.pack(side='top', fill='x')
        lbl_entropy = tk.Label(ent_title_frame, text="ENTROPY%:", bg=PANEL_COLOR, fg=SEPIA_ACTIVE, font=FONT_SMALL)
        lbl_entropy.pack(side='left')
        self._base_chaos_w = 380
        self._base_chaos_h = 18
        self.chaos_banner = ChaosBanner(ent_title_frame, text="[GLOBAL ANALOG CHAOS INJECTOR]", width=self._base_chaos_w, height=self._base_chaos_h)
        self.chaos_banner.pack(side='left', padx=(4, 0))

        ent_slider_frame = tk.Frame(self.ent_container, bg=PANEL_COLOR)
        ent_slider_frame.pack(side='top', fill='x', pady=(1, 0))
        self.entropy_var = tk.IntVar(value=0)
        self._base_entropy_len = 428
        self.ent_scale = tk.Scale(ent_slider_frame, from_=0, to=100, orient='horizontal', variable=self.entropy_var,
                             length=self._base_entropy_len, sliderlength=24, width=14,
                             bg=PANEL_COLOR, fg=SEPIA_ACTIVE, activebackground=SEPIA_ACTIVE,
                             highlightthickness=0, troughcolor=INPUT_BG, showvalue=0)
        self.ent_scale.pack(side='left', padx=(0, 6))
        self.ent_lbl = tk.Label(ent_slider_frame, text="0", bg=INPUT_BG, fg=SEPIA_ACTIVE, font=FONT_SMALL,
                           width=4, relief='sunken', bd=1, pady=1)
        self.ent_lbl.pack(side='left')
        self.ent_scale.configure(command=lambda val, l=self.ent_lbl: l.config(text=str(int(float(val)))))
        make_scale_value_editable(self.ent_scale, self.ent_lbl, self.entropy_var, 0, 100)
        ToolTip(self.ent_scale, "Global Chaos Injector. Injects random analog micro-timing drift and increases Rest probabilities across all channels to simulate a drifting, unstable analog sequencer.")

        # -------------------------------------------------------------------------
        # 3. Right Wing: Harmonic Progression Matrix (ROOT, PROG, xMETER, SCALE, RECIPE)
        # Positioned directly under PORT OUT on the right side
        # -------------------------------------------------------------------------
        body_right = tk.Frame(self.global_body_frame, bg=PANEL_COLOR)
        body_right.grid(row=0, column=2, sticky='e', padx=(4, 10), pady=3)

        self.harm_routing_frame = tk.Frame(body_right, bg=PANEL_COLOR)
        self.harm_routing_frame.pack(side='right', fill='y', padx=0, pady=2)
        self.harm_routing_frame.grid_columnconfigure(0, weight=1)

        # Row 0: ROOT, PROG (5 slots), xMETER
        row0_harm = tk.Frame(self.harm_routing_frame, bg=PANEL_COLOR)
        row0_harm.grid(row=0, column=0, sticky='ew', pady=(1, 2))

        lbl_root = tk.Label(row0_harm, text="ROOT:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
        lbl_root.pack(side='left', padx=(2, 2))
        self.root_var = tk.StringVar(value="C")
        root_menu = tk.OptionMenu(row0_harm, self.root_var, *ROOT_NOTES)
        root_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=2, padx=2, pady=0)
        root_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
        root_menu.pack(side='left', padx=(0, 6))
        ToolTip(root_menu, "Global Base Pitch Constraint. Every interval, scale, chord, and bassline across all channels is mathematically calculated relative to this absolute anchor pitch.")

        lbl_prog = tk.Label(row0_harm, text="PROG:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
        lbl_prog.pack(side='left', padx=(2, 2))
        self.prog_vars = []
        for slot_idx in range(5):
            p_var = tk.StringVar(value="-")
            self.prog_vars.append(p_var)
            p_menu = tk.OptionMenu(row0_harm, p_var, "-", *ROOT_NOTES)
            p_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=1, padx=1, pady=0)
            p_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, font=FONT_SMALL)
            p_menu.pack(side='left', padx=1)
            ToolTip(p_menu, f"Progression Slot {slot_idx + 1}. Sets the root pitch for this chord step. When set to '-', this slot is skipped. The sequencer advances to the next active slot every xMETER cycles.")
        ToolTip(lbl_prog, "Algorithmic Chord Progression Array. The sequencer automatically steps through these specific root notes over time. Slots set to '-' are skipped.")

        lbl_prate = tk.Label(row0_harm, text="xMETER:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL)
        lbl_prate.pack(side='left', padx=(6, 2))
        self.prate_var = tk.IntVar(value=4)
        prate_menu = tk.OptionMenu(row0_harm, self.prate_var, 1, 2, 4, 8, 16, 32)
        prate_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=2, padx=1, pady=0)
        prate_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, font=FONT_SMALL)
        prate_menu.pack(side='left')
        ToolTip(prate_menu, "Progression Rate Multiplier. Calculates exactly how many full Master METER cycles must execute before PROG advances to the next root note.")

        # Row 1: SCALE (stretched across, width=10 anchor='w' matching PORT IN/OUT above)
        row1_scale = tk.Frame(self.harm_routing_frame, bg=PANEL_COLOR)
        row1_scale.grid(row=1, column=0, sticky='ew', pady=(1, 2))

        lbl_scale = tk.Label(row1_scale, text="SCALE:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=10, anchor='w')
        lbl_scale.pack(side='left', padx=(2, 2))
        self.scale_var = tk.StringVar(value="Natural Minor (Aeolian)")
        scale_menu = tk.OptionMenu(row1_scale, self.scale_var, *list(SCALES.keys()))
        scale_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG, highlightthickness=1, font=FONT_SMALL, bd=1, width=22, padx=2, pady=0)
        scale_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
        scale_menu.pack(side='left', fill='x', expand=True, padx=(2, 2))
        ToolTip(scale_menu, "Global Harmonic Constraint. Forces the stochastic pitch generation array to rigidly conform to the exact intervals defined by this specific musical scale.")

        # Row 2: RECIPE (stretched across, width=10 anchor='w' matching PORT IN/OUT above)
        row2_recipe = tk.Frame(self.harm_routing_frame, bg=PANEL_COLOR)
        row2_recipe.grid(row=2, column=0, sticky='ew', pady=(1, 2))

        lbl_recipe = tk.Label(row2_recipe, text="RECIPE:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=10, anchor='w')
        lbl_recipe.pack(side='left', padx=(2, 2))
        self.recipe_var = tk.StringVar(value="Custom / Manual")
        self.recipe_menu = tk.OptionMenu(row2_recipe, self.recipe_var, *list(RECIPES.keys()))
        self.recipe_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, highlightthickness=1, font=FONT_SMALL, bd=1, width=22, padx=2, pady=0)
        self.recipe_menu["menu"].config(bg=PANEL_COLOR, fg=FG_COLOR, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, font=FONT_SMALL)
        self.recipe_menu.pack(side='left', fill='x', expand=True, padx=(2, 2))
        ToolTip(self.recipe_menu, "Pre-configured Interval Probability Presets. Activating a recipe overrides melodic channel sliders with aesthetic weights.")

        # Row 3: MOTION (Root Motion Traversal) & DISTRO (Stochastic Probability Distribution)
        row3_motion_dist = tk.Frame(self.harm_routing_frame, bg=PANEL_COLOR)
        row3_motion_dist.grid(row=3, column=0, sticky='ew', pady=(1, 2))

        lbl_motion = tk.Label(row3_motion_dist, text="MOTION:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=10, anchor='w')
        lbl_motion.pack(side='left', padx=(2, 2))
        self.motion_var = tk.StringVar(value="Linear Loop (1->2->3->4)")
        self.motion_menu = tk.OptionMenu(row3_motion_dist, self.motion_var,
            "Linear Loop (1->2->3->4)",
            "Pendulum (Ping-Pong)",
            "Tonic Anchor (Pedal Root)",
            "Brownian Walk (Drift)",
            "Turnaround Snap (Resolve)",
            "Chaos Shuffle (Stochastic)"
        )
        self.motion_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG,
                                highlightthickness=1, font=FONT_SMALL, bd=1, width=15, padx=2, pady=0, anchor='w')
        self.motion_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
        self.motion_menu.pack(side='left', padx=(0, 6))
        ToolTip(self.motion_menu, "Root Motion Traversal. Determines how the global engine steps through active PROG root notes over time: Linear Loop, Ping-Pong Pendulum, Tonic Anchor Pedal, Brownian Drift, Turnaround Snap, or Chaos Shuffle.")

        lbl_dist = tk.Label(row3_motion_dist, text="DISTRO:", bg=PANEL_COLOR, fg=FG_COLOR, font=FONT_SMALL, width=8, anchor='w')
        lbl_dist.pack(side='left', padx=(2, 2))
        self.distro_var = tk.StringVar(value="Boltzmann (Organic)")
        self.distro_menu = tk.OptionMenu(row3_motion_dist, self.distro_var,
            "Boltzmann (Organic)",
            "Gaussian (Tonal Center)",
            "Cauchy (Xenakis Leaps)",
            "1/f Pink (Fractal Drift)",
            "Tension & Resolve (Tidal)",
            "Weibull (Kinetic Bounces)"
        )
        self.distro_menu.config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, activeforeground=INPUT_FG,
                                highlightthickness=1, font=FONT_SMALL, bd=1, width=15, padx=2, pady=0, anchor='w')
        self.distro_menu["menu"].config(bg=INPUT_BG, fg=INPUT_FG, activebackground=ACCENT_BRUISED, font=FONT_SMALL)
        self.distro_menu.pack(side='left', fill='x', expand=True, padx=(0, 2))
        ToolTip(self.distro_menu, "Master Stochastic Probability Distribution. Governs the mathematical curvature of melodic interval dispersion and tonal gravity: Boltzmann Organic singing lines, Gaussian Tonal Center gravity, Cauchy Xenakis heavy-tailed leaps, 1/f Pink fractal drift, Tension & Resolve tidal turnaround, or Weibull kinetic bounces.")

        # Backward compatibility aliases
        self.controls_frame = self.harm_routing_frame
        self.ctrl_top = row0_harm
        self.ctrl_harm = row0_harm
        self.ctrl_bot = row3_motion_dist
        self.ctrl_ports = body_center

        # =========================================================================
        # 3 INDEPENDENT SECTION BANKS (Cyberdeck Decoupled Layout)
        # =========================================================================

        # 1. PERCUSSION CORE
        self.bank_perc = tk.Frame(self.ui_frame, bg=BG_GRAD_BOT)
        self.bank_perc.pack(side='top', fill='x', padx=12, pady=(1, 2))

        self.header_perc = tk.Frame(self.bank_perc, bg=HEADER_BG, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.header_perc.pack(side='top', fill='x', pady=(0, 1))

        tk.Label(self.header_perc, text=" /// ⏣ PERCUSSION CORE /// ", bg=HEADER_BG, fg="#ff8a4c", font=FONT_HDR_TITLE).pack(side='left', padx=4, pady=0)
        tk.Button(self.header_perc, text="[ ▼ UNFOLD ]", command=lambda: self.expand_channel_group(['percussion']),
                  bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                  font=FONT_HDR_BTN, relief='flat', bd=1, padx=3, pady=0, cursor="hand2").pack(side='left', padx=2, pady=0)
        tk.Button(self.header_perc, text="[ ▲ COMPRESS ]", command=lambda: self.collapse_channel_group(['percussion']),
                  bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                  font=FONT_HDR_BTN, relief='flat', bd=1, padx=3, pady=0, cursor="hand2").pack(side='left', padx=2, pady=0)

        self.grid_perc = tk.Frame(self.bank_perc, bg=BG_GRAD_BOT)
        self.grid_perc.pack(side='top', fill='x')

        # 2. HARMONIC MATRIX (Melodic / Polyphonic)
        self.bank_mel = tk.Frame(self.ui_frame, bg=BG_GRAD_BOT)
        self.bank_mel.pack(side='top', fill='x', padx=12, pady=(1, 2))

        self.header_mel = tk.Frame(self.bank_mel, bg=HEADER_BG, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.header_mel.pack(side='top', fill='x', pady=(0, 1))

        tk.Label(self.header_mel, text=" /// ⏣ HARMONIC MATRIX /// ", bg=HEADER_BG, fg="#ff8a4c", font=FONT_HDR_TITLE).pack(side='left', padx=4, pady=0)
        tk.Button(self.header_mel, text="[ ▼ UNFOLD ]", command=lambda: self.expand_channel_group(['melodic', 'polyphonic']),
                  bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                  font=FONT_HDR_BTN, relief='flat', bd=1, padx=3, pady=0, cursor="hand2").pack(side='left', padx=2, pady=0)
        tk.Button(self.header_mel, text="[ ▲ COMPRESS ]", command=lambda: self.collapse_channel_group(['melodic', 'polyphonic']),
                  bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                  font=FONT_HDR_BTN, relief='flat', bd=1, padx=3, pady=0, cursor="hand2").pack(side='left', padx=2, pady=0)

        self.grid_mel = tk.Frame(self.bank_mel, bg=BG_GRAD_BOT)
        self.grid_mel.pack(side='top', fill='x')

        # 3. MODULATION BUS (LFOs)
        self.bank_mod = tk.Frame(self.ui_frame, bg=BG_GRAD_BOT)
        self.bank_mod.pack(side='top', fill='x', padx=12, pady=(1, 2))

        self.header_mod = tk.Frame(self.bank_mod, bg=HEADER_BG, highlightthickness=1, highlightbackground=ACCENT_BRUISED)
        self.header_mod.pack(side='top', fill='x', pady=(0, 1))

        tk.Label(self.header_mod, text=" /// ⏣ MODULATION BUS /// ", bg=HEADER_BG, fg="#ff8a4c", font=FONT_HDR_TITLE).pack(side='left', padx=4, pady=0)
        tk.Button(self.header_mod, text="[ ▼ UNFOLD ]", command=lambda: self.expand_channel_group(['modulation']),
                  bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                  font=FONT_HDR_BTN, relief='flat', bd=1, padx=3, pady=0, cursor="hand2").pack(side='left', padx=2, pady=0)
        tk.Button(self.header_mod, text="[ ▲ COMPRESS ]", command=lambda: self.collapse_channel_group(['modulation']),
                  bg=INPUT_BG, fg=SEPIA_ACTIVE, activebackground=ACCENT_BRUISED, activeforeground=LED_ON,
                  font=FONT_HDR_BTN, relief='flat', bd=1, padx=3, pady=0, cursor="hand2").pack(side='left', padx=2, pady=0)

        self.grid_mod = tk.Frame(self.bank_mod, bg=BG_GRAD_BOT)
        self.grid_mod.pack(side='top', fill='x')

        # =========================================================================

        channel_definitions = [
            ("BD", "percussion"), ("SD", "percussion"), ("HHT", "percussion"),
            ("Bass", "melodic"), ("Plasma", "melodic"), ("GM", "melodic"),
            ("Panharmonium", "melodic"), ("Pigments", "polyphonic"), ("Hydrasynth", "polyphonic"),
            ("MOD 1", "modulation"), ("MOD 2", "modulation"), ("MOD 3", "modulation"),
            ("MOD 4", "modulation"), ("MOD 5", "modulation"), ("MOD 6", "modulation"), ("MOD 7", "modulation"),
            ("MOD 8", "modulation"), ("MOD 9", "modulation"), ("MOD 10", "modulation")
        ]

        self.channel_views = []
        for name, ctype in channel_definitions:
            if ctype == 'percussion': parent = self.grid_perc
            elif ctype in ['melodic', 'polyphonic']: parent = self.grid_mel
            else: parent = self.grid_mod
            self.channel_views.append(ChannelView(parent, name, ctype, mem_callback=self.handle_mem_click))
        self._channel_views_by_name = {v.name: v for v in self.channel_views}
        self._layout_channels()

        self.engine = SequencerEngine(self.channel_views, self.get_all_settings)

        def update_recipe_dropdown(*args):
            active_scale = SCALES.get(self.scale_var.get(), [])
            menu = self.recipe_menu["menu"]
            menu.delete(0, 'end')
            
            for group_name, options in RECIPE_GROUPS:
                if group_name != "MANUAL":
                    menu.add_separator()
                    menu.add_command(label=f"── {group_name} ──", state="disabled")
                for recipe_name in options:
                    weights = RECIPES.get(recipe_name, {})
                    display_name = recipe_name
                    if recipe_name != "Custom / Manual":
                        recipe_intervals = [interval for interval, weight in weights.items() if weight > 0]
                        is_compatible = all(interval == 12 or interval in active_scale for interval in recipe_intervals)
                        prefix = "[✔] " if is_compatible else "[X] "
                        display_name = f"{prefix}{recipe_name}"
                    
                    menu.add_command(label=display_name, command=tk._setit(self.recipe_var, display_name))
            
            menu.config(bg=PANEL_COLOR, fg=FG_COLOR, activebackground=SEPIA_ACTIVE, activeforeground=LED_OFF, font=FONT_SMALL)

        def on_recipe_change(*args):
            selection = self.recipe_var.get()
            if "Custom / Manual" in selection: return
            
            clean_selection = selection.replace("[✔] ", "").replace("[X] ", "")
            weights = RECIPES.get(clean_selection, {})
            
            for view in self.channel_views:
                if view.channel_type in ['melodic', 'polyphonic']:
                    for i in range(13):
                        view.vars['note_probs'][i].set(weights.get(i, 0))
                    for cb in view._update_callbacks:
                        try: cb()
                        except Exception: pass

        self.recipe_var.trace_add('write', on_recipe_change)
        
        def on_scale_change(*args):
            self._begin_toggle_transition()
            try:
                new_scale = self.scale_var.get()
                for view in self.channel_views:
                    if view.channel_type in ['melodic', 'polyphonic']:
                        view.rebuild_intervals(new_scale)
                update_recipe_dropdown()
            finally:
                self._finish_toggle_transition()

        self.scale_var.trace_add('write', on_scale_change)
        
        update_recipe_dropdown()
        self.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.apply_ui_scale()
        self._fit_to_screen()
        self._initial_state = copy.deepcopy(self.get_all_settings())
        self._state_pusher()

    def handle_mem_click(self, ch_name, slot, click_type="left"):
        settings = self.engine.cached_settings
        if not settings: return
        ch_data = settings['channels'].get(ch_name)
        if not ch_data: return
        
        has_data = self.engine.memory_slots[ch_name].get(slot) is not None
        
        if click_type == "right":
            if has_data:
                self.engine.memory_slots[ch_name][slot] = None
                for view in self.channel_views:
                    if view.name == ch_name: view.update_mem_btn_color(slot, False)
            return

        is_locked = ch_data.get('locked', False)
        
        if not has_data:
            buf = [
                self.engine._copy_event(ev)
                for ev in self.engine.turing_buffers[ch_name]
            ]
            time_div = 2 if settings.get('half_time') else 1
            current_eff_tick = self.engine.current_tick // time_div
            lock_len = max(1, min(64, int(ch_data.get('lock_len', 32))))
            locked_now = self.engine.eff_lock.get(ch_name, (is_locked, lock_len))[0]
            capture_scale = list(SCALES.get(settings.get('global_scale', 'Natural Minor (Aeolian)'), [0, 3, 5, 7, 10]))
            active_slot = self.engine.playing_mem.get(ch_name)
            active_memory = self.engine.memory_slots.get(ch_name, {}).get(active_slot) if active_slot is not None else None
            if active_memory and active_memory.get('scale_intervals'):
                capture_scale = list(active_memory['scale_intervals'])
            # Capture and flatten the exact phrase that was just heard (including live mutation when locked,
            # or the rolling history window when unlocked) as a normalized [0..383] phrase with start_tick = 0.
            if locked_now:
                buf = self.engine.capture_heard_phrase(ch_name, lock_len, buf)
            else:
                buf = self.engine.snapshot_rolling_phrase(ch_name, lock_len, current_eff_tick)
            self.engine.memory_slots[ch_name][slot] = {
                'buffer': buf,
                'lock_len': lock_len,
                'scale_intervals': capture_scale,
                'start_tick': 0
            }
            slot_data = self.engine.memory_slots[ch_name][slot]
            for view in self.channel_views:
                if view.name == ch_name: view.update_mem_btn_color(slot, True, slot_data)
        else:
            self.engine.trigger_memory_recall(ch_name, slot)

    def _init_fonts(self):
        global FONT_MAIN, FONT_BOLD, FONT_SMALL, FONT_HDR_TITLE, FONT_HDR_BTN, SLIDER_LEN
        self._font_spec = {
            'main': (11, 'normal', 8),
            'bold': (11, 'bold', 8),
            'small': (9, 'normal', 7),
            'hdr_title': (8, 'normal', 6),
            'hdr_btn': (8, 'normal', 6),
            'logo_art': (6, 'normal', 4),
            'logo_sub': (10, 'normal', 7)
        }
        self._fonts = {k: tkfont.Font(family='Consolas', size=v[0], weight=v[1]) for k, v in self._font_spec.items()}
        FONT_MAIN, FONT_BOLD, FONT_SMALL = (self._fonts[k] for k in ('main', 'bold', 'small'))
        FONT_HDR_TITLE, FONT_HDR_BTN = (self._fonts[k] for k in ('hdr_title', 'hdr_btn'))
        self._base_slider_len = 106
        SLIDER_LEN = self._base_slider_len

    def _set_font_factor(self, factor):
        for k, f in self._fonts.items():
            base, _, floor = self._font_spec[k]
            size = max(floor, int(round(base * factor)))
            if size != f.cget('size'): f.configure(size=size)

    def apply_ui_scale(self, *args):
        val_str = self.zoom_var.get() if hasattr(self, 'zoom_var') else "100%"
        if args and isinstance(args[0], str) and '%' in args[0]:
            val_str = args[0]
        try:
            factor = float(val_str.replace('%', '').strip()) / 100.0
        except Exception:
            factor = 1.0

        self._begin_toggle_transition()
        self._ui_factor = factor

        self._set_font_factor(factor)

        global SLIDER_LEN
        if not hasattr(self, '_base_slider_len'):
            self._base_slider_len = 106
        SLIDER_LEN = int(round(self._base_slider_len * factor))

        for cv in getattr(self, 'channel_views', []):
            for sc in getattr(cv, '_interval_scales', []) + getattr(cv, '_duration_scales', []):
                try:
                    if sc.winfo_exists(): sc.config(length=SLIDER_LEN)
                except Exception: pass

        zoom_dims = {
            0.75: (537, 88),
            1.00: (655, 121),
            1.25: (773, 156),
            1.50: (928, 182)
        }
        logo_w, logo_h = zoom_dims.get(round(factor, 2), (int(round(655 * factor)), int(round(121 * factor))))
        if hasattr(self, 'logo_canvas'):
            self.logo_canvas.resize(logo_w, logo_h, factor)
        if hasattr(self, 'vector_scope'):
            self.vector_scope.resize(logo_w, logo_h)

        if hasattr(self, 'hdr_left_flank') and hasattr(self, 'hdr_right_flank') and hasattr(self, '_base_flank_w') and hasattr(self, '_base_flank_h'):
            new_flank_w = int(round(self._base_flank_w * factor))
            new_flank_h = int(round(self._base_flank_h * factor))
            self.hdr_left_flank.config(width=new_flank_w, height=new_flank_h)
            self.hdr_right_flank.config(width=new_flank_w, height=new_flank_h)

        if hasattr(self, 'meter_bridge'):
            mb_w = int(round(480 * factor))
            mb_h = int(round(86 * factor))
            self.meter_bridge.resize(mb_w, mb_h)
            if hasattr(self, 'ent_scale') and hasattr(self, '_base_entropy_len'):
                new_ent_len = int(round(self._base_entropy_len * factor))
                self.ent_scale.config(length=new_ent_len)
            if hasattr(self, 'chaos_banner') and hasattr(self, '_base_chaos_w'):
                new_cb_w = int(round(self._base_chaos_w * factor))
                new_cb_h = int(round(self._base_chaos_h * factor))
                self.chaos_banner.resize(new_cb_w, new_cb_h)

        for cv in getattr(self, 'channel_views', []):
            if hasattr(cv, 'aksak_gauge'):
                ag_w = int(round(500 * factor))
                ag_h = int(round(60 * factor))
                cv.aksak_gauge.config(width=ag_w, height=ag_h)
                cv.aksak_gauge.w = ag_w
                cv.aksak_gauge.h = ag_h
                try:
                    blocks = cv._get_active_aksak_blocks()
                    cur = getattr(cv, '_last_perc_cur_step', 0) or 0
                    cv.aksak_gauge.redraw(blocks, cur)
                except Exception: pass

            if hasattr(cv, 'eucl_pulse_strip'):
                eps_w = int(round(320 * factor))
                eps_h = int(round(44 * factor))
                cv.eucl_pulse_strip.config(width=eps_w, height=eps_h)
                cv.eucl_pulse_strip.w = eps_w
                cv.eucl_pulse_strip.h = eps_h
                try:
                    s = cv.vars['eucl_steps'].get()
                    p = cv.vars['eucl_pulses'].get()
                    r = cv.vars['eucl_rot'].get()
                    cur = getattr(cv, '_last_perc_cur_step', 0) or 0
                    cv.eucl_pulse_strip.redraw(s, p, r, cur)
                except Exception: pass

            if hasattr(cv, 'eucl_radar'):
                er_size = int(round(96 * factor))
                cv.eucl_radar.config(width=er_size, height=er_size)
                cv.eucl_radar.size = er_size
                cv.eucl_radar.cx = er_size / 2.0
                cv.eucl_radar.cy = er_size / 2.0
                cv.eucl_radar.r = (er_size / 2.0) - 8.0
                try:
                    s = cv.vars['eucl_steps'].get()
                    p = cv.vars['eucl_pulses'].get()
                    r = cv.vars['eucl_rot'].get()
                    cur = getattr(cv, '_last_perc_cur_step', 0) or 0
                    cv.eucl_radar.redraw(s, p, r, cur)
                except Exception: pass

        # Settle zoomed widget geometry before measuring column widths in _layout_channels
        self.ui_frame.update_idletasks()
        self._layout_channels()
        self._finish_toggle_transition()

    def _set_window_redraw(self, enabled):
        """Freeze/unfreeze Win32 window painting (WM_SETREDRAW) during multi-widget reflows
        and UI zoom changes so the entire frame updates atomically with zero visual tearing."""
        if sys.platform != "win32":
            return
        try:
            hwnd = self.winfo_id()
            user32 = ctypes.windll.user32
            user32.SendMessageW(hwnd, 0x000B, 1 if enabled else 0, 0)
            if enabled:
                # RDW_INVALIDATE (0x0001) | RDW_ERASE (0x0004) | RDW_ALLCHILDREN (0x0080) | RDW_UPDATENOW (0x0100) | RDW_FRAME (0x0400)
                user32.RedrawWindow(hwnd, None, None, 0x0585)
        except Exception:
            pass

    def _begin_toggle_transition(self):
        self._is_toggling = True
        self._suspend_sync = True
        self._set_window_redraw(False)

    def _end_toggle_transition(self):
        self._is_toggling = False

    def _finish_toggle_transition(self):
        try:
            self.ui_frame.update_idletasks()
            self._suspend_sync = False
            self._sync_canvas_window()
            self.update_idletasks()
        finally:
            self._set_window_redraw(True)
        self.after(60, self._end_toggle_transition)

    def toggle_channel_view(self, cv):
        self._begin_toggle_transition()
        try:
            if cv.is_expanded():
                cv.collapse()
            else:
                cv.expand()
        finally:
            pass
        self._finish_toggle_transition()

    def expand_all_channels(self):
        self._begin_toggle_transition()
        try:
            for cv in getattr(self, 'channel_views', []):
                cv.expand()
        finally:
            pass
        self._finish_toggle_transition()

    def collapse_all_channels(self):
        self._begin_toggle_transition()
        try:
            for cv in getattr(self, 'channel_views', []):
                cv.collapse()
        finally:
            pass
        self._finish_toggle_transition()

    def expand_channel_group(self, target_types):
        self._begin_toggle_transition()
        try:
            for cv in getattr(self, 'channel_views', []):
                if cv.channel_type in target_types:
                    cv.expand()
        finally:
            pass
        self._finish_toggle_transition()

    def collapse_channel_group(self, target_types):
        self._begin_toggle_transition()
        try:
            for cv in getattr(self, 'channel_views', []):
                if cv.channel_type in target_types:
                    cv.collapse()
        finally:
            pass
        self._finish_toggle_transition()

    def focus_channel_group(self, target_types):
        self._begin_toggle_transition()
        try:
            views = getattr(self, 'channel_views', [])
            is_active = all(
                cv.is_expanded() if cv.channel_type in target_types else not cv.is_expanded()
                for cv in views
            )
            if is_active:
                for cv in views:
                    cv.collapse()
            else:
                for cv in views:
                    if cv.channel_type in target_types:
                        cv.expand()
                    else:
                        cv.collapse()
        finally:
            pass
        self._finish_toggle_transition()

    def _layout_channels(self, *args):
        percs = [v for v in self.channel_views if v.channel_type == 'percussion']
        mels = [v for v in self.channel_views if v.channel_type in ['melodic', 'polyphonic']]
        mods = [v for v in self.channel_views if v.channel_type == 'modulation']

        body_ws = [
            getattr(v, 'body_frame', v).winfo_reqwidth()
            for v in (percs + mels)
            if hasattr(v, 'body_frame') and getattr(v, 'is_expanded', lambda: True)()
        ]
        if body_ws and max(body_ws) > 200:
            self._base_col_w = max(body_ws) + 10
        else:
            self._base_col_w = getattr(self, '_base_col_w', 1054)

        self._base_master_w = self._base_col_w * 3 + 24
        self._base_mod_w = max(1, (self._base_col_w * 3) // 5 - 6)

        # Percussion Core: 3 columns wide (configured to identical uniform width as melodic)
        for c in range(3):
            self.grid_perc.grid_columnconfigure(c, weight=1, uniform='pcols', minsize=self._base_col_w)
        for i, v in enumerate(percs):
            if v.winfo_manager() != 'grid':
                v.grid(in_=self.grid_perc, row=i // 3, column=i % 3, padx=3, pady=3, sticky='nsew')

        # Harmonic Matrix (Synths): 3 columns wide
        for c in range(3):
            self.grid_mel.grid_columnconfigure(c, weight=1, uniform='mcols', minsize=self._base_col_w)
        for i, v in enumerate(mels):
            if v.winfo_manager() != 'grid':
                v.grid(in_=self.grid_mel, row=i // 3, column=i % 3, padx=3, pady=3, sticky='nsew')

        # Modulation Bus (LFOs): 5 columns wide (2 rows of 5, matching collective width above)
        for c in range(5):
            self.grid_mod.grid_columnconfigure(c, weight=1, uniform='modcols', minsize=self._base_mod_w)
        for i, v in enumerate(mods):
            if v.winfo_manager() != 'grid':
                v.grid(in_=self.grid_mod, row=i // 5, column=i % 5, padx=3, pady=3, sticky='nsew')

    def _layout_master(self, wrapped):
        pass

    def _sync_canvas_window(self, event=None):
        if getattr(self, '_suspend_sync', False):
            return
        base_w = getattr(self, '_base_master_w', 3186)
        req_w = max(base_w, self.ui_frame.winfo_reqwidth())
        req_h = self.ui_frame.winfo_reqheight()
        canvas_w = self.canvas.winfo_width()
        canvas_h = self.canvas.winfo_height()

        if canvas_w <= 10 or canvas_h <= 10:
            return

        # Dynamic scrollbar management: auto-hide scrollbars when UI fits in viewport
        scroll_changed = False
        if hasattr(self, 'v_scroll'):
            if req_h > canvas_h and canvas_h > 100:
                if self.v_scroll.winfo_manager() != 'grid':
                    self.v_scroll.grid(row=0, column=1, sticky="ns")
                    scroll_changed = True
            else:
                if self.v_scroll.winfo_manager() == 'grid':
                    self.v_scroll.grid_remove()
                    scroll_changed = True

        if hasattr(self, 'h_scroll'):
            if req_w > canvas_w and canvas_w > 100:
                if self.h_scroll.winfo_manager() != 'grid':
                    self.h_scroll.grid(row=1, column=0, sticky="ew")
                    scroll_changed = True
            else:
                if self.h_scroll.winfo_manager() == 'grid':
                    self.h_scroll.grid_remove()
                    scroll_changed = True

        # Recalculate canvas dimensions after scrollbar layout
        if scroll_changed:
            self.update_idletasks()
        canvas_w = self.canvas.winfo_width()
        canvas_h = self.canvas.winfo_height()

        x_offset = max(0, (canvas_w - req_w) // 2)
        self.canvas.coords(self.canvas_window, x_offset, 0)
        self.canvas.itemconfig(
            self.canvas_window,
            width=req_w,
            height=max(canvas_h, req_h))
        self.canvas.configure(scrollregion=(0, 0, max(canvas_w, x_offset + req_w), max(canvas_h, req_h)))

    def _fit_to_screen(self):
        self.update_idletasks()
        self._layout_channels()
        self.ui_frame.update_idletasks()
        self._sync_canvas_window()

    def _toggle_logo(self, event=None):
        if hasattr(self, 'logo_canvas'):
            self.logo_canvas._on_click(event)

    def expand_global_engine(self):
        if hasattr(self, 'global_body_frame') and self.global_body_frame.winfo_manager() != 'pack':
            self.toggle_global_engine()

    def collapse_global_engine(self):
        if hasattr(self, 'global_body_frame') and self.global_body_frame.winfo_manager() == 'pack':
            self.toggle_global_engine()

    def toggle_global_engine(self):
        self._begin_toggle_transition()
        try:
            if hasattr(self, 'global_body_frame'):
                if self.global_body_frame.winfo_manager() == 'pack':
                    self.global_body_frame.pack_forget()
                    if hasattr(self, 'global_toggle_btn'):
                        try: self.global_toggle_btn.config(text="[ ▼ UNFOLD ]")
                        except Exception: pass
                else:
                    self.global_body_frame.pack(side='top', fill='x', padx=0, pady=(2, 4))
                    if hasattr(self, 'global_toggle_btn'):
                        try: self.global_toggle_btn.config(text="[ ▲ COMPRESS ]")
                        except Exception: pass
        finally:
            pass
        self._finish_toggle_transition()

    toggle_global_body = toggle_global_engine

    def _state_pusher(self):
        try:
            if not getattr(self, '_is_toggling', False):
                self._state_pusher_body()
        except Exception:
            log_exc('ui_pusher')
        finally:
            try:
                is_min = (self.state() == 'iconic')
                delay = 200 if is_min else 50
                self.after(delay, self._state_pusher)
            except Exception: pass

    def request_phase_reset(self):
        if hasattr(self, 'phase_reset_btn'):
            self.phase_reset_btn.config(text="SYNCING TO 1...", bg=SEPIA_ACTIVE, fg=LED_OFF)
        if hasattr(self, 'engine'):
            self.engine.request_phase_reset()

    def randomize_all_controls(self):
        """Intelligently randomizes all creative controls across the Stochastic Composer.
        Strictly preserves: assigned MIDI channels, LCK lock states, SEQ sequencer chain states,
        and M1-M10 stored memory slots."""
        self._begin_toggle_transition()
        try:
            # 1. Global Harmonic & Progression Controls
            self.root_var.set(random.choice(ROOT_NOTES))
            self.scale_var.set(random.choice(list(SCALES.keys())))
            self.recipe_var.set("Custom / Manual")
            for p_var in getattr(self, 'prog_vars', []):
                p_var.set(random.choice(['-'] + ROOT_NOTES))
            self.prate_var.set(random.choice([1, 2, 4, 8]))
            self.phrase_var.set(random.choice([8, 12, 16, 24, 32]))
            self.tempo_var.set(random.randint(95, 135))
            self.entropy_var.set(random.randint(0, 45))
            self.half_time_var.set(random.random() < 0.2)
            if hasattr(self, 'motion_var'):
                self.motion_var.set(random.choice([
                    "Linear Loop (1->2->3->4)",
                    "Pendulum (Ping-Pong)",
                    "Tonic Anchor (Pedal Root)",
                    "Brownian Walk (Drift)",
                    "Turnaround Snap (Resolve)",
                    "Chaos Shuffle (Stochastic)"
                ]))
            if hasattr(self, 'distro_var'):
                self.distro_var.set(random.choice([
                    "Boltzmann (Organic)",
                    "Gaussian (Tonal Center)",
                    "Cauchy (Xenakis Leaps)",
                    "1/f Pink (Fractal Drift)",
                    "Tension & Resolve (Tidal)",
                    "Weibull (Kinetic Bounces)"
                ]))

            # 2. Channel Views
            all_eucl = [opt for _, opts in EUCLID_GROUPS for opt in opts if '(' in opt and ')' in opt]
            perc_macros = ["Static", "Void", "Evolve", "Drive", "Stutter", "Ghost", "Swarm", "Disintegration"]
            mel_macros = ["Static", "Humanize", "Octave Drop", "Octave Leap", "Grace Notes", "Echo", "Tremolo", "Pedal Point", "Drone Collapse", "Micro-Drift"]
            valid_waves = ["Sine", "Triangle", "Saw Up", "Saw Down", "Pulse", "Random", "SlewRand", "S&H", "ExpDecay", "Chaos"]
            valid_rates = list(MOD_RATE_BEATS.keys())
            valid_chords = ["Triad", "7th", "Sus4", "Add9", "Open 5th"]

            for cv in self.channel_views:
                # PRESERVED ACROSS ALL CHANNELS: midi_chan, locked, seq_active, memory_slots
                if cv.channel_type == 'percussion':
                    if not getattr(cv.vars.get('seq_active', None), 'get', lambda: False)():
                        mode = random.choice(['EUCLID', 'ADDITIVE'])
                        cv.vars['perc_mode'].set(mode)
                    else:
                        mode = cv.vars['perc_mode'].get()

                    if mode == 'EUCLID' and all_eucl:
                        preset_name = random.choice(all_eucl)
                        try:
                            s, p, r = map(int, preset_name.split('(')[-1].strip(')').split(':'))
                            cv.vars['eucl_steps'].set(s)
                            cv.vars['eucl_pulses'].set(p)
                            cv.vars['eucl_rot'].set(r)
                            if 'eucl_preset' in cv.vars: cv.vars['eucl_preset'].set(preset_name)
                        except Exception: pass
                    elif mode == 'ADDITIVE':
                        meter_name = random.choice(list(ADDITIVE_METERS.keys()))
                        if 'add_meter' in cv.vars: cv.vars['add_meter'].set(meter_name)

                    cv.vars['swing'].set(random.randint(0, 45))
                    cv.vars['drift'].set(random.randint(5, 35))
                    cv.vars['mutation'].set(random.randint(0, 40))
                    if 'v_min' in cv.vars: cv.vars['v_min'].set(random.randint(60, 85))
                    if 'v_max' in cv.vars: cv.vars['v_max'].set(random.randint(95, 125))
                    if 'ths_v' in cv.vars: cv.vars['ths_v'].set(random.randint(90, 125))
                    if 'ars_v' in cv.vars: cv.vars['ars_v'].set(random.randint(60, 95))
                    if 'ars_rst' in cv.vars: cv.vars['ars_rst'].set(random.randint(0, 40))
                    cv.vars['macro_state'].set(random.choice(perc_macros))

                elif cv.channel_type in ['melodic', 'polyphonic']:
                    dur_weights = {}
                    for k in cv.vars['duration_probs']:
                        dur_weights[k] = random.choice([0, 0, random.randint(20, 100)])
                    if sum(dur_weights.values()) == 0:
                        dur_weights['1/4'] = 80
                        dur_weights['1/8'] = 60
                    for k, v in dur_weights.items():
                        cv.vars['duration_probs'][k].set(v)
                    cv.vars['rest_prob'].set(random.randint(0, 35))

                    int_weights = {}
                    for k in cv.vars['note_probs']:
                        int_weights[k] = random.choice([0, 0, random.randint(20, 100)])
                    if random.random() < 0.6: int_weights[0] = random.randint(50, 100)
                    if random.random() < 0.5: int_weights[7] = random.randint(40, 80)
                    if sum(int_weights.values()) == 0: int_weights[0] = 80
                    for k, v in int_weights.items():
                        cv.vars['note_probs'][k].set(v)

                    vmin = random.randint(45, 75)
                    vmax = random.randint(vmin + 15, 125)
                    cv.vars['v_min'].set(vmin)
                    cv.vars['v_max'].set(vmax)

                    cv.vars['inertia'].set(random.randint(25, 85))
                    cv.vars['gravity'].set(random.randint(20, 80))
                    cv.vars['drift'].set(random.randint(5, 35))
                    cv.vars['mutation'].set(random.randint(0, 40))

                    if cv.name == 'Bass':
                        oct_val = random.choice([1, 2])
                        cv.vars['min_oct'].set(oct_val)
                        cv.vars['max_oct'].set(oct_val + random.choice([0, 1]))
                    else:
                        oct_val = random.choice([2, 3, 4])
                        cv.vars['min_oct'].set(oct_val)
                        cv.vars['max_oct'].set(oct_val + random.choice([1, 2]))

                    cv.vars['macro_state'].set(random.choice(mel_macros))

                    if cv.channel_type == 'polyphonic' and 'chord_type' in cv.vars:
                        cv.vars['chord_type'].set(random.choice(valid_chords))

                elif cv.channel_type == 'modulation':
                    cv.vars['waveform'].set(random.choice(valid_waves))
                    cv.vars['rate'].set(random.choice(valid_rates))
                    cv.vars['depth'].set(random.randint(25, 85))

                # Sync shadow state (base_vars) so engine settings immediately reflect cosmic mutation
                for k, var_obj in cv.vars.items():
                    if not isinstance(var_obj, dict):
                        try: cv.base_vars[k] = var_obj.get()
                        except Exception: pass

                for cb in getattr(cv, '_update_callbacks', []):
                    try: cb()
                    except Exception: pass

            if hasattr(self, 'ent_lbl') and hasattr(self, 'entropy_var'):
                self.ent_lbl.config(text=str(int(float(self.entropy_var.get()))))
        finally:
            self._finish_toggle_transition()

    def refresh_ports(self):
        try: outs = mido.get_output_names()
        except Exception: log_exc('port_refresh_out', 0); outs = []
        try: ins = mido.get_input_names()
        except Exception: log_exc('port_refresh_in', 0); ins = []
        for widget, var, names, empty in ((self.port_menu, self.port_var, outs, "No Output Found"),
                                          (self.inport_menu, self.inport_var, ins, "No Input Found")):
            names = list(names) or [empty]
            menu = widget["menu"]
            menu.delete(0, "end")
            for n in names:
                menu.add_command(label=n, command=tk._setit(var, n))
            if var.get() not in names: var.set(names[0])

    def _handle_engine_fault(self, msg):
        try: self.engine.stop()
        except Exception: log_exc('stop_after_fault')
        try: self.start_btn.config(text="ENGAGE", bg=ACCENT_BRUISED, fg=FG_COLOR)
        except Exception: pass
        self.after(0, lambda: messagebox.showerror("MIDI Output", msg))

    def _update_midi_chan_editable_state(self, editable):
        """Propagate transport lock to all channel views to freeze/unfreeze MIDI channel selectors."""
        for cv in getattr(self, 'channel_views', []):
            if hasattr(cv, 'set_midi_chan_editable'):
                cv.set_midi_chan_editable(editable)

    def _state_pusher_body(self):
        is_min = (self.state() == 'iconic')

        # Synchronize MIDI channel editable state with engine transport
        if hasattr(self, 'engine'):
            current_running = bool(self.engine.running)
            if not hasattr(self, '_last_known_running') or self._last_known_running != current_running:
                self._last_known_running = current_running
                self._update_midi_chan_editable_state(not current_running)

        if self.sync_var.get() == "EXT":
            self.tempo_var.set(int(round(self.engine.ext_bpm)))

        if not is_min:
            # Update Digital Nixie Transport Counter
            if hasattr(self, 'nixie_counter') and hasattr(self, 'engine'):
                try:
                    bpm_val = float(self.tempo_var.get()) if hasattr(self, 'tempo_var') else float(getattr(self.engine, 'tempo', 120.0))
                    phrase_len = int(self.phrase_var.get()) if hasattr(self, 'phrase_var') else 16
                    time_div = 2 if (hasattr(self, 'half_time_var') and self.half_time_var.get()) else 1
                    self.nixie_counter.update_pos(self.engine.current_tick, phrase_len, time_div, bpm=bpm_val, running=self.engine.running)
                except Exception: pass

            # Update Master 16-Channel Hardware Meter Bridge (with live channel role mapping)
            if hasattr(self, 'meter_bridge') and hasattr(self, 'engine'):
                try:
                    if not self.engine.running or not hasattr(self, '_cached_full_roles'):
                        abbrev_map = {
                            "BD": "BD", "SD": "SD", "HHT": "HHT",
                            "Bass": "BAS", "Plasma": "PLA", "GM": "GM",
                            "Panharmonium": "PAN", "Pigments": "PIG", "Hydrasynth": "HYD"
                        }
                        role_map = {}
                        for cv in self.channel_views:
                            if cv.channel_type in ('percussion', 'melodic', 'polyphonic') and 'midi_chan' in cv.vars:
                                try:
                                    ch_idx = max(0, min(15, int(cv.vars['midi_chan'].get()) - 1))
                                    role_map[ch_idx] = abbrev_map.get(cv.name, cv.name[:3].upper())
                                except Exception:
                                    pass
                        self._cached_full_roles = [role_map.get(ch, f"M{ch+1:02d}" if ch != 15 else "MST") for ch in range(16)]
                    self.meter_bridge.update_traffic(self.engine.midi_channel_activity, self.engine.midi_cc_activity, custom_roles=self._cached_full_roles)
                except Exception: pass

            # Tick Global Analog Chaos Injector Gradient Banner
            if hasattr(self, 'chaos_banner'):
                try: self.chaos_banner.tick_anim(dt=0.05)
                except Exception: pass

            # Update Mauve Zone Interactive Art Logo
            if hasattr(self, 'logo_canvas') and hasattr(self, 'engine'):
                try:
                    self.logo_canvas.tick_anim(running=self.engine.running)
                except Exception: pass

            # Update Retro Lissajous Harmonic Vector Scope
            if hasattr(self, 'vector_scope') and hasattr(self, 'engine'):
                try:
                    with self.engine.midi_lock:
                        sounding_snapshot = set(self.engine.sounding)
                    self.vector_scope.update_scope(sounding_snapshot)
                except Exception: pass

            # Update Percussion Real-Time Playhead Step (Euclid Radar & Pulse Strip, Aksak Gauge)
            if hasattr(self, 'engine') and self.engine.running:
                pos_dict = getattr(self.engine, 'perc_playback_pos', {})
                for view in self.channel_views:
                    if view.channel_type == 'percussion' and view.is_expanded():
                        info = pos_dict.get(view.name)
                        if info:
                            mode, cur_step = info[0], info[1]
                            last_info = getattr(view, '_last_perc_info', None)
                            if last_info != info:
                                view._last_perc_info = info
                                if mode == 'EUCLID':
                                    s_eff = info[2] if len(info) > 2 else None
                                    p_eff = info[3] if len(info) > 3 else None
                                    r_eff = info[4] if len(info) > 4 else None
                                    view.update_euclid_playback(cur_step, steps=s_eff, pulses=p_eff, rot=r_eff)
                                elif mode == 'ADDITIVE':
                                    b_eff = info[3] if len(info) > 3 and isinstance(info[3], list) else (info[2] if len(info) > 2 and isinstance(info[2], list) else None)
                                    view.update_additive_playback(cur_step, blocks=b_eff)
            elif hasattr(self, 'engine') and not self.engine.running:
                for view in self.channel_views:
                    if view.channel_type == 'percussion':
                        if getattr(view, '_last_perc_info', None) is not None:
                            view._last_perc_info = None
                            view.update_euclid_playback(0)
                            view.update_additive_playback(0)

        # Drain UI events safely from thread-safe deque (with list fallback)
        events = []
        q = getattr(self.engine, 'ui_events', None)
        if q is not None:
            if hasattr(q, 'popleft'):
                while q:
                    try:
                        events.append(q.popleft())
                    except IndexError:
                        break
            else:
                while q:
                    try:
                        events.append(q.pop(0))
                    except IndexError:
                        break
        ch_map = getattr(self, '_channel_views_by_name', {})

        if not hasattr(self, '_pending_seq_steps'):
            self._pending_seq_steps = {}

        if not is_min and self._pending_seq_steps:
            for ch_name, step_idx in self._pending_seq_steps.items():
                v = ch_map.get(ch_name)
                if v: v.set_active_seq_step(step_idx)
            self._pending_seq_steps.clear()

        for ev in events:
            ev_type = ev[0]
            if is_min and ev_type in ('flash', 'master_flash', 'mod_led', 'mem_flash', 'seq_step_active'):
                if ev_type == 'seq_step_active' and len(ev) > 2:
                    self._pending_seq_steps[ev[1]] = ev[2]
                continue
            if ev_type == 'flash':
                v = ch_map.get(ev[1])
                if v:
                    intervals = ev[2] if len(ev) > 2 else None
                    dur = ev[3] if len(ev) > 3 else None
                    v.flash_led(intervals, dur)
            elif ev_type == 'master_flash':
                is_db = ev[1] if len(ev) > 1 else False
                self.flash_master_led(is_db)
            elif ev_type == 'mod_led':
                v = ch_map.get(ev[1])
                if v: v.update_led_brightness(ev[2])
            elif ev_type == 'set_root':
                self.root_var.set(ev[1])
            elif ev_type == 'update_local_var':
                v = ch_map.get(ev[1])
                if v: v.set_settings({ev[2]: ev[3]})
            elif ev_type == 'mem_state':
                v = ch_map.get(ev[1])
                if v: v.set_mem_state(ev[2], ev[3])
            elif ev_type == 'mem_flash':
                v = ch_map.get(ev[1])
                if v: v.flash_mem(ev[2])
            elif ev_type == 'toggle_lock':
                self.toggle_channel_lock(ev[1])
            elif ev_type == 'engine_fault':
                self._handle_engine_fault(ev[1])
            elif ev_type == 'seq_step_active':
                v = ch_map.get(ev[1])
                if v:
                    v.set_active_seq_step(ev[2])
                    v.flash_seq_step(ev[2])
            elif ev_type == 'phase_reset_complete':
                if hasattr(self, 'phase_reset_btn'):
                    self.phase_reset_btn.config(text="SYNCED!", bg="#4a734a", fg="#ffffff")
                    self.after(800, lambda: self.phase_reset_btn.config(text="PHASE RESET", bg=INPUT_BG, fg=FG_COLOR))

        try: self.engine.cached_settings = self.get_all_settings()
        except Exception: log_exc('get_all_settings')
            
        if not is_min:
            mod_matrix = self.engine.mod_matrix
            toggles = self.engine.toggle_state
            for view in self.channel_views:
                mods = dict(mod_matrix.get(view.name, {}))
                for p, on in list(toggles.get(view.name, {}).items()):
                    mods[p] = 1.0 if on else 0.0   # engine's pulse-latched ACT/LCK state drives the UI
                view.apply_mod_visuals(mods)
                if view.channel_type == 'modulation':
                    scope_info = self.engine.mod_scope_data.get(view.name)
                    if scope_info:
                        view.update_scope(*scope_info)
        
    def _update_local_var(self, ch_name, var_name, value):
        for view in self.channel_views:
            if view.name == ch_name and var_name in view.vars:
                view.vars[var_name].set(value)

    def on_closing(self):
        try:
            if self.engine.running:
                self.engine.stop()
        except Exception:
            log_exc('on_closing')
        finally:
            self.destroy()

    def toggle_channel_lock(self, channel_name):
        for view in self.channel_views:
            if view.name == channel_name:
                self.after(0, view.toggle_lock_state)
                break

    def flash_master_led(self, is_downbeat=False):
        color = MEM_PLAY_BORDER if is_downbeat else LED_ON
        def _flash_safe():
            try:
                self.master_led_canvas.itemconfig(self.master_led_circle, fill=color)
                self.after(50, lambda: self.master_led_canvas.itemconfig(self.master_led_circle, fill=LED_OFF))
            except Exception: pass
        self.after(0, _flash_safe)

    def get_all_settings(self):
        current_state = self.engine.cached_settings if self.engine.cached_settings else {}
        try: t = max(1, int(self.tempo_var.get()))
        except Exception: t = current_state.get('tempo', 115)
        
        try: ph = max(1, int(self.phrase_var.get()))
        except Exception: ph = current_state.get('master_phrase', 16)
        
        try: ent = int(self.entropy_var.get())
        except Exception: ent = current_state.get('entropy', 0)

        settings = {
            'tempo': t, 
            'sync_mode': self.sync_var.get(), 
            'master_phrase': ph, 
            'root_note': self.root_var.get(), 
            'global_scale': self.scale_var.get(), 
            'progression': [v.get() for v in self.prog_vars], 
            'prog_rate': self.prate_var.get(), 
            'entropy': ent, 
            'half_time': self.half_time_var.get(), 
            'root_motion': self.motion_var.get() if hasattr(self, 'motion_var') else "Linear Loop (1->2->3->4)",
            'distro': self.distro_var.get() if hasattr(self, 'distro_var') else "Boltzmann (Organic)",
            'channels': {}
        }
        for view in self.channel_views: 
            ch_cache = current_state.get('channels', {}).get(view.name, None)
            settings['channels'][view.name] = view.get_settings(ch_cache)
        return settings

    def save_state(self):
        filepath = filedialog.asksaveasfilename(defaultextension=".json", initialfile="mauve_zone_state.json", title="Save Engine Memory", filetypes=(("JSON Configurations", "*.json"), ("All Files", "*.*")))
        if not filepath: return
        try:
            data = self.get_all_settings()
            data['memory_slots'] = self.engine.memory_slots
            tmp = filepath + ".tmp"
            with open(tmp, 'w') as f: json.dump(data, f, indent=4)
            os.replace(tmp, filepath)      # never leave a half-written save behind
            self.flash_master_led()
        except Exception as e:
            log_exc('save_state', 0)
            messagebox.showerror("Save Failed", f"Could not save the state:\n{e}")

    def load_state(self):
        filepath = filedialog.askopenfilename(title="Recall Engine Memory", filetypes=(("JSON Configurations", "*.json"), ("All Files", "*.*")))
        if not filepath: return
        try:
            with open(filepath, 'r') as f: state = json.load(f)
            
            # --- PHASE 1: DRY RUN VALIDATION (All or Nothing) ---
            if not isinstance(state, dict): 
                raise ValueError("Save file is not a valid JSON dictionary.")
                
            validated_mem = {}
            if 'memory_slots' in state:
                for ch_name, slots in state['memory_slots'].items():
                    if not isinstance(slots, dict): 
                        raise ValueError(f"Memory structure for {ch_name} is corrupt.")
                    validated_mem[ch_name] = {}
                    for k, v in slots.items():
                        try: slot_idx = int(k)
                        except ValueError: continue
                        
                        # Strictly reject injected out-of-bounds ghost slots
                        if not (1 <= slot_idx <= 10): 
                            continue 
                            
                        # Validate exact buffer array architecture
                        if v is not None and not self._valid_mem_slot(v):
                            raise ValueError(f"Memory slot M{slot_idx} on {ch_name} is corrupted or mathematically incompatible.")
                        validated_mem[ch_name][slot_idx] = v

            # --- PHASE 2: ATOMIC HOT-SWAP ---
            # (Execution only reaches here if the entire JSON is structurally flawless)
            
            if 'tempo' in state: self.tempo_var.set(state['tempo'])
            if 'sync_mode' in state: self.sync_var.set(state['sync_mode'])
            if 'master_phrase' in state: self.phrase_var.set(state['master_phrase'])
            if 'root_note' in state: self.root_var.set(state['root_note'])
            if 'global_scale' in state: self.scale_var.set(state['global_scale'])
            if 'progression' in state:
                for i, val in enumerate(state['progression']):
                    if i < len(self.prog_vars): self.prog_vars[i].set(val)
            if 'prog_rate' in state: self.prate_var.set(state['prog_rate'])
            if 'entropy' in state: self.entropy_var.set(state['entropy'])
            if 'half_time' in state: self.half_time_var.set(state['half_time'])
            if 'root_motion' in state and hasattr(self, 'motion_var'):
                self.motion_var.set(state['root_motion'])
            if 'distro' in state and hasattr(self, 'distro_var'):
                self.distro_var.set(state['distro'])
            
            if 'channels' in state:
                for view in self.channel_views:
                    if view.name in state['channels']: 
                        view.set_settings(state['channels'][view.name])
            
            # Purge all live memory slots to prevent ghost residue from the previous session
            for ch in self.engine.memory_slots:
                for i in range(1, 11):
                    self.engine.memory_slots[ch][i] = None
                    for view in self.channel_views:
                        if view.name == ch: view.update_mem_btn_color(i, False)
            
            # Inject the strictly validated memory
            for ch_name, slots in validated_mem.items():
                if ch_name in self.engine.memory_slots:
                    for slot_idx, v in slots.items():
                        self.engine.memory_slots[ch_name][slot_idx] = v
                        for view in self.channel_views:
                            if view.name == ch_name:
                                view.update_mem_btn_color(slot_idx, v is not None, v)
                                
            self.flash_master_led()
            
        except Exception as e:
            log_exc('load_state', 0)
            messagebox.showerror("Load Failed", f"The engine rejected this file. It may be corrupt or from an incompatible older version.\n\nYour live session was not altered.\n\nError: {e}")

    def init_state(self):
        """Factory Master Reset: Restores all 25 channels, probability matrices, scales,
        chord progression arrays, and memory slots back to clean initial startup state."""
        confirm = messagebox.askyesno(
            "Initialize Composer",
            "Are you sure you want to initialize the entire composer back to factory startup settings?\n\nThis will clear all channel sequences, probability weights, scales, and memory slots M1-M10.",
            parent=self
        )
        if not confirm:
            return

        # 1. Gracefully halt transport if running
        if self.engine.running:
            self.toggle_sequencer()

        # 2. Restore global variables from initial state capture
        if hasattr(self, '_initial_state') and self._initial_state:
            state = copy.deepcopy(self._initial_state)

            if 'tempo' in state: self.tempo_var.set(state['tempo'])
            if 'sync_mode' in state: self.sync_var.set(state['sync_mode'])
            if 'master_phrase' in state: self.phrase_var.set(state['master_phrase'])
            if 'root_note' in state: self.root_var.set(state['root_note'])
            if 'global_scale' in state: self.scale_var.set(state['global_scale'])
            if 'progression' in state:
                for i, val in enumerate(state['progression']):
                    if i < len(self.prog_vars): self.prog_vars[i].set(val)
            if 'prog_rate' in state: self.prate_var.set(state['prog_rate'])
            if 'entropy' in state: self.entropy_var.set(state['entropy'])
            if 'half_time' in state: self.half_time_var.set(state['half_time'])
            if hasattr(self, 'recipe_var'): self.recipe_var.set("Custom / Manual")
            if hasattr(self, 'motion_var'): self.motion_var.set("Linear Loop (1->2->3->4)")
            if hasattr(self, 'distro_var'): self.distro_var.set("Boltzmann (Organic)")

            # 3. Restore all 25 channel views to factory state
            if 'channels' in state:
                for view in self.channel_views:
                    if view.name in state['channels']:
                        view.set_settings(state['channels'][view.name])

        # 4. Clear all memory slots M1-M10 across all channels
        for ch in self.engine.memory_slots:
            for i in range(1, 11):
                self.engine.memory_slots[ch][i] = None
                for view in self.channel_views:
                    if view.name == ch:
                        view.update_mem_btn_color(i, False)

        # 5. Reset internal engine transport buffers & state
        self.engine._reset_transport_state()

        # 6. Visual confirmation feedback
        self.flash_master_led()
        if hasattr(self, 'init_btn'):
            orig_bg = self.init_btn.cget('bg')
            orig_fg = self.init_btn.cget('fg')
            self.init_btn.config(text="INITIALIZED!", bg="#4a734a", fg="#ffffff")
            self.after(1000, lambda: self.init_btn.config(text="INIT", bg=orig_bg, fg=orig_fg))

    @staticmethod
    def _valid_mem_slot(v):
        """A recalled phrase that is malformed would raise on every tick, so reject it at load time."""
        try:
            if not isinstance(v, dict) or not 1 <= int(v.get('lock_len')) <= 64: return False
            int(v.get('start_tick', 0))
            buf = v.get('buffer')
            if not isinstance(buf, list) or len(buf) != 384: return False
            for e in buf:
                if e is None: continue
                float(e['base_note']); float(e['vel'])
                for p in e['phrase']:
                    float(p['note_offset']); float(p['start_offset']); float(p['dur']); float(p['vel_mod'])
            return True
        except Exception:
            return False

    def toggle_sequencer(self):
        if not self.engine.running:
            self.engine.start(self.port_var.get(), self.inport_var.get())
            if not self.engine.running:
                messagebox.showerror("MIDI Output", self.engine.last_error or "Could not open the MIDI output port. Check PORT OUT.")
                return
            self.start_btn.config(text="HALT", bg=SEPIA_ACTIVE, fg=LED_OFF)
            self._update_midi_chan_editable_state(False)
        else:
            self.engine.stop()
            self.start_btn.config(text="ENGAGE", bg=ACCENT_BRUISED, fg=FG_COLOR)
            self._update_midi_chan_editable_state(True)

if __name__ == "__main__":
    if sys.platform == 'win32':
        try:
            import ctypes
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(f"MauveZone.StochasticComposer.v{APP_VERSION}")
        except Exception:
            pass
    app = Application()
    app.mainloop()
