{{-- Member Loan Payment Status --}}
<x-app-layout title="Payment Status">

    <x-module-hero title="Payment Status" :description="($loanApplication->loanProduct?->name ?? 'Loan') . ' — ' . $loanApplication->reference_number" icon="fa-receipt">
        <x-slot name="backButton">
            <a href="{{ route('member.loans.show', $loanApplication) }}" class="inline-flex items-center gap-2 text-white/80 hover:text-white text-sm transition">
                <i class="fas fa-arrow-left"></i> Back to Loan
            </a>
        </x-slot>
        <x-slot name="tabs">
            <a href="{{ route('member.dashboard') }}" class="module-hero-tab">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            <a href="{{ route('member.loans.index') }}" class="module-hero-tab">
                <i class="fas fa-list"></i> My Loans
            </a>
            <a href="{{ route('member.loans.show', $loanApplication) }}" class="module-hero-tab">
                <i class="fas fa-eye"></i> Loan Details
            </a>
            <a href="{{ route('member.loans.schedule', $loanApplication) }}" class="module-hero-tab">
                <i class="fas fa-calendar"></i> Schedule
            </a>
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        <div class="max-w-2xl mx-auto">

            {{-- Status Card --}}
            <div id="status-card" class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-6">

                {{-- Processing state (default) --}}
                <div id="state-processing" class="p-8 text-center">
                    <div class="w-20 h-20 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-spinner fa-spin text-yellow-500 text-3xl"></i>
                    </div>
                    <h2 class="text-xl font-bold text-gray-900 mb-2">Waiting for Confirmation</h2>
                    <p class="text-gray-600 text-sm mb-4">
                        A payment prompt has been sent to your MTN MoMo number.<br>
                        Please check your phone and enter your PIN to confirm.
                    </p>
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-left mb-4">
                        <p class="text-xs text-yellow-800 font-semibold mb-1">What to do now:</p>
                        <ol class="text-xs text-yellow-700 space-y-1">
                            <li>1. Check your phone for an MTN MoMo payment prompt</li>
                            <li>2. Enter your MoMo PIN to approve the payment</li>
                            <li>3. This page will update automatically once confirmed</li>
                        </ol>
                    </div>
                    <p class="text-xs text-gray-400">
                        Reference: <span class="font-mono">{{ $transaction->transaction_reference }}</span>
                    </p>
                </div>

                {{-- Success state (hidden initially) --}}
                <div id="state-success" class="p-8 text-center hidden">
                    <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-check-circle text-green-500 text-3xl"></i>
                    </div>
                    <h2 class="text-xl font-bold text-gray-900 mb-2">Payment Confirmed!</h2>
                    <p class="text-gray-600 text-sm mb-4">
                        Your payment has been received and your loan balance has been updated.
                    </p>
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
                        <div class="grid grid-cols-2 gap-4 text-sm">
                            <div>
                                <div class="text-xs text-gray-500">Amount Paid</div>
                                <div class="font-bold text-green-700" id="paid-amount">—</div>
                            </div>
                            <div>
                                <div class="text-xs text-gray-500">Remaining Balance</div>
                                <div class="font-bold text-gray-900" id="remaining-balance">—</div>
                            </div>
                        </div>
                    </div>
                    <a href="{{ route('member.loans.show', $loanApplication) }}"
                       class="inline-flex items-center px-6 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm font-medium">
                        <i class="fas fa-eye mr-2"></i> View Loan Details
                    </a>
                </div>

                {{-- Failed state (hidden initially) --}}
                <div id="state-failed" class="p-8 text-center hidden">
                    <div class="w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-times-circle text-red-500 text-3xl"></i>
                    </div>
                    <h2 class="text-xl font-bold text-gray-900 mb-2">Payment Failed</h2>
                    <p class="text-gray-600 text-sm mb-4" id="failed-reason">
                        The payment was not completed. This may be because you cancelled the prompt,
                        had insufficient funds, or the request timed out.
                    </p>
                    <div class="flex flex-col sm:flex-row gap-3 justify-center">
                        <a href="{{ route('member.loans.repay', $loanApplication) }}"
                           class="inline-flex items-center justify-center px-6 py-2.5 bg-yellow-500 text-yellow-900 rounded-lg hover:bg-yellow-400 transition text-sm font-medium">
                            <i class="fas fa-redo mr-2"></i> Try Again
                        </a>
                        <a href="{{ route('member.loans.show', $loanApplication) }}"
                           class="inline-flex items-center justify-center px-6 py-2.5 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition text-sm font-medium">
                            <i class="fas fa-eye mr-2"></i> View Loan
                        </a>
                    </div>
                </div>

            </div>

            {{-- Transaction Details --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                    <h3 class="text-sm font-semibold text-gray-700">Transaction Details</h3>
                </div>
                <div class="p-6 grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <div class="text-xs text-gray-500 mb-0.5">Reference</div>
                        <div class="font-mono text-gray-900 text-xs">{{ $transaction->transaction_reference }}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-500 mb-0.5">Amount</div>
                        <div class="font-semibold text-gray-900">{{ number_format($transaction->amount, 2) }} {{ $loanApplication->currency }}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-500 mb-0.5">Phone</div>
                        <div class="font-mono text-gray-900 text-xs">{{ $transaction->payment_phone }}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-500 mb-0.5">Initiated</div>
                        <div class="text-gray-900 text-xs">{{ $transaction->initiated_at?->format('M d, Y H:i') }}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-500 mb-0.5">Status</div>
                        <div id="tx-status-badge">
                            @php
                                $txBadge = match($transaction->status) {
                                    'completed' => 'bg-green-100 text-green-700',
                                    'failed'    => 'bg-red-100 text-red-700',
                                    'cancelled' => 'bg-gray-100 text-gray-600',
                                    default     => 'bg-yellow-100 text-yellow-700',
                                };
                            @endphp
                            <span class="px-2 py-0.5 rounded-full text-xs font-semibold {{ $txBadge }}">
                                {{ ucfirst($transaction->status) }}
                            </span>
                        </div>
                    </div>
                    @if($transaction->external_reference)
                        <div>
                            <div class="text-xs text-gray-500 mb-0.5">MoMo Reference</div>
                            <div class="font-mono text-gray-900 text-xs">{{ $transaction->external_reference }}</div>
                        </div>
                    @endif
                </div>
            </div>

        </div>
    </div>

</x-app-layout>

@push('scripts')
<script>
(function () {
    const txRef   = @json($transaction->transaction_reference);
    const txId    = @json($transaction->id);
    const loanId  = @json($loanApplication->id);
    const currency = @json($loanApplication->currency);

    // Initial status from server
    let currentStatus = @json($transaction->status);

    const stateProcessing = document.getElementById('state-processing');
    const stateSuccess    = document.getElementById('state-success');
    const stateFailed     = document.getElementById('state-failed');

    function showState(state) {
        stateProcessing.classList.add('hidden');
        stateSuccess.classList.add('hidden');
        stateFailed.classList.add('hidden');
        document.getElementById('state-' + state).classList.remove('hidden');
    }

    function updateBadge(status) {
        const badge = document.getElementById('tx-status-badge');
        const colors = {
            completed: 'bg-green-100 text-green-700',
            failed:    'bg-red-100 text-red-700',
            cancelled: 'bg-gray-100 text-gray-600',
            processing:'bg-blue-100 text-blue-700',
            pending:   'bg-yellow-100 text-yellow-700',
        };
        const cls = colors[status] || 'bg-gray-100 text-gray-600';
        badge.innerHTML = `<span class="px-2 py-0.5 rounded-full text-xs font-semibold ${cls}">${status.charAt(0).toUpperCase() + status.slice(1)}</span>`;
    }

    // Apply initial state
    if (currentStatus === 'completed') {
        showState('success');
    } else if (currentStatus === 'failed' || currentStatus === 'cancelled') {
        showState('failed');
    } else {
        showState('processing');
    }

    // Poll every 5 seconds if still processing
    if (currentStatus !== 'completed' && currentStatus !== 'failed' && currentStatus !== 'cancelled') {
        let attempts = 0;
        const maxAttempts = 24; // 2 minutes total

        const poll = setInterval(async function () {
            attempts++;
            if (attempts > maxAttempts) {
                clearInterval(poll);
                // Show a timeout message inside the processing state
                const p = stateProcessing.querySelector('p');
                if (p) p.textContent = 'The payment is taking longer than expected. Please check your loan details page or contact support if the issue persists.';
                return;
            }

            try {
                const res = await fetch(`/member/loans/${loanId}/payment-status-check/${txId}`, {
                    headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
                });
                if (!res.ok) return;
                const data = await res.json();

                currentStatus = data.status;
                updateBadge(currentStatus);

                if (currentStatus === 'completed') {
                    clearInterval(poll);
                    if (data.amount_paid) {
                        document.getElementById('paid-amount').textContent =
                            parseFloat(data.amount_paid).toFixed(2) + ' ' + currency;
                    }
                    if (data.outstanding_balance !== undefined) {
                        document.getElementById('remaining-balance').textContent =
                            parseFloat(data.outstanding_balance).toFixed(2) + ' ' + currency;
                    }
                    showState('success');
                } else if (currentStatus === 'failed' || currentStatus === 'cancelled') {
                    clearInterval(poll);
                    if (data.error_message) {
                        document.getElementById('failed-reason').textContent = data.error_message;
                    }
                    showState('failed');
                }
            } catch (e) {
                // Network error — keep polling
            }
        }, 5000);
    }
})();
</script>
@endpush
