//+------------------------------------------------------------------+
//| Switcher(drag).mq5                                               |
//| Symbol / timeframe switcher: a small bar at the bottom centre of |
//| the chart with the previous pair, the pair, the timeframe and the|
//| next pair. The pair and timeframe buttons open a list above it.  |
//+------------------------------------------------------------------+
#property copyright   "c. 2026, LuxAlgo"
#property link "http://www.Forex-Station.com/"
#property version     "1.00"
#property description "Symbol / timeframe switcher at the bottom centre of the chart."
#property description "Previous / next pair, the pair and the timeframe: the pair and timeframe buttons open a list above the bar, hover a pair name for a light wave, click to switch the chart."

#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0

enum CPC_THEME
{
   CPC_NEON   = 0, // Neon (blue / red)
   CPC_MONO   = 1, // Mono (gray / white)
   CPC_SUNSET = 2, // Sunset (amber / pink)
   CPC_ICE    = 3, // Ice (ice blue / lavender)
   CPC_OCEAN  = 4  // Ocean / coral
};

enum CPC_FONT
{
   FONT_ARIAL        = 0,  // Arial
   FONT_ARIAL_BOLD   = 1,  // Arial Bold
   FONT_TAHOMA       = 2,  // Tahoma
   FONT_TAHOMA_BOLD  = 3,  // Tahoma Bold
   FONT_VERDANA      = 4,  // Verdana
   FONT_SEGOE_UI     = 5,  // Segoe UI
   FONT_CONSOLAS     = 6,  // Consolas
   FONT_COURIER_NEW  = 7,  // Courier New
   FONT_CALIBRI      = 8,  // Calibri
   FONT_TREBUCHET    = 9,  // Trebuchet MS
   FONT_BAHNSCHRIFT  = 10  // Bahnschrift
};

enum CPC_LAYOUT
{
   LAYOUT_HORIZONTAL = 0, // Horizontal (auto-wrap to next row)
   LAYOUT_VERTICAL   = 1  // Vertical (auto-wrap to next column)
};

enum CPC_DISPLAY_MODE
{
   MODE_NORMAL = 0, // Normal (Always Visible - Combined Panel)
   MODE_POPUP  = 1  // Popup (Open on Click)
};

input group "=== Display Mode ==="
input CPC_DISPLAY_MODE InpDisplayMode = MODE_POPUP;    // Display Mode

input group "=== Behavior ==="
input bool      InpDraggable    = true;      // Drag panel by grip or background
input bool      InpStartMin     = false;     // Start minimized
input string    UniqueID        = "CPCDB";   // Unique ID (saved position & remove copy)

input group "=== Theme Font ==="
input CPC_THEME        Theme          = CPC_SUNSET;     // Color theme
input CPC_FONT         InpFont        = FONT_ARIAL;     // Font family
input int              InpFontSize    = 9;              // Font size (pt)
input double           Ui_scale       = 1.00;           // Text and UI scale
input int              Bar_tr         = 50;             // Panel contrast / shade (%)

input group "=== Panel Position Layout ==="
input int              InpSubWindow   = 0;                    // SubWindow (0 = Main Chart)
input ENUM_BASE_CORNER InpCorner      = CORNER_LEFT_LOWER;    // Panel corner
input int              InpPanelX      = 10;                   // Panel X axis offset (px)
input int              InpPanelY      = 60;                   // Panel Y axis offset (px)
input int              InpPanelWidth  = 500;                  // Control Bar Width in px (0 = Auto)
input int              InpPanelHeight = 50;                   // Control Bar Height in px (0 = Auto)

input group "=== Symbols Source Layout ==="
input bool       InpUseMarketWatch = true;              // Use Market Watch symbols instead of Manual
input int        InpMaxMWSymbols   = 20;                // Max Market Watch symbols to show (0 = All)
input string     InpManualSymbols  = "XAUUSD;XAGUSD";   // Manual symbols (';' or ',' separated; blank = default 28 FX + Metals)
input CPC_LAYOUT InpSymLayout      = LAYOUT_VERTICAL;   // Symbols orientation
input int        InpSymWidth       = 180;               // Symbol button width (px, 0 = Auto)
input int        InpSymHeight      = 40;                // Symbol button height (px, 0 = Auto)

input group "=== Timeframe Layout ==="
input CPC_LAYOUT InpTfLayout       = LAYOUT_VERTICAL;     // Timeframes orientation
input int        InpTfWidth        = 70;                  // Timeframe button width (px, 0 = Auto)
input int        InpTfHeight       = 40;                  // Timeframe button height (px, 0 = Auto)

//--- Theme color tables
int gTheme = 0;
const color TH_DN[5]   = {C'255,32,104',  C'255,32,104',  C'255,61,127', C'168,139,255', C'255,122,89'};
const color TH_G1[5]   = {C'255,32,104',  C'58,58,66',    C'255,61,127', C'30,74,168',   C'46,230,200'};
const color TH_G2[5]   = {C'166,77,255',  C'140,140,150', C'255,122,69', C'79,141,255',  C'143,185,168'};
const color TH_G3[5]   = {C'123,92,255',  C'255,255,255', C'255,200,87', C'189,235,255', C'255,122,89'};
const color TH_TINT[5] = {C'123,92,255',  C'128,128,138', C'255,122,69', C'79,141,255',  C'95,175,160'};

color DC_PANEL = C'13,10,21',    DC_CHIP = C'19,15,30';
color DC_LINE  = C'42,33,64',    DC_EDGE = C'58,47,82';
color DC_TEXT  = C'243,238,255', DC_SOFT = C'207,196,230', DC_MUTED = C'169,157,194';
color DC_DN    = C'255,32,104';
color DC_NEON1 = C'255,32,104',  DC_NEON2 = C'166,77,255', DC_NEON3 = C'123,92,255';

//--- Default fallback pairs (used if Manual list is empty and Market Watch is off)
#define DEF_PAIRS 31
#define DEF_FX    28
const string DEF_NAME[DEF_PAIRS] =
{
   "AUDCAD", "AUDCHF", "AUDJPY", "AUDNZD", "AUDUSD", "CADCHF", "CADJPY",
   "CHFJPY", "EURAUD", "EURCAD", "EURCHF", "EURGBP", "EURJPY", "EURNZD",
   "EURUSD", "GBPAUD", "GBPCAD", "GBPCHF", "GBPJPY", "GBPNZD", "GBPUSD",
   "NZDCAD", "NZDCHF", "NZDJPY", "NZDUSD", "USDCAD", "USDCHF", "USDJPY",
   "XAGUSD", "XAUUSD", "XPDUSD"
};

#define SW_TFS 21
const ENUM_TIMEFRAMES SW_PER[SW_TFS] =
{
   PERIOD_M1,  PERIOD_M2,  PERIOD_M3,  PERIOD_M4,  PERIOD_M5, PERIOD_M6, PERIOD_M10,
   PERIOD_M12, PERIOD_M15, PERIOD_M20, PERIOD_M30, PERIOD_H1, PERIOD_H2, PERIOD_H3,
   PERIOD_H4,  PERIOD_H6,  PERIOD_H8,  PERIOD_H12, PERIOD_D1, PERIOD_W1, PERIOD_MN1
};

//--- Hit codes
#define SW_GRIP  99
#define SW_PREV  100
#define SW_PAIR  101
#define SW_TF    102
#define SW_NEXT  103
#define SW_CLOSE 104
#define SW_MIN   105
#define SW_T0    300    // + timeframe index (300..320)
#define SW_P0    1000   // + symbol index (1000+)

//--- Active symbol list
string gSymDisp[];
string gSymReal[];
int    gSymCount = 0;
bool   gSymLoaded = false;
bool   gIsDefaultList = false;

