<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\ContractRequest;
use Livewire\Attributes\On;
use Livewire\Component;

/**
 * Lists a client's e-signature requests with their aggregate status, and an
 * offcanvas drill-down: each request's Fintrixor documents, each document's
 * status + full webhook event timeline. Mirrors CommunicationTimeline.
 */
class EsignTimeline extends Component
{
    public Client $client;

    /** ID of the request whose documents/events are open in the offcanvas. */
    public ?int $openRequestId = null;

    public function mount(Client $client): void
    {
        $this->client = $client;
    }

    #[On('esignRequestSent')]
    public function refreshTimeline(): void
    {
        $this->openRequestId = null;
    }

    public function openRequest(int $id): void
    {
        $this->openRequestId = $id;
        $this->dispatch('esign-open-offcanvas');
    }

    public function closeRequest(): void
    {
        $this->openRequestId = null;
    }

    public function render()
    {
        $requests = $this->client->contractRequests()
            ->withCount('esignDocuments')
            ->latest()
            ->get();

        $openRequest = $this->openRequestId
            ? ContractRequest::with(['esignDocuments.contract', 'esignDocuments.esignEvents'])
                ->find($this->openRequestId)
            : null;

        return view('components.client.esign-timeline', compact('requests', 'openRequest'));
    }
}
