/**
 * MediaTasker — Dialog Utility
 *
 * Global dialog/confirmation system used across all frontend modules.
 *
 * @package MediaTasker
 */

/* global jQuery */

(function ($) {
    'use strict';

    window.MEDIAT_Dialog = {
        show: function (options) {
            var defaults = {
                title: 'Alert',
                message: '',
                type: 'alert', // 'alert' or 'confirm'
                confirmText: 'OK',
                cancelText: 'Cancel',
                confirmClass: 'mediat_btn-primary',
                onConfirm: function () { },
                onCancel: function () { }
            };
            var settings = $.extend({}, defaults, options);

            var $dialog = $('.mediat_custom-dialog');
            var $title = $dialog.find('.mediat_custom-dialog-title');
            var $message = $dialog.find('.mediat_custom-dialog-message');
            var $btnConfirm = $dialog.find('.mediat_custom-dialog-confirm');
            var $btnCancel = $dialog.find('.mediat_custom-dialog-cancel');
            var $overlay = $('.mediat_overlay-backdrop');

            if (!$dialog.length) return; // Fail gracefully if shortcode isn't rendered

            $title.text(settings.title);
            $message.html(settings.message);

            $btnConfirm.text(settings.confirmText)
                .removeClass('mediat_btn-primary mediat_btn-danger mediat_btn-secondary')
                .addClass(settings.confirmClass);

            $btnCancel.text(settings.cancelText);

            if (settings.type === 'confirm') {
                $btnCancel.show();
            } else {
                $btnCancel.hide();
            }

            // Cleanup old events
            $btnConfirm.off('click');
            $btnCancel.off('click');

            $btnConfirm.on('click', function () {
                settings.onConfirm();
                closeDialog();
            });

            $btnCancel.on('click', function () {
                settings.onCancel();
                closeDialog();
            });

            function closeDialog() {
                $dialog.prop('open', false);
                $overlay.removeClass('is-active');
            }

            $overlay.addClass('is-active');
            $dialog.prop('open', true);
        }
    };
})(jQuery);
