/**
 * Moves keyboard focus out of the parent page button and into the embedded `play.html` iframe.
 */
export function focusIframeContents(
  iframe: HTMLIFrameElement,
  triggerButton?: HTMLButtonElement | null
): void {
  triggerButton?.blur();
  iframe.focus();
  try {
    iframe.contentWindow?.focus();
    const innerDoc = iframe.contentDocument;
    if (innerDoc) {
      const introDialog = innerDoc.getElementById(
        'GTAIntroDialog'
      ) as HTMLDialogElement | null;
      const playButton = innerDoc.getElementById(
        'GTAIntroPlayButton'
      ) as HTMLButtonElement | null;
      if (
        introDialog &&
        (introDialog.open || introDialog.hasAttribute('open')) &&
        playButton &&
        !playButton.hidden &&
        !playButton.disabled
      ) {
        playButton.focus();
        return;
      }
      if (innerDoc.body) {
        if (!innerDoc.body.hasAttribute('tabindex')) {
          innerDoc.body.setAttribute('tabindex', '-1');
        }
        innerDoc.body.focus({ preventScroll: true });
      }
    }
  } catch {
    // Ignore cross-origin frame access errors if any
  }
}

/**
 * Attaches fullscreen toggle behavior to the embedded `play.html` iframe on `index.html`.
 */
export function initDemoFullscreenButton(): void {
  const fullscreenBtn = document.getElementById(
    'GTAFullscreenButton'
  ) as HTMLButtonElement | null;
  const iframe = document.getElementById(
    'GTADemoIframe'
  ) as HTMLIFrameElement | null;

  if (!fullscreenBtn || !iframe) return;

  fullscreenBtn.addEventListener('click', () => {
    if (document.fullscreenElement) {
      void document.exitFullscreen?.();
      return;
    }

    focusIframeContents(iframe, fullscreenBtn);

    if (typeof iframe.requestFullscreen === 'function') {
      void iframe
        .requestFullscreen()
        .then(() => {
          focusIframeContents(iframe, fullscreenBtn);
          if (
            typeof window !== 'undefined' &&
            typeof window.requestAnimationFrame === 'function'
          ) {
            window.requestAnimationFrame(() => {
              focusIframeContents(iframe, fullscreenBtn);
            });
          }
        })
        .catch(() => {
          focusIframeContents(iframe, fullscreenBtn);
        });
    }
  });

  document.addEventListener('fullscreenchange', () => {
    if (document.fullscreenElement === iframe) {
      focusIframeContents(iframe, fullscreenBtn);
    }
  });
}

if (typeof document !== 'undefined') {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDemoFullscreenButton);
  } else {
    initDemoFullscreenButton();
  }
}
