//+------------------------------------------------------------------+
//|                                          Critter_ATR(wizard).mq5 |
//|                     Standalone MQL5 ATR Indicator — Pixel Wizard |
//|    Converted from KenKaiii/gg-framework (AGPL-3.0-only) to MQL5. |
//|     Walks along the bottom of the main MT5 chart and speaks live |
//|         ATR values in a pixel-art speech bubble ("ATR(14)=..."). |
//+------------------------------------------------------------------+
#property copyright "© c. 2026, Forex-Station"
#property link "https://forex-station.com/post1295587980.html#p1295587980"
#property version   "1.00"
#property description "Animated 18x18 pixel-art Wizard ATR indicator walking along the bottom of the main chart. Speaks live ATR(period) randomly & when clicked!"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   0

//--- ATR Indicator Inputs
input int    InpAtrPeriod     = 14;    // ATR Period
input int    InpDecimals      = -1;    // Decimals (-1 = auto symbol _Digits)
input double InpHighVolMult   = 1.35;  // High volatility ratio vs 20-bar avg (red text)
input double InpLowVolMult    = 0.70;  // Low volatility ratio vs 20-bar avg (purple text)

//--- Speech & Appearance Inputs
input double InpSpeakMinSec   = 4.5;   // Min seconds between random ATR speech
input double InpSpeakMaxSec   = 10.0;  // Max seconds between random ATR speech
input double InpSpeakDuration = 3.5;   // Speech bubble duration (sec)
input int    InpScale         = 2;     // Pixel scale (2 = 36x36 px Wizard)
input int    InpBottomMargin  = 2;     // Distance above main chart bottom (px)
input int    InpSideMargin    = 8;     // Left/Right patrol margin (px)
input double InpWalkSpeed     = 26.0;  // Walk speed (px / sec)
input bool   InpShowShadow    = true;  // Show ground shadow beneath Wizard
input bool   InpMixEmotes     = false; // Occasionally show pixel icon emotes too
input bool   InpClickToSpook  = true;  // Click Wizard to spook & speak live ATR
input bool   InpChartBack     = false; // Draw behind candlesticks (false = front)

//--- Sprite & canvas geometry (art cells)
#define WIZ_CELLS      18
#define CANVAS_W_CELLS 96
#define CANVAS_H_CELLS 38
#define WALK_FRAME_MS  170    // Walk cadence (from critter-floor.ts walk.frameMs)
#define TIMER_MS       33     // ~30 FPS animation tick

//--- Emote IDs (used only when InpMixEmotes = true)
#define EMOTE_NONE  0
#define EMOTE_HEART 1
#define EMOTE_NOTE  2
#define EMOTE_STAR  3

//--- Indicator calculation buffer & ATR handle
double g_atrBuf[];
int    g_atrHandle = INVALID_HANDLE;
double g_atrValue  = EMPTY_VALUE;
double g_atrAvg    = EMPTY_VALUE;
bool   g_atrValid  = false;
int    g_lastZone  = 0;       // -1 = low vol, 0 = normal, +1 = high vol

//--- Exact shaded palette from critter-sprites.ts ("wizard") + critter-shade.ts (0xAARRGGBB)
const uint g_wizPalette[32] =
{
   0x00000000, 0xFF360A7A, 0xFFE1B5F3, 0xFFC783F2, 0xFF2A0B4A, 0xFF682609,
   0xFFFFFEFC, 0xFF9A4AF0, 0xFFFEFDF4, 0xFFFFD23F, 0xFF5B0CE2, 0xFF820479,
   0xFFFC7BAE, 0xFFFF3FA4, 0xFFF200AF, 0xFF4D084A, 0xFF440AA5, 0xFFB00198,
   0xFF1E0C1F, 0xFF170A2E, 0xFFFFE14D, 0xFF7A62A2, 0xFFE8E4F0, 0xFFAC9AC9,
   0xFFEB7B3C, 0xFFBC592B, 0xFF693024, 0xFFFEE4BA, 0xFFFFD3A8, 0xFFDF7E00,
   0xFF411915, 0xFFFDED89
};

//--- Frame 0: walk stance A, glowing yellow eyes open (18x18)
const uchar g_wizF0[324] =
{
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 2, 7, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 9,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 9,10,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,11,12,13,13,14,14,14,15, 0, 0, 0, 0,
    0, 1, 1, 1, 1, 1,16,17,17,17,17,17,17,16, 1, 1, 4, 0,
    1, 2, 2, 3, 3, 3, 3, 7, 7, 7, 7, 7, 7, 3, 3, 7, 7, 4,
    4, 7, 7, 7, 7, 7, 7,10,10,10,10,10,10, 7, 7, 7,10, 4,
    0, 4, 4,16,16,16,16,16,16,16,16,16,16,16,16, 4, 4, 0,
    0, 0, 0,18,19,19,19,19,19,19,19,19,19,19,18, 0, 0, 0,
    0, 0, 0,18,19,19,19,20,19,19,19,20,19,19,18, 0, 0, 0,
    0, 0, 0, 0,18,19,21,21,21,21,21,21,19,18, 0, 0, 0, 0,
    0, 0, 0, 0, 1,21,22,22,22,22,23,23,21,24,25,26, 0, 0,
    0, 0, 0, 1, 2, 7,21,23,23,23,23,23,21,24,27,28,26, 0,
    0, 0, 0, 1, 3,10,10,16,21,21,21,16, 3,16,28,28,26, 0,
    0, 0, 0, 4, 7, 7,10, 7, 6, 9,10,10, 7, 7,26,26, 0, 0,
    0, 0, 0, 0, 4,16,16,10,29,29,10,16,16, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0,18, 4, 4,30,30, 4, 4,18, 0, 0, 0, 0, 0
};

