// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TMB Invest — NightFib Edition
//@version=6
indicator("TMB Invest - Supply & Demand Zones [NightFib]", overlay=true, max_boxes_count=500)

// ============================================================================
// INPUTS
// ============================================================================

lookback   = input.int(10, "Lookback Periode", minval=3)
maxZones   = input.int(5, "Max Zonen", minval=1, maxval=250)
zoneExt    = input.int(50, "Zone Verlängerung (Bars)", minval=10, maxval=1000)

// NightFib Palette: Supply = White (Short), Demand = Blue (Long)
colSupply  = input.color(color.new(#FFFFFF, 82), "Supply Fill (Short = White)")
colDemand  = input.color(color.new(#4A90E2, 80), "Demand Fill (Long = Blue)")
colSupplyB = input.color(color.new(#FFFFFF, 40), "Supply Rahmen")
colDemandB = input.color(color.new(#4A90E2, 30), "Demand Rahmen")

// ============================================================================
// ZONE DETECTION
// ============================================================================

isSupply = not na(ta.pivothigh(high, lookback, lookback)) and close < open[lookback]
isDemand = not na(ta.pivotlow(low, lookback, lookback)) and close > open[lookback]

var box[] supplyBoxes = array.new_box()
var box[] demandBoxes = array.new_box()

// ============================================================================
// SUPPLY ZONE (WHITE)
// ============================================================================

if isSupply
    top    = high[lookback]
    bottom = math.max(open[lookback], close[lookback])
    b = box.new(bar_index - lookback, top, bar_index + zoneExt, bottom, 
         border_color=colSupplyB, 
         bgcolor=colSupply, 
         border_width=1, 
         text="Supply", 
         text_color=color.new(#FFFFFF, 30), 
         text_size=size.small, 
         text_halign=text.align_left, 
         text_valign=text.align_top)
    array.push(supplyBoxes, b)
    if array.size(supplyBoxes) > maxZones
        box.delete(array.shift(supplyBoxes))

// ============================================================================
// DEMAND ZONE (BLUE)
// ============================================================================

if isDemand
    bottom = low[lookback]
    top    = math.min(open[lookback], close[lookback])
    b = box.new(bar_index - lookback, top, bar_index + zoneExt, bottom, 
         border_color=colDemandB, 
         bgcolor=colDemand, 
         border_width=1, 
         text="Demand", 
         text_color=color.new(#7FC6E0, 30), 
         text_size=size.small, 
         text_halign=text.align_left, 
         text_valign=text.align_bottom)
    array.push(demandBoxes, b)
    if array.size(demandBoxes) > maxZones
        box.delete(array.shift(demandBoxes))
