// Absolutely-positioned highlight bar that follows the cursor/finger Y position.
// Respects prefers-reduced-motion: caller should not enable this automatically
// when the OS reduced-motion preference is active.
const HEIGHT = 56;
let guide: HTMLElement | null = null;
let handler: ((e: MouseEvent | TouchEvent) => void) | null = null;

export function toggle(on: boolean): void {
  if (on) {
    if (document.getElementById('accessmate-reading-guide')) return;
    guide = document.createElement('div');
    guide.id = 'accessmate-reading-guide';
    guide.style.cssText =
      'position:fixed;left:0;right:0;' +
      `height:${HEIGHT}px;` +
      'background:rgba(255,255,150,.38);' +
      'pointer-events:none;' +
      'z-index:2147483646;' +
      'top:-100px;';
    document.body.appendChild(guide);

    handler = (e: MouseEvent | TouchEvent) => {
      const y = 'touches' in e ? e.touches[0].clientY : (e as MouseEvent).clientY;
      if (guide) guide.style.top = `${y - HEIGHT / 2}px`;
    };
    document.addEventListener('mousemove', handler as EventListener, { passive: true });
    document.addEventListener('touchmove', handler as EventListener, { passive: true });
  } else {
    guide?.remove();
    guide = null;
    if (handler) {
      document.removeEventListener('mousemove', handler as EventListener);
      document.removeEventListener('touchmove', handler as EventListener);
      handler = null;
    }
  }
}
