/**
 * WPUF Invoice Menu JavaScript
 * Handles 3-dot menu interactions for the invoices table
 *
 * @since 4.2.7
 */
(function ($) {
    "use strict";

    $(document).ready(function () {
        // Toggle menu on button click
        $(".wpuf-invoice-menu-button").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            var menu = $(this).siblings(".wpuf-invoice-menu");
            var isVisible = menu.is(":visible");
            var $row = $(this).closest("tr");
            var isLastRow = $row.is(":last-child");

            // Close all other menus
            $(".wpuf-invoice-menu").hide().removeClass("wpuf-block").addClass("wpuf-hidden");
            $(".wpuf-invoice-menu").css({
                top: "",
                bottom: "",
                "margin-top": "",
                "margin-bottom": "",
            });

            // Toggle current menu
            if (!isVisible) {
                // Check if it's the last row
                if (isLastRow || $row.next("tr").length === 0) {
                    // Position menu upward for last row
                    menu.css({
                        bottom: "100%",
                        top: "auto",
                        "margin-bottom": "0.5rem",
                        "margin-top": "0",
                    });
                } else {
                    // Position menu downward for other rows
                    menu.css({
                        top: "100%",
                        bottom: "auto",
                        "margin-top": "0.5rem",
                        "margin-bottom": "0",
                    });
                }
                menu.show().removeClass("wpuf-hidden").addClass("wpuf-block");
            }
        });

        // Close menu when clicking outside
        $(document).on("click", function (e) {
            if (!$(e.target).closest(".wpuf-invoice-menu-wrapper").length) {
                $(".wpuf-invoice-menu").hide().removeClass("wpuf-block").addClass("wpuf-hidden");
            }
        });
    });
})(jQuery);
