//+------------------------------------------------------------------+
//|                                             Critter_RSI(bee).mq5 |
//|                Standalone MQL5 RSI Indicator — Pixel Bee Critter |
//|    Converted from KenKaiii/gg-framework (AGPL-3.0-only) to MQL5. |
//|    Hovers along the bottom of the main MT5 chart and speaks live |
//|       RSI values in a pixel-art speech bubble ("RSI(14) = ..."). |
//+------------------------------------------------------------------+
#property copyright "© c. 2026, Forex-Station"
#property link "https://forex-station.com/post1295587976.html#p1295587976"
#property version   "1.00"
#property description "Animated 18x18 pixel-art Bee RSI indicator hovering at the bottom of the main chart. Speaks live RSI(period) randomly & when clicked!"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   0

//--- RSI Indicator Inputs
input int                InpRsiPeriod     = 14;          // RSI Period
input ENUM_APPLIED_PRICE InpRsiPrice      = PRICE_CLOSE; // RSI Applied Price
input double             InpOverbought    = 70.0;        // Overbought level (red text)
input double             InpOversold      = 30.0;        // Oversold level (green text)

//--- Speech & Appearance Inputs
input double             InpSpeakMinSec   = 4.5;         // Min seconds between random RSI speech
input double             InpSpeakMaxSec   = 10.0;        // Max seconds between random RSI speech
input double             InpSpeakDuration = 3.2;         // Speech bubble duration (sec)
input int                InpScale         = 2;           // Pixel scale (2 = 36x36 px Bee)
input int                InpBottomMargin  = 2;           // Distance above main chart bottom (px)
input int                InpSideMargin    = 8;           // Left/Right patrol margin (px)
input double             InpCruiseSpeed   = 32.0;        // Flight speed (px / sec)
input bool               InpShowShadow    = true;        // Show hovering ground shadow
input bool               InpMixEmotes     = false;       // Occasionally show pixel icon emotes too
input bool               InpClickToSpook  = true;        // Click the Bee to spook & speak RSI
input bool               InpChartBack     = false;       // Draw behind candlesticks (false = front)

//--- Sprite & canvas geometry (art cells)
#define BEE_CELLS      18
#define CANVAS_W_CELLS 84
#define CANVAS_H_CELLS 38
#define FRAME_MS       70     // Wing-flap cadence (from critter-floor.ts hover.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 & RSI handle
double g_rsiBuf[];
int    g_rsiHandle = INVALID_HANDLE;
double g_rsiValue  = EMPTY_VALUE;
bool   g_rsiValid  = false;
int    g_lastZone  = 0;       // -1 = oversold, 0 = neutral, +1 = overbought

//--- Exact 26-color shaded palette from critter-sprites.ts + critter-shade.ts (0xAARRGGBB)
const uint g_beePalette[26] =
{
   0x00000000, 0xFA092DBB, 0xFF2C1013, 0xFF946E31, 0xFF5A3A1C, 0xFF240E19,
   0xFA141C69, 0xE6FAFEFF, 0xC7EEFCFE, 0xC7D6F0FF, 0xFA1C52EA, 0xFF351511,
   0xC7E3F8FE, 0xFFFFFFFF, 0xC765A8FF, 0xFF823009, 0xFFB04D03, 0xFFF9EFB1,
   0xFFFCEB7B, 0xFFFFD23F, 0xFFF28900, 0xFF4D1D15, 0xFF1E0C1F, 0xFFFF8A5C,
   0xFF7A2E2A, 0xFF462214
};

