<!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 }} — Assinatura</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>[x-cloak]{display:none!important}</style>
</head>
<body class="min-h-screen bg-slate-50 text-slate-900 antialiased" x-data="signaturePortal()" x-cloak>
    <header class="border-b border-slate-200 bg-white">
        <div class="mx-auto flex max-w-2xl 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">{{ $request->title }} · {{ $signer->role->label() }}</p>
            </div>
        </div>
    </header>

    <main class="mx-auto max-w-2xl px-4 py-6">
        @if ($request->message)
            <p class="mb-4 rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">{{ $request->message }}</p>
        @endif

        <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm prose prose-sm max-w-none">
            {!! $version?->html_body !!}
        </div>

        @if ($canSign)
            <section class="mt-6 space-y-4 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h2 class="text-sm font-semibold">Assinar documento</h2>
                <p class="text-xs text-slate-500">Digite seu nome completo e confirme com o código enviado por WhatsApp.</p>

                <div>
                    <label class="block text-xs font-medium text-slate-600">Nome completo</label>
                    <input type="text" x-model="typedName" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Como consta no documento">
                </div>

                <div class="flex flex-wrap items-end gap-2">
                    <div class="flex-1">
                        <label class="block text-xs font-medium text-slate-600">Código de verificação</label>
                        <input type="text" x-model="otp" maxlength="6" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm tracking-widest" placeholder="000000">
                    </div>
                    <button type="button" @click="requestOtp()" :disabled="otpLoading" class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700">
                        <span x-text="otpLoading ? 'Enviando…' : 'Receber código'"></span>
                    </button>
                </div>

                <div class="flex flex-wrap gap-2">
                    <button type="button" @click="sign()" class="rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white">Assinar</button>
                    <button type="button" @click="confirmReject = true" class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700">Recusar</button>
                </div>

                <p class="text-xs text-slate-500" x-text="message"></p>
            </section>
        @else
            <p class="mt-6 rounded-lg bg-slate-100 px-4 py-3 text-sm text-slate-700">
                Status: {{ $signer->status->label() }} · {{ $request->status->label() }}
            </p>
        @endif
    </main>

    <div
        x-show="confirmReject"
        x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
        @click.self="confirmReject = false"
        style="display: none;"
    >
        <div class="w-full max-w-sm rounded-xl bg-white p-5 shadow-lg" role="dialog" aria-modal="true" @click.stop>
            <h3 class="text-base font-semibold text-slate-900">Recusar a assinatura?</h3>
            <p class="mt-2 text-sm text-slate-600">Você não poderá assinar este documento depois de recusar.</p>
            <div class="mt-4 flex justify-end gap-2">
                <button type="button" class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-50" @click="confirmReject = false">
                    Voltar
                </button>
                <button type="button" class="rounded-lg bg-red-600 px-3 py-1.5 text-sm font-semibold text-white hover:bg-red-500" @click="reject()">
                    Sim, recusar
                </button>
            </div>
        </div>
    </div>

    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script>
        function signaturePortal() {
            return {
                typedName: @json($signer->name),
                otp: '',
                message: '',
                otpLoading: false,
                confirmReject: false,
                async requestOtp() {
                    this.otpLoading = true;
                    this.message = 'Enviando código…';
                    const res = await fetch(@json(route('signatures.public.otp', $token)), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json',
                        },
                    });
                    const data = await res.json();
                    this.otpLoading = false;
                    if (!res.ok) { this.message = data.message || 'Erro ao enviar código.'; return; }
                    this.message = 'Código enviado. Verifique seu WhatsApp.';
                },
                async sign() {
                    this.message = 'Registrando assinatura…';
                    const res = await fetch(@json(route('signatures.public.sign', $token)), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json',
                        },
                        body: JSON.stringify({ typed_name: this.typedName, otp: this.otp }),
                    });
                    const data = await res.json();
                    if (!res.ok) { this.message = data.message || 'Erro ao assinar.'; return; }
                    this.message = 'Documento assinado. Obrigado!';
                    setTimeout(() => location.reload(), 800);
                },
                async reject() {
                    this.confirmReject = false;
                    this.message = 'Registrando recusa…';
                    const res = await fetch(@json(route('signatures.public.reject', $token)), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json',
                        },
                        body: JSON.stringify({ reason: null }),
                    });
                    const data = await res.json();
                    if (!res.ok) { this.message = data.message || 'Erro ao recusar.'; return; }
                    this.message = 'Recusa registrada.';
                    setTimeout(() => location.reload(), 800);
                },
            };
        }
    </script>
</body>
</html>