//--- Geometry & Subwindow state
int    gSubWin  = 0;
int    gSubYOff = 0;
int    gW = 0, gH = 0;

//--- Object prefixes (strictly separated to prevent ghost objects)
string gPrefix    = "";
string gBarPrefix = "";
string gPopPrefix = "";

//--- UI state
bool   gSwShown     = false;
int    gSwPop       = 0;       // Popup mode only: 0 = none, SW_PAIR, SW_TF
int    gLastPop     = -1;
bool   gMinimized   = false;
bool   gLastMin     = false;
string gLastNormSig = "";
int    gSwHov       = 0;

//--- Dynamic hit-test arrays
int    gSwN = 0;
int    gSwC[], gSwX1[], gSwY1[], gSwX2[], gSwY2[];
int    gSwBox[3][4];           // [0] main bar, [1] popup / TF box, [2] Symbols box

//--- Panel position & dragging
//--- gSavedX/gSavedY store the user's preferred dragged spot; gBarX/gBarY are clamped live to stay visible
int    gSavedX = 0, gSavedY = 0;
int    gBarX   = 0, gBarY   = 0;
int    gBarW   = 0, gBarH   = 0;
bool   gBarDragged = false;
bool   gDragging   = false;
int    gDragX = 0, gDragY = 0, gDragBX = 0, gDragBY = 0;

//--- Mouse & Switching
string          gGoSym = "";
ENUM_TIMEFRAMES gGoTf  = PERIOD_CURRENT;
bool            gPrevDown  = false;
int             gPress     = 0;
bool            gScrollOff = false;
bool            gMouseWas  = false;
bool            gMouseRef  = false;

//+------------------------------------------------------------------+
//| Helpers                                                          |
//+------------------------------------------------------------------+
color ColorMix(const color c1, const color c2, const double t)
{
   int a = (int)c1, b = (int)c2;
   int r = (int)MathRound((a & 255) * t + (b & 255) * (1.0 - t));
   int g = (int)MathRound(((a >> 8) & 255) * t + ((b >> 8) & 255) * (1.0 - t));
   int l = (int)MathRound(((a >> 16) & 255) * t + ((b >> 16) & 255) * (1.0 - t));
   return (color)(r | (g << 8) | (l << 16));
}

int S(const double v)
{
   return (int)MathRound(v * MathMax(0.5, Ui_scale));
}

int FontPt(const double basePt)
{
   return MathMax(6, (int)MathRound(basePt * MathMax(0.5, Ui_scale)));
}

string GetFontName(const CPC_FONT f, const bool preferBold = false)
{
   switch(f)
   {
      case FONT_ARIAL:       return preferBold ? "Arial Bold" : "Arial";
      case FONT_ARIAL_BOLD:  return "Arial Bold";
      case FONT_TAHOMA:      return preferBold ? "Tahoma Bold" : "Tahoma";
      case FONT_TAHOMA_BOLD: return "Tahoma Bold";
      case FONT_VERDANA:     return preferBold ? "Verdana Bold" : "Verdana";
      case FONT_SEGOE_UI:    return preferBold ? "Segoe UI Bold" : "Segoe UI";
      case FONT_CONSOLAS:    return preferBold ? "Consolas Bold" : "Consolas";
      case FONT_COURIER_NEW: return preferBold ? "Courier New Bold" : "Courier New";
      case FONT_CALIBRI:     return preferBold ? "Calibri Bold" : "Calibri";
      case FONT_TREBUCHET:   return preferBold ? "Trebuchet MS Bold" : "Trebuchet MS";
      case FONT_BAHNSCHRIFT: return "Bahnschrift";
   }
   return "Arial";
}

void ThemeApply()
{
   int t = MathMax(0, MathMin(4, gTheme));
   DC_DN    = TH_DN[t];
   DC_NEON1 = TH_G1[t];
   DC_NEON2 = TH_G2[t];
   DC_NEON3 = TH_G3[t];

   double shade = MathMax(0.0, MathMin(1.0, (100 - MathMax(0, MathMin(100, Bar_tr))) / 100.0));

   if(t == CPC_NEON)
   {
      DC_PANEL = ColorMix(C'18,14,29', C'8,6,14', shade);
      DC_CHIP  = C'24,19,38';
      DC_LINE  = C'42,33,64';
      DC_EDGE  = C'68,55,96';
      DC_TEXT  = C'243,238,255';
      DC_SOFT  = C'207,196,230';
      DC_MUTED = C'169,157,194';
      return;
   }

   color k = TH_TINT[t];
   DC_PANEL = ColorMix(k, ColorMix(C'14,14,18', C'6,6,8', shade), 0.08);
   DC_CHIP  = ColorMix(k, C'20,20,26',    0.11);
   DC_LINE  = ColorMix(k, C'34,34,42',    0.22);
   DC_EDGE  = ColorMix(k, C'62,62,74',    0.25);
   DC_TEXT  = ColorMix(k, C'244,244,248', 0.06);
   DC_SOFT  = ColorMix(k, C'210,210,218', 0.14);
   DC_MUTED = ColorMix(k, C'166,166,176', 0.18);
}

string SwTfName(const ENUM_TIMEFRAMES tf)
{
   ENUM_TIMEFRAMES t = (tf == PERIOD_CURRENT) ? (ENUM_TIMEFRAMES)_Period : tf;
   if(t == PERIOD_MN1) return "MN";
   return StringSubstr(EnumToString(t), 7);
}

void ReadGeom()
{
   int totalWin = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
   if(totalWin < 1) totalWin = 1;
   gSubWin  = MathMax(0, MathMin(InpSubWindow, totalWin - 1));
   gW       = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
   gH       = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, gSubWin);
   gSubYOff = (int)ChartGetInteger(0, CHART_WINDOW_YDISTANCE, gSubWin);
}

