@extends('layouts.gestao')

@section('title', 'Perguntas do Protocolo')

@section('content')
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
    {{-- Breadcrumb + título --}}
    <div class="flex items-center gap-2 text-sm text-gray-500">
        <a href="{{ route('protocolos.index') }}" class="hover:text-gray-700">Protocolos</a>
        <span>/</span>
        <span class="text-gray-700">Perguntas</span>
    </div>

    <div class="mt-2 flex items-center justify-between">
        <div>
            <h1 class="text-2xl font-semibold tracking-tight text-gray-900">Perguntas</h1>
            <p class="text-sm text-gray-500">Cadastre perguntas e opções de resposta para este protocolo.</p>
        </div>
        <a href="{{ route('protocolos.index') }}" class="hidden sm:inline-flex items-center gap-2 text-sm px-3 py-2 rounded-lg border border-gray-200 text-gray-700 hover:bg-gray-50">Voltar</a>
    </div>

    {{-- Alertas --}}
    @if (session('success'))
        <div class="mt-4 rounded-lg border border-green-200 bg-green-50 text-green-800 px-4 py-3">
            {{ session('success') }}
        </div>
    @endif

    @if ($errors->any())
        <div class="mt-4 rounded-lg border border-red-200 bg-red-50 text-red-800 px-4 py-3">
            <div class="font-medium">Ocorreram erros ao enviar o formulário:</div>
            <ul class="mt-2 list-disc list-inside text-sm">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    {{-- NOVA PERGUNTA --}}
    <div class="mt-6 bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden">
        <div class="px-4 sm:px-6 py-4 border-b border-gray-200">
            <h2 class="text-base font-semibold text-gray-900">Nova Pergunta</h2>
            <p class="text-sm text-gray-500">Defina o texto, a ordem de exibição e as opções com pontuação.</p>
        </div>

        <form method="POST" action="{{ route('protocolos.perguntas.store', $protocolo) }}" class="px-4 sm:px-6 py-6 space-y-6" autocomplete="off" novalidate>
            @csrf
            <div class="grid grid-cols-1 md:grid-cols-6 gap-4">
                {{-- Pergunta --}}
                <div class="md:col-span-4">
                    <label class="block text-sm font-medium text-gray-700">Pergunta <span class="text-red-600">*</span></label>
                    <input type="text" name="texto" value="{{ old('texto') }}" class="mt-1 block w-full rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent {{ $errors->has('texto') ? 'ring-2 ring-red-500 border-transparent' : '' }}" required>
                    @if($errors->has('texto'))
                        <p class="mt-1 text-xs text-red-600">{{ $errors->first('texto') }}</p>
                    @else
                        <p class="mt-1 text-xs text-gray-500">Ex.: "Como você avalia seu nível de estresse hoje?"</p>
                    @endif
                </div>

                {{-- Ordem --}}
                <div class="md:col-span-2">
                    @php $proximaOrdem = (optional($protocolo->perguntas)->max('ordem') ?? 0) + 1; @endphp
                    <label class="block text-sm font-medium text-gray-700">Ordem <span class="text-red-600">*</span></label>
                    <input type="number" name="ordem" value="{{ old('ordem', $proximaOrdem) }}" class="mt-1 block w-full rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent {{ $errors->has('ordem') ? 'ring-2 ring-red-500 border-transparent' : '' }}">
                    @if($errors->has('ordem'))
                        <p class="mt-1 text-xs text-red-600">{{ $errors->first('ordem') }}</p>
                    @else
                        <p class="mt-1 text-xs text-gray-500">A posição em que a pergunta aparecerá.</p>
                    @endif
                </div>
            </div>

            {{-- Opções --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Opções <span class="text-red-600">*</span></label>
                <div id="opcoes-container" class="space-y-2">
                    @php $oldOpcoes = old('opcoes', []); @endphp
                    @if(!empty($oldOpcoes))
                        @foreach($oldOpcoes as $idx => $op)
                            <div class="opcao-row flex gap-2">
                                <input type="text" name="opcoes[{{ $idx }}][texto]" value="{{ $op['texto'] ?? '' }}" placeholder="Texto" class="flex-1 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                                <input type="number" name="opcoes[{{ $idx }}][pontuacao]" value="{{ $op['pontuacao'] ?? '' }}" placeholder="Pontuação" class="w-32 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                                <button type="button" class="rm-opcao inline-flex items-center justify-center w-10 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50" aria-label="Remover opção">&times;</button>
                            </div>
                        @endforeach
                    @else
                        <div class="opcao-row flex gap-2">
                            <input type="text" name="opcoes[0][texto]" placeholder="Texto" class="flex-1 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                            <input type="number" name="opcoes[0][pontuacao]" placeholder="Pontuação" class="w-32 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                            <button type="button" class="rm-opcao inline-flex items-center justify-center w-10 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50" aria-label="Remover opção">&times;</button>
                        </div>
                    @endif
                </div>
                <div class="mt-2 flex items-center gap-3">
                    <button type="button" id="add-opcao" class="text-sm inline-flex items-center gap-2 text-blue-700 hover:text-blue-800">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"><path d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"/></svg>
                        Adicionar opção
                    </button>
                    <span class="text-xs text-gray-500">Inclua pelo menos uma opção.</span>
                </div>
                @if($errors->has('opcoes'))
                    <p class="mt-2 text-xs text-red-600">{{ $errors->first('opcoes') }}</p>
                @endif
            </div>

            <div class="pt-2">
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg">Salvar Pergunta</button>
            </div>
        </form>
    </div>

    {{-- LISTA DE PERGUNTAS --}}
    <div class="mt-10">
        <h2 class="text-lg font-semibold text-gray-900">Perguntas Cadastradas</h2>
        @if($protocolo->perguntas->isEmpty())
            <div class="mt-4 px-4 py-10 text-center bg-white border border-gray-200 rounded-xl">
                <div class="mx-auto w-12 h-12 rounded-full bg-gray-100 text-gray-400 flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="currentColor"><path d="M12 6a1 1 0 011 1v4h4a1 1 0 110 2h-4v4a1 1 0 11-2 0v-4H7a1 1 0 110-2h4V7a1 1 0 011-1z"/></svg>
                </div>
                <p class="mt-3 text-sm text-gray-600">Nenhuma pergunta cadastrada ainda.</p>
            </div>
        @else
            <ul class="mt-4 space-y-3">
                @foreach ($protocolo->perguntas->sortBy('ordem') as $pergunta)
                    <li class="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
                        <div class="flex items-start justify-between gap-3">
                            <div>
                                <div class="font-medium text-gray-900">{{ $pergunta->ordem }}. {{ $pergunta->texto }}</div>
                                <ul class="mt-2 flex flex-wrap gap-2 text-sm">
                                    @foreach ($pergunta->opcoes as $opcao)
                                        <li class="inline-flex items-center gap-2 rounded-full border border-gray-200 px-3 py-1">
                                            <span class="text-gray-700">{{ $opcao->texto }}</span>
                                            <span class="text-xs rounded-full bg-gray-100 px-2 py-0.5 text-gray-700">{{ $opcao->pontuacao }} pts</span>
                                            <form action="{{ route('protocolos.perguntas.opcoes.destroy', [$protocolo, $pergunta, $opcao]) }}" method="POST" onsubmit="return confirm('Deseja excluir esta opção?')">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="text-red-600 hover:text-red-800" aria-label="Excluir opção">&times;</button>
                                            </form>
                                        </li>
                                    @endforeach
                                </ul>
                            </div>
                            <div class="flex items-center gap-2">
                                <a href="{{ route('protocolos.perguntas.edit', [$protocolo, $pergunta]) }}" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg border border-blue-200 text-blue-700 hover:bg-blue-50">Editar</a>
                                <form action="{{ route('protocolos.perguntas.destroy', [$protocolo, $pergunta]) }}" method="POST" onsubmit="return confirm('Deseja excluir esta pergunta?')">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg border border-red-200 text-red-700 hover:bg-red-50">Excluir</button>
                                </form>
                            </div>
                        </div>
                    </li>
                @endforeach
            </ul>
        @endif
    </div>
</div>

{{-- JS: adicionar/remover opções --}}
<script>
    (function(){
        const container = document.getElementById('opcoes-container');
        const btnAdd = document.getElementById('add-opcao');
        if(!container || !btnAdd) return;

        const rowTemplate = (i) => `
            <div class=\"opcao-row flex gap-2\">
                <input type=\"text\" name=\"opcoes[${i}][texto]\" placeholder=\"Texto\" class=\"flex-1 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500\" required>
                <input type=\"number\" name=\"opcoes[${i}][pontuacao]\" placeholder=\"Pontuação\" class=\"w-32 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500\" required>
                <button type=\"button\" class=\"rm-opcao inline-flex items-center justify-center w-10 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50\" aria-label=\"Remover opção\">&times;</button>
            </div>`;

        const countRows = () => container.querySelectorAll('.opcao-row').length;
        let idx = countRows();

        btnAdd.addEventListener('click', () => {
            container.insertAdjacentHTML('beforeend', rowTemplate(idx++));
        });

        container.addEventListener('click', (e) => {
            if(e.target.classList.contains('rm-opcao')){
                const rows = container.querySelectorAll('.opcao-row');
                if(rows.length <= 1) return; // mantém pelo menos 1
                e.target.closest('.opcao-row').remove();
            }
        });
    })();
</script>
@endsection