//--- Frame 1: walk stance B, hat star twinkle, glowing eyes open (18x18)
const uchar g_wizF1[324] =
{
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 8, 7, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 6, 7,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 2,31, 7,29,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,11,12,13,13,14,14,14,15, 0, 0, 0, 0,
    0, 1, 1, 1, 1, 1,16,17,17,17,17,17,17,16, 1, 1, 4, 0,
    1, 2, 2, 3, 3, 3, 3, 7, 7, 7, 7, 7, 7, 3, 3, 7, 7, 4,
    4, 7, 7, 7, 7, 7, 7,10,10,10,10,10,10, 7, 7, 7,10, 4,
    0, 4, 4,16,16,16,16,16,16,16,16,16,16,16,16, 4, 4, 0,
    0, 0, 0,18,19,19,19,19,19,19,19,19,19,19,18, 0, 0, 0,
    0, 0, 0,18,19,19,19,20,19,19,19,20,19,19,18, 0, 0, 0,
    0, 0, 0, 0,18,19,21,21,21,21,21,21,19,18, 0, 0, 0, 0,
    0, 0, 0, 0, 1,21,22,22,22,22,23,23,21,24,25,26, 0, 0,
    0, 0, 0, 1, 2, 7,21,23,23,23,23,23,21,24,27,28,26, 0,
    0, 0, 0, 1, 3,10,10,16,21,21,21,16, 3,16,28,28,26, 0,
    0, 0, 0, 4, 7, 7,10, 7, 6, 9,10,10, 7, 7,26,26, 0, 0,
    0, 0, 0, 0, 4, 4,16,10,29,29,10,16, 4, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 4, 4,30,30, 4, 4, 0, 0, 0, 0, 0, 0
};

//--- Blink Frame 0: walk stance A, eyes closed (18x18)
const uchar g_wizB0[324] =
{
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 2, 7, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 9,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 9,10,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,11,12,13,13,14,14,14,15, 0, 0, 0, 0,
    0, 1, 1, 1, 1, 1,16,17,17,17,17,17,17,16, 1, 1, 4, 0,
    1, 2, 2, 3, 3, 3, 3, 7, 7, 7, 7, 7, 7, 3, 3, 7, 7, 4,
    4, 7, 7, 7, 7, 7, 7,10,10,10,10,10,10, 7, 7, 7,10, 4,
    0, 4, 4,16,16,16,16,16,16,16,16,16,16,16,16, 4, 4, 0,
    0, 0, 0,18,19,19,19,19,19,19,19,19,19,19,18, 0, 0, 0,
    0, 0, 0,18,19,19,19,19,19,19,19,19,19,19,18, 0, 0, 0,
    0, 0, 0, 0,18,19,21,21,21,21,21,21,19,18, 0, 0, 0, 0,
    0, 0, 0, 0, 1,21,22,22,22,22,23,23,21,24,25,26, 0, 0,
    0, 0, 0, 1, 2, 7,21,23,23,23,23,23,21,24,27,28,26, 0,
    0, 0, 0, 1, 3,10,10,16,21,21,21,16, 3,16,28,28,26, 0,
    0, 0, 0, 4, 7, 7,10, 7, 6, 9,10,10, 7, 7,26,26, 0, 0,
    0, 0, 0, 0, 4,16,16,10,29,29,10,16,16, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0,18, 4, 4,30,30, 4, 4,18, 0, 0, 0, 0, 0
};

//--- Blink Frame 1: walk stance B, eyes closed (18x18)
const uchar g_wizB1[324] =
{
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 8, 7, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 6, 7,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 2,31, 7,29,10, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,11,12,13,13,14,14,14,15, 0, 0, 0, 0,
    0, 1, 1, 1, 1, 1,16,17,17,17,17,17,17,16, 1, 1, 4, 0,
    1, 2, 2, 3, 3, 3, 3, 7, 7, 7, 7, 7, 7, 3, 3, 7, 7, 4,
    4, 7, 7, 7, 7, 7, 7,10,10,10,10,10,10, 7, 7, 7,10, 4,
    0, 4, 4,16,16,16,16,16,16,16,16,16,16,16,16, 4, 4, 0,
    0, 0, 0,18,19,19,19,19,19,19,19,19,19,19,18, 0, 0, 0,
    0, 0, 0,18,19,19,19,19,19,19,19,19,19,19,18, 0, 0, 0,
    0, 0, 0, 0,18,19,21,21,21,21,21,21,19,18, 0, 0, 0, 0,
    0, 0, 0, 0, 1,21,22,22,22,22,23,23,21,24,25,26, 0, 0,
    0, 0, 0, 1, 2, 7,21,23,23,23,23,23,21,24,27,28,26, 0,
    0, 0, 0, 1, 3,10,10,16,21,21,21,16, 3,16,28,28,26, 0,
    0, 0, 0, 4, 7, 7,10, 7, 6, 9,10,10, 7, 7,26,26, 0, 0,
    0, 0, 0, 0, 4, 4,16,10,29,29,10,16, 4, 4, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 4, 4,30,30, 4, 4, 0, 0, 0, 0, 0, 0
};

