(function($) {
    'use strict';

    if (typeof seoFuryTickets === 'undefined') return;

    var nonce = seoFuryTickets.nonce;
    var ajaxUrl = seoFuryTickets.ajaxUrl;
    var i18n = seoFuryTickets.i18n || {};
    var currentTicketId = null;

    // --- Helpers ---

    var statusLabels = {
        open: i18n.statusOpen || 'Open',
        awaiting_reply: i18n.statusAwaiting || 'Awaiting Reply',
        resolved: i18n.statusResolved || 'Resolved',
        closed: i18n.statusClosed || 'Closed'
    };

    function statusBadge(status) {
        var cls = 'sf-status-badge sf-status-' + (status || 'open');
        var label = statusLabels[status] || status || 'Unknown';
        return '<span class="' + cls + '">' + label + '</span>';
    }

    function escapeHtml(str) {
        if (!str) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    function formatDate(d) {
        if (!d) return '—';
        var dt = new Date(d);
        if (isNaN(dt.getTime())) return '—';
        return dt.toLocaleDateString() + ' ' + dt.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
    }

    function showToast(msg, type) {
        var $t = $('#sf-support-toast');
        $t.removeClass('sf-toast-error sf-toast-success')
          .addClass(type === 'error' ? 'sf-toast-error' : (type === 'success' ? 'sf-toast-success' : ''))
          .text(msg)
          .stop(true)
          .fadeIn(200);
        setTimeout(function() { $t.fadeOut(400); }, 3500);
    }

    // --- Load Tickets List ---

    function loadTickets() {
        $('#sf-tickets-list').html(
            '<div class="sf-support-loading">' +
            '<div class="sf-support-spinner"></div>' +
            '<span>' + escapeHtml(i18n.loadingTickets || 'Loading tickets...') + '</span></div>'
        );

        $.post(ajaxUrl, {
            action: 'seo_fury_get_tickets',
            nonce: nonce,
            page: 1
        }, function(res) {
            if (res.success && res.data && res.data.tickets) {
                renderTicketsList(res.data.tickets);
            } else {
                var msg = (res.data && res.data.message) ? res.data.message : (i18n.failedLoad || 'Failed to load tickets');
                var isExpired = msg.toLowerCase().indexOf('expired') !== -1 || msg.toLowerCase().indexOf('token') !== -1;
                var hint, icon;
                if (isExpired) {
                    icon = 'dashicons-update';
                    hint = '<p style="margin-bottom:16px">' + escapeHtml(i18n.sessionExpired || 'Your session has expired. Please re-activate your license key in the License tab.') + '</p>' +
                           '<div style="display:flex;gap:8px;justify-content:center">' +
                           '<a href="?page=seo-fury&tab=license" class="sf-support-btn sf-support-btn-primary" style="text-decoration:none">' + escapeHtml(i18n.goToLicense || 'Go to License') + '</a>' +
                           '<a href="https://dashboard.seo-fury.com/register" target="_blank" class="sf-support-btn sf-support-btn-ghost" style="text-decoration:none">' + escapeHtml(i18n.createAccount || 'Create Account') + '</a>' +
                           '</div>';
                } else {
                    icon = 'dashicons-warning';
                    hint = '<p>' + escapeHtml(i18n.checkLicense || 'Please check your license and internet connection.') + '</p>';
                }
                $('#sf-tickets-list').html(
                    '<div class="sf-support-empty">' +
                    '<div class="sf-support-empty-icon"><span class="dashicons ' + icon + '"></span></div>' +
                    '<h4>' + escapeHtml(msg) + '</h4>' +
                    hint + '</div>'
                );
            }
        }).fail(function() {
            $('#sf-tickets-list').html(
                '<div class="sf-support-empty">' +
                '<div class="sf-support-empty-icon"><span class="dashicons dashicons-warning"></span></div>' +
                '<h4>' + escapeHtml(i18n.connectionError || 'Connection Error') + '</h4>' +
                '<p>' + escapeHtml(i18n.connectionErrorMsg || 'Could not connect to support server. Please try again later.') + '</p></div>'
            );
        });
    }

    function renderTicketsList(tickets) {
        if (!tickets.length) {
            $('#sf-tickets-list').html(
                '<div class="sf-support-empty">' +
                '<div class="sf-support-empty-icon"><span class="dashicons dashicons-format-chat"></span></div>' +
                '<h4>' + escapeHtml(i18n.noTickets || 'No tickets yet') + '</h4>' +
                '<p>' + escapeHtml(i18n.noTicketsHint || 'Click "New Ticket" if you need help!') + '</p></div>'
            );
            return;
        }

        var html = '<div class="sf-support-card" style="padding:0;overflow:hidden;">' +
            '<table class="sf-tickets-table"><thead><tr>' +
            '<th>' + escapeHtml(i18n.subject || 'Subject') + '</th>' +
            '<th>' + escapeHtml(i18n.status || 'Status') + '</th>' +
            '<th>' + escapeHtml(i18n.created || 'Created') + '</th>' +
            '<th>' + escapeHtml(i18n.lastUpdate || 'Last Update') + '</th>' +
            '</tr></thead><tbody>';

        tickets.forEach(function(t) {
            html += '<tr class="sf-ticket-row" data-id="' + t._id + '">' +
                '<td class="sf-ticket-subject">' + escapeHtml(t.subject) + '</td>' +
                '<td>' + statusBadge(t.status) + '</td>' +
                '<td>' + formatDate(t.createdAt) + '</td>' +
                '<td>' + formatDate(t.lastReplyAt) + '</td>' +
                '</tr>';
        });

        html += '</tbody></table></div>';
        $('#sf-tickets-list').html(html);
    }

    // --- Load Ticket Detail ---

    function loadTicketDetail(ticketId) {
        currentTicketId = ticketId;
        $('#sf-tickets-list, #sf-create-ticket-form, #sf-faq-suggestions').hide();
        $('#sf-ticket-detail').show().html(
            '<div class="sf-support-loading">' +
            '<div class="sf-support-spinner"></div>' +
            '<span>' + escapeHtml(i18n.loadingTicket || 'Loading ticket...') + '</span></div>'
        );

        $.post(ajaxUrl, {
            action: 'seo_fury_get_ticket',
            nonce: nonce,
            ticket_id: ticketId
        }, function(res) {
            if (!res.success) {
                var errMsg = (res.data && res.data.message) ? res.data.message : (i18n.failedLoadTicket || 'Failed to load ticket');
                $('#sf-ticket-detail').html(
                    '<div class="sf-support-card">' +
                    '<a href="#" class="sf-back-to-list" style="color:var(--sf-primary);font-size:13px;text-decoration:none;">&laquo; ' + escapeHtml(i18n.backToTickets || 'Back to Tickets') + '</a>' +
                    '<p style="color:var(--sf-danger);margin-top:12px;">' + escapeHtml(errMsg) + '</p></div>'
                );
                return;
            }

            var ticket = res.data;
            var messages = ticket.messages || [];
            var isClosed = ticket.status === 'closed' || ticket.status === 'resolved';

            // Messages HTML
            var msgsHtml = '';
            messages.forEach(function(msg) {
                var cls = msg.sender === 'admin' ? 'sf-msg-admin' : (msg.sender === 'system' ? 'sf-msg-system' : 'sf-msg-user');
                var align = msg.sender === 'admin' ? 'flex-end' : 'flex-start';
                msgsHtml += '<div style="display:flex;justify-content:' + align + ';">' +
                    '<div class="sf-msg-bubble ' + cls + '">' +
                    '<div class="sf-msg-sender">' + escapeHtml(msg.senderName || msg.sender) + '</div>' +
                    '<div class="sf-msg-text">' + escapeHtml(msg.text) + '</div>' +
                    '<div class="sf-msg-time">' + formatDate(msg.createdAt) + '</div>' +
                    '</div></div>';
            });

            if (!messages.length) {
                msgsHtml = '<p style="text-align:center;color:var(--sf-gray-400);font-size:13px;padding:16px 0;">' + escapeHtml(i18n.noMessages || 'No messages yet.') + '</p>';
            }

            var html = '<div class="sf-support-card" style="padding:12px 20px;margin-bottom:12px;">' +
                '<a href="#" class="sf-back-to-list" style="color:var(--sf-primary);font-size:13px;font-weight:500;text-decoration:none;">&laquo; ' + escapeHtml(i18n.backToTickets || 'Back to Tickets') + '</a>' +
                '</div>' +
                '<div class="sf-support-card">' +
                '<div class="sf-ticket-detail-header">' +
                '<div>' +
                '<h3 class="sf-ticket-detail-subject">' + escapeHtml(ticket.subject) + '</h3>' +
                '<div class="sf-ticket-detail-meta">' + escapeHtml(i18n.created || 'Created') + ': ' + formatDate(ticket.createdAt) + ' &middot; ' + escapeHtml(i18n.lastUpdate || 'Last Update') + ': ' + formatDate(ticket.lastReplyAt) + '</div>' +
                '</div>' +
                '<div>' + statusBadge(ticket.status) + '</div>' +
                '</div>' +
                '<div class="sf-ticket-messages" id="sf-ticket-messages">' + msgsHtml + '</div>';

            if (!isClosed) {
                html += '<div class="sf-ticket-reply-area">' +
                    '<textarea id="sf-reply-text" rows="3" placeholder="' + escapeHtml(i18n.typeReply || 'Type your reply...') + '"></textarea>' +
                    '<div class="sf-ticket-reply-actions">' +
                    '<button type="button" class="sf-support-btn sf-support-btn-primary" id="sf-send-reply">' +
                    '<span class="dashicons dashicons-yes"></span> ' + escapeHtml(i18n.sendReply || 'Send Reply') + '</button>' +
                    '<button type="button" class="sf-support-btn sf-support-btn-danger sf-support-btn-sm" id="sf-close-ticket-btn">' +
                    escapeHtml(i18n.closeTicket || 'Close Ticket') + '</button>' +
                    '</div></div>';
            } else {
                html += '<p style="text-align:center;color:var(--sf-gray-400);font-size:13px;padding:16px 0;">' + escapeHtml(i18n.ticketIsClosed || 'This ticket is closed.') + '</p>';
            }

            html += '</div>';
            $('#sf-ticket-detail').html(html);

            // Scroll messages to bottom
            var mc = document.getElementById('sf-ticket-messages');
            if (mc) mc.scrollTop = mc.scrollHeight;
        }).fail(function() {
            $('#sf-ticket-detail').html(
                '<div class="sf-support-card">' +
                '<a href="#" class="sf-back-to-list" style="color:var(--sf-primary);font-size:13px;text-decoration:none;">&laquo; ' + escapeHtml(i18n.backToTickets || 'Back to Tickets') + '</a>' +
                '<p style="color:var(--sf-danger);margin-top:12px;">' + escapeHtml(i18n.connectionRetry || 'Connection error. Please try again.') + '</p></div>'
            );
        });
    }

    // --- Initialization ---

    $(document).ready(function() {
        if ($('#seo-fury-support-wrap').length === 0) return;

        loadTickets();

        // Create ticket toggle
        $(document).on('click', '#sf-create-ticket-btn', function() {
            var $form = $('#sf-create-ticket-form');
            if ($form.is(':visible')) {
                $form.slideUp(200);
            } else {
                $form.slideDown(200);
                $('#sf-faq-suggestions').slideUp(200);
            }
        });

        // Cancel ticket
        $(document).on('click', '#sf-cancel-ticket', function() {
            $('#sf-create-ticket-form').slideUp(200);
        });

        // Submit ticket
        $(document).on('click', '#sf-submit-ticket', function() {
            var $btn = $(this);
            var subject = $.trim($('#sf-ticket-subject').val());
            var message = $.trim($('#sf-ticket-message').val());

            if (!subject || !message) {
                showToast(i18n.fillFields || 'Please fill in both subject and message.', 'error');
                return;
            }

            $btn.prop('disabled', true).find('.dashicons').removeClass('dashicons-yes-alt').addClass('dashicons-update sf-spin-icon');

            $.post(ajaxUrl, {
                action: 'seo_fury_create_ticket',
                nonce: nonce,
                subject: subject,
                message: message
            }, function(res) {
                $btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update sf-spin-icon').addClass('dashicons-yes-alt');

                if (!res.success) {
                    showToast(res.data ? res.data.message : (i18n.errorCreating || 'Error creating ticket'), 'error');
                    return;
                }

                var data = res.data;
                var faqSuggestions = data.faqSuggestions || [];
                currentTicketId = data.ticket ? data.ticket._id : null;

                if (faqSuggestions.length > 0) {
                    // Show FAQ suggestions
                    $('#sf-create-ticket-form').slideUp(200);
                    var faqHtml = '';
                    faqSuggestions.forEach(function(faq) {
                        faqHtml += '<div class="sf-faq-item">' +
                            '<h5>' + escapeHtml(faq.title) + '</h5>' +
                            '<p>' + escapeHtml(faq.body ? faq.body.substring(0, 200) : '') + '</p>' +
                            '<button type="button" class="sf-support-btn sf-support-btn-success sf-support-btn-sm" data-faq-helped="' + faq._id + '">' +
                            '<span class="dashicons dashicons-thumbs-up"></span> ' + escapeHtml(i18n.thisHelped || 'This helped!') + '</button>' +
                            '</div>';
                    });
                    $('#sf-faq-list').html(faqHtml);
                    $('#sf-faq-suggestions').slideDown(200);
                } else {
                    showToast(i18n.ticketSubmitted || "Ticket submitted! We'll reply within 24 hours.", 'success');
                    $('#sf-create-ticket-form').slideUp(200);
                    $('#sf-ticket-subject, #sf-ticket-message').val('');
                    loadTickets();
                }
            }).fail(function() {
                $btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update sf-spin-icon').addClass('dashicons-yes-alt');
                showToast(i18n.connectionRetry || 'Connection error. Please try again.', 'error');
            });
        });

        // FAQ helped
        $(document).on('click', '[data-faq-helped]', function() {
            var faqId = $(this).data('faq-helped');
            $.post(ajaxUrl, {
                action: 'seo_fury_faq_feedback',
                nonce: nonce,
                ticket_id: currentTicketId,
                helpful: true,
                faq_id: faqId
            });
            showToast(i18n.gladHelped || 'Great! Glad we could help.', 'success');
            $('#sf-faq-suggestions').slideUp(200);
            $('#sf-ticket-subject, #sf-ticket-message').val('');
            loadTickets();
        });

        // Escalate to human
        $(document).on('click', '#sf-escalate-ticket', function() {
            var $btn = $(this);
            $btn.prop('disabled', true);
            $.post(ajaxUrl, {
                action: 'seo_fury_faq_feedback',
                nonce: nonce,
                ticket_id: currentTicketId,
                helpful: false
            }, function() {
                $btn.prop('disabled', false);
                showToast(i18n.ticketSent || "Ticket sent to our support team. We'll reply within 24 hours.", 'success');
                $('#sf-faq-suggestions').slideUp(200);
                $('#sf-ticket-subject, #sf-ticket-message').val('');
                loadTickets();
            }).fail(function() {
                $btn.prop('disabled', false);
                showToast(i18n.errorEscalating || 'Error escalating ticket.', 'error');
            });
        });

        // Click ticket row
        $(document).on('click', '.sf-ticket-row', function() {
            loadTicketDetail($(this).data('id'));
        });

        // Back to list
        $(document).on('click', '.sf-back-to-list', function(e) {
            e.preventDefault();
            $('#sf-ticket-detail').hide();
            $('#sf-tickets-list').show();
            loadTickets();
        });

        // Send reply
        $(document).on('click', '#sf-send-reply', function() {
            var $btn = $(this);
            var text = $.trim($('#sf-reply-text').val());
            if (!text) {
                showToast(i18n.enterReply || 'Please enter a reply.', 'error');
                return;
            }

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update sf-spin-icon"></span> ' + escapeHtml(i18n.sending || 'Sending...'));

            $.post(ajaxUrl, {
                action: 'seo_fury_reply_ticket',
                nonce: nonce,
                ticket_id: currentTicketId,
                message: text
            }, function(res) {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes"></span> ' + escapeHtml(i18n.sendReply || 'Send Reply'));
                if (res.success) {
                    showToast(i18n.replySent || 'Reply sent!', 'success');
                    loadTicketDetail(currentTicketId);
                } else {
                    showToast(res.data ? res.data.message : (i18n.errorReply || 'Error sending reply'), 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes"></span> ' + escapeHtml(i18n.sendReply || 'Send Reply'));
                showToast(i18n.connectionRetry || 'Connection error.', 'error');
            });
        });

        // Close ticket
        $(document).on('click', '#sf-close-ticket-btn', function() {
            if (!confirm(i18n.closeConfirm || 'Close this ticket?')) return;
            var $btn = $(this);
            $btn.prop('disabled', true);

            $.post(ajaxUrl, {
                action: 'seo_fury_close_ticket',
                nonce: nonce,
                ticket_id: currentTicketId
            }, function(res) {
                if (res.success) {
                    showToast(i18n.ticketClosed || 'Ticket closed.', 'success');
                    $('#sf-ticket-detail').hide();
                    $('#sf-tickets-list').show();
                    loadTickets();
                } else {
                    $btn.prop('disabled', false);
                    showToast(res.data ? res.data.message : (i18n.errorClosing || 'Error closing ticket'), 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                showToast(i18n.connectionRetry || 'Connection error.', 'error');
            });
        });
    });

})(jQuery);
