<?php

namespace App\Components\Client\Witness;

use App\Components\Client\Concerns\InteractsWithWitnessStatement;
use App\Models\Client\Client;
use App\Models\Document\Document;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

/**
 * Concept 3 — Document-first split view. A source-document viewer on the left
 * beside the editable statement on the right, so an answer can be traced to its
 * source without leaving the page.
 */
class WitnessSplitView extends Component
{
    use AuthorizesRequests, InteractsWithWitnessStatement;

    public ?int $focusedDocumentId = null;

    public ?int $focusedPage = null;

    public function mount(Client $client): void
    {
        $this->authorize('clients.witness.view');
        $this->designMode = request()->routeIs('clients.witness.concept.*');
        $this->demoState = $this->designMode ? request()->query('state') : null;
        $this->bootWitnessWorkspace($client);
    }

    public function focusEvidence(int $evidenceItemId): void
    {
        $item = $this->service()->confirmedEvidence($this->statement())->firstWhere('id', $evidenceItemId);

        if ($item) {
            $this->focusedDocumentId = $item->document_id;
            $this->focusedPage = $item->page;
        }
    }

    public function focusExhibit(int $exhibitId): void
    {
        $exhibit = $this->statement()->exhibits()->find($exhibitId);

        if ($exhibit) {
            $this->focusedDocumentId = $exhibit->document_id;
            $this->focusedPage = $exhibit->page;
        }
    }

    public function render()
    {
        $document = $this->focusedDocumentId
            ? Document::find($this->focusedDocumentId)
            : null;

        return view('components.client.witness.witness-split-view', array_merge($this->witnessData(), [
            'focusedDocument' => $document,
            'focusedPage' => $this->focusedPage,
        ]))->layout('layouts.dashboard');
    }
}