//--- Runtime canvas state
string g_objName = "";
string g_resName = "";
int    g_scale   = 2;
int    g_bmpW    = 192;
int    g_bmpH    = 76;
uint   g_buf[];

//--- Wizard physics & AI state
double g_x            = 220.0;
double g_targetX      = 420.0;
double g_vx           = 0.0;
bool   g_facingLeft   = false;
double g_stepAccMs    = 0.0;
int    g_walkFrame    = 0;

//--- Blink state
bool   g_blinking     = false;
double g_blinkTimer   = 3.4;

//--- Idle / Patrol state
bool   g_idling       = false;
double g_stateTimer   = 3.0;

//--- Spook / Jump state
double g_spookTimer   = 0.0;
double g_jumpOffset   = 0.0;
double g_jumpVel      = 0.0;

//--- Speech bubble state (single-line "ATR(14)=..." readout or optional emote)
string g_speechText   = "";
uint   g_speechColor  = 0xFF1E0C1F;
int    g_emote        = EMOTE_NONE;
double g_bubbleTimer  = 0.0;
double g_nextSpeak    = 1.2;

//--- Timing & cached screen bounds
ulong  g_lastTickMs   = 0;
int    g_lastDrawX    = -9999;
int    g_lastDrawY    = -9999;
double g_pollAcc      = 0.0;

//+------------------------------------------------------------------+
//| Helper: random double in [lo, hi]                                |
//+------------------------------------------------------------------+
double RandRange(const double lo, const double hi)
{
   double a = MathMin(lo, hi);
   double b = MathMax(lo, hi);
   return a + ((double)MathRand() / 32767.0) * (b - a);
}

//+------------------------------------------------------------------+
//| Read latest live ATR(InpAtrPeriod) & 20-bar average baseline     |
//+------------------------------------------------------------------+
bool RefreshAtrValue()
{
   if(g_atrHandle == INVALID_HANDLE)
      return false;

   double tmp[20];
   int copied = CopyBuffer(g_atrHandle, 0, 0, 20, tmp);
   if(copied >= 1 && MathIsValidNumber(tmp[0]) && tmp[0] != EMPTY_VALUE)
   {
      // CopyBuffer without series indexing returns oldest..newest, so latest is tmp[copied - 1]
      g_atrValue = tmp[copied - 1];
      double sum = 0.0;
      int cnt = 0;
      for(int i = 0; i < copied; i++)
      {
         if(MathIsValidNumber(tmp[i]) && tmp[i] != EMPTY_VALUE && tmp[i] > 0.0)
         {
            sum += tmp[i];
            cnt++;
         }
      }
      g_atrAvg   = (cnt > 0) ? (sum / (double)cnt) : g_atrValue;
      g_atrValid = true;
      return true;
   }
   return g_atrValid;
}

//+------------------------------------------------------------------+
//| Color for ATR reading based on relative volatility               |
//+------------------------------------------------------------------+
uint AtrTextColor(const double atr, const double avg)
{
   if(avg > 0.0)
   {
      if(atr >= avg * InpHighVolMult) return 0xFFC82834; // High volatility (red)
      if(atr <= avg * InpLowVolMult)  return 0xFF5B36A8; // Low volatility (wizard purple)
   }
   return 0xFF1E0C1F;
}

//+------------------------------------------------------------------+
//| Format "ATR(14)=0.00125"                                         |
//+------------------------------------------------------------------+
string FormatAtrSpeech(const bool exclaimed)
{
   int period = MathMax(1, InpAtrPeriod);
   int digits = (InpDecimals >= 0) ? MathMin(8, InpDecimals) : MathMax(0, MathMin(6, _Digits));
   if(g_atrValid)
      return StringFormat("ATR(%d)=%s%s", period, DoubleToString(g_atrValue, digits), exclaimed ? "!" : "");
   return StringFormat("ATR(%d)=--", period);
}

//+------------------------------------------------------------------+
//| Trigger a live single-line "ATR(14)=..." speech bubble           |
//+------------------------------------------------------------------+
void SpeakAtr(const bool exclaimed = false)
{
   RefreshAtrValue();
   g_emote       = EMOTE_NONE;
   g_speechText  = FormatAtrSpeech(exclaimed);
   g_speechColor = g_atrValid ? AtrTextColor(g_atrValue, g_atrAvg) : 0xFF1E0C1F;
   ObjectSetString(0, g_objName, OBJPROP_TOOLTIP, StringFormat("Wizard %s (click to poke)", g_speechText));
   g_bubbleTimer = MathMax(1.0, InpSpeakDuration);
}

