; =====================================================================
; BEJEWELED - Mark Fischer Kinetic KINETIC OP-ART EDITION (FullHD 1920x1080 PureBasic Engine)
; VERSION 007 - SYMMETRIC MUSEUM WALL FRAMING FIX (100% VISIBLE BOTTOM FRAME):
; - Built strictly on top of BEJEWELED_006.pb (100% PureBasic 6.41 & Debugger safe).
; - GALLERY FRAME & PURE WALL ART GEOMETRY FIX:
;   * Root Cause in v006: #TargetArenaPx = 984 produced up to 984x984 canvas + 76px
;     Passepartout + 24px signature margin + 16px outer frame = 1100px total height
;     (ending at y = 1102..1106, cutting off the entire bottom frame below 1080px!).
;   * Fix in v007: Recalibrated #TargetArenaPx = 880 (80x80 = 80 * 11px = 880x880 crisp
;     odd-centered cells!) and centered the COMPLETE framed artwork (including top/bottom
;     collector frame, taller French-style signature Passepartout, and 3D gallery shadow)
;     vertically on the 1920x1080 wall -> generous 46px museum wall above the top frame
;     AND 52px museum wall below the bottom frame (42px below the wall shadow) at ALL
;     matrix sizes from 8x8 to 80x80!
; - Mark Fischer Kinetic OP-ART METAMORPHOSIS ("Planetary Folklore" & "Vega" Series):
;   * Museum-grade framed artwork architecture: Passepartout gallery frame,
;     kinetic chromatic canvas, signed exhibition plaque ("M. FISCHER 007/2026"),
;     and live optical magnifying Loupe in the right gallery panel for fine 80x80 inspection!
;   * Every cell is an authentic Mark Fischer Kinetic "Unite Plastique" (colored geometric square
;     housing a contrasting precision inner form: Concentric Disc, Vega Sphere-Illusion,
;     Kinetic Lozenge, Tilted Axonometric Cube, Nested Bauhaus Square, Polar Cross,
;     Dual-Hemisphere Yin-Orb, and Rotating Zebra Op-Art Singularity).
; - DYNAMIC SCALING UP TO 80x80 (6,400 OP-ART UNITS!):
;   * Seamless scaling from 8x8 up to 80x80 (presets 8, 16, 32, 64, 80, -/+2, Mouse Wheel).
;   * Gallery Wall Art Mode ("PURE ARTWORK" / Right-Click): Hides side placards so the
;     complete framed Mark Fischer Kinetic painting hangs centered with full frame & shadow on the wall!
; =====================================================================

EnableExplicit

#MinGridN = 8
#MaxGridN = 80
#TargetArenaPx   = 880 ; Max 880x880 canvas -> full frame + signature + shadow fits 1080p with ~46px wall margins!
#FramePadPx      = 32  ; Archival Passepartout width (left, right, top)
#FrameSigExtraPx = 22  ; Extra bottom Passepartout height for pencil signature (bottom mat = 54px)
#FrameRimPx      = 8   ; Collector outer frame thickness (all 4 sides)
#FrameShadowPx   = 10  ; 3D gallery wall drop shadow offset

; Gem Types (1..7 Mark Fischer Kinetic Unites Plastiques, 8 = Zebra Kinetic Hypercube)
#Gem_None      = 0
#Gem_Cobalt    = 1 ; Ultramarine / Cyan Concentric Vega Disc
#Gem_Emerald   = 2 ; Viridian / Chartreuse Nested Bauhaus Square
#Gem_Crimson   = 3 ; Vermilion / Magenta Kinetic Lozenge (Diamond)
#Gem_Ochre     = 4 ; Cadmium Gold / Warm Ivory Tilted Op-Cube
#Gem_Violet    = 5 ; Deep Violet / Lilac Offset Optical Sphere
#Gem_Orange    = 6 ; Tangier Orange / Turquoise Axial Cross
#Gem_Silver    = 7 ; Graphite / Pearl Split-Hemisphere Op-Disc
#Gem_Hypercube = 8 ; Black & White Zebra Op-Art Singularity

; Special Modifiers
#Spec_None  = 0
#Spec_Flame = 1 ; 4-match creates Kinetic Pulse Unit (3x3 chromatic wave on match)

; Engine States
#State_Idle       = 0
#State_SwapAnim   = 1
#State_RevertAnim = 2
#State_ClearAnim  = 3
#State_FallAnim   = 4

Structure Cell
  gem.i
  spec.i
  yOffset.f
  marked.i
  spawnSpec.i
  spawnGem.i
EndStructure

Structure Spark
  active.i
  x.f
  y.f
  vx.f
  vy.f
  life.f
  col.i
  size.f
EndStructure

Structure UIButton
  x.i
  y.i
  w.i
  h.i
  label.s
  sub.s
EndStructure

Global GridN.i = 8
Global CellPx.i = 110
Global BoardPx.i = 880
Global BoardX.i = 520
Global BoardY.i = 86