//--- Frame 0: wings up, eyes open (18x18)
const uchar g_beeF0[324] =
{
    0, 1, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 2, 3, 4, 2, 6, 0,
    1, 7, 8, 9,10,11, 5, 0, 0, 0, 0, 0, 1,11,10, 8,12, 6,
    1, 8,13, 9,14,14,10,15,15,15,15, 1, 7, 9,12,13, 9, 6,
    1,12, 9,14,10,10,16,17,17,18,19,16,10,10,14, 9,14, 6,
    6, 9,14,10,18,18,17,17,17,18,18,18,19,20,10, 9,14, 6,
    0, 1,16,18,18,18,17,17,17,18,18,18,19,20,20,16, 6, 0,
    0,15,18,18,17,17,17,17,18,18,18,18,18,19,20,20,21, 0,
    0,15,18,17,17,17,13,22,18,18,18,13,22,19,19,20,21, 0,
   15,17,17,17,18,18,22,22,18,19,19,22,22,19,19,19,19,21,
   15,17,18,23,23,18,18,18,19,24,24,19,19,23,23,20,20,21,
   15,19,18,19,19,19,19,19,19,19,20,20,20,20,20,20,20,21,
    5, 4, 4, 4, 4, 4, 4, 4, 4, 4,25,25,25,25, 4, 4, 4, 5,
    0, 5, 4, 4, 4, 4, 4, 4,25,25,25,25,25, 4,11,11, 5, 0,
    0, 0, 5,19,19,19,19,20,20,20,20,20,20,11,19,19,20,21,
    0, 0, 0,21, 4, 4,25,25,25,25,25,25,25,25,21,20,21, 0,
    0, 0, 0, 0, 5,19,19,19,19,19,19,19,19, 5, 0,21, 0, 0,
    0, 0, 0, 0, 0,21,21,21,16,16,16,21,21, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 5,25, 5, 0, 0, 0, 0, 0, 0, 0
};

//--- Frame 1: wings down, eyes open (18x18)
const uchar g_beeF1[324] =
{
    0, 0, 0, 2, 3, 4, 5, 0, 0, 0, 0, 0, 2, 3, 4, 5, 0, 0,
    0, 0, 1,10,11,11, 5, 0, 0, 0, 0, 0, 2,11,11, 6, 0, 0,
    0, 1, 7,12,14, 6, 0,15,15,15,15,15,10, 7,12,12, 6, 0,
    1, 8,13,14,10,16,15,17,17,18,19,16,16,10,14,13, 9, 6,
    1,12,14,10,18,17,17,17,17,18,18,18,18,20,10, 9, 9, 6,
    6, 9,10,18,18,17,17,17,17,18,18,18,18,20,20,10, 9, 6,
    0, 1,18,18,17,17,17,17,18,18,18,18,18,19,20,20, 6, 0,
    0,15,18,17,17,17,13,22,18,18,18,13,22,19,19,20,21, 0,
   15,17,17,17,18,18,22,22,18,19,19,22,22,19,19,19,19,21,
   15,17,18,23,23,18,18,18,19,24,24,19,19,23,23,20,20,21,
   15,19,18,19,19,19,19,19,19,19,20,20,20,20,20,20,20,21,
    5, 4, 4, 4, 4, 4, 4, 4, 4, 4,25,25,25,25, 4, 4, 4, 5,
    0, 5, 4, 4, 4, 4, 4, 4,25,25,25,25,25, 4,11,11, 5, 0,
    0, 0, 5,19,19,19,19,20,20,20,20,20,20,11,19,19,20,21,
    0, 0, 0,21, 4, 4,25,25,25,25,25,25,25,25,21,20,21, 0,
    0, 0, 0, 0, 5,19,19,19,19,19,19,19,19, 5, 0,21, 0, 0,
    0, 0, 0, 0, 0,21,21,21,16,16,16,21,21, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 5,25, 5, 0, 0, 0, 0, 0, 0, 0
};

