/**
 * Live Support Chat – Chatter Dashboard JS
 * Responsive: desktop + mobile drawer support
 */
/* global lscChatter, jQuery */
(function ($) {
    'use strict';

    var POLL_MS = 3000;

    var S = {
        activeChatId : null,
        lastMsgId    : 0,
        pollTimer    : null,
        knownChats   : {},
        audio        : null,
        agentInitial : 'A',
        isMobile     : false,
    };

    /* ── Init ──────────────────────────────────────────────────────────── */
    $(function () {
        S.audio        = document.getElementById('lsc-notification-sound');
        S.agentInitial = ($('.lsc-avatar-lg').text() || 'A').trim().charAt(0).toUpperCase();
        S.isMobile     = window.innerWidth <= 768;

        bindEvents();
        startPolling();

        // Track resize
        $(window).on('resize', function () { S.isMobile = window.innerWidth <= 768; });
    });

    /* ── Events ─────────────────────────────────────────────────────────── */
    function bindEvents() {
        // Open sidebar (hamburger + "View chats" button in empty state)
        $('#lsc-hamburger, .lsc-hamburger-trigger, #lsc-open-sidebar-empty').on('click', openSidebar);

        // Close sidebar (overlay click, close button inside sidebar, back button)
        $('#lsc-overlay, #lsc-sidebar-close').on('click', closeSidebar);

        // Keyboard: Escape closes sidebar
        $(document).on('keydown', function (e) {
            if (e.key === 'Escape') closeSidebar();
        });

        // Back button in active chat (mobile → return to sidebar)
        $('#lsc-back-btn').on('click', function () {
            if (S.isMobile) openSidebar();
        });

        // Select a chat from sidebar
        $(document).on('click', '.lsc-chat-item', function () {
            openChat(parseInt($(this).data('chat-id'), 10), $(this));
        });

        // Close the active chat session
        $('#lsc-close-chat-btn').on('click', function () {
            if (!S.activeChatId) return;
            if (!window.confirm(lscChatter.i18n.confirmClose)) return;
            closeChat(S.activeChatId);
        });

        // Send reply: button click
        $(document).on('click', '#lsc-reply-send-btn', sendReply);

        // Send reply: Enter key (Shift+Enter = newline)
        $(document).on('keydown', '#lsc-reply-input', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendReply();
            }
            // Auto-grow textarea
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 100) + 'px';
        });
    }

    /* ── Sidebar open / close ──────────────────────────────────────────── */
    function openSidebar() {
        $('#lsc-sidebar').addClass('open');
        $('#lsc-overlay').addClass('active');
        $('body').css('overflow', 'hidden');
    }

    function closeSidebar() {
        $('#lsc-sidebar').removeClass('open');
        $('#lsc-overlay').removeClass('active');
        $('body').css('overflow', '');
    }

    /* ── Open a chat ───────────────────────────────────────────────────── */
    function openChat(chatId, $item) {
        S.activeChatId = chatId;
        S.lastMsgId    = 0;

        $('.lsc-chat-item').removeClass('active');
        $item.addClass('active');
        $item.find('.lsc-unread-pip').remove();

        var name  = ($item.data('name') || '').trim() || lscChatter.i18n.visitor;
        var email = ($item.data('email') || '').trim();

        $('#lsc-topbar-avatar').text(name.charAt(0).toUpperCase());
        $('#lsc-topbar-name').text(name);
        $('#lsc-topbar-email').text(email);

        $('#lsc-main-empty').hide();
        $('#lsc-active-chat').show();
        $('#lsc-messages-panel').empty();

        // On mobile: close the sidebar drawer to show the conversation
        if (S.isMobile) closeSidebar();

        fetchMessages(chatId, 0);
        setTimeout(function () { $('#lsc-reply-input').focus(); }, 120);
    }

    /* ── Send reply ────────────────────────────────────────────────────── */
    function sendReply() {
        var msg = $('#lsc-reply-input').val().trim();
        if (!msg || !S.activeChatId) return;

        var $btn = $('#lsc-reply-send-btn').prop('disabled', true);

        $.post(lscChatter.ajaxUrl, {
            action  : 'lsc_chatter_reply',
            nonce   : lscChatter.nonce,
            chat_id : S.activeChatId,
            message : msg,
        }, function (res) {
            if (res.success) {
                appendMsg({ sender: 'chatter', content: msg, time: nowTime() });
                $('#lsc-reply-input').val('').css('height', 'auto');
                scrollBottom();
            } else {
                showToast('Error', res.data && res.data.message ? res.data.message : 'Could not send.', 'error');
            }
        }).always(function () {
            $btn.prop('disabled', false);
            $('#lsc-reply-input').focus();
        });
    }

    /* ── Close a chat session ──────────────────────────────────────────── */
    function closeChat(chatId) {
        $.post(lscChatter.ajaxUrl, {
            action  : 'lsc_close_chat',
            nonce   : lscChatter.nonce,
            chat_id : chatId,
        }, function (res) {
            if (!res.success) return;
            $('.lsc-chat-item[data-chat-id="' + chatId + '"]').remove();
            delete S.knownChats[chatId];
            S.activeChatId = null;
            S.lastMsgId    = 0;
            $('#lsc-active-chat').hide();
            $('#lsc-main-empty').show();
            if (S.isMobile) openSidebar();
            checkEmpty();
        });
    }

    /* ── Polling ───────────────────────────────────────────────────────── */
    function startPolling() {
        stopPolling();
        poll();
        S.pollTimer = setInterval(poll, POLL_MS);
    }
    function stopPolling() {
        if (S.pollTimer) { clearInterval(S.pollTimer); S.pollTimer = null; }
    }

    function poll() {
        $.post(lscChatter.ajaxUrl, {
            action   : 'lsc_chatter_poll',
            nonce    : lscChatter.nonce,
            chat_id  : S.activeChatId || 0,
            since_id : S.lastMsgId,
        }, function (res) {
            if (!res.success) return;
            updateSidebar(res.data.chats    || []);
            handleMessages(res.data.messages || []);
        });
    }

    /* ── Fetch messages (initial load for a chat) ──────────────────────── */
    function fetchMessages(chatId, sinceId) {
        $.post(lscChatter.ajaxUrl, {
            action   : 'lsc_chatter_poll',
            nonce    : lscChatter.nonce,
            chat_id  : chatId,
            since_id : sinceId,
        }, function (res) {
            if (!res.success) return;
            $.each(res.data.messages || [], function (i, m) {
                appendMsg(m);
                if (m.id > S.lastMsgId) S.lastMsgId = m.id;
            });
            scrollBottom();
        });
    }

    /* ── Update sidebar list ───────────────────────────────────────────── */
    function updateSidebar(chats) {
        var totalUnread = 0;
        var currentIds  = {};

        $.each(chats, function (i, c) {
            currentIds[c.id] = true;
            totalUnread += (c.unread || 0);

            var $el = $('.lsc-chat-item[data-chat-id="' + c.id + '"]');

            if ($el.length) {
                $el.find('.lsc-unread-pip').remove();
                if (c.unread > 0 && c.id !== S.activeChatId) {
                    $el.find('.lsc-chat-item-top').append(
                        $('<span class="lsc-unread-pip"></span>').text(c.unread)
                    );
                }
                $el.find('.lsc-chat-item-time').text(c.updated_at || '');
            } else {
                // Brand-new chat
                $('#lsc-chat-list').prepend(buildChatItem(c));
                S.knownChats[c.id] = true;
                if (S.activeChatId !== c.id) {
                    playSound();
                    showToast(lscChatter.i18n.newMessage, c.visitor_name || lscChatter.i18n.visitor, 'chat');
                }
            }
        });

        // Remove chats no longer in the list
        $('.lsc-chat-item').each(function () {
            var id = parseInt($(this).data('chat-id'), 10);
            if (!currentIds[id]) {
                if (id === S.activeChatId) {
                    S.activeChatId = null;
                    $('#lsc-active-chat').hide();
                    $('#lsc-main-empty').show();
                    if (S.isMobile) openSidebar();
                }
                $(this).remove();
            }
        });

        // Global unread badge (sidebar header + mobile topbar)
        var $badge = $('#lsc-total-unread');
        var $mob   = $('#lsc-mobile-unread');
        if (totalUnread > 0) {
            $badge.text(totalUnread).show();
            $mob.text(totalUnread).show();
        } else {
            $badge.hide();
            $mob.hide();
        }

        checkEmpty();
    }

    function buildChatItem(c) {
        var name    = (c.visitor_name || '').trim() || lscChatter.i18n.visitor;
        var initial = name.charAt(0).toUpperCase();

        var $item = $('<div class="lsc-chat-item"></div>')
            .attr({ 'data-chat-id': c.id, 'data-name': c.visitor_name || '', 'data-email': c.visitor_email || '' });

        var $avatar = $('<div class="lsc-chat-avatar"></div>').text(initial);
        var $body   = $('<div class="lsc-chat-item-body"></div>');
        var $top    = $('<div class="lsc-chat-item-top"></div>');
        var $name   = $('<div class="lsc-chat-item-name"></div>').text(name);
        var $time   = $('<div class="lsc-chat-item-time"></div>').text(c.updated_at || '');
        var $sub    = $('<div class="lsc-chat-item-sub"></div>').text(c.visitor_email || lscChatter.i18n.visitor);

        $top.append($name);
        if (c.unread > 0) {
            $top.append($('<span class="lsc-unread-pip"></span>').text(c.unread));
        } else {
            $top.append($time);
        }

        $body.append($top).append($sub);
        return $item.append($avatar).append($body);
    }

    /* ── Handle new incoming messages ──────────────────────────────────── */
    function handleMessages(messages) {
        if (!messages.length) return;
        var hasVisitor = false;
        $.each(messages, function (i, m) {
            appendMsg(m);
            if (m.id > S.lastMsgId) S.lastMsgId = m.id;
            if (m.sender === 'visitor') hasVisitor = true;
        });
        if (hasVisitor) {
            playSound();
            showToast(lscChatter.i18n.newMessage, '', 'chat');
        }
        scrollBottom();
    }

    /* ── Render a message bubble ───────────────────────────────────────── */
    function appendMsg(m) {
        var isChatter = (m.sender === 'chatter');
        var icon      = isChatter ? S.agentInitial : 'V';
        var label     = isChatter ? lscChatter.i18n.you : (m.visitor_name || lscChatter.i18n.visitor);

        var $wrap   = $('<div class="lsc-ch-msg"></div>').addClass(m.sender);
        var $row    = $('<div class="lsc-ch-msg-row"></div>');
        var $ico    = $('<div class="lsc-msg-icon"></div>').text(icon);
        var $bubble = $('<div class="lsc-ch-msg-bubble"></div>').text(m.content);
        var $time   = $('<div class="lsc-ch-msg-time"></div>').text(label + (m.time ? ' · ' + m.time : ''));

        $row.append($ico).append($bubble);
        $wrap.append($row).append($time);
        $('#lsc-messages-panel').append($wrap);
    }

    /* ── Toast ─────────────────────────────────────────────────────────── */
    function showToast(title, subtitle, type) {
        var icon = type === 'error' ? '⚠' : '💬';
        var $t   = $('<div class="lsc-toast"></div>');
        var $i   = $('<div class="lsc-toast-icon"></div>').text(icon);
        var $b   = $('<div class="lsc-toast-body"></div>');
        var $cl  = $('<button class="lsc-toast-close" aria-label="close">×</button>');

        $b.append($('<div class="lsc-toast-title"></div>').text(title));
        if (subtitle) $b.append($('<div class="lsc-toast-sub"></div>').text(subtitle));
        $cl.on('click', function () { $t.remove(); });
        $t.append($i).append($b).append($cl);
        $('body').append($t);
        setTimeout(function () { $t.fadeOut(400, function () { $(this).remove(); }); }, 4500);
    }

    /* ── Helpers ───────────────────────────────────────────────────────── */
    function scrollBottom() {
        var p = document.getElementById('lsc-messages-panel');
        if (p) p.scrollTop = p.scrollHeight;
    }
    function checkEmpty() {
        if ($('.lsc-chat-item').length) $('#lsc-empty-msg').hide();
        else $('#lsc-empty-msg').show();
    }
    function playSound() {
        if (S.audio) { S.audio.currentTime = 0; S.audio.play().catch(function () {}); }
    }
    function nowTime() {
        var d = new Date();
        return ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2);
    }

}(jQuery));
