(function ($) {
    'use strict';

    var cfg = window.macaMenulistPaymentsPosWarning || {};
    var pendingCheckbox = null;

    function $master() {
        return $('input[name="maca_menulist_payments_use_online"]');
    }

    function $modal() {
        return $('#maca-pos-warning-modal');
    }

    function scrollAtBottom($scroll) {
        var el = $scroll[0];
        if (!el) {
            return true;
        }
        return el.scrollHeight - el.scrollTop <= el.clientHeight + 12;
    }

    function updateAckState() {
        var $scroll = $('#maca-pos-warning-scroll');
        var $ack = $('#maca-pos-warning-ack');
        var $continue = $('#maca-pos-warning-continue');
        var $hint = $('#maca-pos-warning-scroll-hint');
        var atBottom = scrollAtBottom($scroll);

        if (atBottom) {
            $ack.prop('disabled', false);
            $hint.attr('hidden', 'hidden');
        } else {
            $ack.prop('checked', false).prop('disabled', true);
            $continue.prop('disabled', true);
            $hint.removeAttr('hidden');
        }
    }

    function buildBodyHtml() {
        var parts = [
            '<p>' + (cfg.intro || '') + '</p>',
            '<p>' + (cfg.notPos || '') + '</p>',
            '<p>' + (cfg.doNotEnable || '') + '</p>',
            '<p>' + (cfg.yourResponsibility || '') + '</p>',
            '<p>' + (cfg.receipts || '') + '</p>'
        ];

        if (cfg.swedenExtra) {
            parts.push('<p>' + cfg.swedenExtra + '</p>');
        }

        if (cfg.guideUrl && cfg.guideLinkText) {
            parts.push(
                '<p><a href="' + cfg.guideUrl + '" target="_blank" rel="noopener noreferrer">' +
                    cfg.guideLinkText +
                    '</a></p>'
            );
        }

        return parts.join('');
    }

    function openModal() {
        if (!$modal().length) {
            return;
        }

        $('#maca-pos-warning-title').text(cfg.title || '');
        $('#maca-pos-warning-body').html(buildBodyHtml());
        $('#maca-pos-warning-ack-label').text(cfg.ackLabel || '');
        $('#maca-pos-warning-scroll-hint').text(cfg.scrollHint || '');
        $('#maca-pos-warning-cancel').text(cfg.cancel || 'Cancel');
        $('#maca-pos-warning-continue').text(cfg.continue || 'Continue').prop('disabled', true);
        $('#maca-pos-warning-ack').prop('checked', false).prop('disabled', true);

        $modal().removeAttr('hidden').attr('aria-hidden', 'false');
        $('body').addClass('maca-pos-warning-modal-open');

        var $scroll = $('#maca-pos-warning-scroll');
        $scroll.scrollTop(0);
        window.setTimeout(updateAckState, 0);
        window.setTimeout(updateAckState, 50);
        $('#maca-pos-warning-cancel').trigger('focus');
    }

    function closeModal() {
        $modal().attr('hidden', 'hidden').attr('aria-hidden', 'true');
        $('body').removeClass('maca-pos-warning-modal-open');
        pendingCheckbox = null;
    }

    function applyOnlineDefaults() {
        $('input[name="maca_menulist_payments_enabled"]').prop('checked', true);
        $('input[name="maca_menulist_payments_allow_online"]').prop('checked', true);
    }

    function confirmPending() {
        $('#maca_online_payment_pos_ack').val('1');

        if (pendingCheckbox) {
            pendingCheckbox.prop('checked', true).data('maca-pos-user-confirmed', true);
            applyOnlineDefaults();
            pendingCheckbox = null;
        }

        syncOnlineSections();
        closeModal();
    }

    function syncOnlineSections() {
        var on = $master().is(':checked');

        $('.maca-payments-online-options').prop('hidden', !on);
        $('.maca-payments-online-tips-options').prop('hidden', !on);
        $('.maca-payments-provider-cards').prop('hidden', !on);
        $('.maca-payments-online-disabled-notice').prop('hidden', on);

        $('.maca-payments-online-input').prop('disabled', !on);

        $('.maca-payments-tabs .nav-tab[data-payments-tab="tips"], .maca-payments-tabs .nav-tab[data-payments-tab="providers"]')
            .toggleClass('maca-payments-tab--requires-online', !on);
    }

    function requestAckForMaster($input) {
        if ($input.prop('disabled') || $input.data('maca-pos-user-confirmed')) {
            return;
        }

        pendingCheckbox = $input;
        openModal();
    }

    $(function () {
        if (!$('.maca-payments-settings-form').length || !$master().length) {
            return;
        }

        if (!cfg.title && !cfg.intro) {
            return;
        }

        syncOnlineSections();

        $(document).on('change', 'input[name="maca_menulist_payments_use_online"]', function () {
            var $input = $(this);
            if ($input.prop('disabled')) {
                return;
            }

            if (!$input.is(':checked')) {
                $input.removeData('maca-pos-user-confirmed');
                $('#maca_online_payment_pos_ack').val('0');
                syncOnlineSections();
                return;
            }

            if ($input.data('maca-pos-user-confirmed')) {
                syncOnlineSections();
                return;
            }

            $input.prop('checked', false);
            requestAckForMaster($input);
        });

        $('#maca-pos-warning-scroll').on('scroll', updateAckState);

        $('#maca-pos-warning-ack').on('change', function () {
            $('#maca-pos-warning-continue').prop('disabled', !$(this).is(':checked'));
        });

        $('#maca-pos-warning-continue').on('click', function () {
            if (!$('#maca-pos-warning-ack').is(':checked') || $('#maca-pos-warning-ack').prop('disabled')) {
                return;
            }
            confirmPending();
        });

        $modal().on('click', '[data-maca-pos-warning-close]', function () {
            closeModal();
        });

        $(document).on('keydown', function (event) {
            if (event.key === 'Escape' && !$modal().is('[hidden]')) {
                closeModal();
            }
        });
    });
})(jQuery);