//+------------------------------------------------------------------+
//| Symbol List Resolution (Market Watch / Manual / Default)         |
//+------------------------------------------------------------------+
string ResolveSingleSymbol(const string raw, const string pre, const string suf)
{
   bool custom = false;
   if(SymbolExist(raw, custom)) return raw;

   string withAffix = pre + raw + suf;
   if((pre != "" || suf != "") && SymbolExist(withAffix, custom))
      return withAffix;

   string upperRaw = raw;
   StringToUpper(upperRaw);
   string best = "";
   int tot = SymbolsTotal(false);
   for(int k = 0; k < tot; k++)
   {
      string s = SymbolName(k, false);
      string u = s;
      StringToUpper(u);
      if(StringFind(u, upperRaw) < 0) continue;
      if(best != "" && StringLen(s) >= StringLen(best)) continue;
      if(SymbolInfoInteger(s, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_DISABLED) continue;
      best = s;
   }
   return best;
}

void DetectBrokerAffix(string &pre, string &suf)
{
   pre = ""; suf = "";
   for(int i = 0; i < DEF_PAIRS; i++)
   {
      int p = StringFind(_Symbol, DEF_NAME[i]);
      if(p >= 0)
      {
         pre = StringSubstr(_Symbol, 0, p);
         suf = StringSubstr(_Symbol, p + StringLen(DEF_NAME[i]));
         return;
      }
   }
}

void LoadSymbols(const bool force = false)
{
   if(gSymLoaded && !force) return;
   gSymLoaded     = true;
   gIsDefaultList = false;
   gSymCount      = 0;
   ArrayResize(gSymDisp, 0);
   ArrayResize(gSymReal, 0);

   //--- Mode 1: Market Watch
   if(InpUseMarketWatch)
   {
      int mwTotal = SymbolsTotal(true);
      int limit   = (InpMaxMWSymbols > 0) ? MathMin(mwTotal, InpMaxMWSymbols) : mwTotal;
      ArrayResize(gSymDisp, limit);
      ArrayResize(gSymReal, limit);
      for(int i = 0; i < limit; i++)
      {
         string s = SymbolName(i, true);
         gSymDisp[gSymCount] = s;
         gSymReal[gSymCount] = s;
         gSymCount++;
      }
      return;
   }

   string pre = "", suf = "";
   DetectBrokerAffix(pre, suf);

   //--- Mode 2: Manual Symbols
   string cleaned = InpManualSymbols;
   StringReplace(cleaned, ",", ";");
   StringTrimLeft(cleaned);
   StringTrimRight(cleaned);

   if(StringLen(cleaned) > 0)
   {
      string parts[];
      int n = StringSplit(cleaned, ';', parts);
      ArrayResize(gSymDisp, n);
      ArrayResize(gSymReal, n);
      for(int i = 0; i < n; i++)
      {
         string item = parts[i];
         StringTrimLeft(item);
         StringTrimRight(item);
         if(item == "") continue;
         gSymDisp[gSymCount] = item;
         gSymReal[gSymCount] = ResolveSingleSymbol(item, pre, suf);
         gSymCount++;
      }
      if(gSymCount > 0)
      {
         ArrayResize(gSymDisp, gSymCount);
         ArrayResize(gSymReal, gSymCount);
         return;
      }
   }

   //--- Mode 3: Default 28 FX + Metals fallback
   gIsDefaultList = true;
   ArrayResize(gSymDisp, DEF_PAIRS);
   ArrayResize(gSymReal, DEF_PAIRS);
   for(int i = 0; i < DEF_PAIRS; i++)
   {
      gSymDisp[i] = DEF_NAME[i];
      gSymReal[i] = ResolveSingleSymbol(DEF_NAME[i], pre, suf);
   }
   gSymCount = DEF_PAIRS;
}

int CurrentSymbolIndex()
{
   for(int i = 0; i < gSymCount; i++)
      if(gSymReal[i] == _Symbol) return i;
   for(int i = 0; i < gSymCount; i++)
      if(StringFind(_Symbol, gSymDisp[i]) >= 0) return i;
   return -1;
}

//+------------------------------------------------------------------+
//| Deterministic Native Object Primitives                           |
//+------------------------------------------------------------------+
void PutRect(const string name, const int x1, const int y1, const int x2, const int y2,
             const color bg, const color border, const int zOrder = 10)
{
   int w = MathMax(1, x2 - x1 + 1);
   int h = MathMax(1, y2 - y1 + 1);

   if(ObjectFind(0, name) < 0)
      ObjectCreate(0, name, OBJ_RECTANGLE_LABEL, gSubWin, 0, 0);

   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x1);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y1);
   ObjectSetInteger(0, name, OBJPROP_XSIZE, w);
   ObjectSetInteger(0, name, OBJPROP_YSIZE, h);
   ObjectSetInteger(0, name, OBJPROP_BGCOLOR, bg);
   ObjectSetInteger(0, name, OBJPROP_COLOR, border);
   ObjectSetInteger(0, name, OBJPROP_BORDER_TYPE, BORDER_FLAT);
   ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
   ObjectSetInteger(0, name, OBJPROP_BACK, false);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, name, OBJPROP_ZORDER, zOrder);
   ObjectSetString(0, name, OBJPROP_TOOLTIP, "\n");
}

void PutText(const string name, const int x, const int y, const string text,
             const color clr, const int fontSize, const string fontName,
             const ENUM_ANCHOR_POINT anchor = ANCHOR_CENTER, const int zOrder = 12)
{
   if(ObjectFind(0, name) < 0)
      ObjectCreate(0, name, OBJ_LABEL, gSubWin, 0, 0);

   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, anchor);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetString(0, name, OBJPROP_FONT, fontName);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, fontSize);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_BACK, false);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, name, OBJPROP_ZORDER, zOrder);
   ObjectSetString(0, name, OBJPROP_TOOLTIP, "\n");
}

void AddHitRect(const int code, const int x1, const int y1, const int x2, const int y2)
{
   if(gSwN >= ArraySize(gSwC))
   {
      int nextCap = gSwN + 64;
      ArrayResize(gSwC,  nextCap);
      ArrayResize(gSwX1, nextCap);
      ArrayResize(gSwY1, nextCap);
      ArrayResize(gSwX2, nextCap);
      ArrayResize(gSwY2, nextCap);
   }
   gSwC[gSwN]  = code;
   gSwX1[gSwN] = x1;
   gSwY1[gSwN] = y1;
   gSwX2[gSwN] = x2;
   gSwY2[gSwN] = y2;
   gSwN++;
}

void DrawButton(const string pfx, const int code, const int x1, const int y1, const int x2, const int y2,
                const string text, const bool active, const int arrow, const bool live = true)
{
   bool hov = (live && gSwHov == code);

   color bg = live ? DC_CHIP : ColorMix(DC_CHIP, DC_PANEL, 0.45);
   if(active)   bg = ColorMix(DC_NEON2, DC_CHIP, 0.38);
   else if(hov) bg = ColorMix(DC_NEON2, DC_CHIP, 0.22);

   color border = active ? DC_DN : hov ? DC_NEON2 : live ? DC_EDGE : DC_LINE;
   color txtClr = (active || hov) ? DC_TEXT : live ? DC_SOFT : DC_EDGE;

   string id = IntegerToString(code);
   PutRect(pfx + "BT_" + id, x1, y1, x2, y2, bg, border, 12);

   int cx        = (x1 + x2) / 2;
   int cy        = (y1 + y2) / 2;
   int fSize     = FontPt(MathMax(6, InpFontSize));
   string fMain  = GetFontName(InpFont, active);
   string fArrow = GetFontName(InpFont, true);

   if(text != "")
   {
      int tx = cx - (arrow == 2 ? S(5) : 0);
      PutText(pfx + "TX_" + id, tx, cy, text, txtClr, fSize, fMain, ANCHOR_CENTER, 13);
   }

   if(arrow == 2)
      PutText(pfx + "AR_" + id, x2 - S(7), cy, active ? "v" : "^", txtClr, MathMax(6, fSize - 1), fArrow, ANCHOR_CENTER, 13);
   else if(arrow == -1)
      PutText(pfx + "AR_" + id, cx, cy, "<", txtClr, fSize, fArrow, ANCHOR_CENTER, 13);
   else if(arrow == 1)
      PutText(pfx + "AR_" + id, cx, cy, ">", txtClr, fSize, fArrow, ANCHOR_CENTER, 13);

   if(live) AddHitRect(code, x1, y1, x2, y2);
}

void DrawHead(const string pfx, const string id, const int x1, const int x2, const int y, const int h, const string label)
{
   int cy = y + (h - S(2)) / 2;
   int pt = FontPt(MathMax(6, InpFontSize - 1));
   PutText(pfx + "HD_" + id, x1 + S(2), cy, label, DC_MUTED, pt, GetFontName(InpFont, true), ANCHOR_LEFT, 12);

   int textW = (int)MathRound(StringLen(label) * pt * 0.85);
   int lx = x1 + S(2) + textW + S(6);
   if(lx < x2)
      PutRect(pfx + "LN_" + id, lx, cy, x2, cy, DC_EDGE, DC_EDGE, 11);
   else
      ObjectDelete(0, pfx + "LN_" + id);
}