//--- Blink Frame 0: wings up, eyes closed (18x18)
const uchar g_beeB0[324] =
{
    0, 1, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 2, 3, 4, 2, 6, 0,
    1, 7, 8, 9,10,11, 5, 0, 0, 0, 0, 0, 1,11,10, 8,12, 6,
    1, 8,13, 9,14,14,10,15,15,15,15, 1, 7, 9,12,13, 9, 6,
    1,12, 9,14,10,10,16,17,17,18,19,16,10,10,14, 9,14, 6,
    6, 9,14,10,18,18,17,17,17,18,18,18,19,20,10, 9,14, 6,
    0, 1,16,18,18,18,17,18,18,18,18,18,19,20,20,16, 6, 0,
    0,15,18,18,17,19,19,19,19,19,19,19,19,19,20,20,21, 0,
    0,15,18,17,19,19,19,19,19,19,19,19,19,19,19,20,21, 0,
   15,17,17,18,19,20,16,16,18,19,20,16,16,18,18,19,19,21,
   15,17,18,23,23,19,18,17,17,24,24,18,17,23,23,19,20,21,
   15,19,19,19,19,18,18,17,17,18,18,18,18,19,20,20,20,21,
    5, 4, 4, 4, 4, 3, 3, 3, 3, 3, 4, 4, 4,25, 4, 4, 4, 5,
    0, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4,25,25, 4,11,11, 5, 0,
    0, 0, 5,19,19,19,19,19,20,20,20,20,20,11,19,19,20,21,
    0, 0, 0,21, 4, 4,25,25,25,25,25,25,25,25,21,20,21, 0,
    0, 0, 0, 0, 5,19,19,19,19,19,19,19,19, 5, 0,21, 0, 0,
    0, 0, 0, 0, 0,21,21,21,16,16,16,21,21, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 5,25, 5, 0, 0, 0, 0, 0, 0, 0
};

//--- Blink Frame 1: wings down, eyes closed (18x18)
const uchar g_beeB1[324] =
{
    0, 0, 0, 2, 3, 4, 5, 0, 0, 0, 0, 0, 2, 3, 4, 5, 0, 0,
    0, 0, 1,10,11,11, 5, 0, 0, 0, 0, 0, 2,11,11, 6, 0, 0,
    0, 1, 7,12,14, 6, 0,15,15,15,15,15,10, 7,12,12, 6, 0,
    1, 8,13,14,10,16,15,17,17,18,19,16,16,10,14,13, 9, 6,
    1,12,14,10,18,17,17,17,17,18,18,18,18,20,10, 9, 9, 6,
    6, 9,10,18,18,17,17,18,18,18,18,18,18,20,20,10, 9, 6,
    0, 1,18,18,17,19,19,19,19,19,19,19,19,19,20,20, 6, 0,
    0,15,18,17,19,19,19,19,19,19,19,19,19,19,19,20,21, 0,
   15,17,17,18,19,20,16,16,18,19,20,16,16,18,18,19,19,21,
   15,17,18,23,23,19,18,17,17,24,24,18,17,23,23,19,20,21,
   15,19,19,19,19,18,18,17,17,18,18,18,18,19,20,20,20,21,
    5, 4, 4, 4, 4, 3, 3, 3, 3, 3, 4, 4, 4,25, 4, 4, 4, 5,
    0, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4,25,25, 4,11,11, 5, 0,
    0, 0, 5,19,19,19,19,19,20,20,20,20,20,11,19,19,20,21,
    0, 0, 0,21, 4, 4,25,25,25,25,25,25,25,25,21,20,21, 0,
    0, 0, 0, 0, 5,19,19,19,19,19,19,19,19, 5, 0,21, 0, 0,
    0, 0, 0, 0, 0,21,21,21,16,16,16,21,21, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 5,25, 5, 0, 0, 0, 0, 0, 0, 0
};

//--- Runtime canvas state
string g_objName = "";
string g_resName = "";
int    g_scale   = 2;
int    g_bmpW    = 168;
int    g_bmpH    = 76;
uint   g_buf[];

//--- Bee physics & AI state
double g_x            = 120.0;
double g_targetX      = 260.0;
double g_vx           = 0.0;
bool   g_facingLeft   = false;
double g_phase        = 0.0;      // Hover sine phase
double g_flapAccMs    = 0.0;
int    g_wingFrame    = 0;

//--- Blink state
bool   g_blinking     = false;
double g_blinkTimer   = 3.0;

//--- Idle / Wander state
bool   g_idling       = false;
double g_stateTimer   = 3.5;

//--- Spook / Jump state
double g_spookTimer   = 0.0;
double g_jumpOffset   = 0.0;      // Extra upward art cells on click spook
double g_jumpVel      = 0.0;

