/**
 * Parse a streaming-platform page URL (YouTube, Vimeo, Dailymotion …) into a
 * player embed URL, applying the block's playback options as provider-specific
 * query params. Mirrors axcelersblocks_video_parse_embed() in PHP.
 *
 * Returns { provider, id, src } for a recognised platform, or null otherwise
 * (the caller then falls back to WordPress oEmbed on the front end).
 */

const YT_RE  = /(?:youtube\.com\/(?:watch\?(?:.*&)?v=|embed\/|shorts\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/i;
const VIM_RE = /vimeo\.com\/(?:video\/|channels\/[A-Za-z0-9]+\/|groups\/[A-Za-z0-9]+\/videos\/|album\/\d+\/video\/)?(\d+)/i;
const DM_RE  = /(?:dailymotion\.com\/(?:video|embed\/video)\/|dai\.ly\/)([A-Za-z0-9]+)/i;

const bool = ( v ) => ( v ? '1' : '0' );

export function buildEmbedSrc( url, opts = {} ) {
  if ( ! url || typeof url !== 'string' ) return null;
  const { autoplay = false, muted = false, loop = false, controls = true, playsInline = true } = opts;

  let m;

  // ── YouTube ────────────────────────────────────────────────────────────────
  if ( ( m = url.match( YT_RE ) ) ) {
    const id = m[ 1 ];
    const params = new URLSearchParams();
    params.set( 'rel', '0' );
    params.set( 'playsinline', bool( playsInline ) );
    if ( autoplay ) params.set( 'autoplay', '1' );
    if ( muted || autoplay ) params.set( 'mute', '1' );
    if ( ! controls ) params.set( 'controls', '0' );
    if ( loop ) { params.set( 'loop', '1' ); params.set( 'playlist', id ); } // loop needs playlist
    return { provider: 'youtube', id, src: `https://www.youtube.com/embed/${ id }?${ params.toString() }` };
  }

  // ── Vimeo ──────────────────────────────────────────────────────────────────
  if ( ( m = url.match( VIM_RE ) ) ) {
    const id = m[ 1 ];
    const params = new URLSearchParams();
    if ( autoplay ) params.set( 'autoplay', '1' );
    if ( muted || autoplay ) params.set( 'muted', '1' );
    if ( loop ) params.set( 'loop', '1' );
    if ( ! controls ) params.set( 'controls', '0' );
    params.set( 'playsinline', bool( playsInline ) );
    return { provider: 'vimeo', id, src: `https://player.vimeo.com/video/${ id }?${ params.toString() }` };
  }

  // ── Dailymotion ────────────────────────────────────────────────────────────
  if ( ( m = url.match( DM_RE ) ) ) {
    const id = m[ 1 ];
    const params = new URLSearchParams();
    if ( autoplay ) params.set( 'autoplay', '1' );
    if ( muted || autoplay ) params.set( 'mute', '1' );
    if ( ! controls ) params.set( 'controls', '0' );
    return { provider: 'dailymotion', id, src: `https://www.dailymotion.com/embed/video/${ id }?${ params.toString() }` };
  }

  return null;
}

export const EMBED_ALLOW = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share';