void DrawGrip(const int x1, const int y1, const int x2, const int y2)
{
   color gripBg  = (gSwHov == SW_GRIP || gDragging) ? ColorMix(DC_NEON2, DC_CHIP, 0.25) : DC_PANEL;
   color gripBrd = (gSwHov == SW_GRIP || gDragging) ? DC_NEON2 : DC_LINE;
   PutRect(gBarPrefix + "GR_BOX", x1, y1, x2, y2, gripBg, gripBrd, 11);

   int dotSz    = MathMax(2, S(2));
   int gcx      = (x1 + x2) / 2;
   int gcy      = (y1 + y2) / 2;
   int dIdx     = 0;
   color dotClr = (gSwHov == SW_GRIP || gDragging) ? DC_TEXT : DC_MUTED;

   for(int r = -1; r <= 1; r++)
   {
      for(int c = -1; c <= 1; c += 2)
      {
         int dx = gcx + c * S(3) - dotSz / 2;
         int dy = gcy + r * S(4) - dotSz / 2;
         PutRect(gBarPrefix + "GR_" + IntegerToString(dIdx++), dx, dy, dx + dotSz - 1, dy + dotSz - 1, dotClr, dotClr, 12);
      }
   }
   if(InpDraggable) AddHitRect(SW_GRIP, x1, y1, x2, y2);
}

//+------------------------------------------------------------------+
//| Shared Main Control Bar Helper                                   |
//+------------------------------------------------------------------+
void MeasureControlBar(int &barW, int &barH, int &bh, int &wPair, int &wTf)
{
   int pad    = S(5);
   int gap    = S(3);
   int gripW  = S(18);
   int wStep  = S(22);
   int wMin   = S(22);
   int wClose = S(22);

   bh   = (InpPanelHeight > 0) ? MathMax(14, InpPanelHeight - pad * 2) : S(22);
   barH = (InpPanelHeight > 0) ? MathMax(20, InpPanelHeight)           : (pad * 2 + bh);

   wPair = S(100);
   wTf   = S(56);

   if(gMinimized)
   {
      barW = pad * 2 + gripW + wMin + wClose + gap * 2;
      return;
   }

   int fixedW = pad * 2 + gripW + wStep * 2 + wMin + wClose + gap * 6;
   if(InpPanelWidth > 0)
   {
      int targetW = MathMax(fixedW + 90, InpPanelWidth);
      targetW     = MathMin(targetW, MathMax(fixedW + 90, gW - S(8)));
      int flexW   = targetW - fixedW;
      wPair       = (int)MathRound(flexW * 0.63);
      wTf         = flexW - wPair;
      barW        = targetW;
   }
   else
   {
      barW = fixedW + wPair + wTf;
   }
}

void DrawControlBarAt(const int bx1, const int by1, const int barW, const int barH,
                      const int bh, const int wPair, const int wTf, const bool showArrows)
{
   int pad    = S(5);
   int gap    = S(3);
   int gripW  = S(18);
   int wStep  = S(22);
   int wMin   = S(22);
   int wClose = S(22);

   int bx2 = bx1 + barW - 1;
   int by2 = by1 + barH - 1;

   gSwBox[0][0] = bx1; gSwBox[0][1] = by1;
   gSwBox[0][2] = bx2; gSwBox[0][3] = by2;

   PutRect(gBarPrefix + "BG",  bx1, by1, bx2, by2, DC_PANEL, DC_NEON3, 10);
   PutRect(gBarPrefix + "TOP", bx1 + 1, by1, bx2 - 1, by1, DC_NEON1, DC_NEON1, 11);

   int x  = bx1 + pad;
   int y1 = by1 + pad;
   int y2 = y1 + bh - 1;

   DrawGrip(x, y1, x + gripW - 1, y2);
   x += gripW + gap;

   if(gMinimized)
   {
      DrawButton(gBarPrefix, SW_MIN,   x, y1, x + wMin - 1,   y2, "+", false, 0);
      x += wMin + gap;
      DrawButton(gBarPrefix, SW_CLOSE, x, y1, x + wClose - 1, y2, "x", false, 0);
      return;
   }

   int curIdx = CurrentSymbolIndex();
   int arr    = showArrows ? 2 : 0;

   //--- Full Control Bar: [:::] [<] [SYMBOL] [>] [TF] [-] [x]
   DrawButton(gBarPrefix, SW_PREV, x, y1, x + wStep - 1, y2, "", false, -1);
   x += wStep + gap;

   string pairCap = (curIdx >= 0) ? gSymDisp[curIdx] : _Symbol;
   DrawButton(gBarPrefix, SW_PAIR, x, y1, x + wPair - 1, y2, pairCap, (showArrows && gSwPop == SW_PAIR), arr);
   x += wPair + gap;

   DrawButton(gBarPrefix, SW_NEXT, x, y1, x + wStep - 1, y2, "", false, 1);
   x += wStep + gap;

   DrawButton(gBarPrefix, SW_TF, x, y1, x + wTf - 1, y2, SwTfName((ENUM_TIMEFRAMES)_Period), (showArrows && gSwPop == SW_TF), arr);
   x += wTf + gap;

   DrawButton(gBarPrefix, SW_MIN, x, y1, x + wMin - 1, y2, "-", false, 0);
   x += wMin + gap;

   DrawButton(gBarPrefix, SW_CLOSE, x, y1, x + wClose - 1, y2, "x", false, 0);
}

//+------------------------------------------------------------------+
//| Position Resolver: Retains Saved Spot & Never Disappears         |
//+------------------------------------------------------------------+
void ResolveBarPosition(const int panelW, const int panelH)
{
   int targetX = 0, targetY = 0;

   if(gBarDragged)
   {
      targetX = gSavedX;
      targetY = gSavedY;
   }
   else
   {
      switch(InpCorner)
      {
         case CORNER_LEFT_UPPER:
            targetX = InpPanelX;
            targetY = InpPanelY;
            break;
         case CORNER_RIGHT_UPPER:
            targetX = gW - panelW - InpPanelX;
            targetY = InpPanelY;
            break;
         case CORNER_LEFT_LOWER:
            targetX = InpPanelX;
            targetY = gH - panelH - InpPanelY;
            break;
         case CORNER_RIGHT_LOWER:
            targetX = gW - panelW - InpPanelX;
            targetY = gH - panelH - InpPanelY;
            break;
      }
   }

   gBarX = MathMax(0, MathMin(targetX, MathMax(0, gW - panelW)));
   gBarY = MathMax(0, MathMin(targetY, MathMax(0, gH - panelH)));
}

