jQuery(document).ready(function($){
  $(document).on('click', '.sifency-video-button', function(e){
    e.preventDefault();
    e.stopImmediatePropagation();

    var $wrapper = $(this).closest('.sifency-video-wrapper');
    var $modal   = $wrapper.find('.sifency-video-modal');
    var $content = $modal.find('.sifency-video-modal-content');

    var type = $wrapper.data('video-type');
    var url  = $wrapper.data('video-url');
    var mute = $wrapper.data('mute');

    if(!url) return;

    var embed = '';
    if(type === 'youtube' || type === 'vimeo'){
      var sep = url.includes('?') ? '&' : '?';
      url += sep + 'autoplay=1';
      if(mute === 'yes'){ url += '&mute=1'; }
      embed = '<iframe src="'+url+'" allow="autoplay; fullscreen" allowfullscreen style="width:100%; height:100%; border:none;"></iframe>';
    } else if(type === 'self_hosted'){
      embed = '<video controls autoplay '+(mute==='yes'?'muted':'')+' style="width:100%; height:100%;">';
      embed += '<source src="'+url+'" type="video/mp4">';
      embed += '</video>';
    }

    $modal.appendTo('body');
    $content.html(embed);
    $modal.addClass('is-active').css('display','flex');
    $('body').addClass('sifency-modal-open');
  });

  $(document).on('click', '.sifency-video-modal-close, .sifency-modal-overlay', function(){
    closeVideoModal();
  });

  $(document).on('keyup', function(e){
    if(e.key === 'Escape'){
      var $modal = $('.sifency-video-modal.is-active');
      if($modal.length){ closeVideoModal(); }
    }
  });

  function closeVideoModal(){
    var $modal   = $('.sifency-video-modal.is-active');
    var $content = $modal.find('.sifency-video-modal-content');
    var $wrapper = $('.sifency-video-wrapper');

    $modal.removeClass('is-active');
    $('body').removeClass('sifency-modal-open');

    setTimeout(function(){
      $modal.css('display','none');
      $content.empty();
      if($wrapper.length){ $modal.appendTo($wrapper); }
    },300);
  }
});
