@props([
    'question',           // App\Support\Witness\WitnessQuestion
    'sectionKey',
    'value' => null,      // current buffer value
    'meta' => null,       // App\Models\Witness\WitnessStatementAnswer|null
    'showOrigin' => true,
    'validationRequested' => false,
    'touched' => [],
])

@php
    $model = "answers.$sectionKey.{$question->key}";
    $fieldId = "wq-$sectionKey-{$question->key}";
    $key = "$sectionKey.{$question->key}";
    $isSuggested = $meta && $meta->review_status === 'suggested';
    $isRequiredMissing = $question->required && ! $question->isAnswered($value) && ! $isSuggested;
    // Validation stays neutral until requested or the field has been interacted with.
    $showError = $isRequiredMissing && ($validationRequested || in_array($key, $touched, true));
    $describedBy = collect([$question->help ? "$fieldId-help" : null, $showError ? "$fieldId-error" : null])->filter()->implode(' ');
    $isProvenance = $meta && $meta->origin === 'evidence' && in_array($meta->review_status, ['accepted', 'edited'], true);
@endphp

<div class="witness-question mb-4" wire:key="q-{{ $sectionKey }}-{{ $question->key }}">
    <label for="{{ $fieldId }}" class="form-label fw-semibold mb-1 d-flex align-items-center gap-2 flex-wrap">
        <span>
            {{ $question->label }}
            @if($question->required)
                <span class="text-muted" title="Required before generation" aria-hidden="true">*</span>
                <span class="visually-hidden">(required)</span>
            @endif
        </span>
        @if($showOrigin && $meta && ! $isSuggested)
            <x-witness.review-status :status="$meta->review_status" :origin="$meta->origin" />
        @endif
    </label>

    @if($question->help)
        <div id="{{ $fieldId }}-help" class="form-text mt-0 mb-2">{{ $question->help }}</div>
    @endif

    @switch($question->type)
        @case('long_text')
            <textarea id="{{ $fieldId }}" rows="5"
                      class="form-control @if($showError) is-invalid @endif"
                      wire:model="{{ $model }}"
                      wire:change="saveAnswer('{{ $sectionKey }}', '{{ $question->key }}')"
                      @if($describedBy) aria-describedby="{{ $describedBy }}" @endif
                      @if($showError) aria-invalid="true" @endif></textarea>
            @break

        @case('date')
            <input type="date" id="{{ $fieldId }}" style="max-width: 16rem;"
                   class="form-control @if($showError) is-invalid @endif"
                   wire:model="{{ $model }}"
                   wire:change="saveAnswer('{{ $sectionKey }}', '{{ $question->key }}')"
                   @if($showError) aria-invalid="true" aria-describedby="{{ $describedBy }}" @endif>
            @break

        @case('select')
            <select id="{{ $fieldId }}" style="max-width: 24rem;"
                    class="form-select @if($showError) is-invalid @endif"
                    wire:model="{{ $model }}"
                    wire:change="saveAnswer('{{ $sectionKey }}', '{{ $question->key }}')"
                    @if($showError) aria-invalid="true" aria-describedby="{{ $describedBy }}" @endif>
                <option value="">— Select —</option>
                @foreach($question->options as $opt)
                    <option value="{{ $opt }}">{{ $opt }}</option>
                @endforeach
            </select>
            @break

        @case('boolean')
        @case('declaration')
            <div class="btn-group" role="group" aria-label="{{ $question->label }}">
                <button type="button"
                        class="btn {{ $value === true ? 'btn-success' : 'btn-outline-success' }}"
                        aria-pressed="{{ $value === true ? 'true' : 'false' }}"
                        wire:click="saveBoolean('{{ $sectionKey }}', '{{ $question->key }}', true)">
                    <span class="mdi mdi-check" aria-hidden="true"></span> Yes
                </button>
                <button type="button"
                        class="btn {{ $value === false ? 'btn-danger' : 'btn-outline-danger' }}"
                        aria-pressed="{{ $value === false ? 'true' : 'false' }}"
                        wire:click="saveBoolean('{{ $sectionKey }}', '{{ $question->key }}', false)">
                    <span class="mdi mdi-close" aria-hidden="true"></span> No
                </button>
            </div>
            @break

        @case('multiselect')
            {{-- Selectable chips with large touch targets. --}}
            <div role="group" aria-label="{{ $question->label }}"
                 class="d-flex flex-wrap gap-2 @if($showError) border border-danger rounded p-2 @endif">
                @foreach($question->options as $opt)
                    <input type="checkbox" class="btn-check" id="{{ $fieldId }}-{{ $loop->index }}"
                           value="{{ $opt }}" wire:model="{{ $model }}"
                           wire:change="saveAnswer('{{ $sectionKey }}', '{{ $question->key }}')">
                    <label class="btn btn-sm btn-outline-primary rounded-pill" for="{{ $fieldId }}-{{ $loop->index }}">{{ $opt }}</label>
                @endforeach
            </div>
            @break

        @case('repeater')
            @php $rows = is_array($value) ? $value : []; @endphp
            <div class="witness-repeater border rounded p-2">
                @forelse($rows as $index => $row)
                    <div class="row g-2 align-items-end mb-2 pb-2 border-bottom" wire:key="rep-{{ $sectionKey }}-{{ $question->key }}-{{ $index }}">
                        @foreach($question->fields as $sub)
                            <div class="col-md">
                                <label class="form-label small text-muted mb-0" for="{{ $fieldId }}-{{ $index }}-{{ $sub->key }}">{{ $sub->label }}</label>
                                <input type="text" id="{{ $fieldId }}-{{ $index }}-{{ $sub->key }}" class="form-control form-control-sm"
                                       wire:model="answers.{{ $sectionKey }}.{{ $question->key }}.{{ $index }}.{{ $sub->key }}"
                                       wire:change="saveAnswer('{{ $sectionKey }}', '{{ $question->key }}')">
                            </div>
                        @endforeach
                        <div class="col-md-auto">
                            <button type="button" class="btn btn-sm btn-outline-danger"
                                    wire:click="removeRepeaterRow('{{ $sectionKey }}', '{{ $question->key }}', {{ $index }})"
                                    aria-label="Remove row {{ $index + 1 }}">
                                <span class="mdi mdi-delete-outline" aria-hidden="true"></span>
                            </button>
                        </div>
                    </div>
                @empty
                    <p class="text-muted small mb-2">No entries yet.</p>
                @endforelse
                <button type="button" class="btn btn-sm btn-outline-primary"
                        wire:click="addRepeaterRow('{{ $sectionKey }}', '{{ $question->key }}')">
                    <span class="mdi mdi-plus" aria-hidden="true"></span> Add entry
                </button>
            </div>
            @break

        @default
            <input type="text" id="{{ $fieldId }}"
                   class="form-control @if($showError) is-invalid @endif"
                   wire:model="{{ $model }}"
                   wire:change="saveAnswer('{{ $sectionKey }}', '{{ $question->key }}')"
                   @if($describedBy) aria-describedby="{{ $describedBy }}" @endif
                   @if($showError) aria-invalid="true" @endif>
    @endswitch

    {{-- Provenance: an accepted evidence answer keeps a compact trace. --}}
    @if($isProvenance && ($meta->provenance['excerpt'] ?? null))
        <div class="form-text text-success-emphasis mt-1">
            <span class="mdi mdi-source-branch" aria-hidden="true"></span>
            Accepted from {{ $meta->provenance['document'] ?? 'evidence' }}@if($meta->provenance['page'] ?? null), page {{ $meta->provenance['page'] }}@endif
        </div>
    @endif

    @if($showError)
        <div id="{{ $fieldId }}-error" class="invalid-feedback d-block small">
            This answer is required before the statement can be generated.
        </div>
    @elseif($isRequiredMissing)
        <div class="form-text small"><span class="mdi mdi-asterisk" aria-hidden="true" style="font-size:.6rem;"></span> Required for generation</div>
    @endif
</div>
