// auxmeter.js — AUX Service Cursor Sweep Theatre (Fire-and-Forget Mode)

const BASE_STEP_MS = 8;
const TRIGGER_HOLD_MS = 200;

const TRIGGER_MARKERS = [
  'TASK:', 'Task:', 'task:',
  'AUXCALL@', 'AUXMAP@', 'AUXFIND@', 'AUXSEARCH@',
  'Recording Sheet', 'recording sheet', 'RECORDING SHEET'
];

let cursor = null;
let trail = null;
let timer = null;
let triggerTimer = null;
let chars = [];
let idx = 0;
let triggerAt = -1;
let trailX = 0;
let lastY = -9999;
let runId = 0;

// SECTION: Dynamic DOM Styles & Skin Configurations

function init() {
  if (document.getElementById('aux-meter-cursor')) {
    cursor = document.getElementById('aux-meter-cursor');
    trail = document.getElementById('aux-meter-trail');
    return;
  }

  const style = document.createElement('style');
  style.id = 'aux-meter-styles';
  style.textContent = `
    #aux-meter-cursor {
      position: fixed;
      top: 0;
      left: 0;
      width: 42px;
      height: 34px;
      pointer-events: none;
      z-index: 2147483646;
      will-change: transform, opacity;
      display: grid;
      grid-template-columns: repeat(2, 13px);
      grid-template-rows: repeat(4, 5px);
      gap: 4px 5px;
      align-items: end;
      justify-content: center;
      opacity: .72;
      filter: drop-shadow(0 0 12px rgba(181, 120, 255, .77));
      transition: opacity .22s ease, filter .22s ease;
    }

    #aux-meter-cursor i {
      display: block;
      width: 13px;
      height: 5px;
      border-radius: 1px;
      opacity: .88;
      background: rgba(117, 59, 171, .74);
      box-shadow: 0 0 5px rgba(181, 120, 255, .64);
    }

    #aux-meter-cursor i:nth-child(1) { grid-column: 1; grid-row: 4; background: rgba(63, 31, 112, .80); }
    #aux-meter-cursor i:nth-child(2) { grid-column: 2; grid-row: 4; background: rgba(82, 37, 125, .76); }
    #aux-meter-cursor i:nth-child(3) { grid-column: 1; grid-row: 3; background: rgba(150, 93, 207, .78); }
    #aux-meter-cursor i:nth-child(4) { grid-column: 2; grid-row: 3; background: rgba(70, 25, 92, .78); }
    #aux-meter-cursor i:nth-child(5) { grid-column: 1; grid-row: 2; background: rgba(226, 210, 255, .76); }
    #aux-meter-cursor i:nth-child(6) { grid-column: 2; grid-row: 2; background: rgba(150, 93, 207, .72); }
    #aux-meter-cursor i:nth-child(7) { grid-column: 2; grid-row: 1; background: rgba(232, 218, 255, .82); }

    #aux-meter-cursor.reading {
      opacity: .92;
      filter: drop-shadow(0 0 14px rgba(190, 130, 255, .82));
    }

    #aux-meter-cursor.trigger {
      opacity: .98;
      filter: drop-shadow(0 0 16px rgba(255, 75, 215, .92));
    }

    #aux-meter-cursor.trigger i:nth-child(7) { background: rgba(255, 35, 208, .92); box-shadow: 0 0 10px rgba(255, 75, 220, .88); }
    #aux-meter-cursor.trigger i:nth-child(6) { background: rgba(202, 39, 181, .78); box-shadow: 0 0 8px rgba(255, 75, 220, .66); }

    #aux-meter-trail {
      position: fixed;
      top: 0;
      left: 0;
      height: 1.4em;
      pointer-events: none;
      z-index: 2147483645;
      will-change: transform, width, opacity;
      background: linear-gradient(90deg, transparent, rgba(101, 55, 180, .48) 65%, rgba(115, 70, 200, .47));
      border-bottom: 1px solid rgba(120, 75, 210, .41);
      opacity: .08;
    }

    /* Studio Mode Overrides — Auburn Gold Brown & Yellow Telemetry Theme */
    body[data-skin="studio"] #aux-meter-cursor {
      filter: drop-shadow(0 0 12px rgba(235, 160, 40, .75));
    }
    body[data-skin="studio"] #aux-meter-cursor i {
      background: rgba(160, 95, 30, .75);
      box-shadow: 0 0 5px rgba(220, 145, 35, .60);
    }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(1) { background: rgba(90, 50, 15, .85); }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(2) { background: rgba(110, 60, 20, .80); }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(3) { background: rgba(175, 110, 35, .80); }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(4) { background: rgba(130, 75, 25, .80); }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(5) { background: rgba(250, 215, 115, .80); }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(6) { background: rgba(205, 135, 40, .75); }
    body[data-skin="studio"] #aux-meter-cursor i:nth-child(7) { background: rgba(255, 230, 140, .85); }

    body[data-skin="studio"] #aux-meter-cursor.trigger {
      filter: drop-shadow(0 0 16px rgba(255, 210, 0, .95));
    }
    body[data-skin="studio"] #aux-meter-cursor.trigger i:nth-child(7) { background: rgba(255, 220, 0, .95); box-shadow: 0 0 10px rgba(255, 210, 0, .90); }
    body[data-skin="studio"] #aux-meter-cursor.trigger i:nth-child(6) { background: rgba(230, 150, 10, .85); box-shadow: 0 0 8px rgba(255, 190, 0, .70); }

    body[data-skin="studio"] #aux-meter-trail {
      background: linear-gradient(90deg, transparent, rgba(160, 95, 30, .40) 65%, rgba(205, 135, 40, .45));
      border-bottom: 1px solid rgba(175, 110, 35, .35);
    }
  `;
  document.head.appendChild(style);

  cursor = document.createElement('div');
  cursor.id = 'aux-meter-cursor';
  cursor.className = 'idle';
  cursor.innerHTML = '<i></i><i></i><i></i><i></i><i></i><i></i><i></i>';
  document.body.appendChild(cursor);

  trail = document.createElement('div');
  trail.id = 'aux-meter-trail';
  document.body.appendChild(trail);
}