//+------------------------------------------------------------------+
//| Render: Normal Mode (Full Control Bar + Popup-Style Grids)       |
//+------------------------------------------------------------------+
void DrawNormalMode()
{
   int ctrlBarW = 0, ctrlBarH = 0, bh = 0, wPair = 0, wTf = 0;
   MeasureControlBar(ctrlBarW, ctrlBarH, bh, wPair, wTf);

   //--- Minimized compact pill
   if(gMinimized)
   {
      gBarW = ctrlBarW;
      gBarH = ctrlBarH;
      ResolveBarPosition(ctrlBarW, ctrlBarH);
      DrawControlBarAt(gBarX, gBarY, ctrlBarW, ctrlBarH, bh, wPair, wTf, false);
      gSwShown = true;
      return;
   }

   int pad    = S(4);
   int gap    = S(3);
   int secGap = S(4);

   int tfW  = MathMax(24, (InpTfWidth   > 0) ? InpTfWidth   : S(44));
   int tfH  = MathMax(16, (InpTfHeight  > 0) ? InpTfHeight  : S(26));
   int symW = MathMax(32, (InpSymWidth  > 0) ? InpSymWidth  : S(86));
   int symH = MathMax(16, (InpSymHeight > 0) ? InpSymHeight : S(26));

   int maxW     = MathMax(MathMax(tfW, symW) + pad * 2, gW - S(12));
   int maxGridH = MathMax(MathMax(tfH, symH) + pad * 2, gH - S(12) - ctrlBarH - secGap);

   bool sideBySide  = (InpTfLayout == LAYOUT_VERTICAL);
   bool alignBottom = (InpCorner == CORNER_LEFT_LOWER || InpCorner == CORNER_RIGHT_LOWER);
   bool alignRight  = (InpCorner == CORNER_RIGHT_UPPER || InpCorner == CORNER_RIGHT_LOWER);

   //--- 1. Measure Timeframes Box
   int tfCols = 1, tfRows = 1;
   if(InpTfLayout == LAYOUT_HORIZONTAL)
   {
      int availTfW = MathMax(tfW, maxW - pad * 2);
      int maxC     = MathMax(1, (availTfW + gap) / (tfW + gap));
      tfCols       = MathMin(maxC, SW_TFS);
      tfRows       = (SW_TFS + tfCols - 1) / tfCols;
   }
   else
   {
      int availTfH = MathMax(tfH, maxGridH - pad * 2);
      int maxR     = MathMax(1, (availTfH + gap) / (tfH + gap));
      tfRows       = MathMin(maxR, SW_TFS);
      tfCols       = (SW_TFS + tfRows - 1) / tfRows;
   }
   int tfBoxW = pad * 2 + tfCols * tfW + (tfCols - 1) * gap;
   int tfBoxH = pad * 2 + tfRows * tfH + (tfRows - 1) * gap;

   //--- 2. Measure Symbols Box
   int symCols = 1, symRows = 1;
   int symBoxW = 0, symBoxH = 0;

   if(gSymCount > 0)
   {
      if(InpSymLayout == LAYOUT_HORIZONTAL)
      {
         int availSymW = sideBySide ? MathMax(symW, maxW - tfBoxW - secGap - pad * 2)
                                    : MathMax(symW, maxW - pad * 2);
         int maxC      = MathMax(1, (availSymW + gap) / (symW + gap));
         symCols       = MathMin(maxC, gSymCount);
         symRows       = (gSymCount + symCols - 1) / symCols;
      }
      else
      {
         int availSymH = sideBySide ? MathMax(symH, maxGridH - pad * 2)
                                    : MathMax(symH, maxGridH - tfBoxH - secGap - pad * 2);
         int maxR      = MathMax(1, (availSymH + gap) / (symH + gap));
         symRows       = MathMin(maxR, gSymCount);
         symCols       = (gSymCount + symRows - 1) / symRows;
      }
      symBoxW = pad * 2 + symCols * symW + (symCols - 1) * gap;
      symBoxH = pad * 2 + symRows * symH + (symRows - 1) * gap;
   }

   //--- 3. Combined Bounding Dimensions & Position
   int gridsW = sideBySide ? (tfBoxW + (gSymCount > 0 ? secGap + symBoxW : 0))
                           : MathMax(tfBoxW, symBoxW);
   int gridsH = sideBySide ? MathMax(tfBoxH, symBoxH)
                           : (tfBoxH + (gSymCount > 0 ? secGap + symBoxH : 0));

   int totalW = MathMax(ctrlBarW, gridsW);
   int totalH = ctrlBarH + secGap + gridsH;

   gBarW = totalW;
   gBarH = totalH;

   ResolveBarPosition(totalW, totalH);

   //--- 4. Position & Draw Main Control Bar
   int ctrlX     = alignRight ? (gBarX + totalW - ctrlBarW) : gBarX;
   int ctrlY     = alignBottom ? (gBarY + gridsH + secGap) : gBarY;
   int gridsTopY = alignBottom ? gBarY : (gBarY + ctrlBarH + secGap);

   DrawControlBarAt(ctrlX, ctrlY, ctrlBarW, ctrlBarH, bh, wPair, wTf, false);

   //--- 5. Position & Draw Timeframes Box
   int tfX = sideBySide ? (alignRight ? (gBarX + totalW - gridsW) : gBarX)
                        : (alignRight ? (gBarX + totalW - tfBoxW) : gBarX);
   int tfY = (sideBySide && alignBottom) ? (gridsTopY + gridsH - tfBoxH) : gridsTopY;

   gSwBox[1][0] = tfX;
   gSwBox[1][1] = tfY;
   gSwBox[1][2] = tfX + tfBoxW - 1;
   gSwBox[1][3] = tfY + tfBoxH - 1;

   PutRect(gBarPrefix + "TF_BG",  tfX, tfY, tfX + tfBoxW - 1, tfY + tfBoxH - 1, DC_PANEL, DC_NEON3, 10);
   PutRect(gBarPrefix + "TF_TOP", tfX + 1, tfY, tfX + tfBoxW - 2, tfY, DC_NEON1, DC_NEON1, 11);

   for(int i = 0; i < SW_TFS; i++)
   {
      int col = (InpTfLayout == LAYOUT_HORIZONTAL) ? (i % tfCols) : (i / tfRows);
      int row = (InpTfLayout == LAYOUT_HORIZONTAL) ? (i / tfCols) : (i % tfRows);
      int cx1 = tfX + pad + col * (tfW + gap);
      int cy1 = tfY + pad + row * (tfH + gap);
      DrawButton(gBarPrefix, SW_T0 + i, cx1, cy1, cx1 + tfW - 1, cy1 + tfH - 1,
                 SwTfName(SW_PER[i]), SW_PER[i] == (ENUM_TIMEFRAMES)_Period, 0, true);
   }

   //--- 6. Position & Draw Symbols Box
   if(gSymCount > 0)
   {
      int symX = sideBySide ? (tfX + tfBoxW + secGap)
                            : (alignRight ? (gBarX + totalW - symBoxW) : gBarX);
      int symY = sideBySide ? (alignBottom ? (gridsTopY + gridsH - symBoxH) : gridsTopY)
                            : (tfY + tfBoxH + secGap);

      gSwBox[2][0] = symX;
      gSwBox[2][1] = symY;
      gSwBox[2][2] = symX + symBoxW - 1;
      gSwBox[2][3] = symY + symBoxH - 1;

      PutRect(gBarPrefix + "SY_BG",  symX, symY, symX + symBoxW - 1, symY + symBoxH - 1, DC_PANEL, DC_NEON3, 10);
      PutRect(gBarPrefix + "SY_TOP", symX + 1, symY, symX + symBoxW - 2, symY, DC_NEON1, DC_NEON1, 11);

      int curIdx = CurrentSymbolIndex();
      for(int i = 0; i < gSymCount; i++)
      {
         int col = (InpSymLayout == LAYOUT_HORIZONTAL) ? (i % symCols) : (i / symRows);
         int row = (InpSymLayout == LAYOUT_HORIZONTAL) ? (i / symCols) : (i % symRows);
         int cx1 = symX + pad + col * (symW + gap);
         int cy1 = symY + pad + row * (symH + gap);
         DrawButton(gBarPrefix, SW_P0 + i, cx1, cy1, cx1 + symW - 1, cy1 + symH - 1,
                    gSymDisp[i], i == curIdx, 0, gSymReal[i] != "");
      }
   }

   gSwShown = true;
}

