(function ($) {
    'use strict';

    $(function () {
        var config = window.macaMenulistMenuPreview || {};
        var $datetime = $('#maca-menu-preview-datetime');
        var $website = $('#maca-menu-preview-website');
        var $qr = $('#maca-menu-preview-qr');
        var $label = $('#maca-menu-preview-active-label');
        var debounceTimer = null;
        var request = null;
        var $grid = $('#maca-menu-preview-grid');
        var previewMode = config.previewMode || 'files';

        if (!$datetime.length || !$website.length || !$qr.length) {
            return;
        }

        function initMenuFilters() {
            if (previewMode !== 'dishes') {
                return;
            }

            if (!window.MacaMenulistDishMenu || typeof window.MacaMenulistDishMenu.init !== 'function') {
                return;
            }

            var root = $grid.length ? $grid.get(0) : document;
            window.MacaMenulistDishMenu.init(root);
        }

        function setLoading(isLoading) {
            $website.toggleClass('is-loading', isLoading);
            $qr.toggleClass('is-loading', isLoading);
        }

        function formatActiveLabel(formatted) {
            if (!formatted || !config.activeLabel) {
                return '';
            }

            return config.activeLabel.replace('%s', formatted);
        }

        function escapeHtml(text) {
            return $('<div>').text(text || '').html();
        }

        function renderDiagnostics(diagnostics) {
            var $details = $('#maca-menu-preview-diagnostics');
            var $body = $('#maca-menu-preview-diagnostics-body');
            var $note = $details.find('.maca-menu-preview-diagnostics-note');

            if (!$details.length || !$body.length || !diagnostics || !diagnostics.categories) {
                return;
            }

            if (diagnostics.exclusive_campaign_mode && diagnostics.campaigns_active) {
                if (!$note.length) {
                    $note = $('<p>', {
                        'class': 'description maca-menu-preview-diagnostics-note',
                        text: config.exclusiveCampaignNote || ''
                    });
                    $details.children('summary').after($note);
                }
                $note.show();
            } else if ($note.length) {
                $note.hide();
            }

            $body.empty();

            diagnostics.categories.forEach(function (row) {
                var websiteMenu = row.website_menu
                    ? '<br><span class="maca-menu-preview-menu-ref">' + escapeHtml(row.website_menu) + '</span>'
                    : '';
                var qrMenu = row.qr_menu
                    ? '<br><span class="maca-menu-preview-menu-ref">' + escapeHtml(row.qr_menu) + '</span>'
                    : '';

                var $tr = $('<tr>');
                $tr.append($('<td>').text(row.name || ''));
                $tr.append(
                    $('<td>').html(
                        '<span class="maca-menu-preview-status maca-menu-preview-status--' + escapeHtml(row.website || '') + '">'
                        + escapeHtml(row.website_label || '')
                        + '</span>'
                        + websiteMenu
                    )
                );
                $tr.append(
                    $('<td>').html(
                        '<span class="maca-menu-preview-status maca-menu-preview-status--' + escapeHtml(row.qr || '') + '">'
                        + escapeHtml(row.qr_label || '')
                        + '</span>'
                        + qrMenu
                    )
                );
                $body.append($tr);
            });
        }

        function updatePreview(options) {
            options = options || {};
            var datetime = $datetime.val();

            if (!options.useNow && !datetime) {
                return;
            }

            if (!config.ajaxUrl) {
                return;
            }

            if (request && request.abort) {
                request.abort();
            }

            setLoading(true);

            request = $.post(config.ajaxUrl, {
                action: 'maca_menu_schedule_preview',
                nonce: config.nonce,
                datetime: datetime,
                use_now: options.useNow ? '1' : '0'
            })
                .done(function (response) {
                    if (!response || !response.success || !response.data) {
                        window.alert(config.error || 'Could not load preview.');
                        return;
                    }

                    if (response.data.preview_mode) {
                        previewMode = response.data.preview_mode;
                    }

                    $website.html(response.data.website || '');
                    $qr.html(response.data.qr || '');

                    if (response.data.datetime_local) {
                        $datetime.val(response.data.datetime_local);
                    }

                    if (response.data.label) {
                        $label.text(formatActiveLabel(response.data.label));
                    }

                    if (response.data.diagnostics) {
                        renderDiagnostics(response.data.diagnostics);
                    }

                    initMenuFilters();
                })
                .fail(function () {
                    window.alert(config.error || 'Could not load preview.');
                })
                .always(function () {
                    setLoading(false);
                    request = null;
                });
        }

        function scheduleUpdate() {
            window.clearTimeout(debounceTimer);
            debounceTimer = window.setTimeout(function () {
                updatePreview();
            }, 400);
        }

        $('#maca-menu-preview-update').on('click', function (event) {
            event.preventDefault();
            updatePreview();
        });

        $('#maca-menu-preview-now').on('click', function (event) {
            event.preventDefault();
            updatePreview({ useNow: true });
        });

        $datetime.on('change input', scheduleUpdate);

        initMenuFilters();
    });
}(jQuery));