//+------------------------------------------------------------------+
//| Helper: draw one scaled art pixel (with alpha compositing)       |
//+------------------------------------------------------------------+
void PutArtPixel(const int ax, const int ay, const uint argb)
{
   uint a = (argb >> 24) & 0xFF;
   if(a == 0)
      return;
   if(ax < 0 || ax >= CANVAS_W_CELLS || ay < 0 || ay >= CANVAS_H_CELLS)
      return;

   int px0 = ax * g_scale;
   int py0 = ay * g_scale;

   for(int dy = 0; dy < g_scale; dy++)
   {
      int rowOff = (py0 + dy) * g_bmpW + px0;
      for(int dx = 0; dx < g_scale; dx++)
      {
         if(a == 255)
         {
            g_buf[rowOff + dx] = argb;
         }
         else
         {
            uint dst = g_buf[rowOff + dx];
            uint da  = (dst >> 24) & 0xFF;
            if(da == 0)
            {
               g_buf[rowOff + dx] = argb;
            }
            else
            {
               uint sr = (argb >> 16) & 0xFF;
               uint sg = (argb >> 8)  & 0xFF;
               uint sb =  argb        & 0xFF;
               uint dr = (dst >> 16)  & 0xFF;
               uint dg = (dst >> 8)   & 0xFF;
               uint db =  dst         & 0xFF;
               uint invA = 255 - a;
               uint outA = a + ((da * invA) / 255);
               if(outA > 255) outA = 255;
               uint outR = (sr * a + dr * invA) / 255;
               uint outG = (sg * a + dg * invA) / 255;
               uint outB = (sb * a + db * invA) / 255;
               g_buf[rowOff + dx] = (outA << 24) | (outR << 16) | (outG << 8) | outB;
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Crisp 7-row pixel font for ATR speech bubbles ("ATR(14)=...")    |
//+------------------------------------------------------------------+
void GetPixelGlyph(const ushort ch, string &rows[])
{
   ArrayResize(rows, 7);
   switch(ch)
   {
      case 'A':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="####";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]="#..#"; break;
      case 'T':
         rows[0]="#####"; rows[1]="..#.."; rows[2]="..#.."; rows[3]="..#..";
         rows[4]="..#.."; rows[5]="..#.."; rows[6]="..#.."; break;
      case 'R':
         rows[0]="###."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="###.";
         rows[4]="#.#."; rows[5]="#..#"; rows[6]="#..#"; break;
      case '(':
         rows[0]="..#";  rows[1]=".#.";  rows[2]="#..";  rows[3]="#..";
         rows[4]="#..";  rows[5]=".#.";  rows[6]="..#";  break;
      case ')':
         rows[0]="#..";  rows[1]=".#.";  rows[2]="..#";  rows[3]="..#";
         rows[4]="..#";  rows[5]=".#.";  rows[6]="#..";  break;
      case '=':
         rows[0]="...."; rows[1]="...."; rows[2]="####"; rows[3]="....";
         rows[4]="####"; rows[5]="...."; rows[6]="...."; break;
      case '.':
         rows[0]="..";   rows[1]="..";   rows[2]="..";   rows[3]="..";
         rows[4]="..";   rows[5]="##";   rows[6]="##";   break;
      case '-':
         rows[0]="...."; rows[1]="...."; rows[2]="...."; rows[3]="####";
         rows[4]="...."; rows[5]="...."; rows[6]="...."; break;
      case '!':
         rows[0]="##";   rows[1]="##";   rows[2]="##";   rows[3]="##";
         rows[4]="..";   rows[5]="##";   rows[6]="##";   break;
      case '0':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="#..#";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '1':
         rows[0]=".#.";  rows[1]="##.";  rows[2]=".#.";  rows[3]=".#.";
         rows[4]=".#.";  rows[5]=".#.";  rows[6]="###";  break;
      case '2':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="...#"; rows[3]="..#.";
         rows[4]=".#.."; rows[5]="#..."; rows[6]="####"; break;
      case '3':
         rows[0]="###."; rows[1]="...#"; rows[2]="...#"; rows[3]=".##.";
         rows[4]="...#"; rows[5]="...#"; rows[6]="###."; break;
      case '4':
         rows[0]="#..#"; rows[1]="#..#"; rows[2]="#..#"; rows[3]="####";
         rows[4]="...#"; rows[5]="...#"; rows[6]="...#"; break;
      case '5':
         rows[0]="####"; rows[1]="#..."; rows[2]="###."; rows[3]="...#";
         rows[4]="...#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '6':
         rows[0]=".##."; rows[1]="#..."; rows[2]="###."; rows[3]="#..#";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '7':
         rows[0]="####"; rows[1]="...#"; rows[2]="..#."; rows[3]="..#.";
         rows[4]=".#.."; rows[5]=".#.."; rows[6]=".#.."; break;
      case '8':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]=".##.";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '9':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]=".###";
         rows[4]="...#"; rows[5]="..#."; rows[6]="##.."; break;
      case ' ':
      default:
         rows[0]="...";  rows[1]="...";  rows[2]="...";  rows[3]="...";
         rows[4]="...";  rows[5]="...";  rows[6]="...";  break;
   }
}

//+------------------------------------------------------------------+
//| Measure pixel text width in art cells                            |
//+------------------------------------------------------------------+
int MeasurePixelText(const string text)
{
   int n = StringLen(text);
   if(n <= 0) return 0;
   int total = 0;
   string rows[];
   for(int i = 0; i < n; i++)
   {
      GetPixelGlyph(StringGetCharacter(text, i), rows);
      total += StringLen(rows[0]);
      if(i < n - 1) total += 1;
   }
   return total;
}

//+------------------------------------------------------------------+
//| Draw a single line of crisp pixel text at (x0, y0)               |
//+------------------------------------------------------------------+
void DrawPixelText(const int x0, const int y0, const string text, const uint col)
{
   int curX = x0;
   int n    = StringLen(text);
   string rows[];
   for(int i = 0; i < n; i++)
   {
      GetPixelGlyph(StringGetCharacter(text, i), rows);
      int gw = StringLen(rows[0]);
      for(int y = 0; y < 7; y++)
      {
         for(int x = 0; x < gw; x++)
         {
            if(StringGetCharacter(rows[y], x) == '#')
               PutArtPixel(curX + x, y0 + y, col);
         }
      }
      curX += gw + 1;
   }
}

//+------------------------------------------------------------------+
//| Draw shared chamfered pixel-art paper bubble shell & tail        |
//+------------------------------------------------------------------+
void DrawBubbleShell(const int bx, const int by, const int bw, const int bh)
{
   const uint INK   = 0xFF1E0C1F;
   const uint PAPER = 0xFFF4F8FC;
   const uint SHADE = 0xFFD2DDEA;

   for(int y = 0; y < bh; y++)
   {
      for(int x = 0; x < bw; x++)
      {
         bool corner = ((x == 0 || x == bw - 1) && (y == 0 || y == bh - 1));
         if(corner)
            continue;
         bool border = (x == 0 || x == bw - 1 || y == 0 || y == bh - 1);
         if(border)
            PutArtPixel(bx + x, by + y, INK);
         else if(y == bh - 2)
            PutArtPixel(bx + x, by + y, SHADE);
         else
            PutArtPixel(bx + x, by + y, PAPER);
      }
   }

   // Stepped pixel tail centered over the Wizard
   int tx = CANVAS_W_CELLS / 2;
   int ty = by + bh - 1;
   PutArtPixel(tx - 1, ty,     SHADE);
   PutArtPixel(tx,     ty,     SHADE);
   PutArtPixel(tx - 2, ty + 1, INK);
   PutArtPixel(tx - 1, ty + 1, SHADE);
   PutArtPixel(tx,     ty + 1, INK);
   PutArtPixel(tx - 1, ty + 2, INK);
}

//+------------------------------------------------------------------+
//| Draw single-line "ATR(14)=..." speech bubble above Wizard        |
//+------------------------------------------------------------------+
void DrawAtrBubble(const int wizTopY, const string text, const uint valueColor)
{
   int tw = MeasurePixelText(text);
   if(tw <= 0) return;

   int bw = MathMin(CANVAS_W_CELLS, tw + 6);
   int bh = 7 + 5; // 12 cells: border + pad + 7px font + shade + border
   int bx = (CANVAS_W_CELLS - bw) / 2;
   int by = wizTopY - bh - 2;
   if(by < 0) by = 0;

   DrawBubbleShell(bx, by, bw, bh);
   DrawPixelText(bx + (bw - tw) / 2, by + 2, text, valueColor);
}

//+------------------------------------------------------------------+
//| Draw optional pixel icon emote bubble above the Wizard           |
//+------------------------------------------------------------------+
void DrawEmoteBubble(const int wizTopY, const int emote)
{
   if(emote == EMOTE_NONE)
      return;

   string glyph[];
   uint glyphCol = 0xFF1E0C1F;

   switch(emote)
   {
      case EMOTE_HEART:
         ArrayResize(glyph, 5);
         glyph[0] = ".#.#."; glyph[1] = "#####"; glyph[2] = "#####";
         glyph[3] = ".###."; glyph[4] = "..#..";
         glyphCol = 0xFFE0364F;
         break;
      case EMOTE_NOTE:
         ArrayResize(glyph, 5);
         glyph[0] = "..###"; glyph[1] = "..#.#"; glyph[2] = "..#..";
         glyph[3] = "###.."; glyph[4] = "###..";
         glyphCol = 0xFF6A3FC0;
         break;
      case EMOTE_STAR:
         ArrayResize(glyph, 5);
         glyph[0] = "..#.."; glyph[1] = "#####"; glyph[2] = ".###.";
         glyph[3] = ".#.#."; glyph[4] = "#...#";
         glyphCol = 0xFFC98A10;
         break;
      default:
         return;
   }

   int gh = ArraySize(glyph);
   int gw = StringLen(glyph[0]);
   int bw = gw + 6;
   int bh = gh + 5;
   int bx = (CANVAS_W_CELLS - bw) / 2;
   int by = wizTopY - bh - 2;
   if(by < 0) by = 0;

   DrawBubbleShell(bx, by, bw, bh);

   int gx0 = bx + 3;
   int gy0 = by + 2;
   for(int y = 0; y < gh; y++)
   {
      for(int x = 0; x < gw; x++)
      {
         if(StringGetCharacter(glyph[y], x) == '#')
            PutArtPixel(gx0 + x, gy0 + y, glyphCol);
      }
   }
}

//+------------------------------------------------------------------+
//| Draw ground shadow directly under the Wizard's robe              |
//+------------------------------------------------------------------+
void DrawShadow(const double liftCells)
{
   if(!InpShowShadow)
      return;

   int halfW = (liftCells > 3.0) ? 4 : ((liftCells > 1.0) ? 5 : 6);
   int cx    = CANVAS_W_CELLS / 2;
   int sy    = CANVAS_H_CELLS - 2;

   for(int x = cx - halfW; x < cx + halfW; x++)
   {
      bool edge = (x == cx - halfW || x == cx + halfW - 1);
      PutArtPixel(x, sy,     edge ? 0x44140A18 : 0x88140A18);
      if(!edge)
         PutArtPixel(x, sy + 1, 0x55140A18);
   }
}

//+------------------------------------------------------------------+
//| Draw the 18x18 shaded Wizard sprite                              |
//+------------------------------------------------------------------+
void DrawWizard(const int ox, const int oy)
{
   for(int y = 0; y < WIZ_CELLS; y++)
   {
      int rowBase = y * WIZ_CELLS;
      for(int x = 0; x < WIZ_CELLS; x++)
      {
         int sx = g_facingLeft ? (WIZ_CELLS - 1 - x) : x;
         uchar idx = 0;
         if(g_blinking)
            idx = (g_walkFrame == 0) ? g_wizB0[rowBase + sx] : g_wizB1[rowBase + sx];
         else
            idx = (g_walkFrame == 0) ? g_wizF0[rowBase + sx] : g_wizF1[rowBase + sx];

         if(idx != 0)
            PutArtPixel(ox + x, oy + y, g_wizPalette[idx]);
      }
   }
}

//+------------------------------------------------------------------+
//| Trigger click-to-spook hop + instant live ATR speech             |
//+------------------------------------------------------------------+
void SpookWizard()
{
   g_spookTimer = 1.6;
   g_idling     = false;
   g_jumpVel    = 40.0;
   SpeakAtr(true);

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
   int minX   = MathMax(0, InpSideMargin);
   int maxX   = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);

   double dist = RandRange(100.0, 220.0);
   if(g_x > (minX + maxX) * 0.5)
      g_targetX = MathMax((double)minX, g_x - dist);
   else
      g_targetX = MathMin((double)maxX, g_x + dist);

   g_facingLeft = (g_targetX < g_x);
}

//+------------------------------------------------------------------+
//| Pick a new patrol destination along the bottom of the main chart |
//+------------------------------------------------------------------+
void PickNextTarget(const int chartW)
{
   int minX = MathMax(0, InpSideMargin);
   int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
   double candidate = RandRange((double)minX, (double)maxX);
   if(MathAbs(candidate - g_x) < 60.0)
      candidate = (g_x > (minX + maxX) * 0.5) ? (double)minX + 16.0 : (double)maxX - 16.0;
   g_targetX = MathMax((double)minX, MathMin((double)maxX, candidate));
}

//+------------------------------------------------------------------+
//| Render current frame to the dynamic MT5 resource                 |
//+------------------------------------------------------------------+
void RenderFrame(const int chartW, const int chartH)
{
   ArrayInitialize(g_buf, 0x00000000);

   // Walks right along the bottom floor of the main chart (1px crisp walk bob + spook jump)
   bool walking = (!g_idling && MathAbs(g_vx) > 2.0);
   double liftCells = (walking && g_walkFrame == 1 ? 1.0 : 0.0) + g_jumpOffset;
   if(liftCells > 6.0) liftCells = 6.0;

   int wizOx   = (CANVAS_W_CELLS - WIZ_CELLS) / 2;
   int groundY = CANVAS_H_CELLS - 1;
   int wizOy   = groundY - WIZ_CELLS - (int)MathRound(liftCells);
   if(wizOy < 0) wizOy = 0;

   DrawShadow(liftCells);
   DrawWizard(wizOx, wizOy);

   if(g_bubbleTimer > 0.0)
   {
      if(g_speechText != "")
         DrawAtrBubble(wizOy, g_speechText, g_speechColor);
      else if(g_emote != EMOTE_NONE)
         DrawEmoteBubble(wizOy, g_emote);
   }

   if(ResourceCreate(g_resName, g_buf, g_bmpW, g_bmpH, 0, 0, g_bmpW, COLOR_FORMAT_ARGB_NORMALIZE))
   {
      int drawX = (int)MathRound(g_x);
      int drawY = MathMax(0, chartH - MathMax(0, InpBottomMargin) - g_bmpH);

      if(drawX != g_lastDrawX)
      {
         ObjectSetInteger(0, g_objName, OBJPROP_XDISTANCE, drawX);
         g_lastDrawX = drawX;
      }
      if(drawY != g_lastDrawY)
      {
         ObjectSetInteger(0, g_objName, OBJPROP_YDISTANCE, drawY);
         g_lastDrawY = drawY;
      }
      ChartRedraw(0);
   }
}

//+------------------------------------------------------------------+
//| Custom indicator initialization                                  |
//+------------------------------------------------------------------+
int OnInit()
{
   MathSrand((uint)(GetTickCount64() ^ (ulong)ChartID() ^ 0x9E3779B9));

   int period = MathMax(1, InpAtrPeriod);
   SetIndexBuffer(0, g_atrBuf, INDICATOR_CALCULATIONS);
   IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("WizardATR(%d)", period));
   IndicatorSetInteger(INDICATOR_DIGITS, (InpDecimals >= 0) ? MathMin(8, InpDecimals) : _Digits);

   g_atrHandle = iATR(_Symbol, _Period, period);
   if(g_atrHandle == INVALID_HANDLE)
   {
      Print("WizardATRCritter: iATR failed, err=", GetLastError());
      return INIT_FAILED;
   }

   g_scale = MathMax(1, MathMin(5, InpScale));
   g_bmpW  = CANVAS_W_CELLS * g_scale;
   g_bmpH  = CANVAS_H_CELLS * g_scale;
   ArrayResize(g_buf, g_bmpW * g_bmpH);
   ArrayInitialize(g_buf, 0x00000000);

   string uid = IntegerToString((long)ChartID()) + "_" + IntegerToString((long)(GetTickCount64() % 100000));
   g_objName  = "WizardATR_" + uid;
   g_resName  = "::" + g_objName;

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
   int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
   if(chartW < 100) chartW = 800;
   if(chartH < 100) chartH = 400;

   int minX = MathMax(0, InpSideMargin);
   int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
   g_x = RandRange((double)minX, (double)maxX);
   PickNextTarget(chartW);
   g_facingLeft = (g_targetX < g_x);
   g_lastTickMs = GetTickCount64();

   RefreshAtrValue();

   if(!ResourceCreate(g_resName, g_buf, g_bmpW, g_bmpH, 0, 0, g_bmpW, COLOR_FORMAT_ARGB_NORMALIZE))
   {
      Print("WizardATRCritter: ResourceCreate failed, err=", GetLastError());
      IndicatorRelease(g_atrHandle);
      g_atrHandle = INVALID_HANDLE;
      return INIT_FAILED;
   }

   if(!ObjectCreate(0, g_objName, OBJ_BITMAP_LABEL, 0, 0, 0))
   {
      Print("WizardATRCritter: ObjectCreate failed, err=", GetLastError());
      ResourceFree(g_resName);
      IndicatorRelease(g_atrHandle);
      g_atrHandle = INVALID_HANDLE;
      return INIT_FAILED;
   }

   ObjectSetInteger(0, g_objName, OBJPROP_CORNER,     CORNER_LEFT_UPPER);
   ObjectSetInteger(0, g_objName, OBJPROP_ANCHOR,     ANCHOR_LEFT_UPPER);
   ObjectSetInteger(0, g_objName, OBJPROP_XDISTANCE,  (int)MathRound(g_x));
   ObjectSetInteger(0, g_objName, OBJPROP_YDISTANCE,  MathMax(0, chartH - MathMax(0, InpBottomMargin) - g_bmpH));
   ObjectSetInteger(0, g_objName, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, g_objName, OBJPROP_SELECTED,   false);
   ObjectSetInteger(0, g_objName, OBJPROP_HIDDEN,     true);
   ObjectSetInteger(0, g_objName, OBJPROP_BACK,       InpChartBack);
   ObjectSetInteger(0, g_objName, OBJPROP_ZORDER,     102);
   ObjectSetString(0,  g_objName, OBJPROP_TOOLTIP,    StringFormat("Wizard ATR(%d) — click to poke!", period));
   ObjectSetString(0,  g_objName, OBJPROP_BMPFILE,    g_resName);

   RenderFrame(chartW, chartH);
   EventSetMillisecondTimer(TIMER_MS);
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Custom indicator deinitialization                                |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   EventKillTimer();
   if(g_objName != "")
      ObjectDelete(0, g_objName);
   if(g_resName != "")
      ResourceFree(g_resName);
   if(g_atrHandle != INVALID_HANDLE)
   {
      IndicatorRelease(g_atrHandle);
      g_atrHandle = INVALID_HANDLE;
   }
   ChartRedraw(0);
}

