(function($) {
    'use strict';

    var vars = window.noesia_vars || null;

    if (!vars) {
        return;
    }

    function stringToHslColor(str, s, l) {
        var hash = 0;
        var i;
        var h;

        str = String(str || '');

        for (i = 0; i < str.length; i += 1) {
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }

        h = hash % 360;

        return 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
    }

    function getPriorityColor(ageSeconds) {
        if (ageSeconds < 30) {
            return { bg_label: '#ffffff', text: '#333' };
        }
        if (ageSeconds < 60) {
            return { bg_label: '#e5e5e5', text: '#333' };
        }
        if (ageSeconds < 120) {
            return { bg_label: '#34c759', text: 'white' };
        }
        if (ageSeconds < 180) {
            return { bg_label: '#ff3b30', text: 'white' };
        }
        if (ageSeconds < 240) {
            return { bg_label: '#007aff', text: 'white' };
        }

        return { bg_label: '#1c1c1e', text: 'white' };
    }

    function showToast(message) {
        $('#ns-toast').remove();
        $('body').append('<div id="ns-toast"></div>');
        $('#ns-toast').text(message);

        setTimeout(function() {
            $('#ns-toast').addClass('show');
        }, 100);

        setTimeout(function() {
            $('#ns-toast').removeClass('show');

            setTimeout(function() {
                $('#ns-toast').remove();
            }, 300);
        }, 3000);
    }

    function performAjaxSend(btnElement, type, label) {
        var $btn = $(btnElement);
        var location = $btn.closest('.ns-app-wrapper').find('.ns-location-input').val() || vars.lbl_unknown;

        $btn.prop('disabled', true).css('opacity', '0.6');

        $.ajax({
            url: vars.ajax_url,
            type: 'POST',
            timeout: 10000,
            dataType: 'json',
            data: {
                action: 'noesia_swa_submit',
                nonce: vars.nonce,
                location: location,
                type: type,
                label: label
            }
        }).done(function(response) {
            if (response && response.success) {
                showToast(response.data && response.data.message ? response.data.message : vars.msg_error_gen);

                setTimeout(function() {
                    $btn.prop('disabled', false).css('opacity', '1');
                }, 15000);

                return;
            }

            showToast(response && response.data && response.data.message ? response.data.message : vars.msg_error_gen);

            setTimeout(function() {
                $btn.prop('disabled', false).css('opacity', '1');
            }, 2000);
        }).fail(function(xhr, status) {
            var msg = (status === 'timeout') ? vars.msg_timeout : vars.msg_conn_error;

            showToast(msg);

            setTimeout(function() {
                $btn.prop('disabled', false).css('opacity', '1');
            }, 2000);
        });
    }

    function renderAllFeeds(requests) {
        var html = '';

        if (!requests.length) {
            $('.ns-feed').html('<div class="ns-loading-state">' + vars.msg_all_quiet + '</div>');
            return;
        }

        $.each(requests, function(index, req) {
            var priority = getPriorityColor(req.age_seconds);
            var uniqueTableColor = stringToHslColor(req.location, 60, 45);
            var typeClass = req.type === 'bill' ? 'ns-type-bill' : (req.type === 'order' ? 'ns-type-order' : (req.type === 'waiter' ? 'ns-type-waiter' : 'ns-type-custom'));
            var safeLoc = $('<div>').text(req.location).html();
            var safeLabel = $('<div>').text(req.label).html();
            var safeTime = $('<div>').text(req.time_diff).html();

            html += '<div class="ns-card" style="border-left: 8px solid ' + uniqueTableColor + ' !important; background-color: #FFFFFF !important;">';
            html += '<div class="ns-card-head">';
            html += '<span class="ns-card-loc" style="color: ' + uniqueTableColor + '; font-weight: 700;">' + safeLoc + '</span>';
            html += '<span class="ns-card-time">' + safeTime + ' ago</span></div>';
            html += '<div class="ns-card-label ' + typeClass + '" style="background-color: ' + priority.bg_label + ' !important; color: ' + priority.text + ' !important; border: 1px solid ' + priority.bg_label + ' !important; box-shadow: none !important;">' + safeLabel + '</div>';
            html += '<button class="ns-done" data-id="' + req.id + '">' + vars.btn_complete + '</button>';
            html += '</div>';
        });

        $('.ns-feed').html(html);
    }

    function bootClientSurface() {
        $(document).on('click', '.ns-action-btn', function(e) {
            var type;
            var label;

            e.preventDefault();
            type = $(this).data('type');
            label = $(this).data('label');
            performAjaxSend(this, type, label);
        });
    }

    function bootDashboardSurface() {
        var $feeds = $('.ns-feed');
        var lastCount = 0;
        var isFirstLoad = true;
        var isSoundActive = false;
        var audio = $('.ns-alert-audio')[0] || null;

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

        $(document).on('click', '.ns-sound-toggle', function(e) {
            var $allBtns;
            var playPromise;

            e.preventDefault();
            $allBtns = $('.ns-sound-toggle');

            if (!isSoundActive) {
                if (audio) {
                    playPromise = audio.play();

                    if (playPromise !== undefined) {
                        playPromise.then(function() {
                            audio.pause();
                            audio.currentTime = 0;
                            isSoundActive = true;
                            $allBtns.addClass('active').text(vars.lbl_sound_on);
                        }).catch(function() {
                            window.alert(vars.msg_audio_blocked || 'Audio blocked. Click OK to enable.');
                        });
                    }
                }
            } else {
                isSoundActive = false;
                $allBtns.removeClass('active').text(vars.lbl_sound_off);
            }
        });

        function fetchRequests() {
            var currentTime = Math.floor(Date.now() / 1000);

            $.ajax({
                url: vars.ajax_url,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'noesia_swa_get_requests',
                    nonce: vars.nonce
                }
            }).done(function(response) {
                var requests;
                var count;

                if (!(response && response.success && response.data)) {
                    return;
                }

                requests = response.data.requests || [];
                count = response.data.count || 0;

                requests.forEach(function(req) {
                    req.age_seconds = currentTime - req.timestamp;
                });

                renderAllFeeds(requests);

                if (!isFirstLoad && count > lastCount && isSoundActive && audio) {
                    audio.play().catch(function() {});
                }

                lastCount = count;
                isFirstLoad = false;
            });
        }

        fetchRequests();
        setInterval(fetchRequests, 7000);

        $(document).on('click', '.ns-done', function(e) {
            var $btn = $(this);
            var card = $btn.closest('.ns-card');
            var postId = $btn.data('id');

            e.preventDefault();
            card.css('opacity', '0.5');

            $.ajax({
                url: vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'noesia_swa_complete',
                    nonce: vars.nonce,
                    post_id: postId
                }
            }).done(function() {
                card.fadeOut(300, function() {
                    $(this).remove();
                });
            });
        });
    }

    $(function() {
        bootClientSurface();
        bootDashboardSurface();
    });
}(jQuery));
