@php
    // cartItems = collection/array of items
    $items = [];
    $totalValue = 0;

    foreach ($cartItems as $row) {
        // cart item theke price + qty nibo
        $price = $row['offer_price'] ?? $row['price'] ?? 0;
        $qty   = $row['qty'] ?? 1;

        $item = [
            'item_id'       => (string) ($row['id'] ?? $row['product_id'] ?? ''),
            'item_name'     => (string) ($row['name'] ?? $row['product_name'] ?? 'Product'),
            'affiliation'   => config('app.name', 'MyCommerce'),
            'item_brand'    => config('app.name', 'MyCommerce'),
            'item_category' => (string) ($row['category_name'] ?? ($row['category']->name ?? '')),
            'price'         => (float) $price,
            'quantity'      => (int) $qty,
        ];

        $items[] = $item;
        $totalValue += $price * $qty;
    }
@endphp

<script>
    window.dataLayer = window.dataLayer || [];

    function pushEcomEvent(eventName, ecommerceData) {
        window.dataLayer.push({ ecommerce: null });
        window.dataLayer.push({
            event: eventName,
            ecommerce: ecommerceData
        });
    }

    (function () {
        var items = @json($items);
        var totalValue = {{ (float) $totalValue }};

        // 1) Cart page load => view_cart
        if (items.length) {
            pushEcomEvent('view_cart', {
                currency: "BDT",
                value: totalValue,
                items: items
            });
        }

        // 2) remove_from_cart => jokhon kono remove button e click hobe
        // NOTE: cart er remove button e data-remove="1" + data-id="" add kore dibo
        document.addEventListener('click', function (e) {
            var btn = e.target.closest('[data-ga-remove="1"]');
            if (!btn) return;

            var productId = btn.getAttribute('data-product-id');

            var item = items.find(function (it) {
                return it.item_id === String(productId);
            });

            if (!item) return;

            pushEcomEvent('remove_from_cart', {
                currency: "BDT",
                value: item.price * item.quantity,
                items: [item]
            });
        });
    })();
</script>
