/**
 * SiteStaffr Dashboard Page JavaScript
 *
 * Handles the new-calls section toggle, carousel navigation,
 * progress circle tooltip, call row inline actions, and mark-read/unread AJAX.
 *
 * 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() {

        // ====================================================================
        // NEW CALLS SECTION - Toggle
        // ====================================================================

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

        // Get saved state from localStorage (or default to expanded if has new calls)
        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;

        // Apply initial state
        if (isExpanded) {
            $content.show();
            $toggleButton.attr('aria-expanded', 'true');
            $toggleButton.find('.dashicons').removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
        } else {
            $content.hide();
            $toggleButton.attr('aria-expanded', 'false');
            $toggleButton.find('.dashicons').removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
        }

        // Toggle functionality - entire header is clickable
        var $header = $('.sitestaffr-new-calls-header');

        $header.on('click', function(e) {
            // Prevent event bubbling
            e.preventDefault();
            e.stopPropagation();

            var expanding = $content.is(':hidden');

            if (expanding) {
                $content.slideDown(300);
                $toggleButton.attr('aria-expanded', 'true');
                $toggleButton.find('.dashicons').removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
                localStorage.setItem(storageKey, 'true');
            } else {
                $content.slideUp(300);
                $toggleButton.attr('aria-expanded', 'false');
                $toggleButton.find('.dashicons').removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
                localStorage.setItem(storageKey, 'false');
            }
        });

        // ====================================================================
        // CAROUSEL - New Calls
        // ====================================================================

        var $carousel    = $('.sitestaffr-new-calls-carousel');
        var $slides      = $('.sitestaffr-carousel-slide');
        var $prevBtn     = $('.sitestaffr-carousel-prev');
        var $nextBtn     = $('.sitestaffr-carousel-next');
        var $dots        = $('.sitestaffr-carousel-dot');
        var currentSlide = 0;
        var totalSlides  = $slides.length;

        function measureSlideHeight($slide) {
            if (!$slide || !$slide.length) {
                return 0;
            }
            if ($slide.hasClass('active')) {
                return $slide.outerHeight();
            }
            $slide.addClass('sitestaffr-slide-measuring');
            var height = $slide.outerHeight();
            $slide.removeClass('sitestaffr-slide-measuring');
            return height;
        }

        function syncCarouselHeight(targetIndex, animateHeight) {
            if (!$carousel.length || !$slides.length) {
                return;
            }
            var $target      = $slides.eq(targetIndex);
            var targetHeight = measureSlideHeight($target);
            if (!targetHeight || targetHeight < 1) {
                return;
            }
            if (animateHeight) {
                $carousel.stop(true, false).animate({ height: targetHeight }, 140);
            } else {
                $carousel.css('height', targetHeight);
            }
        }

        function showSlide(index) {
            // Wrap around
            if (index >= totalSlides) {
                currentSlide = 0;
            } else if (index < 0) {
                currentSlide = totalSlides - 1;
            } else {
                currentSlide = index;
            }

            // Update slides
            $slides.removeClass('active').eq(currentSlide).addClass('active');

            // Update dots
            $dots.removeClass('active').eq(currentSlide).addClass('active');

            // Prevent visual "jump" when slides have different content heights.
            syncCarouselHeight(currentSlide, true);
        }

        // Set initial slide height once on load.
        syncCarouselHeight(currentSlide, false);

        // Navigation buttons
        $prevBtn.on('click', function() {
            showSlide(currentSlide - 1);
        });

        $nextBtn.on('click', function() {
            showSlide(currentSlide + 1);
        });

        // Indicator dots
        $dots.on('click', function() {
            var slideIndex = parseInt($(this).data('slide-to'));
            showSlide(slideIndex);
        });

        // Keyboard navigation
        $(document).on('keydown', function(e) {
            if ($content.is(':visible') && totalSlides > 1) {
                if (e.key === 'ArrowLeft') {
                    showSlide(currentSlide - 1);
                } else if (e.key === 'ArrowRight') {
                    showSlide(currentSlide + 1);
                }
            }
        });

        $(window).on('resize', function() {
            syncCarouselHeight(currentSlide, false);
        });

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

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

        // ====================================================================
        // CIRCULAR PROGRESS TOOLTIP
        // ====================================================================

        var $progressContainer = $('.sitestaffr-progress-circle-container');

        $progressContainer.on('mouseenter', function() {
            var $tooltipEl = $(this).find('.sitestaffr-balance-tooltip');
            if ($tooltipEl.length) {
                $tooltipEl.fadeIn(200);
            }
        });

        $progressContainer.on('mouseleave', function() {
            var $tooltipEl = $(this).find('.sitestaffr-balance-tooltip');
            if ($tooltipEl.length) {
                $tooltipEl.fadeOut(200);
            }
        });

        // ====================================================================
        // INLINE HOVER ACTIONS - Call Rows
        // ====================================================================

        var lastTappedRow = null;
        var isDesktop     = $(window).width() > 782;

        // Click on row background navigates to details
        $('.sitestaffr-call-item').on('click', function(e) {
            var $row     = $(this);
            var $actions = $row.find('.sitestaffr-call-actions');

            // If clicking a button, let it handle
            if ($(e.target).is('button') || $(e.target).closest('button').length) {
                return;
            }

            // Mobile: First tap shows actions, second tap navigates
            if (!isDesktop) {
                if (lastTappedRow !== this) {
                    e.preventDefault();
                    $('.sitestaffr-call-actions').hide();
                    $actions.show();
                    lastTappedRow = this;
                    return;
                }
                // Second tap: fall through to navigate
            }

            var url = $row.data('call-url');
            if (url) {
                window.location.href = url;
            }
        });

        // View Details button
        $('.sitestaffr-call-action-view').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var url = $(this).closest('.sitestaffr-call-item').data('call-url');
            if (url) {
                window.location.href = url;
            }
        });

        // Mark as Read button (AJAX)
        $(document).on('click', '.sitestaffr-call-action-mark-read', function(e) {
            e.preventDefault();
            e.stopPropagation();

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

            $button.prop('disabled', true).text(d.i18n.marking);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_mark_call_read',
                    call_id: callId,
                    nonce: d.nonces.ajax
                },
                success: function(response) {
                    if (response.success) {
                        $row.find('.sitestaffr-badge-new').fadeOut(300, function() {
                            $(this).remove();
                        });
                        $row.removeClass('sitestaffr-call-unread');
                        $button.replaceWith(
                            '<button class="sitestaffr-call-action-secondary sitestaffr-call-action-mark-unread"' +
                            ' data-call-id="' + callId + '" title="' + d.i18n.markAsUnreadTitle + '">' +
                            d.i18n.markUnread + '</button>'
                        );
                    } else {
                        window.alert(d.i18n.errorMarkRead);
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    window.alert(d.i18n.connectionError);
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // Mark as Unread button (AJAX)
        $(document).on('click', '.sitestaffr-call-action-mark-unread', function(e) {
            e.preventDefault();
            e.stopPropagation();

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

            $button.prop('disabled', true).text(d.i18n.marking);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_mark_call_unread',
                    call_id: callId,
                    nonce: d.nonces.ajax
                },
                success: function(response) {
                    if (response.success) {
                        if ($row.find('.sitestaffr-badge-new').length === 0) {
                            $row.find('.sitestaffr-call-number').append(
                                '<span class="sitestaffr-badge-new">' + d.i18n.newBadge + '</span>'
                            );
                        }
                        $row.addClass('sitestaffr-call-unread');
                        $button.replaceWith(
                            '<button class="sitestaffr-call-action-secondary sitestaffr-call-action-mark-read"' +
                            ' data-call-id="' + callId + '" title="' + d.i18n.markAsReadTitle + '">' +
                            d.i18n.markRead + '</button>'
                        );
                    } else {
                        window.alert(d.i18n.errorMarkUnread);
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    window.alert(d.i18n.connectionError);
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // ====================================================================
        // NEW CALLS CAROUSEL - Mark as Read Link
        // ====================================================================

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

            var $button      = $(this);
            var callId       = $button.data('call-id');
            var $slide       = $button.closest('.sitestaffr-carousel-slide');
            var $carouselEl  = $('.sitestaffr-new-calls-carousel');
            var $widget      = $('#sitestaffr-new-calls-section');
            var originalText = $button.text();

            $button.prop('disabled', true).text(d.i18n.marking);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_mark_call_read',
                    call_id: callId,
                    nonce: d.nonces.ajax
                },
                success: function(response) {
                    if (response.success) {
                        $slide.fadeOut(300, function() {
                            $slide.remove();

                            var $remainingSlides = $('.sitestaffr-carousel-slide');

                            if ($remainingSlides.length === 0) {
                                // No more new calls - show empty state
                                var $contentEl = $('#sitestaffr-new-calls-content');
                                $contentEl.html(
                                    '<div class="sitestaffr-new-calls-empty">' +
                                    '<span class="dashicons dashicons-yes-alt"></span>' +
                                    '<p>' + d.i18n.allCaughtUp + '</p>' +
                                    '<span class="sitestaffr-empty-subtitle">' + d.i18n.noNewConversations + '</span>' +
                                    '</div>'
                                );
                                $widget.removeClass('has-new-calls').addClass('no-new-calls');
                                $('.sitestaffr-new-calls-count').remove();
                            } else {
                                $remainingSlides.first().addClass('active').fadeIn(300);

                                var $indicators = $('.sitestaffr-carousel-indicators');
                                if ($indicators.length) {
                                    $indicators.empty();
                                    $remainingSlides.each(function(index) {
                                        var activeClass = index === 0 ? 'active' : '';
                                        $indicators.append(
                                            '<button type="button" class="sitestaffr-carousel-dot ' + activeClass +
                                            '" data-slide-to="' + index + '" aria-label="Go to call ' + (index + 1) + '"></button>'
                                        );
                                    });
                                }

                                $('.sitestaffr-new-calls-count').text($remainingSlides.length);
                            }
                        });
                    } else {
                        window.alert(d.i18n.errorMarkRead);
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    window.alert(d.i18n.connectionError);
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // ====================================================================
        // RESPONSIVE - Update isDesktop on resize
        // ====================================================================

        $(window).on('resize', function() {
            isDesktop = $(window).width() > 782;
            if (isDesktop) {
                lastTappedRow = null;
                $('.sitestaffr-call-actions').hide();
            }
        });

    }); // end ready

})(jQuery);
