'use client';

import { useEffect } from 'react';
import type { PlayerControls } from '../types';
import type { PlayerMeta } from '../context/MetaContext';

const ACTIONS: MediaSessionAction[] = [
  'play',
  'pause',
  'previoustrack',
  'nexttrack',
  'seekbackward',
  'seekforward',
];

export function useMediaSession(
  audio: HTMLAudioElement,
  meta: PlayerMeta,
  controls: PlayerControls,
  onPrev?: () => void,
  onNext?: () => void,
): void {
  useEffect(() => {
    if (typeof navigator === 'undefined' || !('mediaSession' in navigator)) return;
    const ms = navigator.mediaSession;
    try {
      ms.metadata = new MediaMetadata({
        title: meta.title ?? '',
        artist: meta.artist ?? '',
        album: meta.album ?? '',
        artwork: meta.cover
          ? [{ src: meta.cover, sizes: '512x512', type: 'image/jpeg' }]
          : [],
      });
    } catch {
      // ignore
    }

    const handlers: Partial<Record<MediaSessionAction, MediaSessionActionHandler | null>> = {
      play: () => {
        void controls.play();
      },
      pause: () => controls.pause(),
      previoustrack: onPrev ?? null,
      nexttrack: onNext ?? null,
      seekbackward: (details) => {
        const offset = details.seekOffset ?? 10;
        controls.seek(audio.currentTime - offset);
      },
      seekforward: (details) => {
        const offset = details.seekOffset ?? 10;
        controls.seek(audio.currentTime + offset);
      },
    };

    for (const a of ACTIONS) {
      try {
        ms.setActionHandler(a, handlers[a] ?? null);
      } catch {
        // ignore unsupported actions
      }
    }

    return () => {
      for (const a of ACTIONS) {
        try {
          ms.setActionHandler(a, null);
        } catch {
          // ignore
        }
      }
    };
  }, [audio, controls, meta.title, meta.artist, meta.album, meta.cover, onPrev, onNext]);
}
