(function () {
  'use strict';

  if (window.__MY_QX_BOT__) return;
  window.__MY_QX_BOT__ = true;

  const CONFIG = {
    name: 'V1PER X BOT',
    subtitle: 'SMART SIGNAL SYSTEM',

    accent: '#00ff55',
    down: '#ff3b3b',
    cyan: '#00d4ff',

    scanDelay: 1800
  };

  function clamp(value, min, max) {
    return Math.max(min, Math.min(max, value));
  }

  function analyzePixels() {
    let t = 0;
    let m = 0;
    let ok = false;

    const canvases = document.querySelectorAll('canvas');

    for (const canvas of canvases) {
      try {
        const rect = canvas.getBoundingClientRect();

        if (rect.width < 200 || rect.height < 100)
          continue;

        const ctx = canvas.getContext('2d');

        if (!ctx || !canvas.width || !canvas.height)
          continue;

        const data = ctx.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        ).data;

        const w = canvas.width;
        const h = canvas.height;

        let green = 0;
        let red = 0;

        for (let y = 0; y < h; y += 3) {
          for (let x = 0; x < w; x += 3) {

            const i = (y * w + x) * 4;

            const R = data[i];
            const G = data[i + 1];
            const B = data[i + 2];
            const A = data[i + 3];

            if (A < 35)
              continue;

            const brightness =
              (R + G + B) / 3;

            if (brightness < 25 || brightness > 235)
              continue;

            if (
              G > R + 35 &&
              G > B + 35
            ) {
              green++;
            }

            if (
              R > G + 35 &&
              R > B + 35
            ) {
              red++;
            }
          }
        }

        const total = green + red;

        if (total > 10) {
          ok = true;

          t =
            ((green - red) / total) * 100;

          m = t;

          t = clamp(t, -100, 100);
          m = clamp(m, -100, 100);

          break;
        }

      } catch (e) {
        console.debug(
          '[V1PER X BOT] Canvas error',
          e
        );
      }
    }

    return {
      t,
      m,
      ok
    };
  }


  function analyzeDOM() {

    let score = 0;
    let found = 0;

    const elements =
      document.querySelectorAll(
        'span, div, b, strong, td, li'
      );

    for (const el of elements) {

      try {

        const text =
          (el.textContent || '').trim();

        if (!text)
          continue;

        const style =
          getComputedStyle(el);

        const color =
          style.color || '';

        const className =
          typeof el.className === 'string'
            ? el.className.toLowerCase()
            : '';

        const rgb =
          color.match(
            /rgb\((\d+),\s*(\d+),\s*(\d+)\)/
          );

        if (!rgb)
          continue;

        const R = Number(rgb[1]);
        const G = Number(rgb[2]);
        const B = Number(rgb[3]);

        const isGreen =
          G > R + 30 &&
          G > B + 30 &&
          G > 80;

        const isRed =
          R > G + 30 &&
          R > B + 30 &&
          R > 80;

        if (isGreen) {

          score += 2;
          found++;

          if (
            /price|rate|change|tick/.test(
              className
            )
          ) {
            score += 8;
          }
        }

        if (isRed) {

          score -= 2;
          found++;

          if (
            /price|rate|change|tick/.test(
              className
            )
          ) {
            score -= 8;
          }
        }

      } catch (e) {}
    }

    return found
      ? clamp(score, -100, 100)
      : 0;
  }


  function analyzeSVG() {

    let score = 0;
    let found = 0;

    const svgs =
      document.querySelectorAll('svg');

    for (const svg of svgs) {

      try {

        const rect =
          svg.getBoundingClientRect();

        if (
          rect.width < 200 ||
          rect.height < 100
        )
          continue;

        const parts =
          svg.querySelectorAll(
            'path,line,polyline,rect,circle'
          );

        for (const part of parts) {

          try {

            const style =
              getComputedStyle(part);

            const stroke =
              part.getAttribute('stroke') ||
              style.stroke ||
              '';

            const fill =
              part.getAttribute('fill') ||
              style.fill ||
              '';

            if (
              /red/i.test(stroke) ||
              /255,\s*0,\s*0/.test(stroke)
            ) {
              score -= 2;
              found++;
            }

            if (
              /green/i.test(stroke) ||
              /0,\s*255,\s*0/.test(stroke)
            ) {
              score += 2;
              found++;
            }

            if (
              /green/i.test(fill)
            ) {
              score += 1;
              found++;
            }

            if (
              /red/i.test(fill)
            ) {
              score -= 1;
              found++;
            }

          } catch (e) {}
        }

      } catch (e) {}
    }

    return found
      ? clamp(score * 3, -100, 100)
      : 0;
  }
    function calcRSI() {

    const prices = [];

    const selectors = [
      '[class*="history"]',
      '[class*="trades"]',
      '[class*="deals"]',
      '[class*="ticks"]',
      '[class*="list"]'
    ];

    for (const selector of selectors) {

      try {

        const elements =
          document.querySelectorAll(
            selector +
            ' span,' +
            selector +
            ' div,' +
            selector +
            ' td'
          );

        for (const element of elements) {

          const text =
            (element.textContent || '')
              .trim();

          const match =
            text.match(/\d+\.\d{2,}/);

          if (!match)
            continue;

          const value =
            parseFloat(match[0]);

          if (
            value <= 0 ||
            value >= 1000000
          )
            continue;

          const previous =
            prices.length
              ? prices[prices.length - 1]
              : 0;

          if (
            !previous ||
            Math.abs(value - previous)
              < previous * 0.05
          ) {

            prices.push(value);

            if (prices.length >= 20)
              break;
          }
        }

        if (prices.length >= 8)
          break;

      } catch (e) {}
    }

    if (prices.length < 5)
      return 50;

    const n =
      Math.min(
        14,
        prices.length - 1
      );

    const values =
      prices.slice(-n - 1);

    let gains = 0;
    let losses = 0;

    for (
      let i = 1;
      i < values.length;
      i++
    ) {

      const difference =
        values[i] -
        values[i - 1];

      if (difference > 0)
        gains += difference;
      else
        losses += Math.abs(difference);
    }

    gains /= n;
    losses /= n;

    if (!losses)
      return 90;

    if (!gains)
      return 10;

    const rs =
      gains / losses;

    return 100 -
      (100 / (1 + rs));
  }


  function runAnalysis() {

    const pixels =
      analyzePixels();

    const dom =
      analyzeDOM();

    const svg =
      analyzeSVG();

    const rsi =
      calcRSI();

    const rsiScore =
      50 - rsi;

    let total = 0;

    let sources = 0;

    if (pixels.ok) {

      total +=
        pixels.t * 0.30;

      total +=
        pixels.m * 0.15;

      sources += 2;
    }

    if (dom) {

      total +=
        dom * 0.20;

      sources++;
    }

    if (svg) {

      total +=
        svg * 0.20;

      sources++;
    }

    total +=
      rsiScore * 0.15;

    total =
      clamp(
        total,
        -100,
        100
      );

    /*
      IMPORTANT:

      When insufficient page data is available,
      the original bot uses a random fallback.

      This is retained here only to reproduce
      the original behavior.

      It should NOT be interpreted as a
      genuine market prediction.
    */

    if (!sources) {

      total =
        (Math.random() - 0.5) * 80;

    } else if (
      sources <= 2 &&
      Math.abs(total) < 20
    ) {

      total =
        total * 0.5 +
        (Math.random() - 0.5) * 40;
    }

    const confidence =
      clamp(
        50 +
        Math.abs(total) * 0.5,
        55,
        95
      );

    return {

      direction:
        total >= 0
          ? 'UP'
          : 'DOWN',

      confidence:
        Math.round(confidence),

      score:
        Math.round(total),

      sources,

      diagnostics: {
        pixels,
        dom,
        svg,
        rsi
      }
    };
  }
    function createUI() {

      document.querySelectorAll(
        '#shakib-bot-fab, #shakib-bot-panel, #shakib-bot-style'
      ).forEach((element) => element.remove());

    const style =
      document.createElement('style');

    style.id =
      'shakib-bot-style';

    style.textContent = `

      @keyframes botSpin {
        from {
          transform: rotate(0deg);
        }

        to {
          transform: rotate(360deg);
        }
      }

      @keyframes botGlow {

        0%,100% {
          box-shadow:
            0 0 8px #00ff55,
            0 0 20px rgba(0,255,85,.25);
        }

        50% {
          box-shadow:
            0 0 20px #00ff55,
            0 0 40px rgba(0,255,85,.5);
        }
      }

      @keyframes botIn {

        from {
          opacity: 0;
          transform:
            translate(-50%,-50%)
            scale(.75);
        }

        to {
          opacity: 1;
          transform:
            translate(-50%,-50%)
            scale(1);
        }
      }

      #shakib-bot-fab {

        position: fixed;

        right: 20px;
        bottom: 25px;

        width: 62px;
        height: 62px;

        border-radius: 50%;

        border:
          2px solid ${CONFIG.accent};

        background:
          radial-gradient(
            circle,
            #102010,
            #050805
          );

        color:
          ${CONFIG.accent};

        display:
          flex;

        align-items:
          center;

        justify-content:
          center;

        cursor:
          pointer;

        z-index:
          2147483647;

        font:
          bold 11px
          "Courier New";

        animation:
          botGlow 2s infinite;

        user-select:
          none;
      }

     #shakib-bot-panel {
        position: fixed;
        left: 50%;
        top: 50%;

        width: 290px;
        max-width: calc(100vw - 20px);
        box-sizing: border-box;

        background: #050b05;
        border: 2px solid ${CONFIG.accent};
        border-radius: 18px;

        color: white;
        z-index: 2147483646;

        display: none;

        font-family: "Courier New", monospace;

        box-shadow:
            0 0 30px rgba(0,255,85,.35);

        overflow: hidden;

        /* Important */
        transform: translate(-50%, -50%);
        user-select: none;
    }

      #shakib-bot-header {

        padding:
          13px 15px;

        border-bottom:
          1px solid
          rgba(0,255,85,.3);

        display:
          flex;

        justify-content:
          space-between;

        align-items:
          center;

        cursor:
          move;

        touch-action:
          none;
      }

      #shakib-bot-title {

        color:
          ${CONFIG.accent};

        font-size:
          16px;

        font-weight:
          900;
      }

      #shakib-bot-close {

        color:
          #aaa;

        font-size:
          22px;

        cursor:
          pointer;
      }

      #shakib-bot-body {

        padding:
          20px;

        text-align:
          center;
      }

      #shakib-bot-radar {

        width:
          125px;

        height:
          125px;

        margin:
          5px auto 15px;

        border-radius:
          50%;

        border:
          1px solid
          rgba(0,255,85,.5);

        position:
          relative;

        overflow:
          hidden;

        background:
          radial-gradient(
            circle,
            transparent 18%,
            rgba(0,255,85,.05) 19%,
            transparent 20%
          ),
          radial-gradient(
            circle,
            transparent 39%,
            rgba(0,255,85,.05) 40%,
            transparent 41%
          ),
          radial-gradient(
            circle,
            transparent 59%,
            rgba(0,255,85,.05) 60%,
            transparent 61%
          ),
          #071007;
      }

      #shakib-bot-sweep {

        position:
          absolute;

        width:
          50%;

        height:
          2px;

        left:
          50%;

        top:
          50%;

        transform-origin:
          left center;

        background:
          linear-gradient(
            90deg,
            ${CONFIG.accent},
            transparent
          );

        animation:
          botSpin 1.2s
          linear infinite;
      }

      #shakib-bot-status {

        color:
          #aaa;

        font-size:
          11px;

        letter-spacing:
          1px;

        min-height:
          18px;
      }

      #shakib-bot-signal {

        display:
          none;

        font-size:
          44px;

        font-weight:
          900;

        margin:
          8px 0;
      }

      #shakib-bot-signal.up {

        display:
          block;

        color:
          ${CONFIG.accent};

        text-shadow:
          0 0 15px
          ${CONFIG.accent};
      }

      #shakib-bot-signal.down {

        display:
          block;

        color:
          ${CONFIG.down};

        text-shadow:
          0 0 15px
          ${CONFIG.down};
      }

      #shakib-bot-confidence {

        color:
          #aaa;

        font-size:
          11px;

        min-height:
          18px;
      }

      #shakib-bot-scan {

        width:
          90%;

        margin-top:
          12px;

        padding:
          11px;

        border:
          1px solid
          ${CONFIG.accent};

        border-radius:
          9px;

        background:
          rgba(0,255,85,.05);

        color:
          ${CONFIG.accent};

        font:
          bold 12px
          "Courier New";

        cursor:
          pointer;
      }

      #shakib-bot-scan:hover {

        background:
          rgba(0,255,85,.15);
      }
    `;

    document.head.appendChild(style);


    const fab =
      document.createElement('div');

    fab.id =
      'shakib-bot-fab';

    fab.textContent =
      'BOT';

    document.body.appendChild(fab);


    const panel =
      document.createElement('div');

    panel.id =
      'shakib-bot-panel';

    panel.innerHTML = `

      <div id="shakib-bot-header">

        <div id="shakib-bot-title">
          ${CONFIG.name}
        </div>

        <div id="shakib-bot-close">
          ×
        </div>

      </div>

      <div id="shakib-bot-body">

        <div id="shakib-bot-radar">

          <div id="shakib-bot-sweep">
          </div>

        </div>

        <div id="shakib-bot-status">
          READY TO SCAN
        </div>

        <div id="shakib-bot-signal">
        </div>

        <div id="shakib-bot-confidence">
        </div>

        <button id="shakib-bot-scan">
          SMART SCAN
        </button>

      </div>
    `;

    document.body.appendChild(panel);

    /* ============================
      DRAG PANEL
      ============================ */

    const header =
      panel.querySelector('#shakib-bot-header');

    let draggingPanel = false;
    let pointerId = null;
    let startPointerX = 0;
    let startPointerY = 0;
    let startPanelLeft = 0;
    let startPanelTop = 0;
    let previousUserSelect = '';

    function clampPanelToViewport() {
      const rect = panel.getBoundingClientRect();
      const maxLeft = Math.max(0, window.innerWidth - panel.offsetWidth);
      const maxTop = Math.max(0, window.innerHeight - panel.offsetHeight);
      const left = Math.max(0, Math.min(rect.left, maxLeft));
      const top = Math.max(0, Math.min(rect.top, maxTop));

      panel.style.transform = 'none';
      panel.style.left = left + 'px';
      panel.style.top = top + 'px';
    }

    function endPanelDrag() {
      if (!draggingPanel)
        return;

      draggingPanel = false;
      const activePointerId = pointerId;
      pointerId = null;
      document.body.style.userSelect = previousUserSelect;

      if (
        activePointerId !== null &&
        header.hasPointerCapture(activePointerId)
      ) {
        header.releasePointerCapture(activePointerId);
      }
    }

    header.addEventListener('pointerdown', function (e) {
      if (
        !e.isPrimary ||
        (e.pointerType === 'mouse' && e.button !== 0) ||
        e.target.closest(
          '#shakib-bot-close, button, a, input, select, textarea, [contenteditable="true"], [role="button"]'
        )
      ) {
        return;
      }

      const rect = panel.getBoundingClientRect();

      draggingPanel = true;
      pointerId = e.pointerId;
      startPointerX = e.clientX;
      startPointerY = e.clientY;
      startPanelLeft = rect.left;
      startPanelTop = rect.top;
      previousUserSelect = document.body.style.userSelect;

      panel.style.transform = 'none';
      panel.style.left = rect.left + 'px';
      panel.style.top = rect.top + 'px';
      document.body.style.userSelect = 'none';

      try {
        header.setPointerCapture(pointerId);
      } catch (error) {}

      e.preventDefault();
    });

    header.addEventListener('pointermove', function (e) {
      if (!draggingPanel || e.pointerId !== pointerId)
        return;

      const maxLeft = Math.max(0, window.innerWidth - panel.offsetWidth);
      const maxTop = Math.max(0, window.innerHeight - panel.offsetHeight);
      const newLeft = Math.max(
        0,
        Math.min(startPanelLeft + e.clientX - startPointerX, maxLeft)
      );
      const newTop = Math.max(
        0,
        Math.min(startPanelTop + e.clientY - startPointerY, maxTop)
      );

      panel.style.left = newLeft + 'px';
      panel.style.top = newTop + 'px';
      e.preventDefault();
    });

    header.addEventListener('pointerup', function (e) {
      if (e.pointerId === pointerId)
        endPanelDrag();
    });

    header.addEventListener('pointercancel', function (e) {
      if (e.pointerId === pointerId)
        endPanelDrag();
    });

    header.addEventListener('lostpointercapture', function (e) {
      if (e.pointerId === pointerId)
        endPanelDrag();
    });

    window.addEventListener('resize', function () {
      if (panel.style.display !== 'none')
        clampPanelToViewport();
    });


    const status =
      panel.querySelector(
        '#shakib-bot-status'
      );

    const signal =
      panel.querySelector(
        '#shakib-bot-signal'
      );

    const confidence =
      panel.querySelector(
        '#shakib-bot-confidence'
      );

    const scan =
      panel.querySelector(
        '#shakib-bot-scan'
      );

    const sweep =
      panel.querySelector(
        '#shakib-bot-sweep'
      );

    const close =
      panel.querySelector(
        '#shakib-bot-close'
      );


    function runScan() {

      status.textContent =
        'SCANNING PAGE...';

      signal.style.display =
        'none';

      confidence.textContent =
        '';

      sweep.style.animation =
        'botSpin .6s linear infinite';

      setTimeout(() => {

        const result =
          runAnalysis();

        sweep.style.animation =
          'none';

        status.textContent =
          'SCAN COMPLETE';

        signal.textContent =
          result.direction;

        signal.className =
          result.direction === 'UP'
            ? 'up'
            : 'down';

        signal.style.display =
          'block';

        confidence.textContent =
          `HEURISTIC CONFIDENCE: ${result.confidence}%`;

        console.log(
          '[V1PER X BOT]',
          result
        );

      }, CONFIG.scanDelay);
    }


    fab.onclick = function () {

      if (
        panel.style.display ===
        'block'
      ) {

        runScan();

      } else {

        panel.style.display =
          'block';

        runScan();
      }
    };


    close.onclick = function () {

      panel.style.display =
        'none';

    };


    scan.onclick = function () {

      runScan();

    };
  }



  createUI();

  console.log(
    `[${CONFIG.name}] loaded successfully.`
  );

})();