/* Receiver for "Radio Player" using CAF Receiver SDK */
(function () {
  const STREAM_URL = 'https://live.radio1.si/Radio1MB';

  function $(id) { return document.getElementById(id); }

  document.addEventListener('DOMContentLoaded', () => {
    const context = cast.framework.CastReceiverContext.getInstance();
    const playerManager = context.getPlayerManager();
    const statusEl = $('status');
    const stationEl = $('station');

    // Intercept LOAD to enforce correct metadata for LIVE audio
    playerManager.setMessageInterceptor(
      cast.framework.messages.MessageType.LOAD,
      (request) => {
        if (!request || !request.media) return request;

        request.media.contentId = request.media.contentId || STREAM_URL;
        request.media.contentType = 'audio/mpeg';
        request.media.streamType = cast.framework.messages.StreamType.LIVE;

        request.media.metadata = request.media.metadata || {};
        request.media.metadata.title = request.media.metadata.title || 'Radio 1';
        request.media.metadata.images = request.media.metadata.images || [{ url: 'assets/logo.svg' }];

        return request;
      }
    );

    // Update UI on player state changes
    playerManager.addEventListener(
      cast.framework.events.EventType.PLAYER_STATE_CHANGED,
      () => {
        const state = playerManager.getPlayerState();
        switch (state) {
          case cast.framework.messages.PlayerState.PLAYING:
            statusEl.textContent = 'Playing';
            break;
          case cast.framework.messages.PlayerState.PAUSED:
            statusEl.textContent = 'Paused';
            break;
          case cast.framework.messages.PlayerState.IDLE:
            statusEl.textContent = 'Stopped';
            break;
          default:
            statusEl.textContent = state;
        }
      }
    );

    // When a new media is loaded, reflect metadata (station name, artwork)
    playerManager.addEventListener(cast.framework.events.EventType.LOAD, (event) => {
      const media = event && event.data && event.data.media;
      if (media && media.metadata) {
        if (media.metadata.title) stationEl.textContent = media.metadata.title;
        if (media.metadata.images && media.metadata.images[0] && media.metadata.images[0].url) {
          const img = document.querySelector('#artwork img');
          img.src = media.metadata.images[0].url;
        }
      }
    });

    // Optional: reflect volume in title attribute
    playerManager.addEventListener(cast.framework.events.EventType.VOLUME_CHANGED, (evt) => {
      const level = evt && evt.data && typeof evt.data.level === 'number' ? evt.data.level : null;
      if (level !== null) statusEl.title = `Volume: ${Math.round(level * 100)}%`;
    });

    // Start the cast receiver context
    context.start({ statusText: 'Radio Player Ready' });
  });
})();
