<?php

namespace App\Components\Client\Witness;

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

/**
 * Concept 2 — Guided step-by-step builder. One group per step with linear
 * next/back navigation, a focused single column and a pre-generate review step.
 * Mobile-first.
 */
class WitnessBuilder extends Component
{
    use AuthorizesRequests, InteractsWithWitnessStatement;

    public int $step = 0;

    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);
    }

    /** @return array<int, string> ordered group names */
    protected function stepGroups(): array
    {
        return $this->questionnaire()->groups();
    }

    public function goToStep(int $step): void
    {
        $max = count($this->stepGroups());
        $this->step = max(0, min($step, $max)); // last index = review step
    }

    public function nextStep(): void
    {
        $this->goToStep($this->step + 1);
    }

    public function previousStep(): void
    {
        $this->goToStep($this->step - 1);
    }

    public function render()
    {
        $groups = $this->stepGroups();

        return view('components.client.witness.witness-builder', array_merge($this->witnessData(), [
            'stepGroups' => $groups,
            'isReviewStep' => $this->step >= count($groups),
            'currentGroup' => $groups[$this->step] ?? null,
        ]))->layout('layouts.dashboard');
    }
}