//+------------------------------------------------------------------+
//| Render: Popup Mode (Compact Bar + Click-to-Open Menus)           |
//+------------------------------------------------------------------+
void DrawPopupMode()
{
   int pad = S(5);
   int gap = S(3);

   int barW = 0, barH = 0, bh = 0, wPair = 0, wTf = 0;
   MeasureControlBar(barW, barH, bh, wPair, wTf);

   gBarW = barW;
   gBarH = barH;

   ResolveBarPosition(barW, barH);
   DrawControlBarAt(gBarX, gBarY, barW, barH, bh, wPair, wTf, true);

   if(gMinimized)
   {
      gSwShown = true;
      return;
   }

   int curIdx = CurrentSymbolIndex();

   //--- 2. Popup Menu (Symbols or Timeframes)
   if(gSwPop == SW_PAIR || gSwPop == SW_TF)
   {
      int n = (gSwPop == SW_PAIR) ? gSymCount : SW_TFS;
      if(n > 0)
      {
         bool isPair = (gSwPop == SW_PAIR);
         CPC_LAYOUT layout = isPair ? InpSymLayout : InpTfLayout;

         int cellW = isPair ? ((InpSymWidth  > 0) ? InpSymWidth  : S(86))
                            : ((InpTfWidth   > 0) ? InpTfWidth   : S(44));
         int cellH = isPair ? ((InpSymHeight > 0) ? InpSymHeight : S(26))
                            : ((InpTfHeight  > 0) ? InpTfHeight  : S(26));
         cellW = MathMax(20, cellW);
         cellH = MathMax(16, cellH);

         int headH    = S(16);
         int groupGap = S(6);
         int gapY     = S(4);
         bool useGroups = (isPair && gIsDefaultList);

         int spaceAbove = gBarY - gapY;
         int spaceBelow = gH - (gBarY + barH) - gapY;
         int maxSpaceH  = MathMax(spaceAbove, spaceBelow);
         if(maxSpaceH < cellH + pad * 2) maxSpaceH = MathMax(cellH + pad * 2, gH - S(16));

         int cols = 1, rows = 1, popW = 0, popH = 0;
         int fxCols = 1, mtCols = 1, fxRows = 1;

         if(layout == LAYOUT_HORIZONTAL)
         {
            int availW  = MathMax(cellW, gW - S(16) - pad * 2);
            int maxCols = MathMax(1, (availW + gap) / (cellW + gap));
            cols        = MathMin(maxCols, n);

            if(useGroups)
            {
               fxRows = (DEF_FX + cols - 1) / cols;
               int mtRows = (DEF_PAIRS - DEF_FX + cols - 1) / cols;
               rows = fxRows + mtRows;
               popW = pad * 2 + cols * cellW + (cols - 1) * gap;
               popH = pad * 2 + rows * cellH + (rows - 1) * gap + headH * 2 + groupGap;
            }
            else
            {
               rows = (n + cols - 1) / cols;
               popW = pad * 2 + cols * cellW + (cols - 1) * gap;
               popH = pad * 2 + rows * cellH + (rows - 1) * gap;
            }
         }
         else
         {
            int availH  = MathMax(cellH, maxSpaceH - pad * 2 - (useGroups ? headH : 0));
            int maxRows = MathMax(1, (availH + gap) / (cellH + gap));

            if(useGroups)
            {
               int fxN = DEF_FX;
               int mtN = DEF_PAIRS - DEF_FX;
               rows    = MathMin(maxRows, MathMax(fxN, mtN));
               fxCols  = (fxN + rows - 1) / rows;
               mtCols  = (mtN + rows - 1) / rows;
               cols    = fxCols + mtCols;
               popW    = pad * 2 + cols * cellW + MathMax(0, cols - 2) * gap + groupGap;
               popH    = pad * 2 + headH + rows * cellH + (rows - 1) * gap;
            }
            else
            {
               rows = MathMin(maxRows, n);
               cols = (n + rows - 1) / rows;
               popW = pad * 2 + cols * cellW + (cols - 1) * gap;
               popH = pad * 2 + rows * cellH + (rows - 1) * gap;
            }
         }

         int popX = gBarX + barW / 2 - popW / 2;
         popX = MathMax(0, MathMin(popX, MathMax(0, gW - popW)));

         int popY = 0;
         if(spaceAbove >= popH)
            popY = gBarY - gapY - popH;
         else if(spaceBelow >= popH)
            popY = gBarY + barH + gapY;
         else
            popY = (spaceBelow > spaceAbove) ? (gBarY + barH + gapY) : (gBarY - gapY - popH);
         popY = MathMax(0, MathMin(popY, MathMax(0, gH - popH)));

         gSwBox[1][0] = popX;
         gSwBox[1][1] = popY;
         gSwBox[1][2] = popX + popW - 1;
         gSwBox[1][3] = popY + popH - 1;

         PutRect(gPopPrefix + "BG",  popX, popY, popX + popW - 1, popY + popH - 1, DC_PANEL, DC_NEON3, 10);
         PutRect(gPopPrefix + "TOP", popX + 1, popY, popX + popW - 2, popY, DC_NEON1, DC_NEON1, 11);

         if(isPair)
         {
            if(useGroups && layout == LAYOUT_HORIZONTAL)
            {
               int top2 = popY + pad + headH + fxRows * (cellH + gap) + groupGap;
               DrawHead(gPopPrefix, "FX", popX + pad, popX + popW - 1 - pad, popY + pad, headH, "FOREX");
               DrawHead(gPopPrefix, "MT", popX + pad, popX + popW - 1 - pad, top2,       headH, "METALS");

               for(int i = 0; i < n; i++)
               {
                  int g   = (i < DEF_FX) ? i : (i - DEF_FX);
                  int cx1 = popX + pad + (g % cols) * (cellW + gap);
                  int cy1 = ((i < DEF_FX) ? (popY + pad) : top2) + headH + (g / cols) * (cellH + gap);
                  DrawButton(gPopPrefix, SW_P0 + i, cx1, cy1, cx1 + cellW - 1, cy1 + cellH - 1,
                             gSymDisp[i], i == curIdx, 0, gSymReal[i] != "");
               }
            }
            else if(useGroups && layout == LAYOUT_VERTICAL)
            {
               int fxStartX = popX + pad;
               int fxEndX   = fxStartX + fxCols * cellW + (fxCols - 1) * gap - 1;
               int mtStartX = fxEndX + 1 + groupGap;
               int mtEndX   = mtStartX + mtCols * cellW + (mtCols - 1) * gap - 1;

               DrawHead(gPopPrefix, "FX", fxStartX, fxEndX, popY + pad, headH, "FOREX");
               DrawHead(gPopPrefix, "MT", mtStartX, mtEndX, popY + pad, headH, "METALS");

               for(int i = 0; i < n; i++)
               {
                  bool isFx = (i < DEF_FX);
                  int g     = isFx ? i : (i - DEF_FX);
                  int col   = g / rows;
                  int row   = g % rows;
                  int baseX = isFx ? fxStartX : mtStartX;
                  int cx1   = baseX + col * (cellW + gap);
                  int cy1   = popY + pad + headH + row * (cellH + gap);
                  DrawButton(gPopPrefix, SW_P0 + i, cx1, cy1, cx1 + cellW - 1, cy1 + cellH - 1,
                             gSymDisp[i], i == curIdx, 0, gSymReal[i] != "");
               }
            }
            else
            {
               for(int i = 0; i < n; i++)
               {
                  int col = (layout == LAYOUT_HORIZONTAL) ? (i % cols) : (i / rows);
                  int row = (layout == LAYOUT_HORIZONTAL) ? (i / cols) : (i % rows);
                  int cx1 = popX + pad + col * (cellW + gap);
                  int cy1 = popY + pad + row * (cellH + gap);
                  DrawButton(gPopPrefix, SW_P0 + i, cx1, cy1, cx1 + cellW - 1, cy1 + cellH - 1,
                             gSymDisp[i], i == curIdx, 0, gSymReal[i] != "");
               }
            }
         }
         else
         {
            for(int i = 0; i < SW_TFS; i++)
            {
               int col = (layout == LAYOUT_HORIZONTAL) ? (i % cols) : (i / rows);
               int row = (layout == LAYOUT_HORIZONTAL) ? (i / cols) : (i % rows);
               int cx1 = popX + pad + col * (cellW + gap);
               int cy1 = popY + pad + row * (cellH + gap);
               DrawButton(gPopPrefix, SW_T0 + i, cx1, cy1, cx1 + cellW - 1, cy1 + cellH - 1,
                          SwTfName(SW_PER[i]), SW_PER[i] == (ENUM_TIMEFRAMES)_Period, 0, true);
            }
         }
      }
   }

   gSwShown = true;
}

