<x-app-layout>
    @php
        $statusBadge = fn($s) => match($s) {
            'pending'     => 'bg-warning text-dark',
            'in_progress' => 'bg-primary',
            'completed'   => 'bg-success',
            'approved'    => 'bg-success',
            'rejected'    => 'bg-danger',
            default       => 'bg-secondary',
        };
        $activeStage = $token->activeStage();
    @endphp

    <div class="row g-4">
        <!-- ── Left column ── -->
        <div class="col-lg-8">

            <!-- Token Details -->
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div>
                            <h1 class="h3 fw-bold mb-1">{{ $token->title }}</h1>
                            <p class="text-muted mb-0">{{ $token->category->name }}</p>
                        </div>
                        <span class="badge {{ $statusBadge($token->status) }} fs-6 px-3 py-2">
                            {{ ucfirst(str_replace('_', ' ', $token->status)) }}
                        </span>
                    </div>

                    <div class="row g-3 border-top border-bottom py-3 mb-3">
                        <div class="col-6">
                            <p class="text-muted small mb-1">Created By</p>
                            <p class="fw-medium mb-0">{{ $token->creator->name }}</p>
                        </div>
                        <div class="col-6">
                            <p class="text-muted small mb-1">Created Date</p>
                            <p class="fw-medium mb-0">{{ $token->created_at->format('M d, Y H:i') }}</p>
                        </div>
                    </div>

                    @if ($token->pdf_path || in_array($token->status, ['completed', 'approved', 'rejected']))
                        <div class="d-flex flex-wrap gap-2 mb-3">
                            @if ($token->pdf_path)
                                <a href="{{ Storage::url($token->pdf_path) }}" target="_blank"
                                   class="btn btn-outline-secondary btn-sm">
                                    <i class="bi bi-paperclip me-1"></i>Download Attachment
                                </a>
                            @endif
                            @if (in_array($token->status, ['completed', 'approved', 'rejected']))
                                <a href="{{ route('tokens.summary-pdf', $token) }}" target="_blank"
                                   class="btn btn-outline-secondary btn-sm">
                                    <i class="bi bi-file-earmark-pdf me-1"></i>Download Summary PDF
                                </a>
                            @endif
                        </div>
                    @endif

                    <h6 class="fw-semibold mb-2">Description</h6>
                    <div class="bg-light rounded-3 p-3 text-secondary" style="font-size:.9375rem">
                        {!! $token->description !!}
                    </div>
                </div>
            </div>

            <!-- Approval Timeline -->
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white fw-semibold py-3">
                    <i class="bi bi-diagram-3 me-2 text-primary"></i>Approval Timeline
                </div>
                <div class="card-body p-4">
                    @forelse ($token->tokenApprovals as $approval)
                        @php
                            $isApproved = $approval->status === 'approved';
                            $isRejected = $approval->status === 'rejected';
                        @endphp
                        <div class="d-flex gap-3 {{ $loop->last ? '' : 'mb-4' }}">
                            <!-- Icon + connector -->
                            <div class="d-flex flex-column align-items-center flex-shrink-0">
                                <div class="rounded-circle d-flex align-items-center justify-content-center
                                    {{ $isApproved ? 'bg-success' : ($isRejected ? 'bg-danger' : 'bg-warning') }}"
                                     style="width:38px;height:38px">
                                    <i class="bi {{ $isApproved ? 'bi-check-lg' : ($isRejected ? 'bi-x-lg' : 'bi-hourglass-split') }} text-white"></i>
                                </div>
                                @if (!$loop->last)
                                    <div class="flex-grow-1 border-start border-2 border-light my-1" style="min-height:28px"></div>
                                @endif
                            </div>

                            <!-- Content -->
                            <div class="flex-grow-1 pb-1">
                                <div class="d-flex justify-content-between align-items-start mb-1">
                                    <div>
                                        <p class="fw-semibold mb-0">{{ $approval->stage->department->name }}</p>
                                        <p class="text-muted small mb-0">{{ $approval->stage->role ?? $approval->stage->designation }}</p>
                                    </div>
                                    <span class="badge {{ $isApproved ? 'bg-success' : ($isRejected ? 'bg-danger' : 'bg-warning text-dark') }}">
                                        {{ ucfirst($approval->status) }}
                                    </span>
                                </div>
                                @if ($approval->approver)
                                    <p class="text-muted small mb-1">
                                        <span class="fw-medium text-dark">{{ $approval->approver->name }}</span>
                                        @if ($approval->acted_at)
                                            &mdash; {{ $approval->acted_at->format('M d, Y H:i') }}
                                        @endif
                                    </p>
                                @endif
                                @if ($approval->remarks)
                                    <div class="bg-light rounded-2 p-2 small text-secondary">
                                        <i class="bi bi-chat-left-text me-1"></i><strong>Remarks:</strong> {{ $approval->remarks }}
                                    </div>
                                @endif
                            </div>
                        </div>
                    @empty
                        <p class="text-muted mb-0">No approval records yet.</p>
                    @endforelse
                </div>
            </div>
        </div>

        <!-- ── Right column / Action Panel ── -->
        <div class="col-lg-4" id="decline">
            @if ($canApprove)
                <div class="card border-0 shadow-sm sticky-top" style="top:80px">
                    <div class="card-header bg-primary text-white fw-semibold py-3">
                        <i class="bi bi-lightning-charge me-2"></i>Your Action Required
                    </div>
                    <div class="card-body p-4">
                        @if ($activeStage)
                            <p class="text-muted small mb-3">
                                Stage: <strong>{{ $activeStage->department->name }}</strong> &mdash; {{ $activeStage->role }}
                            </p>
                        @endif

                        <!-- Approve form -->
                        <form action="{{ route('tokens.approve', $token) }}" method="POST" id="approveForm" class="mb-2">
                            @csrf
                            <input type="hidden" name="remarks" id="approve-remarks">
                            <div class="mb-3">
                                <label for="remarks" class="form-label fw-medium small">
                                    Remarks <span class="text-muted fw-normal">(optional)</span>
                                </label>
                                <textarea id="remarks" rows="3" class="form-control form-control-sm"
                                          placeholder="Add any comments..."></textarea>
                            </div>
                            <button type="button" onclick="submitApprove()" class="btn btn-success w-100 mb-2">
                                <i class="bi bi-check-circle me-1"></i>Approve Request
                            </button>
                        </form>

                        <!-- Decline toggle -->
                        <button class="btn btn-danger w-100" type="button"
                                data-bs-toggle="collapse" data-bs-target="#declineCollapse" aria-expanded="false">
                            <i class="bi bi-x-circle me-1"></i>Decline Request
                        </button>
                        <div class="collapse mt-3" id="declineCollapse">
                            <form action="{{ route('tokens.decline', $token) }}" method="POST" id="declineForm">
                                @csrf
                                <div class="mb-3">
                                    <label class="form-label fw-medium small">Reason for Declining <span class="text-danger">*</span></label>
                                    <textarea name="remarks" id="decline-remarks" rows="3" class="form-control form-control-sm"
                                              placeholder="Required — provide a reason..." required></textarea>
                                </div>
                                <button type="submit" class="btn btn-danger btn-sm w-100">
                                    <i class="bi bi-x-circle me-1"></i>Confirm Decline
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

            @elseif ($token->status === 'in_progress')
                <div class="card border-0 shadow-sm sticky-top" style="top:80px">
                    <div class="card-header bg-white fw-semibold py-3">Status</div>
                    <div class="card-body p-4">
                        <div class="alert alert-info mb-0">
                            <strong>Currently awaiting:</strong><br>
                            @if ($activeStage)
                                {{ $activeStage->department->name }} ({{ $activeStage->role }})
                                @if ($activeStage->pinnedUser)
                                    &mdash; {{ $activeStage->pinnedUser->name }}
                                @endif
                            @else
                                Next stage
                            @endif
                        </div>
                    </div>
                </div>

            @else
                <div class="card border-0 shadow-sm sticky-top" style="top:80px">
                    <div class="card-header bg-white fw-semibold py-3">Request Closed</div>
                    <div class="card-body p-4">
                        <p class="text-muted mb-0">This request is no longer under review.</p>
                    </div>
                </div>
            @endif
        </div>
    </div>

    @push('scripts')
    <script>
        function submitApprove() {
            document.getElementById('approve-remarks').value = document.getElementById('remarks').value;
            document.getElementById('approveForm').submit();
        }
    </script>
    @endpush
</x-app-layout>