import { logger } from '@/utils/logger';

/**
 * Starts media playback without leaving the `play()` promise unhandled.
 *
 * `HTMLMediaElement.play()` resolves only once playback has actually begun. If
 * the element is paused — or given a new `src` — while that promise is still
 * pending, the browser rejects it with an `AbortError` (see
 * https://goo.gl/LdLk22). In the story reader that is routine: one shared audio
 * element serves the play/pause button, sentence clicks, paragraph navigation
 * and the progress slider, and on a slow connection the next click lands long
 * before the current clip has buffered. An interruption the user asked for is
 * not a failure, so the AbortError is swallowed.
 *
 * Anything else is reported. `NotAllowedError` in particular means autoplay was
 * blocked and the audio silently never played — that must stay visible.
 */
export function playMedia(element: HTMLMediaElement | null | undefined): void {
  if (!element) {
    return;
  }

  // Older Safari and jsdom return undefined rather than a promise.
  const playPromise = element.play() as Promise<void> | undefined;

  if (!playPromise || typeof playPromise.catch !== 'function') {
    return;
  }

  playPromise.catch((error: unknown) => {
    // Matched by name rather than by type: jsdom's DOMException is not an
    // Error, so an `instanceof` guard would report every interruption.
    if ((error as { name?: string } | null)?.name === 'AbortError') {
      return;
    }

    logger.error('Media playback failed:', error);
  });
}