//+------------------------------------------------------------------+
//| Master Draw Dispatcher                                           |
//+------------------------------------------------------------------+
void SwDraw(const bool forceRebuild = false)
{
   if(gW <= 0 || gH <= 0)
   {
      ReadGeom();
      if(gW <= 0 || gH <= 0) return;
   }

   string normSig = StringFormat("%d|%d|%d|%d", gW, gH, gSymCount, gMinimized ? 1 : 0);
   bool needClearBar = (forceRebuild || gMinimized != gLastMin ||
                        (InpDisplayMode == MODE_NORMAL && normSig != gLastNormSig));

   if(needClearBar)
   {
      ObjectsDeleteAll(0, gBarPrefix);
      ObjectsDeleteAll(0, gPopPrefix);
      gLastMin     = gMinimized;
      gLastPop     = -1;
      gLastNormSig = normSig;
   }
   else if(gSwPop != gLastPop)
   {
      ObjectsDeleteAll(0, gPopPrefix);
   }
   gLastPop = gSwPop;

   gSwN = 0;
   for(int b = 0; b < 3; b++)
   {
      gSwBox[b][0] = 0;  gSwBox[b][1] = 0;
      gSwBox[b][2] = -1; gSwBox[b][3] = -1;
   }

   if(InpDisplayMode == MODE_NORMAL)
      DrawNormalMode();
   else
      DrawPopupMode();
}

//--- Smooth delta shift while dragging (no object recreation)
void ShiftAllObjects(const int dx, const int dy)
{
   if(dx == 0 && dy == 0) return;

   int total = ObjectsTotal(0, gSubWin, -1);
   for(int i = 0; i < total; i++)
   {
      string name = ObjectName(0, i, gSubWin, -1);
      if(StringFind(name, gPrefix) != 0) continue;
      int ox = (int)ObjectGetInteger(0, name, OBJPROP_XDISTANCE);
      int oy = (int)ObjectGetInteger(0, name, OBJPROP_YDISTANCE);
      ObjectSetInteger(0, name, OBJPROP_XDISTANCE, ox + dx);
      ObjectSetInteger(0, name, OBJPROP_YDISTANCE, oy + dy);
   }

   for(int i = 0; i < gSwN; i++)
   {
      gSwX1[i] += dx; gSwX2[i] += dx;
      gSwY1[i] += dy; gSwY2[i] += dy;
   }
   for(int b = 0; b < 3; b++)
   {
      if(gSwBox[b][2] >= gSwBox[b][0])
      {
         gSwBox[b][0] += dx; gSwBox[b][2] += dx;
         gSwBox[b][1] += dy; gSwBox[b][3] += dy;
      }
   }
}

//+------------------------------------------------------------------+
//| Hit Testing & State Persistence                                  |
//+------------------------------------------------------------------+
int SwAt(const int x, const int y)
{
   if(!gSwShown) return 0;
   for(int i = 0; i < gSwN; i++)
      if(x >= gSwX1[i] && x <= gSwX2[i] && y >= gSwY1[i] && y <= gSwY2[i]) return gSwC[i];
   return 0;
}

bool SwIn(const int x, const int y)
{
   if(!gSwShown) return false;
   for(int b = 0; b < 3; b++)
      if(x >= gSwBox[b][0] && x <= gSwBox[b][2] && y >= gSwBox[b][1] && y <= gSwBox[b][3]) return true;
   return false;
}

bool SwInBar(const int x, const int y)
{
   if(InpDisplayMode == MODE_NORMAL) return SwIn(x, y);
   return gSwShown && x >= gSwBox[0][0] && x <= gSwBox[0][2] && y >= gSwBox[0][1] && y <= gSwBox[0][3];
}

string StateKey(const string k)
{
   return "CPC_" + (string)ChartID() + "_" + UniqueID + "_" + k;
}

double ConfigChecksum()
{
   return (double)(InpSubWindow * 1000000 + (int)InpCorner * 100000 + InpPanelX * 100 + InpPanelY);
}

void SaveState()
{
   GlobalVariableSet(StateKey("CFG"), ConfigChecksum());
   GlobalVariableSet(StateKey("DRG"), gBarDragged ? 1.0 : 0.0);
   GlobalVariableSet(StateKey("X"),   (double)gSavedX);
   GlobalVariableSet(StateKey("Y"),   (double)gSavedY);
   GlobalVariableSet(StateKey("MIN"), gMinimized ? 1.0 : 0.0);
}

void LoadState()
{
   gMinimized  = InpStartMin;
   gBarDragged = false;

   if(GlobalVariableCheck(StateKey("MIN")))
      gMinimized = (GlobalVariableGet(StateKey("MIN")) > 0.5);

   // Restore user's dragged position only if position inputs were not changed
   if(InpDraggable &&
      GlobalVariableCheck(StateKey("CFG")) &&
      GlobalVariableGet(StateKey("CFG")) == ConfigChecksum() &&
      GlobalVariableCheck(StateKey("DRG")) &&
      GlobalVariableGet(StateKey("DRG")) > 0.5 &&
      GlobalVariableCheck(StateKey("X")) &&
      GlobalVariableCheck(StateKey("Y")))
   {
      gSavedX     = (int)GlobalVariableGet(StateKey("X"));
      gSavedY     = (int)GlobalVariableGet(StateKey("Y"));
      gBarDragged = true;
   }
}

void ClearState()
{
   GlobalVariableDel(StateKey("CFG"));
   GlobalVariableDel(StateKey("DRG"));
   GlobalVariableDel(StateKey("X"));
   GlobalVariableDel(StateKey("Y"));
   GlobalVariableDel(StateKey("MIN"));
}

void RemoveSelf()
{
   if(!ChartIndicatorDelete(0, 0, UniqueID))
      Print("Currency Pair Changer: could not remove ", UniqueID, ", error ", GetLastError());
}

void SwPress(const int hit)
{
   if(hit == SW_CLOSE)
   {
      RemoveSelf();
      return;
   }
   if(hit == SW_MIN)
   {
      gMinimized = !gMinimized;
      gSwPop     = 0;
      gSwHov     = 0;
      SaveState();
      SwDraw(true);
      ChartRedraw();
      return;
   }
   if(hit == SW_PAIR || hit == SW_TF)
   {
      if(InpDisplayMode != MODE_POPUP) return;
      if(hit == SW_PAIR) LoadSymbols(InpUseMarketWatch);
      gSwPop = (gSwPop == hit) ? 0 : hit;
      SwDraw();
      ChartRedraw();
      return;
   }

   if(hit == SW_PREV || hit == SW_NEXT)
   {
      LoadSymbols(InpUseMarketWatch);
      if(gSymCount > 0)
      {
         int d = (hit == SW_NEXT) ? 1 : -1;
         int i = CurrentSymbolIndex();
         if(i < 0) i = (d > 0) ? -1 : gSymCount;
         for(int k = 0; k < gSymCount; k++)
         {
            i = (i + d + gSymCount) % gSymCount;
            if(gSymReal[i] != "")
            {
               gGoSym = gSymReal[i];
               break;
            }
         }
         gGoTf = (ENUM_TIMEFRAMES)_Period;
      }
   }
   else if(hit >= SW_T0 && hit < SW_T0 + SW_TFS)
   {
      gGoSym = _Symbol;
      gGoTf  = SW_PER[hit - SW_T0];
   }
   else if(hit >= SW_P0 && hit < SW_P0 + gSymCount)
   {
      gGoSym = gSymReal[hit - SW_P0];
      gGoTf  = (ENUM_TIMEFRAMES)_Period;
   }

   gSwPop = 0;
   gSwHov = 0;
   SwDraw();
   ChartRedraw();
}