//+------------------------------------------------------------------+
//| Indicator calculation: populate ATR buffer & volatility alert    |
//+------------------------------------------------------------------+
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[])
{
   int period = MathMax(1, InpAtrPeriod);
   if(g_atrHandle == INVALID_HANDLE || rates_total <= period)
      return 0;

   int toCopy = (prev_calculated <= 0 || prev_calculated > rates_total)
                ? rates_total
                : (rates_total - prev_calculated + 1);
   if(toCopy > rates_total) toCopy = rates_total;

   if(CopyBuffer(g_atrHandle, 0, 0, toCopy, g_atrBuf) <= 0)
      return prev_calculated;

   if(RefreshAtrValue() && g_atrAvg > 0.0)
   {
      int zone = (g_atrValue >= g_atrAvg * InpHighVolMult) ? 1 : ((g_atrValue <= g_atrAvg * InpLowVolMult) ? -1 : 0);
      if(zone == 1 && g_lastZone != 1)
         SpeakAtr(true);
      g_lastZone = zone;
   }

   return rates_total;
}

//+------------------------------------------------------------------+
//| Animation, ATR speech & walk AI tick (~30 FPS, runs 24/7)        |
//+------------------------------------------------------------------+
void OnTimer()
{
   ulong nowMs = GetTickCount64();
   double dtMs = (double)(nowMs - g_lastTickMs);
   g_lastTickMs = nowMs;
   if(dtMs < 1.0)   dtMs = TIMER_MS;
   if(dtMs > 120.0) dtMs = 120.0;
   double dt = dtMs * 0.001;

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
   int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
   if(chartW < 80 || chartH < 80)
      return;

   // Poll live ATR every 0.5s so visible speech stays current
   g_pollAcc += dt;
   if(g_pollAcc >= 0.5)
   {
      g_pollAcc = 0.0;
      RefreshAtrValue();
      if(g_bubbleTimer > 0.0 && g_speechText != "" && g_atrValid)
      {
         bool bang = (StringFind(g_speechText, "!") >= 0);
         g_speechText  = FormatAtrSpeech(bang);
         g_speechColor = AtrTextColor(g_atrValue, g_atrAvg);
      }
   }

   // 1. Spook jump arc
   if(g_jumpOffset > 0.0 || g_jumpVel > 0.0)
   {
      g_jumpOffset += g_jumpVel * dt;
      g_jumpVel    -= 210.0 * dt;
      if(g_jumpOffset <= 0.0)
      {
         g_jumpOffset = 0.0;
         g_jumpVel    = 0.0;
      }
   }
   if(g_spookTimer > 0.0)
      g_spookTimer = MathMax(0.0, g_spookTimer - dt);

   // 2. Blinking timer
   g_blinkTimer -= dt;
   if(g_blinkTimer <= 0.0)
   {
      if(!g_blinking)
      {
         g_blinking   = true;
         g_blinkTimer = 0.14;
      }
      else
      {
         g_blinking   = false;
         g_blinkTimer = RandRange(2.5, 6.0);
      }
   }

   // 3. Random ATR speech timer
   if(g_bubbleTimer > 0.0)
   {
      g_bubbleTimer -= dt;
      if(g_bubbleTimer <= 0.0)
      {
         g_speechText = "";
         g_emote      = EMOTE_NONE;
      }
   }
   else if(g_spookTimer <= 0.0)
   {
      g_nextSpeak -= dt;
      if(g_nextSpeak <= 0.0)
      {
         if(InpMixEmotes && (MathRand() % 4) == 0)
         {
            int picks[3] = { EMOTE_HEART, EMOTE_NOTE, EMOTE_STAR };
            g_speechText  = "";
            g_emote       = picks[MathRand() % 3];
            g_bubbleTimer = 2.0;
         }
         else
         {
            SpeakAtr(false);
         }
         g_nextSpeak = RandRange(MathMax(1.0, InpSpeakMinSec), MathMax(2.0, InpSpeakMaxSec));
      }
   }

   // 4. Walk patrol & idle state machine along the bottom of the main chart
   int minX = MathMax(0, InpSideMargin);
   int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
   if(g_x < minX) g_x = minX;
   if(g_x > maxX) g_x = maxX;

   if(g_idling)
   {
      g_vx *= MathMax(0.0, 1.0 - dt * 10.0);
      g_x  += g_vx * dt;
      g_walkFrame = 0;
      g_stepAccMs = 0.0;
      g_stateTimer -= dt;
      if(g_stateTimer <= 0.0)
      {
         g_idling = false;
         PickNextTarget(chartW);
      }
   }
   else
   {
      double dx    = g_targetX - g_x;
      double dist  = MathAbs(dx);
      double speed = MathMax(8.0, InpWalkSpeed) * ((g_spookTimer > 0.0) ? 2.5 : 1.0);

      if(dist <= 4.0)
      {
         g_vx = 0.0;
         g_walkFrame = 0;
         if(g_spookTimer > 0.0)
         {
            PickNextTarget(chartW);
         }
         else
         {
            g_idling     = true;
            g_stateTimer = RandRange(1.6, 4.5);
         }
      }
      else
      {
         double dir      = (dx > 0.0) ? 1.0 : -1.0;
         double desiredV = dir * speed * MathMin(1.0, dist / 24.0 + 0.30);
         g_vx += (desiredV - g_vx) * MathMin(1.0, dt * 7.0);
         g_x  += g_vx * dt;
         g_facingLeft = (g_vx < -0.5);

         double stepMs = (g_spookTimer > 0.0) ? (WALK_FRAME_MS * 0.55) : (double)WALK_FRAME_MS;
         g_stepAccMs += dtMs;
         if(g_stepAccMs >= stepMs)
         {
            g_stepAccMs = MathMod(g_stepAccMs, stepMs);
            g_walkFrame = 1 - g_walkFrame;
         }
      }
   }

   g_x = MathMax((double)minX, MathMin((double)maxX, g_x));
   RenderFrame(chartW, chartH);
}

//+------------------------------------------------------------------+
//| Chart events: click to spook/speak ATR & chart resize            |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   if(id == CHARTEVENT_OBJECT_CLICK && InpClickToSpook && sparam == g_objName)
   {
      SpookWizard();
      return;
   }

   if(id == CHARTEVENT_CLICK && InpClickToSpook)
   {
      int mx = (int)lparam;
      int my = (int)dparam;
      int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
      int bx = (int)MathRound(g_x);
      int by = MathMax(0, chartH - MathMax(0, InpBottomMargin) - g_bmpH);
      if(mx >= bx && mx <= bx + g_bmpW && my >= by && my <= by + g_bmpH)
         SpookWizard();
      return;
   }

   if(id == CHARTEVENT_CHART_CHANGE)
   {
      int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
      int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
      if(chartW >= 80 && chartH >= 80)
      {
         int minX = MathMax(0, InpSideMargin);
         int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
         g_x       = MathMax((double)minX, MathMin((double)maxX, g_x));
         g_targetX = MathMax((double)minX, MathMin((double)maxX, g_targetX));
         RenderFrame(chartW, chartH);
      }
   }
}
//+------------------------------------------------------------------+
