/**
 * SiteStaffr Call Detail Page JavaScript
 *
 * Handles session ID copy, ban IP, mark unread, delete call,
 * transcript toggle, and report issue modal.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.2.3
 */

(function($) {
    'use strict';

    var d = window.sitestaffrCallDetailData;
    if (!d) {
        return;
    }

    $(document).ready(function() {

        // Click to copy Session ID
        $('.sitestaffr-call-sid-code').on('click', function() {
            var $code = $(this);
            var callSid = $code.text();
            var originalText = callSid;

            // Copy to clipboard
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(callSid).then(function() {
                    $code.text(d.i18n.copied);
                    $code.css('background-color', '#00a32a');
                    $code.css('color', '#fff');

                    setTimeout(function() {
                        $code.text(originalText);
                        $code.css('background-color', '');
                        $code.css('color', '');
                    }, 2000);
                }).catch(function(err) {
                    console.error('SiteStaffr: Failed to copy Session ID:', err);
                });
            } else {
                // Fallback for older browsers
                var tempInput = $('<input>');
                $('body').append(tempInput);
                tempInput.val(callSid).select();
                try {
                    document.execCommand('copy');
                    $code.text(d.i18n.copied);
                    $code.css('background-color', '#00a32a');
                    $code.css('color', '#fff');

                    setTimeout(function() {
                        $code.text(originalText);
                        $code.css('background-color', '');
                        $code.css('color', '');
                    }, 2000);
                } catch (err) {
                    console.error('SiteStaffr: Failed to copy Session ID:', err);
                }
                tempInput.remove();
            }
        });

        // Ban IP button
        $('.sitestaffr-ban-ip-btn').on('click', function() {
            var $btn = $(this);
            var identifier = String($btn.data('identifier') || '').trim();
            var callId = String($btn.data('call-id') || '').trim();
            if (!identifier) {
                return;
            }

            if (!confirm(d.i18n.confirmBan + '\n\n' + identifier)) {
                return;
            }

            var originalText = $btn.text();
            $btn.prop('disabled', true).text(d.i18n.banning);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_ban_visitor',
                    identifier: identifier,
                    reason: 'Banned from call details (Call #' + callId + ')',
                    nonce: d.banNonce
                }
            }).done(function(response) {
                var isSuccess = !!(response && response.success);
                var message = isSuccess
                    ? d.i18n.banSuccess
                    : ((response && response.data && response.data.message) ? response.data.message : d.i18n.banFailed);

                var noticeClass = isSuccess ? 'notice-success' : 'notice-error';
                $('#sitestaffr-call-detail-notice-anchor').after(
                    $('<div class="notice ' + noticeClass + ' is-dismissible"><p></p></div>').find('p').text(message).end()
                );

                if (isSuccess) {
                    $btn.replaceWith('<span class="sitestaffr-status-badge sitestaffr-status-new">' + d.i18n.banned + '</span>');
                } else {
                    $btn.prop('disabled', false).text(originalText);
                }
            }).fail(function() {
                $('#sitestaffr-call-detail-notice-anchor').after(
                    $('<div class="notice notice-error is-dismissible"><p>' + d.i18n.banFailedRetry + '</p></div>')
                );
                $btn.prop('disabled', false).text(originalText);
            });
        });

        // Mark as unread
        $('.pe-action-unread').on('click', function() {
            var $btn = $(this);
            var callId = String($btn.data('call-id') || '').trim();
            if (!callId) return;

            $btn.prop('disabled', true);
            $btn.find('.dashicons').removeClass('dashicons-marker').addClass('dashicons-update');
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_mark_call_unread',
                    call_id: callId,
                    nonce: d.ajaxNonce
                }
            }).done(function(response) {
                if (response && response.success) {
                    window.location.href = d.callsListUrl;
                } else {
                    $btn.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-marker');
                    $btn.prop('disabled', false);
                }
            }).fail(function() {
                $btn.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-marker');
                $btn.prop('disabled', false);
            });
        });

        // Delete call
        $('.pe-action-delete').on('click', function() {
            var $btn = $(this);
            var callId = String($btn.data('call-id') || '').trim();
            if (!callId) return;

            if (!confirm(d.i18n.confirmDelete)) {
                return;
            }

            $btn.prop('disabled', true);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_delete_call',
                    call_id: callId,
                    nonce: d.ajaxNonce
                }
            }).done(function(response) {
                if (response && response.success) {
                    window.location.href = d.dashboardUrl;
                } else {
                    var msg = (response && response.data && response.data.message) ? response.data.message : d.i18n.deleteFailed;
                    $('#sitestaffr-call-detail-notice-anchor').after(
                        $('<div class="notice notice-error is-dismissible"><p></p></div>').find('p').text(msg).end()
                    );
                    $btn.prop('disabled', false);
                }
            }).fail(function() {
                $('#sitestaffr-call-detail-notice-anchor').after(
                    $('<div class="notice notice-error is-dismissible"><p>' + d.i18n.deleteFailedRetry + '</p></div>')
                );
                $btn.prop('disabled', false);
            });
        });

        // Report Issue modal
        var $reportModal = $('#sitestaffr-report-issue-modal');

        function openReportModal() {
            $reportModal.css('display', 'flex').attr('aria-hidden', 'false');
            $('#sitestaffr-report-issue-type').val('');
            $('#sitestaffr-report-issue-note').val('');
            $('.sitestaffr-report-issue-error').hide().text('');
            $('.sitestaffr-report-issue-submit').prop('disabled', false).text(d.i18n.submitReport);
        }

        function closeReportModal() {
            if (document.activeElement && $reportModal[0].contains(document.activeElement)) {
                document.activeElement.blur();
            }
            $reportModal.css('display', 'none').attr('aria-hidden', 'true');
        }

        $('.pe-action-report').on('click', function() {
            openReportModal();
        });

        $reportModal.on('click', '.sitestaffr-modal-close, .sitestaffr-modal-cancel', function() {
            closeReportModal();
        });

        $reportModal.on('click', function(e) {
            if ($(e.target).hasClass('sitestaffr-modal-overlay')) {
                closeReportModal();
            }
        });

        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $reportModal.is(':visible')) {
                closeReportModal();
            }
        });

        $('.sitestaffr-report-issue-submit').on('click', function() {
            var $btn = $(this);
            if ($btn.prop('disabled')) return;
            var issueType = $('#sitestaffr-report-issue-type').val();
            var note = $('#sitestaffr-report-issue-note').val();
            var $error = $('.sitestaffr-report-issue-error');

            if (!issueType) {
                $error.text(d.i18n.selectIssueType).show();
                return;
            }

            $error.hide();
            $btn.prop('disabled', true).text(d.i18n.submitting);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_report_issue',
                    call_id: String($('.pe-action-report').data('call-id') || '').trim(),
                    issue_type: issueType,
                    note: note,
                    nonce: d.ajaxNonce
                }
            }).done(function(response) {
                if (response && response.success) {
                    closeReportModal();
                    $('#sitestaffr-call-detail-notice-anchor').after(
                        $('<div class="notice notice-success is-dismissible"><p></p></div>').find('p').text(response.data.message).end()
                    );
                } else {
                    var msg = (response && response.data && response.data.message) ? response.data.message : d.i18n.reportFailed;
                    $error.text(msg).show();
                    $btn.prop('disabled', false).text(d.i18n.submitReport);
                }
            }).fail(function() {
                $error.text(d.i18n.reportFailed).show();
                $btn.prop('disabled', false).text(d.i18n.submitReport);
            });
        });

        // Mobile accordion: toggle transcript and session details
        $('.sitestaffr-mobile-toggle').on('click', function() {
            var $btn = $(this);
            var $card = $btn.closest('.sitestaffr-detail-card, .pe-business-info-card');
            var isExpanded = $card.hasClass('is-expanded');

            $card.toggleClass('is-expanded');
            $btn.attr('aria-expanded', !isExpanded);
        });
    });

})(jQuery);