void SwGo()
{
   string s = gGoSym;
   gGoSym   = "";
   if(s == "" || (s == _Symbol && gGoTf == (ENUM_TIMEFRAMES)_Period)) return;

   ResetLastError();
   if(s != _Symbol && !SymbolSelect(s, true))
   {
      Print("Currency Pair Changer: could not select ", s, ", error ", GetLastError());
      return;
   }
   if(!ChartSetSymbolPeriod(0, s, gGoTf))
      Print("Currency Pair Changer: could not switch to ", s, " ", EnumToString(gGoTf), ", error ", GetLastError());
}

//+------------------------------------------------------------------+
//| Mouse & Scroll Management                                        |
//+------------------------------------------------------------------+
void SetScroll(const bool on)
{
   if(on)
   {
      if(!gScrollOff) return;
      gScrollOff = false;
      ChartSetInteger(0, CHART_MOUSE_SCROLL, true);
   }
   else
   {
      gScrollOff = true;
      ChartSetInteger(0, CHART_MOUSE_SCROLL, false);
   }
}

string MouseRefKey()
{
   return StringFormat("MT5_DRAG_MM_REF_%I64d", ChartID());
}

void AcquireMouseRef()
{
   ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
   string k  = MouseRefKey();
   int cur   = GlobalVariableCheck(k) ? MathMax(0, (int)GlobalVariableGet(k)) : 0;
   GlobalVariableSet(k, (double)(cur + 1));
   GlobalVariableTemp(k);
   gMouseRef = true;
}

void ReleaseMouseRef()
{
   if(!gMouseRef) return;
   gMouseRef = false;
   string k  = MouseRefKey();
   int next  = GlobalVariableCheck(k) ? MathMax(0, (int)GlobalVariableGet(k) - 1) : 0;
   if(next > 0)
   {
      GlobalVariableSet(k, (double)next);
      GlobalVariableTemp(k);
      return;
   }
   GlobalVariableDel(k);
   if(!gMouseWas) ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, false);
}

void HandleMouse(const int chartX, const int chartY, const bool down)
{
   int x = chartX;
   int y = chartY - gSubYOff;

   if(!down && !gPrevDown && !gDragging)
   {
      int h = SwAt(x, y);
      if(h != gSwHov)
      {
         gSwHov = h;
         SwDraw();
         ChartRedraw();
      }
      return;
   }

   if(gDragging)
   {
      if(down)
      {
         int nextX = MathMax(0, MathMin(gDragBX + (x - gDragX), MathMax(0, gW - gBarW)));
         int nextY = MathMax(0, MathMin(gDragBY + (y - gDragY), MathMax(0, gH - gBarH)));
         int dx    = nextX - gBarX;
         int dy    = nextY - gBarY;
         if(dx != 0 || dy != 0)
         {
            gBarX       = nextX;
            gBarY       = nextY;
            gSavedX     = nextX;
            gSavedY     = nextY;
            gBarDragged = true;
            ShiftAllObjects(dx, dy);
            ChartRedraw();
         }
      }
      else
      {
         gDragging = false;
         SaveState();
         SetScroll(true);
         SwDraw();
         ChartRedraw();
      }
      gPrevDown = down;
      return;
   }

   if(down && !gPrevDown)
   {
      gPress = SwAt(x, y);
      // Start dragging if pressing the grip OR any non-button area of the panel
      if(InpDraggable && (gPress == SW_GRIP || (gPress == 0 && SwInBar(x, y))))
      {
         gDragging = true;
         gPress    = 0;
         gDragX    = x;
         gDragY    = y;
         gDragBX   = gBarX;
         gDragBY   = gBarY;
         if(gSwPop != 0)
         {
            gSwPop = 0;
            gSwHov = 0;
            SwDraw();
            ChartRedraw();
         }
         SetScroll(false);
      }
      else if(gPress > 0 || SwIn(x, y))
      {
         SetScroll(false);
      }

      if(gSwPop != 0 && !SwIn(x, y))
      {
         gSwPop = 0;
         gSwHov = 0;
         SwDraw();
         ChartRedraw();
      }
   }

   if(!down && gPrevDown)
   {
      if(gPress > 0 && SwAt(x, y) == gPress)
         SwPress(gPress);
      SetScroll(true);
      gPress = 0;
   }

   gPrevDown = down;
}

//+------------------------------------------------------------------+
//| Indicator Lifecycle Events                                       |
//+------------------------------------------------------------------+
int OnInit()
{
   gTheme = (int)Theme;
   ThemeApply();

   gPrefix    = "CPC_" + (string)ChartID() + "_" + UniqueID + "_";
   gBarPrefix = gPrefix + "B_";
   gPopPrefix = gPrefix + "P_";

   ObjectsDeleteAll(0, gPrefix);

   gSwShown     = false;
   gSwPop       = 0;
   gLastPop     = -1;
   gLastNormSig = "";
   gSwHov       = 0;
   gSwN         = 0;
   gSymLoaded   = false;
   gGoSym       = "";
   gPrevDown    = false;
   gPress       = 0;
   gScrollOff   = false;
   gDragging    = false;

   IndicatorSetString(INDICATOR_SHORTNAME, UniqueID);

   ReadGeom();
   LoadSymbols(true);
   LoadState();
   gLastMin = gMinimized;

   gMouseWas = (bool)ChartGetInteger(0, CHART_EVENT_MOUSE_MOVE);
   AcquireMouseRef();
   if(!(bool)ChartGetInteger(0, CHART_MOUSE_SCROLL))
      ChartSetInteger(0, CHART_MOUSE_SCROLL, true);

   SwDraw(true);
   ChartRedraw();
   EventSetMillisecondTimer(50);
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   EventKillTimer();
   SetScroll(true);
   gDragging = false;
   if(reason == REASON_REMOVE)
      ClearState();
   ReleaseMouseRef();

   // Avoid deleting objects on TF/symbol change so old instance cannot wipe new instance's panel
   if(reason != REASON_CHARTCHANGE)
      ObjectsDeleteAll(0, gPrefix);

   ChartRedraw();
}

int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[],
                const double &open[], const double &high[], const double &low[], const double &close[],
                const long &tick_volume[], const long &volume[], const int &spread[])
{
   return rates_total;
}

void OnTimer()
{
   if(!(bool)ChartGetInteger(0, CHART_EVENT_MOUSE_MOVE))
      ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);

   if(gGoSym != "" && !gPrevDown)
   {
      SwGo();
      return;
   }

   // Self-healing check: keeps panel visible and properly positioned on any chart or subwindow resize
   int prevW = gW, prevH = gH, prevY = gSubYOff, prevSub = gSubWin;
   ReadGeom();
   if(gW > 0 && gH > 0)
   {
      bool missing = (ObjectFind(0, gBarPrefix + "BG") < 0);
      if(missing || gW != prevW || gH != prevH || gSubYOff != prevY || gSubWin != prevSub)
      {
         SwDraw(missing || gSubWin != prevSub);
         ChartRedraw();
      }
   }
}

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   if(id == CHARTEVENT_CHART_CHANGE)
   {
      ReadGeom();
      SwDraw();
      ChartRedraw();
   }
   else if(id == CHARTEVENT_MOUSE_MOVE)
   {
      HandleMouse((int)lparam, (int)dparam, ((int)StringToInteger(sparam) & 1) != 0);
   }
}
//+--------------------------------------------------------------------------------------------+