/**
 * SiteStaffr Dashboard Page JavaScript
 *
 * Handles the "Needs your attention" section toggle, inline mark-as-read,
 * conversation row navigation, and the plan alert banner dismiss.
 *
 * Data provided via wp_localize_script as window.sitestaffrDashboardData.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.2.3
 */

(function($) {
    'use strict';

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

    $(document).ready(function() {

        // ====================================================================
        // NEEDS YOUR ATTENTION - Section toggle (state persists per browser)
        // ====================================================================

        var $newCallsSection = $('#sitestaffr-new-calls-section');
        var $toggleButton    = $('.sitestaffr-toggle-new-calls');
        var $content         = $('#sitestaffr-new-calls-content');

        var storageKey  = 'sitestaffr_new_calls_expanded';
        var hasNewCalls = $newCallsSection.hasClass('has-new-calls');
        var savedState  = localStorage.getItem(storageKey);
        var isExpanded  = savedState !== null ? (savedState === 'true') : hasNewCalls;

        function applyToggleState(expanded, animate) {
            if (expanded) {
                if (animate) { $content.slideDown(300); } else { $content.show(); }
            } else {
                if (animate) { $content.slideUp(300); } else { $content.hide(); }
            }
            $toggleButton.attr('aria-expanded', expanded ? 'true' : 'false');
            $toggleButton.find('.dashicons')
                .toggleClass('dashicons-arrow-up-alt2', expanded)
                .toggleClass('dashicons-arrow-down-alt2', !expanded);
        }

        applyToggleState(isExpanded, false);

        $('.sitestaffr-new-calls-header').on('click', function(e) {
            e.preventDefault();
            var expanding = $content.is(':hidden');
            applyToggleState(expanding, true);
            localStorage.setItem(storageKey, expanding ? 'true' : 'false');
        });

        // ====================================================================
        // PLAN ALERT BANNER DISMISS
        // ====================================================================

        $('.sitestaffr-plan-alert-dismiss').on('click', function() {
            $(this).closest('.sitestaffr-plan-alert-banner').hide();
        });

        // ====================================================================
        // CONVERSATION ROWS - click navigates to detail
        // ====================================================================

        $(document).on('click', '.sitestaffr-call-item', function(e) {
            // Buttons (Followed up) and links (tel:/mailto:) handle themselves.
            if ($(e.target).is('button, a') || $(e.target).closest('button, a').length) {
                return;
            }
            var url = $(this).data('call-url');
            if (url) {
                window.location.href = url;
            }
        });

        // ====================================================================
        // ACTIVITY - brief-conversations group expand/collapse
        // ====================================================================

        $(document).on('click', '.sitestaffr-brief-toggle', function() {
            var $toggle = $(this);
            var $items  = $toggle.siblings('.sitestaffr-brief-items');
            var expanding = $items.is('[hidden]');
            if (expanding) {
                $items.removeAttr('hidden');
            } else {
                $items.attr('hidden', 'hidden');
            }
            $toggle.attr('aria-expanded', expanding ? 'true' : 'false');
            $toggle.find('.dashicons-arrow-down-alt2, .dashicons-arrow-up-alt2')
                .toggleClass('dashicons-arrow-down-alt2', !expanding)
                .toggleClass('dashicons-arrow-up-alt2', expanding);
        });

        // ====================================================================
        // FOLLOW-UPS - inline "Followed up" (sets the handled flag; distinct
        // from read/viewed so opening a transcript never clears a follow-up)
        // ====================================================================

        function showError(message) {
            if (window.SiteStaffrModal && window.SiteStaffrModal.alertDialog) {
                window.SiteStaffrModal.alertDialog({ message: message });
            } else {
                window.alert(message);
            }
        }

        $(document).on('click', '.sitestaffr-attention-mark-read', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $button = $(this);
            var callId  = $button.data('call-id');
            var $row    = $button.closest('.sitestaffr-slip');

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

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_mark_call_handled',
                    call_id: callId,
                    nonce: d.nonces.ajax
                },
                success: function(response) {
                    if (!response.success) {
                        showError(d.i18n.errorMarkRead);
                        $button.prop('disabled', false);
                        return;
                    }
                    $row.remove();

                    var remaining = $('.sitestaffr-attention-list .sitestaffr-slip').length;
                    if (remaining > 0) {
                        $('.sitestaffr-new-calls-count').text(remaining);
                        return;
                    }
                    // Last follow-up handled — collapse the whole widget into the
                    // slim "clear" bar (matches the server-rendered empty state).
                    $newCallsSection.replaceWith(
                        '<div class="sitestaffr-followups-clear" id="sitestaffr-new-calls-section">' +
                        '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>' +
                        '<span class="sitestaffr-followups-clear-text">' +
                        '<strong>' + d.i18n.allCaughtUp + '</strong> ' + d.i18n.noNewConversations +
                        '</span></div>'
                    );
                },
                error: function() {
                    showError(d.i18n.connectionError);
                    $button.prop('disabled', false);
                }
            });
        });

    }); // end ready

})(jQuery);