// SECTION: Layout Element Scraping

function findTarget() {
  return document.body;
}
function buildChars(rootEl) {
  const out = [];
  const range = document.createRange();
  const walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT, {
    acceptNode(node) {
      const parent = node.parentElement;
      if (!parent) return NodeFilter.FILTER_REJECT;
      if (parent.closest('script, style, noscript, textarea, input, select, option, #aux-meter-cursor, #aux-meter-trail')) {
        return NodeFilter.FILTER_REJECT;
      }
      return String(node.textContent || '').trim()
        ? NodeFilter.FILTER_ACCEPT
        : NodeFilter.FILTER_REJECT;
    }
  });

  while (walker.nextNode()) {
    const node = walker.currentNode;
    const text = String(node.textContent || '');

    for (let i = 0; i < text.length; i++) {
      if (/\s/.test(text[i])) continue;
      try {
        range.setStart(node, i);
        range.setEnd(node, i + 1);
        const r = range.getBoundingClientRect();
        if (
          r.width > 0 &&
          r.height > 0 &&
          r.bottom >= 0 &&
          r.top <= window.innerHeight &&
          r.right >= 0 &&
          r.left <= window.innerWidth
        ) {
          out.push({ x: r.left, y: r.top, h: r.height, ch: text[i] });
        }
      } catch {}
    }
  }

  out.sort((a, b) => Math.abs(a.y - b.y) > 4 ? a.y - b.y : a.x - b.x);
  return out;
}
function place(pos) {
  if (!pos || !cursor || !trail) return;
  const x = Math.max(8, Math.min(window.innerWidth - 56, pos.x));
  const y = Math.max(8, Math.min(window.innerHeight - 42, pos.y));
  const h = Math.max(8, Math.min(pos.h || 18, window.innerHeight - y));

  if (Math.abs(y - lastY) > h * 0.5) trailX = x;
  lastY = y;
  
  cursor.style.transform = `translate(${x}px, ${y}px)`;
  trail.style.transform = `translate(${trailX}px, ${y}px)`;
  trail.style.width = `${Math.max(2, x - trailX)}px`;
  trail.style.height = `${h}px`;
}

function flashTrigger() {
  clearTimeout(triggerTimer);
  cursor.classList.remove('idle', 'reading');
  cursor.classList.add('trigger');
  trail.style.opacity = '.38';

  triggerTimer = setTimeout(() => {
    if (cursor?.classList.contains('trigger')) {
      cursor.classList.replace('trigger', 'reading');
      trail.style.opacity = '.28';
    }
  }, TRIGGER_HOLD_MS);
}

function step(localRunId) {
  if (localRunId !== runId || idx >= chars.length) {
    stop();
    return;
  }

  const pos = chars[idx];
  place(pos);

  if (triggerAt >= 0 && idx >= triggerAt) {
    triggerAt = -1;
    flashTrigger();
  }

  idx += Math.max(3, Math.floor(Math.random() * 10));
  timer = setTimeout(() => step(localRunId), BASE_STEP_MS);
}

// SECTION: Direct Activation Entry (No Gating / No Callbacks)

export function executeFireAndForgetScan(text = '') {
  clearTimeout(timer);
  init();

  const localRunId = ++runId;
  const target = findTarget();
  const raw = String(text || '');

  chars = buildChars(target);
  
  let best = -1;
  TRIGGER_MARKERS.forEach(m => {
    const i = raw.indexOf(m);
    if (i >= 0 && (best < 0 || i < best)) best = i;
  });
  triggerAt = best;

  idx = 0;
  trailX = chars[0]?.x || 0;
  lastY = -9999;

  cursor.classList.remove('idle', 'trigger');
  cursor.classList.add('reading');
  trail.style.opacity = '.28';

  step(localRunId);
}

export function stop() {
  clearTimeout(timer);
  clearTimeout(triggerTimer);
  runId++;

  if (cursor) {
    cursor.remove();
    cursor = null;
  }

  if (trail) {
    trail.remove();
    trail = null;
  }
}