{{--
    Injected globally (via DataController::get_additional_script) on core Purchases /
    Purchase Orders list pages. Lazily adds a "Landed Cost" item to each row's action
    dropdown when it is opened, deriving the parent type + id from the row's own
    view/edit links. The modal itself (landedcost::modal) provides the click handler.

    This is what lets the feature work from a module-only upload — no core file edits.
--}}
<script type="text/javascript">
(function () {
    function boot() {
        if (typeof window.jQuery === 'undefined') { return setTimeout(boot, 50); }
        if (window.__lcInjectInit) { return; }
        window.__lcInjectInit = true;

        var $      = window.jQuery;
        var lcRoot = @json(url('landed-cost'));
        var label  = @json(__('landedcost::lang.landed_cost'));

        // Pull {type,id} from a purchase / purchase-order link inside the dropdown.
        function findParent($menu) {
            var found = null;
            $menu.find('a[href], a[data-href]').each(function () {
                var h = $(this).attr('href') || $(this).attr('data-href') || '';
                var m = h.match(/\/(purchase-order|purchases)\/(\d+)(?:\/edit)?(?:[?#].*)?$/);
                if (m) {
                    found = { type: (m[1] === 'purchase-order') ? 'purchase_order' : 'purchase', id: m[2] };
                    return false; // break
                }
            });
            return found;
        }

        // Lazy-inject when an action dropdown is opened.
        $(document).on('click', '.dropdown-toggle', function () {
            var $menu = $(this).closest('.btn-group, .dropdown').find('.dropdown-menu').first();
            if (!$menu.length || $menu.find('.lc-expenses-btn').length) { return; }

            var p = findParent($menu);
            if (!p) { return; }

            $menu.append(
                '<li class="lc-injected"><a href="#" class="lc-expenses-btn" data-lc-base-url="' +
                lcRoot + '/' + p.type + '/' + p.id +
                '"><i class="fas fa-truck" aria-hidden="true"></i> ' + label + '</a></li>'
            );
        });
    }
    boot();
})();
</script>
