/**
 * 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', async function() {
            var $btn = $(this);
            var identifier = String($btn.data('identifier') || '').trim();
            var callId = String($btn.data('call-id') || '').trim();
            if (!identifier) {
                return;
            }

            var banOk = await window.SiteStaffrModal.confirm({
                message: d.i18n.confirmBan + ' ' + identifier,
                danger: true
            });
            if (!banOk) {
                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 conversation details (Conversation #' + 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-banned">' + 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
        $('.sitestaffr-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);
            });
        });

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

            var trashOk = await window.SiteStaffrModal.confirm({
                message: d.i18n.confirmDelete
            });
            if (!trashOk) {
                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 — chrome (Esc, backdrop, close X, focus trap,
        // focus-return) comes from the shared component.
        var $reportModal = $('#sitestaffr-report-issue-modal');
        var reportController = $reportModal.length && window.SiteStaffrModal
            ? window.SiteStaffrModal.enhance($reportModal[0], {
                onOpen: function() {
                    $('#sitestaffr-report-issue-type').val('');
                    $('#sitestaffr-report-issue-note').val('');
                    $('#sitestaffr-report-issue-include-link').prop('checked', true);
                    $('.sitestaffr-report-issue-error').hide().text('');
                    $('.sitestaffr-report-issue-submit').prop('disabled', false).text(d.i18n.submitReport);
                }
            })
            : null;

        function closeReportModal() {
            if (reportController) {
                reportController.close();
            }
        }

        $('.sitestaffr-action-report').on('click', function() {
            if (reportController) {
                reportController.open();
            }
        });

        $reportModal.on('click', '.sitestaffr-modal-cancel', function() {
            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($('.sitestaffr-action-report').data('call-id') || '').trim(),
                    issue_type: issueType,
                    note: note,
                    include_link: $('#sitestaffr-report-issue-include-link').is(':checked') ? '1' : '0',
                    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);
            });
        });

        // Copy the shareable transcript link (the tokenized viewer page).
        $('.sitestaffr-action-share').on('click', function() {
            var $btn = $(this);
            var url = String($btn.data('share-url') || '');
            if (!url || !navigator.clipboard) return;
            navigator.clipboard.writeText(url).then(function() {
                var $label = $btn.contents().last();
                var original = $label.text();
                $label.replaceWith(' ' + d.i18n.copied);
                setTimeout(function() {
                    $btn.contents().last().replaceWith(' ' + original);
                }, 1500);
            }).catch(function() {});
        });

        // Captured Lead — click-to-copy contact fields
        $('.sitestaffr-lead-copy').on('click', function() {
            var $el = $(this);
            var value = String($el.data('copy') || '');
            if (!value || !navigator.clipboard) return;
            navigator.clipboard.writeText(value).then(function() {
                $el.addClass('is-copied');
                setTimeout(function() { $el.removeClass('is-copied'); }, 1500);
            }).catch(function() {});
        });

        // Copy the recap as plain text (more useful than a full transcript dump).
        $('.sitestaffr-copy-recap-btn').on('click', function() {
            var $btn = $(this);
            var text = $('.sitestaffr-summary-body').text().replace(/\n{3,}/g, '\n\n').trim();
            if (!text || !navigator.clipboard) return;
            navigator.clipboard.writeText(text).then(function() {
                var original = $btn.html();
                $btn.text(d.i18n.copied);
                setTimeout(function() { $btn.html(original); }, 1500);
            }).catch(function() {});
        });

        // Jump to the latest message in long transcripts
        $('.sitestaffr-jump-latest-btn').on('click', function() {
            var $items = $('.sitestaffr-transcript-item');
            if ($items.length) {
                $items.last()[0].scrollIntoView({ behavior: 'smooth', block: 'end' });
            }
        });

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

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

})(jQuery);
