/**
 * Live Support Chat – Frontend Widget JS
 * Handles visitor chat: open/close, send, poll for replies.
 */
/* global lscWidget, jQuery */
(function ($) {
    'use strict';

    /* ── Constants ── */
    var POLL_INTERVAL  = 4000; // ms between polls
    var VISITOR_COOKIE = 'lsc_visitor_id';
    var INFO_COOKIE    = 'lsc_visitor_info_shown';

    /* ── State ── */
    var state = {
        open:      false,
        chatId:    null,
        lastMsgId: 0,
        pollTimer: null,
        infoShown: false,
        audio:     null,
    };

    /* ── DOM references ── */
    var $wrapper, $toggleBtn, $chatWindow, $iconChat, $iconClose;
    var $messages, $messageInput, $sendBtn, $unreadDot;
    var $visitorInfo, $visitorName, $visitorEmail;

    /* ── Init ── */
    $(function () {
        $wrapper     = $('#lsc-chat-wrapper');
        $toggleBtn   = $('#lsc-toggle-btn');
        $chatWindow  = $('#lsc-chat-window');
        $iconChat    = $toggleBtn.find('.lsc-icon-chat');
        $iconClose   = $toggleBtn.find('.lsc-icon-close');
        $messages    = $('#lsc-messages');
        $messageInput = $('#lsc-message-input');
        $sendBtn     = $('#lsc-send-btn');
        $unreadDot   = $('#lsc-unread-dot');
        $visitorInfo = $('#lsc-visitor-info');
        $visitorName  = $('#lsc-visitor-name');
        $visitorEmail = $('#lsc-visitor-email');

        // Preload audio.
        try {
            state.audio = new Audio(lscWidget.soundUrl);
            state.audio.load();
        } catch (e) { /* silent */ }

        // Ensure visitor ID cookie exists.
        ensureVisitorId();

        // Event listeners.
        $toggleBtn.on('click', toggleChat);
        $('#lsc-close-btn').on('click', closeChat);
        $sendBtn.on('click', sendMessage);
        $messageInput.on('keydown', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // Show offline notice if needed.
        if ('offline' === lscWidget.status) {
            appendSystemMessage(lscWidget.offlineMsg);
        }
    });

    /* ── Cookie helpers ── */
    function setCookie(name, value, days) {
        var expires = '';
        if (days) {
            var d = new Date();
            d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
            expires = '; expires=' + d.toUTCString();
        }
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/; SameSite=Lax';
    }

    function getCookie(name) {
        var nameEQ = name + '=';
        var ca     = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i].trim();
            if (0 === c.indexOf(nameEQ)) {
                return decodeURIComponent(c.substring(nameEQ.length));
            }
        }
        return '';
    }

    function ensureVisitorId() {
        var vid = getCookie(VISITOR_COOKIE);
        if (!vid) {
            vid = 'v_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
            setCookie(VISITOR_COOKIE, vid, 30);
        }
        return vid;
    }

    /* ── Toggle / open / close ── */
    function toggleChat() {
        if (state.open) { closeChat(); } else { openChat(); }
    }

    function openChat() {
        state.open = true;
        $chatWindow.show();
        $iconChat.hide();
        $iconClose.show();
        $toggleBtn.attr('aria-expanded', 'true');
        $unreadDot.hide();
        $messages.scrollTop($messages[0].scrollHeight);
        startPolling();
    }

    function closeChat() {
        state.open = false;
        $chatWindow.hide();
        $iconChat.show();
        $iconClose.hide();
        $toggleBtn.attr('aria-expanded', 'false');
        stopPolling();
    }

    /* ── Send message ── */
    function sendMessage() {
        var msg = $messageInput.val().trim();
        if (!msg) { return; }

        var name  = $visitorName.val().trim();
        var email = $visitorEmail.val().trim();

        $sendBtn.prop('disabled', true);

        $.post(lscWidget.ajaxUrl, {
            action:        'lsc_visitor_send',
            nonce:         lscWidget.nonce,
            message:       msg,
            visitor_name:  name,
            visitor_email: email,
        }, function (res) {
            if (res.success) {
                state.chatId = res.data.chat_id;
                appendMessage('visitor', msg, currentTime());
                $messageInput.val('');

                // Hide name/email fields after first message.
                $visitorInfo.slideUp(200);

                startPolling();
            }
        }).always(function () {
            $sendBtn.prop('disabled', false);
            $messageInput.focus();
        });
    }

    /* ── Polling ── */
    function startPolling() {
        stopPolling();
        if (!state.chatId) { return; }
        state.pollTimer = setInterval(poll, POLL_INTERVAL);
        poll(); // immediate first call
    }

    function stopPolling() {
        if (state.pollTimer) {
            clearInterval(state.pollTimer);
            state.pollTimer = null;
        }
    }

    function poll() {
        $.post(lscWidget.ajaxUrl, {
            action:   'lsc_visitor_poll',
            nonce:    lscWidget.nonce,
            since_id: state.lastMsgId,
        }, function (res) {
            if (!res.success) { return; }

            if (res.data.chat_id && !state.chatId) {
                state.chatId = res.data.chat_id;
            }

            var msgs = res.data.messages || [];
            var hasNew = false;

            $.each(msgs, function (i, m) {
                // Only show chatter replies here (visitor msgs already displayed locally).
                if ('chatter' === m.sender) {
                    appendMessage('chatter', m.content, m.time);
                    hasNew = true;
                }
                if (m.id > state.lastMsgId) { state.lastMsgId = m.id; }
            });

            if (hasNew) {
                playSound();
                if (!state.open) { $unreadDot.show(); }
                scrollBottom();
            }
        });
    }

    /* ── Message rendering ── */
    function appendMessage(sender, content, time) {
        var $msg = $('<div class="lsc-msg"></div>').addClass(sender);
        $msg.text(content); // use .text() to escape
        if (time) {
            $msg.append($('<div class="lsc-msg-time"></div>').text(time));
        }
        $messages.append($msg);
        scrollBottom();
        state.lastMsgId = state.lastMsgId || 0;
    }

    function appendSystemMessage(text) {
        if (!text) { return; }
        var $msg = $('<div class="lsc-msg system"></div>').text(text);
        $messages.append($msg);
    }

    function scrollBottom() {
        $messages.scrollTop($messages[0].scrollHeight);
    }

    /* ── Audio ── */
    function playSound() {
        if (state.audio) {
            state.audio.currentTime = 0;
            state.audio.play().catch(function () { /* autoplay blocked */ });
        }
    }

    /* ── Time helper ── */
    function currentTime() {
        var d   = new Date();
        var h   = ('0' + d.getHours()).slice(-2);
        var min = ('0' + d.getMinutes()).slice(-2);
        return h + ':' + min;
    }

}(jQuery));