//--- Speech bubble state (RSI text or optional pixel emote)
string g_speechText   = "";
uint   g_speechColor  = 0xFF1E0C1F;
int    g_emote        = EMOTE_NONE;
double g_bubbleTimer  = 0.0;
double g_nextSpeak    = 1.2;      // Speak shortly after attaching to chart

//--- Timing & cached screen bounds
ulong  g_lastTickMs   = 0;
int    g_lastDrawX    = -9999;
int    g_lastDrawY    = -9999;
double g_rsiPollAcc   = 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 RSI(InpRsiPeriod) value from bar 0              |
//+------------------------------------------------------------------+
bool RefreshRsiValue()
{
   if(g_rsiHandle == INVALID_HANDLE)
      return false;

   double tmp[1];
   if(CopyBuffer(g_rsiHandle, 0, 0, 1, tmp) == 1 && MathIsValidNumber(tmp[0]) && tmp[0] != EMPTY_VALUE)
   {
      g_rsiValue = tmp[0];
      g_rsiValid = true;
      return true;
   }
   return g_rsiValid;
}

//+------------------------------------------------------------------+
//| Color for RSI reading (Overbought red, Oversold green, Ink norm) |
//+------------------------------------------------------------------+
uint RsiTextColor(const double rsi)
{
   if(rsi >= InpOverbought) return 0xFFC82834;
   if(rsi <= InpOversold)   return 0xFF1B7F42;
   return 0xFF1E0C1F;
}

//+------------------------------------------------------------------+
//| Trigger a live "RSI(N) = XX.X" speech bubble                     |
//+------------------------------------------------------------------+
void SpeakRsi(const bool exclaimed = false)
{
   RefreshRsiValue();
   g_emote = EMOTE_NONE;

   if(g_rsiValid)
   {
      g_speechText  = StringFormat("RSI(%d) = %.1f%s", MathMax(1, InpRsiPeriod), g_rsiValue, exclaimed ? "!" : "");
      g_speechColor = RsiTextColor(g_rsiValue);
      ObjectSetString(0, g_objName, OBJPROP_TOOLTIP, StringFormat("Bee %s (click to poke)", g_speechText));
   }
   else
   {
      g_speechText  = StringFormat("RSI(%d) = --.-", MathMax(1, InpRsiPeriod));
      g_speechColor = 0xFF1E0C1F;
   }

   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 speech bubbles ("RSI(14) = 54.2")     |
//+------------------------------------------------------------------+
void GetPixelGlyph(const ushort ch, string &rows[])
{
   ArrayResize(rows, 7);
   switch(ch)
   {
      case 'R':
         rows[0]="###."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="###.";
         rows[4]="#.#."; rows[5]="#..#"; rows[6]="#..#"; break;
      case 'S':
         rows[0]=".###"; rows[1]="#..."; rows[2]="#..."; rows[3]=".##.";
         rows[4]="...#"; rows[5]="...#"; rows[6]="###."; break;
      case 'I':
         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 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 Bee
   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 RSI text speech bubble ("RSI(14) = 54.2") above the Bee     |
//+------------------------------------------------------------------+
void DrawTextBubble(const int beeTopY, const string text, const uint textColor)
{
   int tw = MeasurePixelText(text);
   if(tw <= 0) return;

   int bw = MathMin(CANVAS_W_CELLS, tw + 6);
   int bh = 7 + 5; // 1px border + 1px pad + 7px font + 1px shade + 1px border + 1px breathing
   int bx = (CANVAS_W_CELLS - bw) / 2;
   int by = beeTopY - bh - 2;
   if(by < 0) by = 0;

   DrawBubbleShell(bx, by, bw, bh);

   int curX = bx + (bw - tw) / 2;
   int gy0  = by + 2;
   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, gy0 + y, textColor);
         }
      }
      curX += gw + 1;
   }
}

