// Full-viewport overlay with a 48px transparent slit that follows the cursor/finger.
const SLIT = 48;
const STYLE_BASE =
  'position:fixed;left:0;right:0;background:rgba(0,0,0,.82);pointer-events:none;z-index:2147483645;';

let top: HTMLElement | null = null;
let bot: HTMLElement | null = null;
let handler: ((e: MouseEvent | TouchEvent) => void) | null = null;

export function toggle(on: boolean): void {
  if (on) {
    if (document.getElementById('accessmate-mask-top')) return;
    top = document.createElement('div');
    top.id = 'accessmate-mask-top';
    top.style.cssText = STYLE_BASE + 'top:0;height:0';

    bot = document.createElement('div');
    bot.id = 'accessmate-mask-bot';
    bot.style.cssText = STYLE_BASE + 'bottom:0;height:0';

    document.body.appendChild(top);
    document.body.appendChild(bot);

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