Global Dim Grid.Cell(#MaxGridN - 1, #MaxGridN - 1)
Global Dim Sparks.Spark(767)

; Gallery UI Controls
Global BtnMinus.UIButton
Global BtnPlus.UIButton
Global BtnP8.UIButton
Global BtnP16.UIButton
Global BtnP32.UIButton
Global BtnP64.UIButton
Global BtnP80.UIButton

Global BtnAuto.UIButton
Global BtnSpeed.UIButton
Global BtnHint.UIButton
Global BtnTheme.UIButton
Global BtnPalette.UIButton
Global BtnPureArt.UIButton
Global BtnReset.UIButton
Global BtnExit.UIButton

; Gallery Aesthetic State
Global DarkGallery.i = #False ; #False = Museum Warm Alabaster Wall, #True = Obsidian Night Exhibition
Global VegaPalette.i = 0      ; 0 = Planetary Folklore (Vibrant Pop), 1 = Vega Or-Bleu, 2 = Zebra Monochrome + Red
Global PureArtMode.i = #False ; Hides side consoles -> pure framed wall painting!

; Colors updated by ApplyGalleryTheme()
Global Col_WallBg.i
Global Col_WallSubtle.i
Global Col_FrameOuter.i
Global Col_FrameInner.i
Global Col_Passepartout.i
Global Col_CardBg.i
Global Col_CardBorder.i
Global Col_InkPrimary.i
Global Col_InkMuted.i
Global Col_AccentA.i
Global Col_AccentB.i
Global Col_CanvasGroove.i

Global GameState.i = #State_Idle
Global AutoPlay.i = #False
Global TurboAI.i = #False

Global Score.q = 0
Global BestScore.q = 0
Global Level.i = 1
Global LevelProg.q = 0
Global LevelTarget.q = 1500
Global ComboChain.i = 0
Global BestCombo.i = 0
Global TotalMoves.q = 0
Global Shuffles.i = 0

; Selection & Swap State
Global SelX.i = -1, SelY.i = -1
Global HoverGX.i = -1, HoverGY.i = -1
Global DragStartX.i = -1, DragStartY.i = -1
Global DragActive.i = #False
Global PrevMouseLeft.i = #False
Global PrevMouseRight.i = #False

Global SwapX1.i, SwapY1.i, SwapX2.i, SwapY2.i
Global SwapProgress.f = 0.0
Global ClearProgress.f = 0.0
Global HyperTargetColor.i = 0

; Hint & AI State
Global HintX1.i = -1, HintY1.i = -1, HintX2.i = -1, HintY2.i = -1
Global HintVisible.i = #False
Global NextAIMoveTime.q = 0
Global StatusBanner.s = "UNITE PLASTIQUE READY"
Global StatusTimer.q = 0

; Main Loop Runtime Variables (No Protected in main scope!)
Global MainLastTick.q = 0
Global MainNow.q = 0
Global MainDt.f = 0.0
Global MainMX.i = 0, MainMY.i = 0, MainWheel.i = 0
Global MainLeftDown.i = 0, MainLeftJustPressed.i = 0, MainLeftJustReleased.i = 0
Global MainRightDown.i = 0, MainRightJustPressed.i = 0
Global MainAiX1.i = 0, MainAiY1.i = 0, MainAiX2.i = 0, MainAiY2.i = 0
Global MainLoopX.i = 0, MainLoopY.i = 0

; =====================================================================
; COMPLETE FORWARD DECLARATIONS (100% SINGLE-PASS PUREBASIC 6.41 SAFE)
; =====================================================================
Declare SafeCircle(x.i, y.i, r.i, col.i)
Declare SafeBox(x.i, y.i, w.i, h.i, col.i)
Declare SafeRoundBox(x.i, y.i, w.i, h.i, rx.i, ry.i, col.i)
Declare.i ClampByte(v.i)
Declare.i ShadeColor(col.i, delta.i)
Declare ApplyGalleryTheme()
Declare InitButtons()
Declare RecalcBoardMetrics(newGridN.i)
Declare.i GemBaseColor(gem.i)
Declare.i GemInnerColor(gem.i)
Declare.i GemCoreColor(gem.i)
Declare SpawnBurst(px.f, py.f, col.i, count.i)
Declare UpdateAndDrawSparks()
Declare SwapCellsData(x1.i, y1.i, x2.i, y2.i)
Declare.i RunHorizontalAt(x.i, y.i)
Declare.i RunVerticalAt(x.i, y.i)
Declare.i CheckLocalMatchAt(x.i, y.i)
Declare.i CheckAnyMatchExists()
Declare.i EvaluateLocalSwapWeight(x1.i, y1.i, x2.i, y2.i)
Declare.i FindBestValidMove(*outX1.Integer, *outY1.Integer, *outX2.Integer, *outY2.Integer)
Declare InitBoardNoMatches()
Declare ReshuffleBoard()
Declare Trigger3x3Blast(cx.i, cy.i)
Declare.i MarkAllMatches(pivotX1.i, pivotY1.i, pivotX2.i, pivotY2.i)
Declare ResolveMarkedGems()
Declare.i UpdateFallingGems(dt.f)
Declare StartSwap(x1.i, y1.i, x2.i, y2.i)
Declare.i PointInButton(*b.UIButton, mx.i, my.i)
Declare HandleMouseInput(mx.i, my.i, wheel.i, leftDown.i, leftJustPressed.i, leftJustReleased.i, rightJustPressed.i)
Declare DrawGalleryPlaque(x.i, y.i, w.i, h.i, TitleTxt.s, SubTxt.s)
Declare DrawGalleryButton(*b.UIButton, mx.i, my.i, isActive.i)
Declare DrawMiniButton(*b.UIButton, mx.i, my.i, isActive.i)
Declare DrawMark Fischer KineticUnit(cx.i, cy.i, unitSize.i, gem.i, spec.i, vegaBias.i)
Declare DrawOpticalLoupe(panelX.i, panelY.i, panelW.i)
Declare DrawGalleryCursor(mx.i, my.i)
Declare RenderFrame(mx.i, my.i)

; =====================================================================
; DEBUGGER-PROOF 2D GEOMETRY WRAPPERS (ZERO NEGATIVE RADII OR SIZES!)
; =====================================================================
Procedure SafeCircle(x.i, y.i, r.i, col.i)
  If r >= 1
    Circle(x, y, r, col)
  EndIf
EndProcedure

Procedure SafeBox(x.i, y.i, w.i, h.i, col.i)
  If w >= 1 And h >= 1
    Box(x, y, w, h, col)
  EndIf
EndProcedure

Procedure SafeRoundBox(x.i, y.i, w.i, h.i, rx.i, ry.i, col.i)
  If w >= 2 And h >= 2
    Protected crx.i = rx
    Protected cry.i = ry
    If crx < 0 : crx = 0 : EndIf
    If cry < 0 : cry = 0 : EndIf
    If crx > w / 2 : crx = w / 2 : EndIf
    If cry > h / 2 : cry = h / 2 : EndIf
    RoundBox(x, y, w, h, crx, cry, col)
  ElseIf w >= 1 And h >= 1
    Box(x, y, w, h, col)
  EndIf
EndProcedure

Procedure.i ClampByte(v.i)
  If v < 0 : ProcedureReturn 0 : EndIf
  If v > 255 : ProcedureReturn 255 : EndIf
  ProcedureReturn v
EndProcedure

Procedure.i ShadeColor(col.i, delta.i)
  ProcedureReturn RGB(ClampByte(Red(col) + delta), ClampByte(Green(col) + delta), ClampByte(Blue(col) + delta))
EndProcedure

Procedure ApplyGalleryTheme()
  If DarkGallery
    ; Exhibition Obsidian Night Room
    Col_WallBg       = RGB(14, 15, 18)
    Col_WallSubtle   = RGB(22, 24, 29)
    Col_FrameOuter   = RGB(235, 232, 224)
    Col_FrameInner   = RGB(52, 54, 60)
    Col_Passepartout = RGB(24, 25, 30)
    Col_CardBg       = RGB(20, 22, 27)
    Col_CardBorder   = RGB(64, 68, 78)
    Col_InkPrimary   = RGB(242, 240, 234)
    Col_InkMuted     = RGB(148, 152, 162)
    Col_AccentA      = RGB(0, 175, 240)
    Col_AccentB      = RGB(245, 185, 35)
    Col_CanvasGroove = RGB(10, 10, 14)
  Else
    ; Museum Denise Rene / Bauhaus Alabaster White Gallery Wall
    Col_WallBg       = RGB(242, 239, 232)
    Col_WallSubtle   = RGB(230, 226, 217)
    Col_FrameOuter   = RGB(22, 22, 24)
    Col_FrameInner   = RGB(195, 190, 180)
    Col_Passepartout = RGB(250, 248, 243)
    Col_CardBg       = RGB(248, 246, 240)
    Col_CardBorder   = RGB(196, 191, 180)
    Col_InkPrimary   = RGB(20, 20, 24)
    Col_InkMuted     = RGB(105, 102, 96)
    Col_AccentA      = RGB(18, 70, 195)
    Col_AccentB      = RGB(215, 52, 38)
    Col_CanvasGroove = RGB(18, 18, 22)
  EndIf
EndProcedure

Procedure InitButtons()
  ; Grid Scaling Controls (8x8 .. 80x80)
  BtnMinus\x = 46 : BtnMinus\y = 228 : BtnMinus\w = 78 : BtnMinus\h = 44
  BtnMinus\label = "- 2" : BtnMinus\sub = ""

  BtnPlus\x = 316 : BtnPlus\y = 228 : BtnPlus\w = 78 : BtnPlus\h = 44
  BtnPlus\label = "+ 2" : BtnPlus\sub = ""

  BtnP8\x  = 46  : BtnP8\y  = 282 : BtnP8\w  = 64 : BtnP8\h  = 36 : BtnP8\label  = "8"
  BtnP16\x = 117 : BtnP16\y = 282 : BtnP16\w = 64 : BtnP16\h = 36 : BtnP16\label = "16"
  BtnP32\x = 188 : BtnP32\y = 282 : BtnP32\w = 64 : BtnP32\h = 36 : BtnP32\label = "32"
  BtnP64\x = 259 : BtnP64\y = 282 : BtnP64\w = 64 : BtnP64\h = 36 : BtnP64\label = "64"
  BtnP80\x = 330 : BtnP80\y = 282 : BtnP80\w = 64 : BtnP80\h = 36 : BtnP80\label = "80"

  ; Artistic & Kinetic Modules
  BtnAuto\x = 46 : BtnAuto\y = 354 : BtnAuto\w = 348 : BtnAuto\h = 64
  BtnAuto\label = "KINETIC AUTOPILOT"
  BtnAuto\sub = "AUTONOMOUS OP-ART CHOREOGRAPHY"

  BtnSpeed\x = 46 : BtnSpeed\y = 428 : BtnSpeed\w = 348 : BtnSpeed\h = 60
  BtnSpeed\label = "HIGH-FREQUENCY PULSE"
  BtnSpeed\sub = "ACCELERATE KINETIC METAMORPHOSIS"

  BtnHint\x = 46 : BtnHint\y = 498 : BtnHint\w = 348 : BtnHint\h = 60
  BtnHint\label = "OPTICAL VECTOR HINT"
  BtnHint\sub = "HIGHLIGHT HARMONIC TRANSITION"

  BtnPalette\x = 46 : BtnPalette\y = 592 : BtnPalette\w = 348 : BtnPalette\h = 60
  BtnPalette\label = "CHROMATIC SERIES"
  BtnPalette\sub = "FOLKLORE / VEGA BLEU / ZEBRA"

  BtnTheme\x = 46 : BtnTheme\y = 662 : BtnTheme\w = 348 : BtnTheme\h = 60
  BtnTheme\label = "GALLERY LIGHTING"
  BtnTheme\sub = "ALABASTER MUSEUM / OBSIDIAN NIGHT"

  BtnPureArt\x = 46 : BtnPureArt\y = 732 : BtnPureArt\w = 348 : BtnPureArt\h = 60
  BtnPureArt\label = "PURE WALL ART [R-CLICK]"
  BtnPureArt\sub = "HIDE CONSOLES - PURE FRAMED CANVAS"

  BtnReset\x = 46 : BtnReset\y = 824 : BtnReset\w = 348 : BtnReset\h = 60
  BtnReset\label = "NEW COMPOSITION"
  BtnReset\sub = "GENERATE FRESH Mark Fischer Kinetic MATRIX"

  BtnExit\x = 46 : BtnExit\y = 954 : BtnExit\w = 348 : BtnExit\h = 56
  BtnExit\label = "LEAVE GALLERY [ESC]"
  BtnExit\sub = "EXIT EXHIBITION"
EndProcedure

Procedure RecalcBoardMetrics(newGridN.i)
  If newGridN < #MinGridN : newGridN = #MinGridN : EndIf
  If newGridN > #MaxGridN : newGridN = #MaxGridN : EndIf

  GridN = newGridN
  CellPx = #TargetArenaPx / GridN
  If CellPx < 11 : CellPx = 11 : EndIf ; At 80x80: 880 / 80 = 11px -> 880x880 crisp odd-centered grid!
  BoardPx = GridN * CellPx

  ; Center the COMPLETE framed artwork (including top/bottom frame rim, taller bottom signature
  ; Passepartout, and half the 3D gallery shadow) symmetrically inside 1920x1080!
  Protected totalOuterH.i = BoardPx + (#FramePadPx * 2) + #FrameSigExtraPx + (#FrameRimPx * 2)
  Protected outerTopY.i = (1080 - totalOuterH - (#FrameShadowPx / 2)) / 2

  BoardX = (1920 - BoardPx) / 2
  BoardY = outerTopY + #FrameRimPx + #FramePadPx

  Score = 0 : Level = 1 : LevelProg = 0 : LevelTarget = 1500
  ComboChain = 0 : TotalMoves = 0 : Shuffles = 0
  SelX = -1 : SelY = -1 : HintVisible = #False : DragActive = #False

  StatusBanner = "MATRIX SCALED TO " + Str(GridN) + "x" + Str(GridN) + " (" + Str(CellPx) + "PX)"
  StatusTimer = ElapsedMilliseconds() + 2200
  InitBoardNoMatches()
EndProcedure

; =====================================================================
; Mark Fischer Kinetic AUTHENTIC CHROMATIC PALETTES
; Series 0: "Planetary Folklore" (1964) - High-Contrast Pop Polychrome
; Series 1: "Vega Or / Bleu" (1969) - Deep Cobalt, Turquoise, Gold, Violet
; Series 2: "Zebra / Tekla" (1958) - Graphic Black/Ivory/Silver + Bauhaus Primary
; =====================================================================
Procedure.i GemBaseColor(gem.i)
  Select VegaPalette
    Case 0 ; Planetary Folklore (Vibrant Geometric Pop-Art)
      Select gem
        Case #Gem_Cobalt    : ProcedureReturn RGB(14, 76, 198)   ; Mark Fischer Kinetic Ultramarine
        Case #Gem_Emerald   : ProcedureReturn RGB(0, 158, 96)    ; Kinetic Viridian
        Case #Gem_Crimson   : ProcedureReturn RGB(222, 34, 48)   ; Cadmium Scarlet
        Case #Gem_Ochre     : ProcedureReturn RGB(242, 182, 18)  ; Folklore Ochre Gold
        Case #Gem_Violet    : ProcedureReturn RGB(112, 38, 178)  ; Deep Dioxazine Violet
        Case #Gem_Orange    : ProcedureReturn RGB(238, 98, 20)   ; Vermilion Orange
        Case #Gem_Silver    : ProcedureReturn RGB(44, 52, 64)    ; Graphic Anthracite
        Case #Gem_Hypercube : ProcedureReturn RGB(16, 16, 20)    ; Zebra Singularity
      EndSelect

    Case 1 ; Vega Or & Bleu (Hypnotic Spatial Op-Art)
      Select gem
        Case #Gem_Cobalt    : ProcedureReturn RGB(10, 48, 156)
        Case #Gem_Emerald   : ProcedureReturn RGB(0, 146, 152)
        Case #Gem_Crimson   : ProcedureReturn RGB(196, 28, 84)
        Case #Gem_Ochre     : ProcedureReturn RGB(236, 174, 24)
        Case #Gem_Violet    : ProcedureReturn RGB(78, 34, 150)
        Case #Gem_Orange    : ProcedureReturn RGB(218, 112, 28)
        Case #Gem_Silver    : ProcedureReturn RGB(62, 82, 108)
        Case #Gem_Hypercube : ProcedureReturn RGB(15, 15, 20)
      EndSelect

    Case 2 ; Bauhaus / Zebra Constructivist Edition
      Select gem
        Case #Gem_Cobalt    : ProcedureReturn RGB(20, 64, 172)
        Case #Gem_Emerald   : ProcedureReturn RGB(36, 38, 42)
        Case #Gem_Crimson   : ProcedureReturn RGB(214, 32, 38)
        Case #Gem_Ochre     : ProcedureReturn RGB(238, 190, 22)
        Case #Gem_Violet    : ProcedureReturn RGB(92, 96, 106)
        Case #Gem_Orange    : ProcedureReturn RGB(215, 210, 198)
        Case #Gem_Silver    : ProcedureReturn RGB(148, 152, 160)
        Case #Gem_Hypercube : ProcedureReturn RGB(10, 10, 12)
      EndSelect
  EndSelect
  ProcedureReturn RGB(128, 128, 128)
EndProcedure

Procedure.i GemInnerColor(gem.i)
  Select VegaPalette
    Case 0 ; Contrasting Mark Fischer Kinetic Inner Form Colors (Simultaneous Contrast!)
      Select gem
        Case #Gem_Cobalt    : ProcedureReturn RGB(0, 210, 250)   ; Luminous Cyan inside Ultramarine
        Case #Gem_Emerald   : ProcedureReturn RGB(172, 238, 44)  ; Chartreuse inside Viridian
        Case #Gem_Crimson   : ProcedureReturn RGB(255, 126, 186) ; Pop Rose-Magenta inside Scarlet
        Case #Gem_Ochre     : ProcedureReturn RGB(255, 244, 190) ; Warm Ivory inside Gold
        Case #Gem_Violet    : ProcedureReturn RGB(208, 132, 255) ; Electric Lilac inside Violet
        Case #Gem_Orange    : ProcedureReturn RGB(255, 214, 48)  ; Solar Yellow inside Orange
        Case #Gem_Silver    : ProcedureReturn RGB(236, 238, 242) ; Pure Gallery White inside Anthracite
        Case #Gem_Hypercube : ProcedureReturn RGB(248, 248, 248)
      EndSelect

    Case 1
      Select gem
        Case #Gem_Cobalt    : ProcedureReturn RGB(76, 188, 255)
        Case #Gem_Emerald   : ProcedureReturn RGB(130, 242, 222)
        Case #Gem_Crimson   : ProcedureReturn RGB(255, 138, 168)
        Case #Gem_Ochre     : ProcedureReturn RGB(255, 238, 156)
        Case #Gem_Violet    : ProcedureReturn RGB(186, 142, 255)
        Case #Gem_Orange    : ProcedureReturn RGB(255, 210, 96)
        Case #Gem_Silver    : ProcedureReturn RGB(224, 236, 248)
        Case #Gem_Hypercube : ProcedureReturn RGB(250, 250, 250)
      EndSelect

    Case 2
      Select gem
        Case #Gem_Cobalt    : ProcedureReturn RGB(242, 240, 232)
        Case #Gem_Emerald   : ProcedureReturn RGB(242, 240, 232)
        Case #Gem_Crimson   : ProcedureReturn RGB(22, 22, 26)
        Case #Gem_Ochre     : ProcedureReturn RGB(22, 22, 26)
        Case #Gem_Violet    : ProcedureReturn RGB(238, 190, 22)
        Case #Gem_Orange    : ProcedureReturn RGB(20, 64, 172)
        Case #Gem_Silver    : ProcedureReturn RGB(214, 32, 38)
        Case #Gem_Hypercube : ProcedureReturn RGB(252, 252, 252)
      EndSelect
  EndSelect
  ProcedureReturn RGB(240, 240, 240)
EndProcedure

Procedure.i GemCoreColor(gem.i)
  Select gem
    Case #Gem_Cobalt    : ProcedureReturn RGB(235, 250, 255)
    Case #Gem_Emerald   : ProcedureReturn RGB(12, 62, 42)
    Case #Gem_Crimson   : ProcedureReturn RGB(88, 10, 28)
    Case #Gem_Ochre     : ProcedureReturn RGB(136, 62, 8)
    Case #Gem_Violet    : ProcedureReturn RGB(36, 12, 68)
    Case #Gem_Orange    : ProcedureReturn RGB(24, 86, 168)
    Case #Gem_Silver    : ProcedureReturn RGB(222, 42, 48) ; Bauhaus red focal dot!
    Case #Gem_Hypercube : ProcedureReturn RGB(255, 50, 60)
  EndSelect
  ProcedureReturn RGB(255, 255, 255)
EndProcedure

Procedure SpawnBurst(px.f, py.f, col.i, count.i)
  Protected i.i, k.i, ang.f, spd.f
  ; Scale spark count gracefully so 80x80 stays silky-smooth at 60 FPS
  If GridN >= 48 And count > 3 : count = 3 : ElseIf GridN >= 24 And count > 5 : count = 5 : EndIf
  For k = 1 To count
    For i = 0 To 767
      If Not Sparks(i)\active
        ang = Random(628) * 0.01
        spd = 1.5 + (Random(55) * 0.1)
        Sparks(i)\active = #True
        Sparks(i)\x = px
        Sparks(i)\y = py
        Sparks(i)\vx = Cos(ang) * spd
        Sparks(i)\vy = Sin(ang) * spd
        Sparks(i)\life = 1.0
        Sparks(i)\col = col
        Sparks(i)\size = 2.0 + Random(3)
        Break
      EndIf
    Next
  Next
EndProcedure

Procedure UpdateAndDrawSparks()
  Protected i.i, sz.i
  DrawingMode(#PB_2DDrawing_Default)
  For i = 0 To 767
    If Sparks(i)\active
      Sparks(i)\x + Sparks(i)\vx
      Sparks(i)\y + Sparks(i)\vy
      Sparks(i)\vy + 0.10
      Sparks(i)\life - 0.045
      If Sparks(i)\life <= 0.0
        Sparks(i)\active = #False
      Else
        sz = Int(Sparks(i)\size * Sparks(i)\life)
        If sz < 1 : sz = 1 : EndIf
        SafeBox(Int(Sparks(i)\x), Int(Sparks(i)\y), sz, sz, Sparks(i)\col)
      EndIf
    EndIf
  Next
EndProcedure

; =====================================================================
; HIGH-SPEED O(1) LOCAL & O(N^2) BOARD MATCH ENGINE (ZERO LAG AT 80x80!)
; =====================================================================
Procedure SwapCellsData(x1.i, y1.i, x2.i, y2.i)
  Protected tmpG.i = Grid(x1, y1)\gem
  Protected tmpS.i = Grid(x1, y1)\spec
  Grid(x1, y1)\gem = Grid(x2, y2)\gem
  Grid(x1, y1)\spec = Grid(x2, y2)\spec
  Grid(x2, y2)\gem = tmpG
  Grid(x2, y2)\spec = tmpS
EndProcedure

Procedure.i RunHorizontalAt(x.i, y.i)
  Protected g.i = Grid(x, y)\gem
  If g < 1 Or g > 7 : ProcedureReturn 0 : EndIf
  Protected cnt.i = 1, i.i
  i = x - 1
  While i >= 0 And Grid(i, y)\gem = g : cnt + 1 : i - 1 : Wend
  i = x + 1
  While i < GridN And Grid(i, y)\gem = g : cnt + 1 : i + 1 : Wend
  ProcedureReturn cnt
EndProcedure

Procedure.i RunVerticalAt(x.i, y.i)
  Protected g.i = Grid(x, y)\gem
  If g < 1 Or g > 7 : ProcedureReturn 0 : EndIf
  Protected cnt.i = 1, i.i
  i = y - 1
  While i >= 0 And Grid(x, i)\gem = g : cnt + 1 : i - 1 : Wend
  i = y + 1
  While i < GridN And Grid(x, i)\gem = g : cnt + 1 : i + 1 : Wend
  ProcedureReturn cnt
EndProcedure

Procedure.i CheckLocalMatchAt(x.i, y.i)
  If RunHorizontalAt(x, y) >= 3 Or RunVerticalAt(x, y) >= 3
    ProcedureReturn #True
  EndIf
  ProcedureReturn #False
EndProcedure

Procedure.i CheckAnyMatchExists()
  Protected x.i, y.i, g.i
  For y = 0 To GridN - 1
    For x = 0 To GridN - 3
      g = Grid(x, y)\gem
      If g >= 1 And g <= 7
        If Grid(x + 1, y)\gem = g And Grid(x + 2, y)\gem = g
          ProcedureReturn #True
        EndIf
      EndIf
    Next
  Next
  For x = 0 To GridN - 1
    For y = 0 To GridN - 3
      g = Grid(x, y)\gem
      If g >= 1 And g <= 7
        If Grid(x, y + 1)\gem = g And Grid(x, y + 2)\gem = g
          ProcedureReturn #True
        EndIf
      EndIf
    Next
  Next
  ProcedureReturn #False
EndProcedure

Procedure.i EvaluateLocalSwapWeight(x1.i, y1.i, x2.i, y2.i)
  Protected h1.i = RunHorizontalAt(x1, y1)
  Protected v1.i = RunVerticalAt(x1, y1)
  Protected h2.i = RunHorizontalAt(x2, y2)
  Protected v2.i = RunVerticalAt(x2, y2)
  Protected w.i = 0

  If h1 < 3 And v1 < 3 And h2 < 3 And v2 < 3
    ProcedureReturn 0
  EndIf

  w = 10 + (y1 + y2) * 2
  If h1 >= 3
    w + h1 * h1 * 10
    If h1 >= 5 : w + 320 : ElseIf h1 = 4 : w + 95 : EndIf
  EndIf
  If v1 >= 3
    w + v1 * v1 * 10
    If v1 >= 5 : w + 320 : ElseIf v1 = 4 : w + 95 : EndIf
  EndIf
  If h1 >= 3 And v1 >= 3 : w + 140 : EndIf

  If Not (Grid(x1, y1)\gem = Grid(x2, y2)\gem)
    If h2 >= 3
      w + h2 * h2 * 10
      If h2 >= 5 : w + 320 : ElseIf h2 = 4 : w + 95 : EndIf
    EndIf
    If v2 >= 3
      w + v2 * v2 * 10
      If v2 >= 5 : w + 320 : ElseIf v2 = 4 : w + 95 : EndIf
    EndIf
    If h2 >= 3 And v2 >= 3 : w + 140 : EndIf
  EndIf

  If Grid(x1, y1)\spec = #Spec_Flame Or Grid(x2, y2)\spec = #Spec_Flame
    w + 130
  EndIf

  ProcedureReturn w
EndProcedure

Procedure.i FindBestValidMove(*outX1.Integer, *outY1.Integer, *outX2.Integer, *outY2.Integer)
  Protected x.i, y.i, dir.i, nx.i, ny.i
  Protected bestWeight.i = -1
  Protected bestX1.i = -1, bestY1.i = -1, bestX2.i = -1, bestY2.i = -1
  Protected weight.i

  For y = 0 To GridN - 1
    For x = 0 To GridN - 1
      For dir = 0 To 1
        If dir = 0 : nx = x + 1 : ny = y : Else : nx = x : ny = y + 1 : EndIf
        If nx < GridN And ny < GridN
          If Grid(x, y)\gem = #Gem_Hypercube Or Grid(nx, ny)\gem = #Gem_Hypercube
            weight = 600 + y * 4
            If weight > bestWeight
              bestWeight = weight
              bestX1 = x : bestY1 = y : bestX2 = nx : bestY2 = ny
            EndIf
          ElseIf Grid(x, y)\gem <> Grid(nx, ny)\gem
            SwapCellsData(x, y, nx, ny)
            weight = EvaluateLocalSwapWeight(x, y, nx, ny)
            If weight > bestWeight
              bestWeight = weight
              bestX1 = x : bestY1 = y : bestX2 = nx : bestY2 = ny
            EndIf
            SwapCellsData(x, y, nx, ny)
          EndIf
        EndIf
      Next
    Next
  Next

  If bestWeight > 0
    *outX1\i = bestX1 : *outY1\i = bestY1
    *outX2\i = bestX2 : *outY2\i = bestY2
    ProcedureReturn #True
  EndIf
  ProcedureReturn #False
EndProcedure

Procedure InitBoardNoMatches()
  Protected x.i, y.i, g.i, d1.i, d2.i, d3.i, d4.i
  Protected dropStep.f = CellPx * 0.55
  If dropStep < 8.0 : dropStep = 8.0 : EndIf

  Repeat
    For y = 0 To GridN - 1
      For x = 0 To GridN - 1
        Repeat
          g = Random(6) + 1
        Until (x < 2 Or Not (Grid(x - 1, y)\gem = g And Grid(x - 2, y)\gem = g)) And
              (y < 2 Or Not (Grid(x, y - 1)\gem = g And Grid(x, y - 2)\gem = g))
        Grid(x, y)\gem = g
        Grid(x, y)\spec = #Spec_None
        Grid(x, y)\yOffset = -((GridN - y) * dropStep)
        If Grid(x, y)\yOffset < -520.0 : Grid(x, y)\yOffset = -520.0 : EndIf
        Grid(x, y)\marked = #False
        Grid(x, y)\spawnSpec = #Spec_None
        Grid(x, y)\spawnGem = #Gem_None
      Next
    Next
  Until FindBestValidMove(@d1, @d2, @d3, @d4)
  GameState = #State_FallAnim
EndProcedure

Procedure ReshuffleBoard()
  Protected x.i, y.i, rx.i, ry.i, d1.i, d2.i, d3.i, d4.i, tries.i = 0
  Shuffles + 1
  StatusBanner = "KINETIC PERMUTATION"
  StatusTimer = ElapsedMilliseconds() + 2000

  Repeat
    tries + 1
    For y = 0 To GridN - 1
      For x = 0 To GridN - 1
        rx = Random(GridN - 1)
        ry = Random(GridN - 1)
        If Grid(x, y)\gem <> #Gem_Hypercube And Grid(rx, ry)\gem <> #Gem_Hypercube
          SwapCellsData(x, y, rx, ry)
        EndIf
      Next
    Next
    If tries > 25
      InitBoardNoMatches()
      ProcedureReturn
    EndIf
  Until (Not CheckAnyMatchExists()) And FindBestValidMove(@d1, @d2, @d3, @d4)
EndProcedure

Procedure Trigger3x3Blast(cx.i, cy.i)
  Protected bx.i, by.i
  For by = cy - 1 To cy + 1
    For bx = cx - 1 To cx + 1
      If bx >= 0 And bx < GridN And by >= 0 And by < GridN
        If Grid(bx, by)\gem <> #Gem_None And Not Grid(bx, by)\marked
          Grid(bx, by)\marked = #True
          If Grid(bx, by)\spec = #Spec_Flame
            Grid(bx, by)\spec = #Spec_None
            Trigger3x3Blast(bx, by)
          EndIf
        EndIf
      EndIf
    Next
  Next
  SpawnBurst(BoardX + cx * CellPx + CellPx / 2, BoardY + cy * CellPx + CellPx / 2, Col_AccentB, 16)
EndProcedure

Procedure.i MarkAllMatches(pivotX1.i, pivotY1.i, pivotX2.i, pivotY2.i)
  Protected x.i, y.i, k.i, g.i, runLen.i, foundAny.i = #False
  Protected spawnX.i, spawnY.i

  For y = 0 To GridN - 1
    For x = 0 To GridN - 1
      Grid(x, y)\marked = #False
      Grid(x, y)\spawnSpec = #Spec_None
      Grid(x, y)\spawnGem = #Gem_None
    Next
  Next

  ; Horizontal Runs
  For y = 0 To GridN - 1
    x = 0
    While x < GridN
      g = Grid(x, y)\gem
      runLen = 1
      While x + runLen < GridN And Grid(x + runLen, y)\gem = g
        runLen + 1
      Wend
      If g >= 1 And g <= 7 And runLen >= 3
        foundAny = #True
        spawnX = x + runLen / 2 : spawnY = y
        For k = x To x + runLen - 1
          Grid(k, y)\marked = #True
          If (k = pivotX1 And y = pivotY1) Or (k = pivotX2 And y = pivotY2)
            spawnX = k : spawnY = y
          EndIf
        Next
        If runLen >= 5
          Grid(spawnX, spawnY)\spawnGem = #Gem_Hypercube
          Grid(spawnX, spawnY)\spawnSpec = #Spec_None
        ElseIf runLen = 4
          Grid(spawnX, spawnY)\spawnGem = g
          Grid(spawnX, spawnY)\spawnSpec = #Spec_Flame
        EndIf
      EndIf
      x + runLen
    Wend
  Next

  ; Vertical Runs
  For x = 0 To GridN - 1
    y = 0
    While y < GridN
      g = Grid(x, y)\gem
      runLen = 1
      While y + runLen < GridN And Grid(x, y + runLen)\gem = g
        runLen + 1
      Wend
      If g >= 1 And g <= 7 And runLen >= 3
        foundAny = #True
        spawnX = x : spawnY = y + runLen / 2
        For k = y To y + runLen - 1
          If Grid(x, k)\marked And Grid(x, k)\spawnGem = #Gem_None
            Grid(x, k)\spawnGem = g
            Grid(x, k)\spawnSpec = #Spec_Flame
          EndIf
          Grid(x, k)\marked = #True
          If (x = pivotX1 And k = pivotY1) Or (x = pivotX2 And k = pivotY2)
            spawnX = x : spawnY = k
          EndIf
        Next
        If runLen >= 5
          Grid(spawnX, spawnY)\spawnGem = #Gem_Hypercube
          Grid(spawnX, spawnY)\spawnSpec = #Spec_None
        ElseIf runLen = 4 And Grid(spawnX, spawnY)\spawnGem <> #Gem_Hypercube
          Grid(spawnX, spawnY)\spawnGem = g
          Grid(spawnX, spawnY)\spawnSpec = #Spec_Flame
        EndIf
      EndIf
      y + runLen
    Wend
  Next

  If foundAny
    For y = 0 To GridN - 1
      For x = 0 To GridN - 1
        If Grid(x, y)\marked And Grid(x, y)\spec = #Spec_Flame And Grid(x, y)\spawnSpec = #Spec_None
          Grid(x, y)\spec = #Spec_None
          Trigger3x3Blast(x, y)
        EndIf
      Next
    Next
  EndIf

  ProcedureReturn foundAny
EndProcedure

Procedure ResolveMarkedGems()
  Protected x.i, y.i, writeY.i, clearedCount.i = 0, pts.q, missing.i, i.i

  For y = 0 To GridN - 1
    For x = 0 To GridN - 1
      If Grid(x, y)\marked
        clearedCount + 1
        SpawnBurst(BoardX + x * CellPx + CellPx / 2, BoardY + y * CellPx + CellPx / 2, GemInnerColor(Grid(x, y)\gem), 6)
        If Grid(x, y)\spawnGem <> #Gem_None
          Grid(x, y)\gem = Grid(x, y)\spawnGem
          Grid(x, y)\spec = Grid(x, y)\spawnSpec
          Grid(x, y)\marked = #False
          Grid(x, y)\spawnGem = #Gem_None
          Grid(x, y)\spawnSpec = #Spec_None
        Else
          Grid(x, y)\gem = #Gem_None
          Grid(x, y)\spec = #Spec_None
          Grid(x, y)\marked = #False
        EndIf
      EndIf
    Next
  Next

  ComboChain + 1
  If ComboChain > BestCombo : BestCombo = ComboChain : EndIf
  pts = clearedCount * 50 * ComboChain * Level
  Score + pts
  If Score > BestScore : BestScore = Score : EndIf

  LevelProg + pts
  If LevelProg >= LevelTarget
    LevelProg - LevelTarget
    Level + 1
    LevelTarget = 1500 + (Level - 1) * 1100
    StatusBanner = "EDITION PHASE " + Str(Level)
    StatusTimer = ElapsedMilliseconds() + 2000
  ElseIf ComboChain >= 2
    StatusBanner = "KINETIC RESONANCE x" + Str(ComboChain)
    StatusTimer = ElapsedMilliseconds() + 1400
  EndIf

  ; Collapse columns downward & spawn new Mark Fischer Kinetic units
  For x = 0 To GridN - 1
    writeY = GridN - 1
    For y = GridN - 1 To 0 Step -1
      If Grid(x, y)\gem <> #Gem_None
        If writeY <> y
          Grid(x, writeY)\gem = Grid(x, y)\gem
          Grid(x, writeY)\spec = Grid(x, y)\spec
          Grid(x, writeY)\yOffset = -((writeY - y) * CellPx) + Grid(x, y)\yOffset
          Grid(x, y)\gem = #Gem_None
          Grid(x, y)\spec = #Spec_None
          Grid(x, y)\yOffset = 0.0
        EndIf
        writeY - 1
      EndIf
    Next

    missing = writeY + 1
    For i = 0 To writeY
      Grid(x, i)\gem = Random(6) + 1
      Grid(x, i)\spec = #Spec_None
      Grid(x, i)\yOffset = -((missing - i + 1) * CellPx)
      If Grid(x, i)\yOffset < -480.0 : Grid(x, i)\yOffset = -480.0 : EndIf
      Grid(x, i)\marked = #False
    Next
  Next

  GameState = #State_FallAnim
EndProcedure

Procedure.i UpdateFallingGems(dt.f)
  Protected x.i, y.i, stillFalling.i = #False
  Protected fallSpeed.f = 1350.0 * dt
  If TurboAI : fallSpeed * 2.8 : EndIf

  For y = 0 To GridN - 1
    For x = 0 To GridN - 1
      If Grid(x, y)\yOffset < 0.0
        Grid(x, y)\yOffset + fallSpeed
        If Grid(x, y)\yOffset >= 0.0
          Grid(x, y)\yOffset = 0.0
        Else
          stillFalling = #True
        EndIf
      EndIf
    Next
  Next
  ProcedureReturn stillFalling
EndProcedure

Procedure StartSwap(x1.i, y1.i, x2.i, y2.i)
  SwapX1 = x1 : SwapY1 = y1
  SwapX2 = x2 : SwapY2 = y2
  SwapProgress = 0.0
  SelX = -1 : SelY = -1
  HintVisible = #False
  ComboChain = 0
  SwapCellsData(x1, y1, x2, y2)
  GameState = #State_SwapAnim
EndProcedure

Procedure.i PointInButton(*b.UIButton, mx.i, my.i)
  If mx >= *b\x And mx <= (*b\x + *b\w) And my >= *b\y And my <= (*b\y + *b\h)
    ProcedureReturn #True
  EndIf
  ProcedureReturn #False
EndProcedure

Procedure HandleMouseInput(mx.i, my.i, wheel.i, leftDown.i, leftJustPressed.i, leftJustReleased.i, rightJustPressed.i)
  ; Right-Click anywhere toggles Pure Wall Art mode (hides/shows side gallery placards!)
  If rightJustPressed
    PureArtMode = 1 - PureArtMode
    ProcedureReturn
  EndIf

  ; Mouse Wheel scales the Mark Fischer Kinetic Matrix smoothly between 8x8 and 80x80!
  If wheel > 0 And GridN < #MaxGridN
    RecalcBoardMetrics(GridN + 2)
    ProcedureReturn
  ElseIf wheel < 0 And GridN > #MinGridN
    RecalcBoardMetrics(GridN - 2)
    ProcedureReturn
  EndIf

  ; Update live Hover Grid Coordinates (for precision 80x80 targeting & Loupe!)
  HoverGX = -1 : HoverGY = -1
  If mx >= BoardX And mx < (BoardX + BoardPx) And my >= BoardY And my < (BoardY + BoardPx)
    HoverGX = (mx - BoardX) / CellPx
    HoverGY = (my - BoardY) / CellPx
    If HoverGX < 0 : HoverGX = 0 : ElseIf HoverGX >= GridN : HoverGX = GridN - 1 : EndIf
    If HoverGY < 0 : HoverGY = 0 : ElseIf HoverGY >= GridN : HoverGY = GridN - 1 : EndIf
  EndIf

  ; 1. Gallery Placard Controls (when side panels are visible)
  If Not PureArtMode And leftJustPressed
    If PointInButton(@BtnExit, mx, my)
      End
    ElseIf PointInButton(@BtnMinus, mx, my)
      If GridN > #MinGridN : RecalcBoardMetrics(GridN - 2) : EndIf
      ProcedureReturn
    ElseIf PointInButton(@BtnPlus, mx, my)
      If GridN < #MaxGridN : RecalcBoardMetrics(GridN + 2) : EndIf
      ProcedureReturn
    ElseIf PointInButton(@BtnP8, mx, my)  : RecalcBoardMetrics(8)  : ProcedureReturn
    ElseIf PointInButton(@BtnP16, mx, my) : RecalcBoardMetrics(16) : ProcedureReturn
    ElseIf PointInButton(@BtnP32, mx, my) : RecalcBoardMetrics(32) : ProcedureReturn
    ElseIf PointInButton(@BtnP64, mx, my) : RecalcBoardMetrics(64) : ProcedureReturn
    ElseIf PointInButton(@BtnP80, mx, my) : RecalcBoardMetrics(80) : ProcedureReturn
    ElseIf PointInButton(@BtnAuto, mx, my)
      AutoPlay = 1 - AutoPlay
      SelX = -1 : SelY = -1 : DragActive = #False
      If AutoPlay
        StatusBanner = "KINETIC AUTOPILOT ON"
      Else
        StatusBanner = "MANUAL ATELIER CONTROL"
      EndIf
      StatusTimer = ElapsedMilliseconds() + 1800
      NextAIMoveTime = ElapsedMilliseconds() + 150
      ProcedureReturn
    ElseIf PointInButton(@BtnSpeed, mx, my)
      TurboAI = 1 - TurboAI
      StatusBanner = "KINETIC TEMPO UPDATED"
      StatusTimer = ElapsedMilliseconds() + 1400
      ProcedureReturn
    ElseIf PointInButton(@BtnHint, mx, my)
      If GameState = #State_Idle
        If FindBestValidMove(@HintX1, @HintY1, @HintX2, @HintY2)
          HintVisible = #True
          StatusBanner = "VECTOR (" + Str(HintX1 + 1) + "," + Str(HintY1 + 1) + ") READY"
          StatusTimer = ElapsedMilliseconds() + 1800
        EndIf
      EndIf
      ProcedureReturn
    ElseIf PointInButton(@BtnPalette, mx, my)
      VegaPalette = VegaPalette + 1
      If VegaPalette > 2 : VegaPalette = 0 : EndIf
      Select VegaPalette
        Case 0 : StatusBanner = "SERIES: PLANETARY FOLKLORE"
        Case 1 : StatusBanner = "SERIES: VEGA OR & BLEU"
        Case 2 : StatusBanner = "SERIES: ZEBRA CONSTRUCTIVIST"
      EndSelect
      StatusTimer = ElapsedMilliseconds() + 1800
      ProcedureReturn
    ElseIf PointInButton(@BtnTheme, mx, my)
      DarkGallery = 1 - DarkGallery
      ApplyGalleryTheme()
      ProcedureReturn
    ElseIf PointInButton(@BtnPureArt, mx, my)
      PureArtMode = 1 - PureArtMode
      ProcedureReturn
    ElseIf PointInButton(@BtnReset, mx, my)
      RecalcBoardMetrics(GridN)
      ProcedureReturn
    EndIf
  EndIf

  ; 2. Board Op-Art Unit Interaction (Precision Click-Click OR Micro-Drag!)
  If AutoPlay Or GameState <> #State_Idle
    DragActive = #False
    ProcedureReturn
  EndIf

  If leftJustPressed And HoverGX >= 0 And HoverGY >= 0
    DragStartX = HoverGX : DragStartY = HoverGY : DragActive = #True
    If SelX = -1
      SelX = HoverGX : SelY = HoverGY
    ElseIf SelX = HoverGX And SelY = HoverGY
      SelX = -1 : SelY = -1
    ElseIf Abs(SelX - HoverGX) + Abs(SelY - HoverGY) = 1
      StartSwap(SelX, SelY, HoverGX, HoverGY)
      DragActive = #False
    Else
      SelX = HoverGX : SelY = HoverGY
    EndIf
  ElseIf leftDown And DragActive And HoverGX >= 0 And HoverGY >= 0
    If (HoverGX <> DragStartX Or HoverGY <> DragStartY) And (Abs(HoverGX - DragStartX) + Abs(HoverGY - DragStartY) = 1)
      StartSwap(DragStartX, DragStartY, HoverGX, HoverGY)
      DragActive = #False
    EndIf
  EndIf

  If leftJustReleased
    DragActive = #False
  EndIf
EndProcedure

; =====================================================================
; Mark Fischer Kinetic GALLERY ARCHITECTURE & "UNITE PLASTIQUE" RENDERER
; Every single gem is a geometric Op-Art painting (Square + Inner Form)
; Clean down to 11x11 px (80x80) and monumental at 110x110 px (8x8)!
; =====================================================================
Procedure DrawGalleryPlaque(x.i, y.i, w.i, h.i, TitleTxt.s, SubTxt.s)
  DrawingMode(#PB_2DDrawing_Default)
  ; Subtle gallery drop shadow
  If Not DarkGallery
    SafeBox(x + 4, y + 4, w, h, Col_WallSubtle)
  EndIf
  SafeBox(x, y, w, h, Col_CardBg)
  SafeBox(x, y, w, 5, Col_FrameOuter)

  DrawingMode(#PB_2DDrawing_Outlined)
  SafeBox(x, y, w, h, Col_CardBorder)

  If TitleTxt <> ""
    DrawingMode(#PB_2DDrawing_Transparent)
    DrawingFont(FontID(2))
    DrawText(x + 20, y + 18, TitleTxt, Col_InkPrimary)
    If SubTxt <> ""
      DrawingFont(FontID(4))
      DrawText(x + 20, y + 42, SubTxt, Col_InkMuted)
    EndIf
    LineXY(x + 20, y + 66, x + w - 20, y + 66, Col_CardBorder)
  EndIf
EndProcedure

Procedure DrawGalleryButton(*b.UIButton, mx.i, my.i, isActive.i)
  Protected hover.i = PointInButton(*b, mx, my)
  Protected bgCol.i = Col_CardBg
  Protected brdCol.i = Col_CardBorder
  Protected txtCol.i = Col_InkPrimary
  Protected barCol.i = Col_FrameInner

  If isActive
    bgCol = ShadeColor(Col_CardBg, Bool(DarkGallery) * 18 - Bool(Not DarkGallery) * 12)
    brdCol = Col_AccentA
    barCol = Col_AccentA
    txtCol = Col_AccentA
  ElseIf hover
    bgCol = ShadeColor(Col_CardBg, Bool(DarkGallery) * 12 - Bool(Not DarkGallery) * 7)
    brdCol = Col_InkPrimary
    barCol = Col_AccentB
  EndIf

  DrawingMode(#PB_2DDrawing_Default)
  SafeBox(*b\x, *b\y, *b\w, *b\h, bgCol)
  SafeBox(*b\x, *b\y, 6, *b\h, barCol)

  DrawingMode(#PB_2DDrawing_Outlined)
  SafeBox(*b\x, *b\y, *b\w, *b\h, brdCol)

  DrawingMode(#PB_2DDrawing_Transparent)
  DrawingFont(FontID(3))
  DrawText(*b\x + 16, *b\y + 10, *b\label, txtCol)
  DrawingFont(FontID(4))
  DrawText(*b\x + 16, *b\y + 34, *b\sub, Col_InkMuted)
EndProcedure

Procedure DrawMiniButton(*b.UIButton, mx.i, my.i, isActive.i)
  Protected hover.i = PointInButton(*b, mx, my)
  Protected bgCol.i = Col_CardBg
  Protected brdCol.i = Col_CardBorder
  Protected txtCol.i = Col_InkPrimary

  If isActive
    bgCol = Col_AccentA
    brdCol = Col_AccentA
    txtCol = RGB(255, 255, 255)
  ElseIf hover
    brdCol = Col_InkPrimary
    bgCol = ShadeColor(Col_CardBg, Bool(DarkGallery) * 16 - Bool(Not DarkGallery) * 10)
  EndIf

  DrawingMode(#PB_2DDrawing_Default)
  SafeBox(*b\x, *b\y, *b\w, *b\h, bgCol)
  DrawingMode(#PB_2DDrawing_Outlined)
  SafeBox(*b\x, *b\y, *b\w, *b\h, brdCol)

  DrawingMode(#PB_2DDrawing_Transparent)
  DrawingFont(FontID(3))
  Protected tw.i = TextWidth(*b\label)
  Protected th.i = TextHeight(*b\label)
  DrawText(*b\x + (*b\w - tw) / 2, *b\y + (*b\h - th) / 2, *b\label, txtCol)
EndProcedure

Procedure DrawMark Fischer KineticUnit(cx.i, cy.i, unitSize.i, gem.i, spec.i, vegaBias.i)
  If unitSize < 2 Or gem = #Gem_None : ProcedureReturn : EndIf

  Protected baseCol.i  = ShadeColor(GemBaseColor(gem), vegaBias)
  Protected innerCol.i = ShadeColor(GemInnerColor(gem), vegaBias / 2)
  Protected coreCol.i  = GemCoreColor(gem)
  Protected deepCol.i  = ShadeColor(baseCol, -52)

  Protected half.i = unitSize / 2
  Protected x0.i = cx - half
  Protected y0.i = cy - half
  Protected i.i, span.i, off.i

  ; Proportional Op-Art Radii (100% immune to negative values at ANY scale 8..80!)
  Protected rOuter.i = (unitSize * 39) / 100 : If rOuter < 1 : rOuter = 1 : EndIf
  Protected rMid.i   = (unitSize * 27) / 100 : If rMid < 1   : rMid = 1   : EndIf
  Protected rCore.i  = (unitSize * 14) / 100 : If rCore < 1  : rCore = 1  : EndIf
  Protected sqMid.i  = (unitSize * 58) / 100 : If sqMid < 2  : sqMid = 2  : EndIf
  Protected sqIn.i   = (unitSize * 32) / 100 : If sqIn < 1   : sqIn = 1   : EndIf

  DrawingMode(#PB_2DDrawing_Default)

  ; 1. Mark Fischer Kinetic Outer Chromatic Square ("Unite Plastique" Base Tile)
  SafeBox(x0, y0, unitSize, unitSize, baseCol)

  ; Subtle dark gallery micro-joint when tiles are >= 10px
  If unitSize >= 10
    DrawingMode(#PB_2DDrawing_Outlined)
    SafeBox(x0, y0, unitSize, unitSize, Col_CanvasGroove)
    DrawingMode(#PB_2DDrawing_Default)
  EndIf

  ; 2. Seven Distinct Mark Fischer Kinetic Geometric Inner Artworks + Zebra Singularity
  Select gem
    Case #Gem_Cobalt ; 1: "Vega-Nor" Concentric Optical Target Disc
      SafeCircle(cx, cy, rOuter, innerCol)
      If unitSize >= 14
        SafeCircle(cx, cy, rMid, baseCol)
        SafeCircle(cx, cy, rCore, coreCol)
      ElseIf unitSize >= 8
        SafeCircle(cx, cy, rCore, coreCol)
      EndIf

    Case #Gem_Emerald ; 2: "Hommage a l'Hexagone / Bauhaus" Nested Shifted Squares
      SafeBox(cx - sqMid / 2, cy - sqMid / 2, sqMid, sqMid, innerCol)
      If unitSize >= 14
        off = unitSize / 14
        SafeBox(cx - sqIn / 2 + off, cy - sqIn / 2 - off, sqIn, sqIn, coreCol)
      ElseIf unitSize >= 8
        SafeBox(cx - sqIn / 2, cy - sqIn / 2, sqIn, sqIn, coreCol)
      EndIf

    Case #Gem_Crimson ; 3: "etik-diamond" Mark Fischer Kinetic Inscribed Lozenge + Disc
      For i = -rOuter To rOuter
        span = rOuter - Abs(i)
        LineXY(cx - span, cy + i, cx + span, cy + i, innerCol)
      Next
      If unitSize >= 11
        SafeCircle(cx, cy, rCore + 1, coreCol)
      EndIf

    Case #Gem_Ochre ; 4: "Kepler / Gestalt" Axonometric Illusion Cube (Light Top / Shadow Base)
      SafeBox(cx - sqMid / 2, cy - sqMid / 2, sqMid, sqMid, deepCol)
      SafeBox(cx - sqMid / 2, cy - sqMid / 2, sqMid, sqMid / 2, innerCol)
      If unitSize >= 11
        SafeBox(cx - sqIn / 2, cy - sqIn / 2, sqIn, sqIn, coreCol)
      EndIf

    Case #Gem_Violet ; 5: "CTA-102" Directional Eccentric 3D Sphere Illusion
      off = rOuter / 4 : If off < 1 : off = 1 : EndIf
      SafeCircle(cx, cy, rOuter, deepCol)
      SafeCircle(cx - off / 2, cy - off / 2, rMid + (rOuter - rMid) / 2, innerCol)
      If unitSize >= 11
        SafeCircle(cx - off, cy - off, rCore, RGB(250, 245, 255))
      EndIf

    Case #Gem_Orange ; 6: "Planetary Folklore" Bold Geometric Plus-Cross + Contrasting Lens
      Protected barT.i = (unitSize * 26) / 100 : If barT < 2 : barT = 2 : EndIf
      SafeBox(cx - barT / 2, cy - rOuter, barT, rOuter * 2, innerCol)
      SafeBox(cx - rOuter, cy - barT / 2, rOuter * 2, barT, innerCol)
      If unitSize >= 11
        SafeCircle(cx, cy, rCore + 1, coreCol)
      EndIf

    Case #Gem_Silver ; 7: "Cassiopee" Split-Polarity Optical Disc + Bauhaus Red Focal Point
      SafeBox(cx - rOuter, cy - rOuter, rOuter, rOuter * 2, deepCol)
      SafeBox(cx, cy - rOuter, rOuter, rOuter * 2, innerCol)
      SafeCircle(cx, cy, rMid + 1, innerCol)
      SafeCircle(cx, cy, rCore + 1, coreCol)

    Case #Gem_Hypercube ; 8: "Zebra" Black-and-White Kinetic Op-Art Singularity
      Protected stripeStep.i = unitSize / 5 : If stripeStep < 2 : stripeStep = 2 : EndIf
      Protected nowMs.q = ElapsedMilliseconds()
      Protected nowTicks.q = nowMs / 90
      Protected phase.i = nowTicks & 1
      Protected sIdx.i = 0
      Protected stripeParity.i = 0
      Protected stripeEnd.i = y0 + unitSize - 2
      Protected stripeH.i = stripeStep
      i = y0 + 1
      While i <= stripeEnd
        stripeH = stripeStep
        If i + stripeH - 1 > stripeEnd
          stripeH = stripeEnd - i + 1
        EndIf
        stripeParity = (sIdx + phase) & 1
        If stripeParity = 1
          SafeBox(x0 + 1, i, unitSize - 2, stripeH, RGB(250, 250, 250))
        Else
          SafeBox(x0 + 1, i, unitSize - 2, stripeH, RGB(12, 12, 16))
        EndIf
        sIdx + 1
        i + stripeStep
      Wend
      SafeCircle(cx, cy, rCore + 1, Col_AccentB)
  EndSelect

  ; Kinetic 4-Match Special Modifier: High-Contrast Pulsing Op-Art Ring
  If spec = #Spec_Flame
    Protected rawNowMs.q = ElapsedMilliseconds()
    Protected pulseMs.q = rawNowMs - (rawNowMs / 700) * 700
    Protected pRad.i = rOuter + 1
    If pulseMs < 350 And pRad < half - 1 : pRad + 1 : EndIf
    DrawingMode(#PB_2DDrawing_Outlined)
    SafeCircle(cx, cy, pRad, RGB(255, 255, 255))
    If unitSize >= 16
      SafeBox(x0 + 2, y0 + 2, unitSize - 4, unitSize - 4, RGB(255, 255, 255))
    EndIf
    DrawingMode(#PB_2DDrawing_Default)
  EndIf
EndProcedure

; Live 7x7 Magnifying Gallery Loupe in Right Panel (Essential for 64x64 & 80x80 testing!)
Procedure DrawOpticalLoupe(panelX.i, panelY.i, panelW.i)
  Protected loupeCells.i = 7
  Protected loupeCellPx.i = 36 ; 7 * 36 = 252x252 crisp magnified Mark Fischer Kinetic view!
  Protected loupePx.i = loupeCells * loupeCellPx
  Protected lx0.i = panelX + (panelW - loupePx) / 2
  Protected ly0.i = panelY

  Protected focusX.i = HoverGX
  Protected focusY.i = HoverGY
  If focusX < 0
    If SelX >= 0 : focusX = SelX : focusY = SelY : Else : focusX = GridN / 2 : focusY = GridN / 2 : EndIf
  EndIf

  Protected startX.i = focusX - 3
  Protected startY.i = focusY - 3
  If startX < 0 : startX = 0 : EndIf
  If startY < 0 : startY = 0 : EndIf
  If startX + loupeCells > GridN : startX = GridN - loupeCells : EndIf
  If startY + loupeCells > GridN : startY = GridN - loupeCells : EndIf
  If startX < 0 : startX = 0 : EndIf
  If startY < 0 : startY = 0 : EndIf

  ; Outer Gallery Frame around Loupe
  DrawingMode(#PB_2DDrawing_Default)
  SafeBox(lx0 - 6, ly0 - 6, loupePx + 12, loupePx + 12, Col_FrameOuter)
  SafeBox(lx0, ly0, loupePx, loupePx, Col_CanvasGroove)

  Protected dx.i, dy.i, gx.i, gy.i, uCX.i, uCY.i
  For dy = 0 To loupeCells - 1
    For dx = 0 To loupeCells - 1
      gx = startX + dx
      gy = startY + dy
      If gx < GridN And gy < GridN
        uCX = lx0 + dx * loupeCellPx + loupeCellPx / 2
        uCY = ly0 + dy * loupeCellPx + loupeCellPx / 2
        DrawMark Fischer KineticUnit(uCX, uCY, loupeCellPx - 1, Grid(gx, gy)\gem, Grid(gx, gy)\spec, 0)

        If gx = SelX And gy = SelY
          DrawingMode(#PB_2DDrawing_Outlined)
          SafeBox(lx0 + dx * loupeCellPx + 1, ly0 + dy * loupeCellPx + 1, loupeCellPx - 2, loupeCellPx - 2, RGB(255, 255, 255))
          SafeBox(lx0 + dx * loupeCellPx + 3, ly0 + dy * loupeCellPx + 3, loupeCellPx - 6, loupeCellPx - 6, Col_AccentB)
        ElseIf gx = focusX And gy = focusY
          DrawingMode(#PB_2DDrawing_Outlined)
          SafeBox(lx0 + dx * loupeCellPx + 1, ly0 + dy * loupeCellPx + 1, loupeCellPx - 2, loupeCellPx - 2, RGB(255, 255, 255))
        EndIf
      EndIf
    Next
  Next
EndProcedure

; Ultra-precise Pixel Crosshair Cursor (Leaves center 5x5 px unobstructed for 80x80!)
Procedure DrawGalleryCursor(mx.i, my.i)
  Protected ringCol.i = Col_InkPrimary
  Protected contrastCol.i = Col_Passepartout
  If mx >= BoardX And mx < (BoardX + BoardPx) And my >= BoardY And my < (BoardY + BoardPx)
    ringCol = RGB(255, 255, 255)
    contrastCol = RGB(12, 12, 16)
  EndIf

  DrawingMode(#PB_2DDrawing_Default)
  ; Crisp two-tone crosshair arms with open target window around exact (mx, my) pixel!
  SafeBox(mx - 13, my - 1, 9, 3, contrastCol)
  SafeBox(mx + 5,  my - 1, 9, 3, contrastCol)
  SafeBox(mx - 1, my - 13, 3, 9, contrastCol)
  SafeBox(mx - 1, my + 5,  3, 9, contrastCol)

  LineXY(mx - 12, my, mx - 5, my, ringCol)
  LineXY(mx + 5,  my, mx + 12, my, ringCol)
  LineXY(mx, my - 12, mx, my - 5, ringCol)
  LineXY(mx, my + 5,  mx, my + 12, ringCol)

  ; Exact 1x1 center pixel pinpoint
  Plot(mx, my, ringCol)
EndProcedure

Procedure RenderFrame(mx.i, my.i)
  If StartDrawing(ScreenOutput())
    ; 1. Museum Exhibition Wall
    DrawingMode(#PB_2DDrawing_Default)
    SafeBox(0, 0, 1920, 1080, Col_WallBg)

    ; =================================================================
    ; MUSEUM-FRAMED Mark Fischer Kinetic MASTERPIECE IN THE CENTER
    ; Outer Collector Frame + Wide Archival Passepartout + Signed Label
    ; Guaranteed 100% inside 1920x1080 with generous top & bottom wall!
    ; =================================================================
    Protected fx.i = BoardX - #FramePadPx
    Protected fy.i = BoardY - #FramePadPx
    Protected fw.i = BoardPx + #FramePadPx * 2
    Protected fh.i = BoardPx + #FramePadPx * 2 + #FrameSigExtraPx

    Protected ox.i = fx - #FrameRimPx
    Protected oy.i = fy - #FrameRimPx
    Protected ow.i = fw + #FrameRimPx * 2
    Protected oh.i = fh + #FrameRimPx * 2

    ; Architectural Gallery Wall Shadow (cast cleanly from the outer collector frame!)
    If Not DarkGallery
      SafeBox(ox + #FrameShadowPx, oy + #FrameShadowPx, ow, oh, RGB(214, 209, 198))
      SafeBox(ox + (#FrameShadowPx / 2), oy + (#FrameShadowPx / 2), ow, oh, RGB(198, 193, 182))
    Else
      SafeBox(ox + #FrameShadowPx, oy + #FrameShadowPx, ow, oh, RGB(5, 5, 7))
      SafeBox(ox + (#FrameShadowPx / 2), oy + (#FrameShadowPx / 2), ow, oh, RGB(8, 9, 12))
    EndIf

    ; Outer Collector Frame + Archival Passepartout Matting
    SafeBox(ox, oy, ow, oh, Col_FrameOuter)
    SafeBox(fx, fy, fw, fh, Col_Passepartout)

    ; Subtle inner museum frame fillet + recessed bevel around the kinetic canvas
    DrawingMode(#PB_2DDrawing_Outlined)
    SafeBox(fx, fy, fw, fh, Col_FrameInner)
    SafeBox(BoardX - 3, BoardY - 3, BoardPx + 6, BoardPx + 6, Col_FrameInner)
    DrawingMode(#PB_2DDrawing_Default)
    SafeBox(BoardX, BoardY, BoardPx, BoardPx, Col_CanvasGroove)

    ; Artist Pencil Signature centered inside the bottom Passepartout (Authentic Serigraph Style!)
    Protected bottomMatH.i = #FramePadPx + #FrameSigExtraPx
    DrawingMode(#PB_2DDrawing_Transparent)
    DrawingFont(FontID(4))
    Protected sigY.i = BoardY + BoardPx + (bottomMatH - TextHeight("M")) / 2
    DrawText(BoardX, sigY, "HOMMAGE A Mark Fischer Kinetic // " + Str(GridN) + "x" + Str(GridN) + " UNITES PLASTIQUES", Col_InkMuted)
    Protected sigRight.s = "M. FISCHER 007/2026"
    DrawText(BoardX + BoardPx - TextWidth(sigRight), sigY, sigRight, Col_InkPrimary)

    ; Render All Mark Fischer Kinetic Kinetic Units (with Vega Spherical Luminance Modulation!)
    Protected x.i, y.i, drawCX.i, drawCY.i, unitSz.i, interp.f
    Protected normX.f, normY.f, distSq.f, vegaBias.i
    Protected halfGrid.f = GridN * 0.5
    Protected invHalf.f = 1.0 / halfGrid

    For y = 0 To GridN - 1
      normY = (y + 0.5 - halfGrid) * invHalf
      For x = 0 To GridN - 1
        If Grid(x, y)\gem <> #Gem_None
          normX = (x + 0.5 - halfGrid) * invHalf
          distSq = normX * normX + normY * normY
          ; Subtle "Vega" spherical light bulge in the center (+20 center luminance, -18 edges)
          If distSq < 1.0
            vegaBias = Int((1.0 - distSq) * 26.0) - 10
          Else
            vegaBias = -14
          EndIf

          drawCX = BoardX + x * CellPx + CellPx / 2
          drawCY = BoardY + y * CellPx + CellPx / 2 + Int(Grid(x, y)\yOffset)

          If GameState = #State_SwapAnim Or GameState = #State_RevertAnim
            interp = SwapProgress
            If GameState = #State_RevertAnim : interp = 1.0 - SwapProgress : EndIf
            If x = SwapX2 And y = SwapY2
              drawCX = BoardX + Int((SwapX1 + (SwapX2 - SwapX1) * interp) * CellPx) + CellPx / 2
              drawCY = BoardY + Int((SwapY1 + (SwapY2 - SwapY1) * interp) * CellPx) + CellPx / 2
            ElseIf x = SwapX1 And y = SwapY1
              drawCX = BoardX + Int((SwapX2 + (SwapX1 - SwapX2) * interp) * CellPx) + CellPx / 2
              drawCY = BoardY + Int((SwapY2 + (SwapY1 - SwapY2) * interp) * CellPx) + CellPx / 2
            EndIf
          EndIf

          unitSz = CellPx
          If GameState = #State_ClearAnim And Grid(x, y)\marked
            unitSz = Int(CellPx * (1.0 - ClearProgress))
          EndIf

          If drawCY >= (BoardY - CellPx) And drawCY <= (BoardY + BoardPx + CellPx) And unitSz >= 2
            ; Clip top spawn cleanly inside canvas so falling gems never cross the top Passepartout!
            If drawCY - unitSz / 2 >= BoardY - 2
              DrawMark Fischer KineticUnit(drawCX, drawCY, unitSz, Grid(x, y)\gem, Grid(x, y)\spec, vegaBias)
            EndIf
          EndIf
        EndIf
      Next
    Next

    ; Precision Reticles on the Canvas (Hover, Hint, Active Selection)
    DrawingMode(#PB_2DDrawing_Outlined)
    If HintVisible And GameState = #State_Idle
      SafeBox(BoardX + HintX1 * CellPx, BoardY + HintY1 * CellPx, CellPx, CellPx, RGB(255, 255, 255))
      SafeBox(BoardX + HintX2 * CellPx, BoardY + HintY2 * CellPx, CellPx, CellPx, RGB(255, 255, 255))
      If CellPx >= 8
        SafeBox(BoardX + HintX1 * CellPx + 1, BoardY + HintY1 * CellPx + 1, CellPx - 2, CellPx - 2, Col_AccentB)
        SafeBox(BoardX + HintX2 * CellPx + 1, BoardY + HintY2 * CellPx + 1, CellPx - 2, CellPx - 2, Col_AccentB)
      EndIf
    EndIf

    If Not AutoPlay And GameState = #State_Idle And HoverGX >= 0 And HoverGY >= 0
      SafeBox(BoardX + HoverGX * CellPx, BoardY + HoverGY * CellPx, CellPx, CellPx, RGB(255, 255, 255))
    EndIf

    If SelX >= 0 And SelY >= 0
      SafeBox(BoardX + SelX * CellPx, BoardY + SelY * CellPx, CellPx, CellPx, RGB(255, 255, 255))
      If CellPx >= 6
        SafeBox(BoardX + SelX * CellPx + 1, BoardY + SelY * CellPx + 1, CellPx - 2, CellPx - 2, Col_AccentB)
      EndIf
    EndIf

    UpdateAndDrawSparks()

    ; =================================================================
    ; SIDE GALLERY PLACARDS (HIDDEN IN PURE WALL ART MODE!)
    ; =================================================================
    If Not PureArtMode
      ; LEFT CURATORIAL CONSOLE (28..412)
      DrawGalleryPlaque(28, 28, 384, 1024, "Mark Fischer Kinetic ATELIER", "KINETIC OP-ART EDITION // V007")

      DrawingMode(#PB_2DDrawing_Transparent)
      DrawingFont(FontID(4))
      DrawText(48, 110, "MATRIX SCALE (8x8 TO 80x80 / MOUSE WHEEL)", Col_InkMuted)

      DrawingFont(FontID(1))
      DrawText(48, 134, Str(GridN) + " x " + Str(GridN), Col_InkPrimary)
      DrawingFont(FontID(3))
      DrawText(215, 144, Str(GridN * GridN) + " UNITS", Col_AccentA)
      DrawingFont(FontID(4))
      DrawText(48, 182, "CELL PITCH : " + Str(CellPx) + " x " + Str(CellPx) + " PIXELS", Col_InkMuted)
      If HoverGX >= 0 And HoverGY >= 0
        DrawText(48, 202, "TARGET PIXEL CELL : X=" + Str(HoverGX + 1) + " Y=" + Str(HoverGY + 1), Col_AccentB)
      Else
        DrawText(48, 202, "TARGET PIXEL CELL : --", Col_InkMuted)
      EndIf

      ; Scale Step Display & Buttons
      DrawMiniButton(@BtnMinus, mx, my, #False)
      DrawingMode(#PB_2DDrawing_Default)
      SafeBox(132, 228, 176, 44, Col_WallSubtle)
      DrawingMode(#PB_2DDrawing_Outlined)
      SafeBox(132, 228, 176, 44, Col_CardBorder)
      DrawingMode(#PB_2DDrawing_Transparent)
      DrawingFont(FontID(3))
      Protected scaleLbl.s = Str(GridN) + "x" + Str(GridN) + " (" + Str(CellPx) + "px)"
      DrawText(132 + (176 - TextWidth(scaleLbl)) / 2, 240, scaleLbl, Col_InkPrimary)
      DrawMiniButton(@BtnPlus, mx, my, #False)

      ; Quick Scale Presets (8 / 16 / 32 / 64 / 80)
      DrawMiniButton(@BtnP8,  mx, my, Bool(GridN = 8))
      DrawMiniButton(@BtnP16, mx, my, Bool(GridN = 16))
      DrawMiniButton(@BtnP32, mx, my, Bool(GridN = 32))
      DrawMiniButton(@BtnP64, mx, my, Bool(GridN = 64))
      DrawMiniButton(@BtnP80, mx, my, Bool(GridN = 80))

      LineXY(46, 336, 394, 336, Col_CardBorder)

      DrawGalleryButton(@BtnAuto,  mx, my, AutoPlay)
      DrawGalleryButton(@BtnSpeed, mx, my, TurboAI)
      DrawGalleryButton(@BtnHint,  mx, my, HintVisible)

      LineXY(46, 574, 394, 574, Col_CardBorder)

      DrawGalleryButton(@BtnPalette, mx, my, #False)
      DrawGalleryButton(@BtnTheme,   mx, my, DarkGallery)
      DrawGalleryButton(@BtnPureArt, mx, my, PureArtMode)

      LineXY(46, 808, 394, 808, Col_CardBorder)

      DrawGalleryButton(@BtnReset, mx, my, #False)
      DrawGalleryButton(@BtnExit,  mx, my, #False)

      ; RIGHT EXHIBITION TELEMETRY & LIVE 7x7 MAGNIFYING LOUPE (1508..1892)
      DrawGalleryPlaque(1508, 28, 384, 536, "EXHIBITION CATALOGUE", "MARK FISCHER // KINETIC SCORE")

      Protected rx.i = 1528
      Protected ry.i = 112
      DrawingMode(#PB_2DDrawing_Transparent)

      DrawingFont(FontID(4)) : DrawText(rx, ry, "HARMONIC ENERGY SCORE", Col_InkMuted) : ry + 22
      DrawingFont(FontID(1)) : DrawText(rx, ry, Str(Score), Col_InkPrimary) : ry + 50

      DrawingFont(FontID(4)) : DrawText(rx, ry, "COLLECTION RECORD", Col_InkMuted) : ry + 20
      DrawingFont(FontID(2)) : DrawText(rx, ry, Str(BestScore), Col_AccentA) : ry + 42

      DrawingFont(FontID(4)) : DrawText(rx, ry, "EDITION PHASE " + RSet(Str(Level), 2, "0"), Col_InkMuted) : ry + 22

      ; Minimalist Bauhaus Progress Bar
      Protected barW.i = 344
      Protected fillW.i = (LevelProg * barW) / LevelTarget
      If fillW > barW : fillW = barW : EndIf
      DrawingMode(#PB_2DDrawing_Default)
      SafeBox(rx, ry, barW, 14, Col_WallSubtle)
      If fillW >= 2
        SafeBox(rx, ry, fillW, 14, Col_AccentA)
      EndIf
      DrawingMode(#PB_2DDrawing_Outlined)
      SafeBox(rx, ry, barW, 14, Col_CardBorder)
      ry + 32

      DrawingMode(#PB_2DDrawing_Transparent)
      DrawingFont(FontID(3))
      DrawText(rx, ry, "TRANSITIONS : " + Str(TotalMoves), Col_InkPrimary) : ry + 28
      DrawText(rx, ry, "CASCADE     : x" + Str(ComboChain) + " (MAX x" + Str(BestCombo) + ")", Col_InkPrimary) : ry + 28
      DrawText(rx, ry, "PERMUTATIONS: " + Str(Shuffles), Col_InkMuted) : ry + 36

      DrawingFont(FontID(4))
      If ElapsedMilliseconds() < StatusTimer
        DrawText(rx, ry, ":: " + StatusBanner, Col_AccentB)
      ElseIf AutoPlay
        DrawText(rx, ry, ":: KINETIC AUTOPILOT ACTIVE", Col_AccentA)
      Else
        DrawText(rx, ry, ":: CLICK OR DRAG ADJACENT UNITS", Col_InkMuted)
      EndIf

      ; LOWER RIGHT PANEL: 7x7 OPTICAL LOUPE FOR 80x80 PRECISION TARGETING
      DrawGalleryPlaque(1508, 584, 384, 468, "OPTICAL LOUPE (7x7)", "PRECISION PIXEL TARGETING MONITOR")
      DrawOpticalLoupe(1508, 682, 384)

      DrawingMode(#PB_2DDrawing_Transparent)
      DrawingFont(FontID(4))
      DrawText(1528, 956, "TIP: RIGHT-CLICK ANYWHERE TO TOGGLE", Col_InkMuted)
      DrawText(1528, 976, "PURE FRAMED WALL ART EXHIBITION MODE!", Col_InkPrimary)
      DrawText(1528, 1004, "WHEEL = SCALE 8..80 | ESC = EXIT", Col_InkMuted)
    EndIf

    ; Precision Pixel Cursor
    DrawGalleryCursor(mx, my)

    StopDrawing()
  EndIf
EndProcedure

; =====================================================================
; MAIN ENGINE BOOTSTRAP (1920x1080 FULLHD + MOUSE + WHEEL + ESC EXIT)
; =====================================================================
RandomSeed(ElapsedMilliseconds())

If Not InitSprite() Or Not InitKeyboard() Or Not InitMouse()
  MessageRequester("System Error", "DirectX/OpenGL initialization failed!")
  End
EndIf

If OpenScreen(1920, 1080, 32, "BEJEWELED - Mark Fischer Kinetic Kinetic Op-Art Edition v007")

  LoadFont(1, "Consolas", 26, #PB_Font_Bold)
  LoadFont(2, "Consolas", 15, #PB_Font_Bold)
  LoadFont(3, "Consolas", 12, #PB_Font_Bold)
  LoadFont(4, "Consolas", 10, #PB_Font_Bold)

  ApplyGalleryTheme()
  InitButtons()
  RecalcBoardMetrics(8)

  MouseLocate(960, 540)
  MainLastTick = ElapsedMilliseconds()

  Repeat
    ; 1. INSTANT GUARANTEED ESC EXIT
    ExamineKeyboard()
    If KeyboardPushed(#PB_Key_Escape)
      Break
    EndIf

    ; 2. PRECISION MOUSE + WHEEL INPUT
    ExamineMouse()
    MainMX = MouseX()
    MainMY = MouseY()
    MainWheel = MouseWheel()
    If MainMX < 0 : MainMX = 0 : ElseIf MainMX > 1919 : MainMX = 1919 : EndIf
    If MainMY < 0 : MainMY = 0 : ElseIf MainMY > 1079 : MainMY = 1079 : EndIf

    MainLeftDown = Bool(MouseButton(#PB_MouseButton_Left) <> 0)
    MainLeftJustPressed = Bool(MainLeftDown And Not PrevMouseLeft)
    MainLeftJustReleased = Bool((Not MainLeftDown) And PrevMouseLeft)
    PrevMouseLeft = MainLeftDown

    MainRightDown = Bool(MouseButton(#PB_MouseButton_Right) <> 0)
    MainRightJustPressed = Bool(MainRightDown And Not PrevMouseRight)
    PrevMouseRight = MainRightDown

    MainNow = ElapsedMilliseconds()
    MainDt = (MainNow - MainLastTick) / 1000.0
    If MainDt <= 0.001 : MainDt = 0.008 : ElseIf MainDt > 0.05 : MainDt = 0.05 : EndIf
    MainLastTick = MainNow

    HandleMouseInput(MainMX, MainMY, MainWheel, MainLeftDown, MainLeftJustPressed, MainLeftJustReleased, MainRightJustPressed)

    ; 3. KINETIC STATE MACHINE
    Select GameState
      Case #State_SwapAnim
        SwapProgress + MainDt * (6.0 + Bool(TurboAI) * 9.0)
        If SwapProgress >= 1.0
          SwapProgress = 1.0
          If Grid(SwapX1, SwapY1)\gem = #Gem_Hypercube Or Grid(SwapX2, SwapY2)\gem = #Gem_Hypercube
            TotalMoves + 1
            If Grid(SwapX1, SwapY1)\gem = #Gem_Hypercube And Grid(SwapX2, SwapY2)\gem = #Gem_Hypercube
              For MainLoopY = 0 To GridN - 1
                For MainLoopX = 0 To GridN - 1 : Grid(MainLoopX, MainLoopY)\marked = #True : Next
              Next
              StatusBanner = "TOTAL KINETIC TABULA RASA!"
            Else
              If Grid(SwapX1, SwapY1)\gem = #Gem_Hypercube
                HyperTargetColor = Grid(SwapX2, SwapY2)\gem
                Grid(SwapX1, SwapY1)\marked = #True
              Else
                HyperTargetColor = Grid(SwapX1, SwapY1)\gem
                Grid(SwapX2, SwapY2)\marked = #True
              EndIf
              For MainLoopY = 0 To GridN - 1
                For MainLoopX = 0 To GridN - 1
                  If Grid(MainLoopX, MainLoopY)\gem = HyperTargetColor
                    Grid(MainLoopX, MainLoopY)\marked = #True
                  EndIf
                Next
              Next
              StatusBanner = "ZEBRA CHROMATIC RESONANCE!"
            EndIf
            StatusTimer = MainNow + 1800
            ClearProgress = 0.0
            GameState = #State_ClearAnim
          ElseIf MarkAllMatches(SwapX1, SwapY1, SwapX2, SwapY2)
            TotalMoves + 1
            ClearProgress = 0.0
            GameState = #State_ClearAnim
          Else
            SwapCellsData(SwapX1, SwapY1, SwapX2, SwapY2)
            SwapProgress = 0.0
            GameState = #State_RevertAnim
          EndIf
        EndIf

      Case #State_RevertAnim
        SwapProgress + MainDt * 7.0
        If SwapProgress >= 1.0
          SwapProgress = 0.0
          GameState = #State_Idle
        EndIf

      Case #State_ClearAnim
        ClearProgress + MainDt * (5.5 + Bool(TurboAI) * 9.5)
        If ClearProgress >= 1.0
          ResolveMarkedGems()
        EndIf

      Case #State_FallAnim
        If Not UpdateFallingGems(MainDt)
          If MarkAllMatches(-1, -1, -1, -1)
            ClearProgress = 0.0
            GameState = #State_ClearAnim
          Else
            If Not FindBestValidMove(@MainAiX1, @MainAiY1, @MainAiX2, @MainAiY2)
              ReshuffleBoard()
            EndIf
            GameState = #State_Idle
            If TurboAI
              NextAIMoveTime = MainNow + 35
            Else
              NextAIMoveTime = MainNow + 280
            EndIf
          EndIf
        EndIf

      Case #State_Idle
        If AutoPlay And MainNow >= NextAIMoveTime
          If FindBestValidMove(@MainAiX1, @MainAiY1, @MainAiX2, @MainAiY2)
            StartSwap(MainAiX1, MainAiY1, MainAiX2, MainAiY2)
          Else
            ReshuffleBoard()
          EndIf
        EndIf
    EndSelect

    ; 4. RENDER GALLERY FRAME
    ClearScreen(Col_WallBg)
    RenderFrame(MainMX, MainMY)
    FlipBuffers()

  ForEver

Else
  MessageRequester("System Error", "FullHD 1920x1080 display mode unavailable!")
EndIf
End
