<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ $tenantName }} — Documentos</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="min-h-screen bg-slate-50 text-slate-900 antialiased">
    <header class="border-b border-slate-200 bg-white">
        <div class="mx-auto flex max-w-lg items-center gap-3 px-4 py-4">
            @if ($logoUrl)
                <img src="{{ $logoUrl }}" alt="" class="h-10 w-10 rounded-lg object-cover">
            @else
                <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-600 text-sm font-bold text-white">
                    {{ strtoupper(substr($tenantName, 0, 1)) }}
                </div>
            @endif
            <div>
                <p class="text-sm font-semibold">{{ $tenantName }}</p>
                <p class="text-xs text-slate-500">Envio de documentos</p>
            </div>
        </div>
    </header>

    <main class="mx-auto max-w-lg px-4 py-6" x-data="portalUpload()">
        <h1 class="text-xl font-semibold">Olá {{ $portal->greeting_name ?: '!' }}</h1>
        <p class="mt-2 text-sm text-slate-600">{{ $portal->intro_message }}</p>

        <div class="mt-5">
            <div class="mb-1 flex items-center justify-between text-xs text-slate-500">
                <span>{{ $portal->documents_total }} documentos</span>
                <span>{{ $progressPercent }}%</span>
            </div>
            <div class="h-2 overflow-hidden rounded-full bg-slate-200">
                <div class="h-full rounded-full bg-emerald-500 transition-all" style="width: {{ $progressPercent }}%"></div>
            </div>
        </div>

        <div class="mt-6 space-y-3">
            @foreach ($portal->requestedDocuments as $doc)
                @php
                    $status = $doc->status->value;
                    $hint = $comments->firstWhere('requested_document_id', $doc->id);
                @endphp
                <section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                    <div class="flex items-start justify-between gap-3">
                        <div>
                            <h2 class="font-medium">{{ $doc->label }}</h2>
                            <p class="mt-0.5 text-xs text-slate-500">{{ $doc->status->label() }}</p>
                            @if ($status === 'rejected' && $hint)
                                <p class="mt-2 rounded-lg bg-amber-50 px-2 py-1.5 text-xs text-amber-800">
                                    Motivo: {{ $hint->body }}
                                </p>
                            @endif
                            @if ($status === 'approved')
                                <p class="mt-2 text-xs font-medium text-emerald-700">✔ Documento aprovado</p>
                            @endif
                        </div>
                        @if ($status === 'approved')
                            <span class="text-emerald-600">✔</span>
                        @elseif (in_array($status, ['uploaded', 'under_analysis', 'under_review'], true))
                            <span class="text-sky-600">◐</span>
                        @else
                            <span class="text-slate-300">◯</span>
                        @endif
                    </div>

                    @if ($status !== 'approved')
                        <div class="mt-3">
                            <label
                                class="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-slate-300 bg-slate-50 px-3 py-4 text-center text-sm text-slate-600 hover:border-emerald-400 hover:bg-emerald-50/40"
                                @dragover.prevent
                                @drop.prevent="onDrop('{{ $doc->id }}', $event)"
                            >
                                <span>Selecionar arquivo ou arrastar aqui</span>
                                <span class="mt-1 text-xs text-slate-400">PDF, JPG, PNG, HEIC, DOCX</span>
                                <input
                                    type="file"
                                    accept=".pdf,.jpg,.jpeg,.png,.heic,.heif,.docx,image/*,application/pdf"
                                    capture="environment"
                                    class="sr-only"
                                    @change="onPick('{{ $doc->id }}', $event)"
                                >
                            </label>
                            <p class="mt-2 text-center text-xs text-slate-400">No celular: use a câmera 📷</p>
                            <p x-show="messages['{{ $doc->id }}']" class="mt-2 text-center text-xs" x-text="messages['{{ $doc->id }}']"></p>
                        </div>
                    @endif
                </section>
            @endforeach
        </div>

        <p class="mt-8 text-center text-xs text-slate-400">
            Seus arquivos são salvos automaticamente. Você pode voltar depois pelo mesmo link.
        </p>
    </main>

    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script>
        function portalUpload() {
            return {
                messages: {},
                async upload(docId, file, via = 'file') {
                    if (!file) return;
                    this.messages[docId] = 'Enviando…';
                    const body = new FormData();
                    body.append('requested_document_id', docId);
                    body.append('file', file);
                    body.append('uploaded_via', via);
                    try {
                        const res = await fetch(@json(route('client-portal.public.upload', $token)), {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Accept': 'application/json',
                            },
                            body,
                        });
                        const data = await res.json();
                        if (!res.ok) throw new Error(data.message || 'Falha no envio');
                        this.messages[docId] = '✔ Enviado — ' + (data.label || '');
                        setTimeout(() => location.reload(), 700);
                    } catch (e) {
                        this.messages[docId] = e.message || 'Erro ao enviar';
                    }
                },
                onPick(docId, event) {
                    const file = event.target.files?.[0];
                    this.upload(docId, file, 'camera');
                },
                onDrop(docId, event) {
                    const file = event.dataTransfer.files?.[0];
                    this.upload(docId, file, 'drop');
                },
            }
        }
    </script>
</body>
</html>
