<?php

declare(strict_types=1);

namespace App\Support\OpsUx;

use App\Filament\Widgets\Inventory\InventoryKpiHeader;
use App\Livewire\BulkOperationProgress;
use Filament\Facades\Filament;

final class OpsUxBrowserEvents
{
    public const RunEnqueued = 'ops-ux:run-enqueued';

    public static function dispatchRunEnqueued(mixed $livewire): void
    {
        if (! is_object($livewire)) {
            return;
        }

        if (! method_exists($livewire, 'dispatch')) {
            return;
        }

        $tenantId = Filament::getTenant()?->getKey();

        // In Livewire v3, dispatch() emits a DOM event that bubbles.
        // Our progress widget is mounted outside the initiating component's DOM tree,
        // so we target it explicitly to ensure it receives the event immediately.
        $livewire->dispatch(self::RunEnqueued, tenantId: $tenantId)->to(BulkOperationProgress::class);
        $livewire->dispatch(self::RunEnqueued, tenantId: $tenantId)->to(InventoryKpiHeader::class);
    }
}
