/**
 * @file
 * Colorbox JS.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.initColorbox = {
    attach: function (context, settings) {
      if (!$.isFunction($.colorbox) || typeof settings.colorbox === 'undefined') {
        return;
      }

      if (settings.colorbox.mobiledetect && window.matchMedia) {
        // Disable Colorbox for small screens.
        var mq = window.matchMedia('(max-device-width: ' + settings.colorbox.mobiledevicewidth + ')');
        if (mq.matches) {
          $.colorbox.remove();
          return;
        }
      }

      settings.colorbox.rel = function () {
        return $(this).data('colorbox-gallery')
      };

      $('.colorbox', context)
        .once('init-colorbox').each(function() {
        // Only images are supported for the "colorbox" class.
        // The "photo" setting forces the href attribute to be treated as an image.
        var extendParams = {
          photo: true
        };
        // If a title attribute is supplied, sanitize it.
        var title = $(this).attr('title');
        if (title) {
          extendParams.title = Drupal.colorbox.sanitizeMarkup(title);
        }
        $(this).colorbox($.extend({}, settings.colorbox, extendParams));
      });

      $('.colorbox', context).colorbox({
        onComplete: function (e) {
          var focus = $('#cboxContent').find('#cboxPrevious').css('display') !== 'none' ? $('#cboxContent').find('#cboxPrevious') : $('#cboxContent').find('#cboxClose');
          focus.focus();

          $('#cboxContent').on('keydown', function (e) {
            var keyCode = e.keyCode || e.which;
            var firstElement = $('#cboxContent').find('#cboxPrevious').last().is(':focus');
            var lastElement = $('#cboxContent').find('#cboxClose').first().is(':focus');
            if (keyCode === 9 && !e.shiftKey && lastElement) {
              e.preventDefault();
              $('#cboxContent').find('#cboxPrevious').first().focus();
            }
            else if (keyCode === 9 && e.shiftKey && firstElement) {
              e.preventDefault();
              $('#cboxContent').find('#cboxClose').first().focus();
            }
          });
        }
      });
    }
  };

  // Create colorbox namespace if it doesn't exist.
  if (!Drupal.hasOwnProperty('colorbox')) {
    Drupal.colorbox = {};
  }

  /**
   * Global function to allow sanitizing captions and control strings.
   *
   * @param markup
   *   String containing potential markup.
   * @return @string
   *  Sanitized string with potentially dangerous markup removed.
   */
  Drupal.colorbox.sanitizeMarkup = function(markup) {
    // If DOMPurify installed, allow some HTML. Otherwise, treat as plain text.
    if (typeof DOMPurify !== 'undefined') {
      var purifyConfig = {
        ALLOWED_TAGS: [
          'a',
          'b',
          'strong',
          'i',
          'em',
          'u',
          'cite',
          'code',
          'br'
        ],
        ALLOWED_ATTR: [
          'href',
          'hreflang',
          'title',
          'target'
        ]
      }
      if (drupalSettings.hasOwnProperty('dompurify_custom_config')) {
        purifyConfig = drupalSettings.dompurify_custom_config;
      }
      return DOMPurify.sanitize(markup, purifyConfig);
    }
    else {
      return Drupal.checkPlain(markup);
    }
  }

})(jQuery, Drupal, drupalSettings);
