(function (window, $) {
    'use strict';

    var nsVars = window.noesia_admin_vars || {};
    var ajaxUrl = String(nsVars.ajax_url || '');
    var nonce = String(nsVars.nonce || '');
    var i18n = (nsVars.i18n && typeof nsVars.i18n === 'object') ? nsVars.i18n : {};
    var modules = window.noesiaSwaAdminModules || (window.noesiaSwaAdminModules = {});
    var state = {
        booted: false,
        poller: null,
        namespace: '.noesiaSwaDesign'
    };

    function escHtml(text) {
        return String(text == null ? '' : text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function getDesignRoot() {
        return $('.noesia-swa-design-module').first();
    }

    var restoreDefaults = {
        icon_menu: '📜',
        btn_menu: 'View Our Menu',
        icon_order: '🍽️',
        btn_order: 'New Order',
        icon_waiter: '🙋',
        btn_waiter: 'Call Waiter',
        icon_bill: '💳',
        btn_bill: 'Bill Please',
        cst1_icon: '💧',
        cst1_label: 'Urgent',
        cst2_icon: '✨',
        cst2_label: 'Pool pls',
        rate_label: 'Rate Us on Google'
    };

    function restoreTextsAndIcons() {
        var confirmed = window.confirm(String(i18n.design_restore_confirm || 'Restore the original texts and icons?'));
        var fieldMap;

        if (!confirmed) {
            return;
        }

        fieldMap = {
            btn_menu: '#noesia-swa-btn-menu',
            icon_menu: '#noesia-swa-icon-menu',
            btn_order: '#noesia-swa-btn-order',
            icon_order: '#noesia-swa-icon-order',
            btn_waiter: '#noesia-swa-btn-waiter',
            icon_waiter: '#noesia-swa-icon-waiter',
            btn_bill: '#noesia-swa-btn-bill',
            icon_bill: '#noesia-swa-icon-bill',
            cst1_label: '#noesia-swa-cst1-label',
            cst1_icon: '#noesia-swa-cst1-icon',
            cst2_label: '#noesia-swa-cst2-label',
            cst2_icon: '#noesia-swa-cst2-icon',
            rate_label: '#noesia-swa-rate-label'
        };

        Object.keys(fieldMap).forEach(function (key) {
            var selector = fieldMap[key];
            var $field = $(selector);

            if ($field.length && Object.prototype.hasOwnProperty.call(restoreDefaults, key)) {
                $field.val(restoreDefaults[key]).trigger('change');
            }
        });
    }


    function requestStrings() {
        var $root = getDesignRoot();
        return {
            empty: String($root.attr('data-noesia-swa-request-empty-text') || i18n.active_requests_empty || 'No active requests right now.'),
            item: String($root.attr('data-noesia-swa-request-label') || 'Request'),
            many: String($root.attr('data-noesia-swa-request-label-many') || i18n.badge_requests_label || 'Active Requests'),
            one: String($root.attr('data-noesia-swa-request-label-one') || i18n.badge_request_singular || 'Active Request')
        };
    }

    function updateRequestPill(count) {
        var n = parseInt(count || 0, 10);
        var strings = requestStrings();
        var $wrapper = $('#noesia-swa-wrapper');
        var $pill = $('#noesia-swa-active-requests-pill');
        var text = '';

        if (isNaN(n) || n < 0) {
            n = 0;
        }

        $wrapper.attr('data-noesia-swa-active-count', String(n));
        $wrapper.attr('data-noesia-swa-active-requests-count', String(n));

        if (!$pill.length) {
            return;
        }

        if (n <= 0) {
            text = String(i18n.no_active_requests || 'No active requests');
        } else if (n === 1) {
            text = '1 ' + strings.one;
        } else {
            text = n + ' ' + strings.many;
        }

        $pill
            .text(text)
            .attr('data-noesia-swa-active-badge-label', strings.many)
            .toggleClass('has-active', n > 0)
            .removeAttr('hidden');
    }

    function renderRequests(items) {
        var strings = requestStrings();
        var targets = ['#noesia-swa-live-requests-preview', '#noesia-swa-live-requests-preview-design'];

        targets.forEach(function (target) {
            var $el = $(target);
            var sliced;
            var html = '';

            if (!$el.length) {
                return;
            }

            if (!Array.isArray(items) || !items.length) {
                $el.removeAttr('style').html('<p class="noesia-swa-muted">' + escHtml(strings.empty) + '</p>');
                return;
            }

            sliced = items.slice(0, 40);
            html = '<div class="noesia-swa-live-list">';

            sliced.forEach(function (item) {
                html += '<div class="noesia-swa-live-item noesia-swa-live-item--compact">';
                html += '<strong>' + escHtml(item.label || strings.item) + '</strong>';

                if (item.location) {
                    html += '<span>' + escHtml(item.location) + '</span>';
                }

                if (item.time_diff) {
                    html += '<em>' + escHtml(item.time_diff) + '</em>';
                }

                html += '</div>';
            });

            html += '</div>';
            $el.html(html);

            if (sliced.length > 4) {
                $el.css({
                    maxHeight: '320px',
                    overflowY: 'auto',
                    paddingRight: '4px'
                });
            } else {
                $el.removeAttr('style');
            }
        });
    }

    function refreshRequests() {
        if (!ajaxUrl || !nonce) {
            return;
        }

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'noesia_swa_get_requests',
                nonce: nonce
            }
        }).done(function (response) {
            if (response && response.success && response.data) {
                updateRequestPill(response.data.count || 0);
                renderRequests(response.data.requests || []);
            }
        });
    }

    function bindEvents() {
        $(document)
            .off('noesiaSwaSectionShown' + state.namespace)
            .on('noesiaSwaSectionShown' + state.namespace, function (event, target) {
                target = String(target || '');

                if (target === 'design' || target === 'dashboard') {
                    refreshRequests();
                }
            })
            .off('click' + state.namespace, '#noesia-swa-design-restore, .noesia-swa-design-restore-button')
            .on('click' + state.namespace, '#noesia-swa-design-restore, .noesia-swa-design-restore-button', function (event) {
                event.preventDefault();
                restoreTextsAndIcons();
            });
    }

    function init() {
        if (state.booted) {
            return;
        }

        bindEvents();
        refreshRequests();

        if (!state.poller) {
            state.poller = window.setInterval(refreshRequests, 30000);
        }

        state.booted = true;
    }

    modules.design = $.extend({}, modules.design || {}, {
        init: init,
        refreshRequests: refreshRequests,
        onSectionOpen: function (target) {
            target = String(target || '');

            if (target === 'design' || target === 'dashboard') {
                refreshRequests();
            }
        }
    });

    $(init);
}(window, jQuery));
