(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: '#63e01b',   // theme color (was green)
    wait: '#ffb020',
    up: '#00ff55',       // kept green for UP signal so it stays distinguishable
    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 getDataQuality(sources) {

    if (sources >= 4)
      return 'GOOD';

    if (sources >= 2)
      return 'LIMITED';

    return 'INSUFFICIENT';
  }


  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
      );

    const dataQuality =
      getDataQuality(sources);

    const diagnostics = {
      pixels,
      dom,
      svg,
      rsi
    };

    /*
      Not enough usable page data: report an explicit WAIT state
      instead of generating a random direction.
    */
    if (sources < 2) {

      return {
        direction: 'WAIT',
        confidence: 0,
        score: 0,
        sources,
        dataQuality: 'INSUFFICIENT',
        diagnostics
      };
    }

    /*
      Weak, low-source result: no reliable direction, so WAIT
      (previously random noise was mixed into this case).
    */
    if (
      sources <= 2 &&
      Math.abs(total) < 20
    ) {

      return {
        direction: 'WAIT',
        confidence: 0,
        score: Math.round(total),
        sources,
        dataQuality,
        diagnostics
      };
    }

    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,

      dataQuality,

      diagnostics
    };
  }
    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 ${CONFIG.accent},
            0 0 20px rgba(22,199,90,.25);
        }

        50% {
          box-shadow:
            0 0 20px ${CONFIG.accent},
            0 0 40px rgba(22,199,90,.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,
            #201010,
            #080505
          );

        color:
          ${CONFIG.accent};

        display:
          flex;

        align-items:
          center;

        justify-content:
          center;

        cursor:
          pointer;

        z-index:
          2147483647;

        font:
          900 11px
          "Courier New";

        font-weight:
          900;

        letter-spacing:
          .5px;

        white-space:
          nowrap;

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

        touch-action:
          none;

        text-align:
          center;

        animation:
          botGlow 2s infinite;

        user-select:
          none;
      }

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

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

        background: #0b0505;
        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(22,199,90,.35);

        overflow: hidden;

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

      #shakib-bot-header {

        padding:
          9px 12px;

        border-bottom:
          1px solid
          rgba(22,199,90,.3);

        display:
          flex;

        justify-content:
          space-between;

        align-items:
          center;

        cursor:
          move;

        touch-action:
          none;
      }

      #shakib-bot-title {

        color:
          ${CONFIG.accent};

        font-size:
          13px;

        font-weight:
          900;
      }

      #shakib-bot-close {

        color:
          #aaa;

        font-size:
          22px;

        cursor:
          pointer;
      }

      #shakib-bot-body {

        padding:
          12px 14px 14px;

        text-align:
          center;
      }

      #shakib-bot-radar {

        width:
          90px;

        height:
          90px;

        margin:
          2px auto 10px;

        border-radius:
          50%;

        border:
          1px solid
          rgba(22,199,90,.5);

        position:
          relative;

        overflow:
          hidden;

        background:
          radial-gradient(
            circle,
            transparent 18%,
            rgba(22,199,90,.05) 19%,
            transparent 20%
          ),
          radial-gradient(
            circle,
            transparent 39%,
            rgba(22,199,90,.05) 40%,
            transparent 41%
          ),
          radial-gradient(
            circle,
            transparent 59%,
            rgba(22,199,90,.05) 60%,
            transparent 61%
          ),
          #100707;
      }

      #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:
          32px;

        font-weight:
          900;

        margin:
          4px 0;
      }

      #shakib-bot-signal.up {

        display:
          block;

        color:
          ${CONFIG.up};

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

      #shakib-bot-signal.down {

        display:
          block;

        color:
          ${CONFIG.down};

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

      #shakib-bot-signal.wait {

        display:
          block;

        color:
          ${CONFIG.wait};

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

      #shakib-bot-scan {

        width:
          90%;

        margin-top:
          8px;

        padding:
          8px;

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

        border-radius:
          9px;

        background:
          rgba(22,199,90,.05);

        color:
          ${CONFIG.accent};

        font:
          bold 11px
          "Courier New";

        cursor:
          pointer;
      }

      #shakib-bot-scan:hover:not(:disabled) {

        background:
          rgba(22,199,90,.15);
      }

      #shakib-bot-scan:disabled {

        opacity:
          .45;

        cursor:
          not-allowed;
      }
    `;

    document.head.appendChild(style);


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

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

    fab.textContent =
      'V1PER X';

    document.body.appendChild(fab);

    /* ============================
      DRAG ICON
      ============================ */

    let fabDragging = false;
    let fabMoved = false;
    let fabPointerId = null;
    let fabStartX = 0;
    let fabStartY = 0;
    let fabStartLeft = 0;
    let fabStartTop = 0;

    function clampFabToViewport() {
      if (!fab.style.left)
        return;

      const maxLeft = Math.max(0, window.innerWidth - fab.offsetWidth);
      const maxTop = Math.max(0, window.innerHeight - fab.offsetHeight);

      fab.style.left =
        Math.max(0, Math.min(parseFloat(fab.style.left) || 0, maxLeft)) + 'px';
      fab.style.top =
        Math.max(0, Math.min(parseFloat(fab.style.top) || 0, maxTop)) + 'px';
    }

    fab.addEventListener('pointerdown', function (e) {
      if (!e.isPrimary || (e.pointerType === 'mouse' && e.button !== 0))
        return;

      const rect = fab.getBoundingClientRect();

      fabDragging = true;
      fabMoved = false;
      fabPointerId = e.pointerId;
      fabStartX = e.clientX;
      fabStartY = e.clientY;
      fabStartLeft = rect.left;
      fabStartTop = rect.top;

      try {
        fab.setPointerCapture(e.pointerId);
      } catch (error) {}
    });

    fab.addEventListener('pointermove', function (e) {
      if (!fabDragging || e.pointerId !== fabPointerId)
        return;

      const dx = e.clientX - fabStartX;
      const dy = e.clientY - fabStartY;

      if (!fabMoved && Math.hypot(dx, dy) < 5)
        return;

      if (!fabMoved) {
        fabMoved = true;
        fab.style.right = 'auto';
        fab.style.bottom = 'auto';
      }

      const maxLeft = Math.max(0, window.innerWidth - fab.offsetWidth);
      const maxTop = Math.max(0, window.innerHeight - fab.offsetHeight);

      fab.style.left =
        Math.max(0, Math.min(fabStartLeft + dx, maxLeft)) + 'px';
      fab.style.top =
        Math.max(0, Math.min(fabStartTop + dy, maxTop)) + 'px';

      e.preventDefault();
    });

    function endFabDrag(e) {
      if (e.pointerId !== fabPointerId)
        return;

      fabDragging = false;
      fabPointerId = null;

      try {
        fab.releasePointerCapture(e.pointerId);
      } catch (error) {}
    }

    fab.addEventListener('pointerup', endFabDrag);
    fab.addEventListener('pointercancel', endFabDrag);
    window.addEventListener('resize', clampFabToViewport);


    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>

        <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 scan =
      panel.querySelector(
        '#shakib-bot-scan'
      );

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

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


    let scanning = false;

    function runScan() {

      if (scanning)
        return;

      scanning = true;
      scan.disabled = true;

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

      signal.style.display =
        'none';

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

      setTimeout(() => {

        try {

          const result =
            runAnalysis();

          status.textContent =
            'SCAN COMPLETE';

          signal.textContent =
            result.direction;

          signal.className =
            result.direction.toLowerCase();

          signal.style.display =
            'block';

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

        } catch (error) {

          status.textContent =
            'SCAN FAILED';

          console.error(
            '[V1PER X BOT] Scan error',
            error
          );

        } finally {

          sweep.style.animation =
            'none';

          scanning = false;
          scan.disabled = false;
        }

      }, CONFIG.scanDelay);
    }


    fab.onclick = function () {

      if (fabMoved) {
        fabMoved = false;
        return;
      }

      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.`
  );

})();