//+------------------------------------------------------------------+
//| Draw optional pixel icon emote bubble above the Bee              |
//+------------------------------------------------------------------+
void DrawEmoteBubble(const int beeTopY, 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 = beeTopY - 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 hovering shadow right on the bottom edge of the main chart  |
//+------------------------------------------------------------------+
void DrawShadow(const double hoverCells)
{
   if(!InpShowShadow)
      return;

   int halfW = (hoverCells > 4.5) ? 4 : ((hoverCells > 2.5) ? 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 Bee sprite                                 |
//+------------------------------------------------------------------+
void DrawBee(const int ox, const int oy)
{
   for(int y = 0; y < BEE_CELLS; y++)
   {
      int rowBase = y * BEE_CELLS;
      for(int x = 0; x < BEE_CELLS; x++)
      {
         int sx = g_facingLeft ? (BEE_CELLS - 1 - x) : x;
         uchar idx = 0;
         if(g_blinking)
            idx = (g_wingFrame == 0) ? g_beeB0[rowBase + sx] : g_beeB1[rowBase + sx];
         else
            idx = (g_wingFrame == 0) ? g_beeF0[rowBase + sx] : g_beeF1[rowBase + sx];

         if(idx != 0)
            PutArtPixel(ox + x, oy + y, g_beePalette[idx]);
      }
   }
}

//+------------------------------------------------------------------+
//| Trigger click-to-spook reaction + instant live RSI speech        |
//+------------------------------------------------------------------+
void SpookBee()
{
   g_spookTimer = 1.6;
   g_idling     = false;
   g_jumpVel    = 36.0;
   SpeakRsi(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);

   // Low hover right above the bottom border of the main MT5 chart
   double hoverCells = 2.0 + MathSin(g_phase * 3.0) * 1.1 + g_jumpOffset;
   if(hoverCells < 0.5) hoverCells = 0.5;
   if(hoverCells > 8.0) hoverCells = 8.0;

   int beeOx   = (CANVAS_W_CELLS - BEE_CELLS) / 2;
   int groundY = CANVAS_H_CELLS - 2;
   int beeOy   = groundY - BEE_CELLS - (int)MathRound(hoverCells);
   if(beeOy < 0) beeOy = 0;

   DrawShadow(hoverCells);
   DrawBee(beeOx, beeOy);

   if(g_bubbleTimer > 0.0)
   {
      if(g_speechText != "")
         DrawTextBubble(beeOy, g_speechText, g_speechColor);
      else if(g_emote != EMOTE_NONE)
         DrawEmoteBubble(beeOy, 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() ^ (uint)ChartID());

   int period = MathMax(1, InpRsiPeriod);
   SetIndexBuffer(0, g_rsiBuf, INDICATOR_CALCULATIONS);
   IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("BeeRSI(%d)", period));
   IndicatorSetInteger(INDICATOR_DIGITS, 2);

   g_rsiHandle = iRSI(_Symbol, _Period, period, InpRsiPrice);
   if(g_rsiHandle == INVALID_HANDLE)
   {
      Print("BeeCritter: iRSI 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  = "BeeCritter_" + 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();

   RefreshRsiValue();

   // Create initial resource BEFORE binding to OBJ_BITMAP_LABEL
   if(!ResourceCreate(g_resName, g_buf, g_bmpW, g_bmpH, 0, 0, g_bmpW, COLOR_FORMAT_ARGB_NORMALIZE))
   {
      Print("BeeCritter: ResourceCreate failed, err=", GetLastError());
      IndicatorRelease(g_rsiHandle);
      g_rsiHandle = INVALID_HANDLE;
      return INIT_FAILED;
   }

   if(!ObjectCreate(0, g_objName, OBJ_BITMAP_LABEL, 0, 0, 0))
   {
      Print("BeeCritter: ObjectCreate failed, err=", GetLastError());
      ResourceFree(g_resName);
      IndicatorRelease(g_rsiHandle);
      g_rsiHandle = 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,     100);
   ObjectSetString(0,  g_objName, OBJPROP_TOOLTIP,    StringFormat("Bee RSI(%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_rsiHandle != INVALID_HANDLE)
   {
      IndicatorRelease(g_rsiHandle);
      g_rsiHandle = INVALID_HANDLE;
   }
   ChartRedraw(0);
}

//+------------------------------------------------------------------+
//| Indicator calculation: populate RSI buffer & detect OB/OS zones  |
//+------------------------------------------------------------------+
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[])
{
   if(g_rsiHandle == INVALID_HANDLE || rates_total <= InpRsiPeriod)
      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_rsiHandle, 0, 0, toCopy, g_rsiBuf) <= 0)
      return prev_calculated;

   // Read live bar 0 RSI
   if(RefreshRsiValue())
   {
      int zone = (g_rsiValue >= InpOverbought) ? 1 : ((g_rsiValue <= InpOversold) ? -1 : 0);
      if(zone != 0 && zone != g_lastZone)
         SpeakRsi(true);
      g_lastZone = zone;
   }

   return rates_total;
}

//+------------------------------------------------------------------+
//| Animation, RSI speech & 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 RSI every 0.5s so live speech stays current even between ticks
   g_rsiPollAcc += dt;
   if(g_rsiPollAcc >= 0.5)
   {
      g_rsiPollAcc = 0.0;
      RefreshRsiValue();
      if(g_bubbleTimer > 0.0 && g_speechText != "" && g_rsiValid)
      {
         bool bang = (StringFind(g_speechText, "!") >= 0);
         g_speechText  = StringFormat("RSI(%d) = %.1f%s", MathMax(1, InpRsiPeriod), g_rsiValue, bang ? "!" : "");
         g_speechColor = RsiTextColor(g_rsiValue);
      }
   }

   // 1. Wing flap cadence (faster when spooked or in OB/OS zone)
   bool excited = (g_spookTimer > 0.0) || (g_rsiValid && (g_rsiValue >= InpOverbought || g_rsiValue <= InpOversold));
   double flapPeriod = (g_spookTimer > 0.0) ? (FRAME_MS * 0.55) : (excited ? (FRAME_MS * 0.78) : (double)FRAME_MS);
   g_flapAccMs += dtMs;
   if(g_flapAccMs >= flapPeriod)
   {
      g_flapAccMs = MathMod(g_flapAccMs, flapPeriod);
      g_wingFrame = 1 - g_wingFrame;
   }

   // 2. Hover bob phase
   g_phase += dt * ((g_spookTimer > 0.0) ? 2.2 : 1.0);

   // 3. Spook jump arc
   if(g_jumpOffset > 0.0 || g_jumpVel > 0.0)
   {
      g_jumpOffset += g_jumpVel * dt;
      g_jumpVel    -= 190.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);

   // 4. 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.4, 5.8);
      }
   }

   // 5. Random "RSI(14) = ..." 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
         {
            SpeakRsi(false);
         }
         g_nextSpeak = RandRange(MathMax(1.0, InpSpeakMinSec), MathMax(2.0, InpSpeakMaxSec));
      }
   }

   // 6. 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 * 8.0);
      g_x  += g_vx * dt;
      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, InpCruiseSpeed) * ((g_spookTimer > 0.0) ? 2.6 : 1.0);

      if(dist <= 4.0)
      {
         g_vx = 0.0;
         if(g_spookTimer > 0.0)
         {
            PickNextTarget(chartW);
         }
         else
         {
            g_idling     = true;
            g_stateTimer = RandRange(1.4, 4.2);
         }
      }
      else
      {
         double dir      = (dx > 0.0) ? 1.0 : -1.0;
         double desiredV = dir * speed * MathMin(1.0, dist / 28.0 + 0.25);
         g_vx += (desiredV - g_vx) * MathMin(1.0, dt * 6.0);
         g_x  += g_vx * dt;
         g_facingLeft = (g_vx < -0.5);
      }
   }

   g_x = MathMax((double)minX, MathMin((double)maxX, g_x));
   RenderFrame(chartW, chartH);
}

//+------------------------------------------------------------------+
//| Chart events: click to spook/speak RSI & 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)
   {
      SpookBee();
      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)
         SpookBee();
      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);
      }
   }
}
//+------------------------------------------------------------------+
