/**
 * LANE-UI — THE SCREEN click-to-enlarge (order 8). The sky is the score; let people look.
 *
 * Clicking THE SCREEN toggles a centered ~2.5× view over a dimmed backdrop. Esc or a
 * click closes it.
 *
 * We enlarge the real `#screen` element with inline styles rather than mirroring it into
 * our own canvas: THE SCREEN is a WebGL canvas, and `drawImage` from a WebGL context
 * without `preserveDrawingBuffer` returns black (verified — the mirror rendered empty).
 * Asking LANE-SCREEN to enable that flag would cost them a frame buffer copy every frame
 * for a feature used occasionally, so the transform is both cheaper and what the order
 * specified.
 *
 * Touching another lane's element is done carefully: we snapshot its `style` attribute on
 * open and restore it verbatim on close, so THE SCREEN's own positioning stays SCREEN's
 * to change.
 */
import { cls, el } from './dom';

export interface ScreenView {
  /** The dimming backdrop, mounted in #ui. */
  el: HTMLElement;
  toggle(): void;
  close(): void;
  isOpen(): boolean;
}

/** Inline styles applied to #screen while enlarged. z-index clears the backdrop (40). */
const ENLARGED = [
  'position:fixed',
  'top:50%',
  'left:50%',
  'transform:translate(-50%,-50%)',
  'width:min(800px, calc(100vw - 80px))',
  'height:auto',
  'z-index:41',
  'cursor:zoom-out',
  'image-rendering:pixelated', // it's a dying video file — let the blocks show
].join(';');

export function createScreenView(source: HTMLElement | null): ScreenView {
  const backdrop = el('div');
  backdrop.id = 'fk-screenview';

  let open = false;
  /** The element's own style attribute before we touched it. */
  let savedStyle: string | null = null;

  function apply() {
    if (!source) return;
    savedStyle = source.getAttribute('style');
    source.setAttribute('style', `${savedStyle ? savedStyle + ';' : ''}${ENLARGED}`);
  }

  function restore() {
    if (!source) return;
    if (savedStyle === null) source.removeAttribute('style');
    else source.setAttribute('style', savedStyle);
    savedStyle = null;
  }

  function close() {
    if (!open) return;
    open = false;
    cls(backdrop, 'is-open', false);
    restore();
  }

  function toggle() {
    if (open) return close();
    open = true;
    cls(backdrop, 'is-open', true);
    apply();
  }

  // A click on the dimmed backdrop closes. So does a click on the enlarged SCREEN, which
  // sits above the backdrop — that's the same toggle listener below.
  backdrop.addEventListener('pointerdown', close);
  source?.addEventListener('pointerdown', toggle);

  return { el: backdrop, toggle, close, isOpen: () => open };
}
