@extends('layouts.app')

@section('title', 'Recruitment Dashboard')

@section('content')
    @include('recruitment.top-submenu')

    @php
        $ctx = $ctx ?? [];
        $kpis = $ctx['kpis'] ?? [];
        $actionQueue = $ctx['action_queue'] ?? [];
        $quickActions = $ctx['quick_actions'] ?? [];
        $toneClasses = [
            'sky' => 'text-sky-600 bg-sky-100',
            'emerald' => 'text-emerald-600 bg-emerald-100',
            'amber' => 'text-amber-600 bg-amber-100',
            'indigo' => 'text-indigo-600 bg-indigo-100',
            'rose' => 'text-rose-600 bg-rose-100',
            'slate' => 'text-slate-600 bg-slate-100',
        ];
        $kpiLeftAccents = [
            'sky' => 'bg-sky-500',
            'emerald' => 'bg-emerald-500',
            'amber' => 'bg-amber-500',
            'indigo' => 'bg-indigo-500',
            'rose' => 'bg-rose-500',
            'slate' => 'bg-slate-400',
        ];
        $accentCycle = ['sky', 'emerald', 'amber', 'indigo', 'rose', 'violet'];
        $accentBgs = [
            'sky' => 'bg-sky-500',
            'emerald' => 'bg-emerald-500',
            'amber' => 'bg-amber-500',
            'indigo' => 'bg-indigo-500',
            'rose' => 'bg-rose-500',
            'violet' => 'bg-violet-500',
        ];
    @endphp

    <div class="space-y-6">
        <div class="rounded-xl border border-slate-200 bg-gradient-to-r from-teal-800 via-teal-700 to-slate-800 px-5 py-5 text-white shadow-sm">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <p class="text-xs font-semibold uppercase tracking-wider text-white/60">{{ $ctx['greeting'] ?? 'Recruitment' }}</p>
                    <h1 class="mt-1 text-xl font-semibold">Hiring pipeline overview</h1>
                    <p class="mt-1 text-sm text-white/75">{{ $ctx['date_label'] ?? now()->format('l, j F Y') }}</p>
                </div>
                @if(! empty($ctx['secondary_stats']))
                    <div class="flex flex-wrap gap-3">
                        @foreach($ctx['secondary_stats'] as $stat)
                            <div class="rounded-lg bg-white/10 px-4 py-2 text-center">
                                <p class="text-xs text-white/70">{{ $stat['label'] }}</p>
                                <p class="text-lg font-semibold">{{ $stat['value'] }}</p>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>

        @if(! empty($actionQueue))
            <div class="rounded-xl border border-amber-200 bg-amber-50/60 p-4">
                <h2 class="mb-3 text-sm font-semibold text-amber-900">Needs attention</h2>
                <div class="grid gap-3 lg:grid-cols-3">
                    @foreach($actionQueue as $item)
                        <div class="rounded-lg border border-amber-100 bg-white p-3">
                            <div class="flex items-center justify-between">
                                <a href="{{ $item['href'] }}" class="font-semibold text-slate-900 hover:text-primary">{{ $item['title'] }}</a>
                                <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs">{{ $item['count'] }}</span>
                            </div>
                            @if(! empty($item['rows']))
                                <ul class="mt-2 space-y-1">
                                    @foreach($item['rows'] as $row)
                                        <li><a href="{{ $row['href'] }}" class="block rounded px-2 py-1 text-xs hover:bg-slate-50"><span class="font-medium">{{ $row['name'] }}</span> <span class="text-slate-500">{{ $row['meta'] }}</span></a></li>
                                    @endforeach
                                </ul>
                            @endif
                        </div>
                    @endforeach
                </div>
            </div>
        @endif

        @if(! empty($kpis))
            <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                @foreach($kpis as $index => $kpi)
                    @php
                        $cycleKey = $accentCycle[$index % count($accentCycle)];
                        $leftAccent = $kpiLeftAccents[$kpi['tone'] ?? ''] ?? ($accentBgs[$cycleKey] ?? 'bg-slate-400');
                    @endphp
                    <a href="{{ $kpi['href'] }}" class="relative block overflow-hidden rounded-2xl border border-slate-200 bg-white p-4 pl-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
                        <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-2xl {{ $leftAccent }}" aria-hidden="true"></span>
                        <p class="text-sm text-slate-500">{{ $kpi['title'] }}</p>
                        <p class="mt-1 text-xl font-semibold text-slate-900">{{ $kpi['value'] }}</p>
                        <p class="mt-1 text-xs text-slate-500">{{ $kpi['hint'] }}</p>
                    </a>
                @endforeach
            </div>
        @endif

        @if(! empty($quickActions))
            @php
                $quickActionStyles = [
                    'sky' => 'border-sky-200 bg-sky-50 text-sky-800 hover:bg-sky-100',
                    'rose' => 'border-rose-200 bg-rose-50 text-rose-800 hover:bg-rose-100',
                    'violet' => 'border-violet-200 bg-violet-50 text-violet-800 hover:bg-violet-100',
                    'emerald' => 'border-emerald-200 bg-emerald-50 text-emerald-800 hover:bg-emerald-100',
                    'amber' => 'border-amber-200 bg-amber-50 text-amber-900 hover:bg-amber-100',
                    'teal' => 'border-teal-200 bg-teal-50 text-teal-800 hover:bg-teal-100',
                    'indigo' => 'border-indigo-200 bg-indigo-50 text-indigo-800 hover:bg-indigo-100',
                    'orange' => 'border-orange-200 bg-orange-50 text-orange-800 hover:bg-orange-100',
                    'slate' => 'border-slate-200 bg-slate-100 text-slate-700 hover:bg-slate-200',
                ];
                $quickActionCycle = array_keys($quickActionStyles);
            @endphp
            <div class="flex flex-wrap gap-3">
                @foreach($quickActions as $index => $action)
                    @php
                        $tone = $action['tone'] ?? $quickActionCycle[$index % count($quickActionCycle)];
                        $toneClass = $quickActionStyles[$tone] ?? $quickActionStyles['slate'];
                    @endphp
                    <a href="{{ $action['href'] }}" class="inline-flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-sm font-medium shadow-sm transition {{ $toneClass }}">
                        <i class="bi {{ $action['icon'] }} text-sm"></i>{{ $action['label'] }}
                    </a>
                @endforeach
            </div>
        @endif

        <div class="grid gap-5 lg:grid-cols-2">
            <x-card>
                <h2 class="mb-4 text-sm font-semibold text-slate-700">Pipeline by stage</h2>
                <div class="h-64"><canvas id="recruitmentPipelineChart"></canvas></div>
            </x-card>
            <x-card>
                <h2 class="mb-4 text-sm font-semibold text-slate-700">Applicants vs referrals (6 months)</h2>
                <div class="h-64"><canvas id="recruitmentApplicantsTrendChart"></canvas></div>
            </x-card>
            <x-card>
                <h2 class="mb-4 text-sm font-semibold text-slate-700">Source split</h2>
                <div class="h-64"><canvas id="recruitmentReferralSplitChart"></canvas></div>
            </x-card>
            <x-card>
                <h2 class="mb-4 text-sm font-semibold text-slate-700">Interview throughput by week</h2>
                <div class="h-64"><canvas id="recruitmentInterviewThroughputChart"></canvas></div>
            </x-card>
        </div>

        @if(($ctx['followUpPreview'] ?? collect())->isNotEmpty())
            <x-card>
                <div class="mb-4 flex items-center justify-between">
                    <h2 class="text-sm font-semibold text-slate-700">Upcoming follow-ups</h2>
                    <a href="{{ route('interviews.index') }}" class="text-xs font-medium text-primary">View interviews</a>
                </div>
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Applicant</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Role</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Follow-up</th>
                            <th class="px-4 py-3 text-right text-xs font-medium uppercase text-slate-500">Action</th>
                        </tr>
                    </x-slot>
                    @foreach($ctx['followUpPreview'] as $fu)
                        <tr>
                            <td class="px-4 py-3 text-sm">{{ $fu->applicant?->name ?? '—' }}</td>
                            <td class="px-4 py-3 text-sm text-slate-600">{{ $fu->applicant?->jobPosting?->title ?? '—' }}</td>
                            <td class="px-4 py-3 text-sm text-slate-600">{{ $fu->follow_up_at?->format('Y-m-d H:i') }}</td>
                            <td class="px-4 py-3 text-right"><a href="{{ route('interviews.edit', $fu) }}" class="text-sm text-primary">Open</a></td>
                        </tr>
                    @endforeach
                </x-table>
            </x-card>
        @endif

        @if(! empty($ctx['referral_leaderboard']))
            <x-card>
                <h2 class="mb-4 text-sm font-semibold text-slate-700">Referral leaderboard (MTD)</h2>
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Employee</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Referrals</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Offers</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Bonus pending</th>
                        </tr>
                    </x-slot>
                    @foreach($ctx['referral_leaderboard'] as $row)
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium">{{ $row['name'] }}</td>
                            <td class="px-4 py-3 text-sm">{{ $row['referrals'] }}</td>
                            <td class="px-4 py-3 text-sm">{{ $row['offers'] }}</td>
                            <td class="px-4 py-3 text-sm">{{ $row['bonus_pending'] > 0 ? number_format($row['bonus_pending'], 2) : '—' }}</td>
                        </tr>
                    @endforeach
                </x-table>
            </x-card>
        @endif

        <x-card>
            <h2 class="mb-4 text-sm font-semibold text-slate-700">Recent activity</h2>
            <x-table>
                <x-slot name="head">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Type</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Name</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Role</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Meta</th>
                        <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Date</th>
                        <th class="px-4 py-3 text-right text-xs font-medium uppercase text-slate-500">Link</th>
                    </tr>
                </x-slot>
                @forelse($ctx['recentActivity'] ?? [] as $row)
                    <tr>
                        <td class="px-4 py-3 text-sm">{{ $row['type'] }}</td>
                        <td class="px-4 py-3 text-sm font-medium">{{ $row['label'] }}</td>
                        <td class="px-4 py-3 text-sm text-slate-600">{{ $row['detail'] }}</td>
                        <td class="px-4 py-3 text-sm text-slate-600">{{ $row['meta'] }}</td>
                        <td class="px-4 py-3 text-sm text-slate-600">{{ $row['at'] }}</td>
                        <td class="px-4 py-3 text-right"><a href="{{ $row['url'] }}" class="text-sm text-primary">Open</a></td>
                    </tr>
                @empty
                    <tr><td colspan="6" class="px-4 py-8 text-center text-sm text-slate-500">No recent activity.</td></tr>
                @endforelse
            </x-table>
        </x-card>
    </div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    if (typeof Chart === 'undefined') return;
    var muted = '#94a3b8', grid = 'rgba(148, 163, 184, 0.2)';
    var base = { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } };

    var p = document.getElementById('recruitmentPipelineChart');
    if (p) new Chart(p, { type: 'bar', data: { labels: @json($ctx['chartPipeline']['labels'] ?? []), datasets: [{ data: @json($ctx['chartPipeline']['data'] ?? []), backgroundColor: 'rgba(13,148,136,0.55)', borderRadius: 6 }] }, options: Object.assign({}, base, { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } }) });

    var t = document.getElementById('recruitmentApplicantsTrendChart');
    if (t) new Chart(t, { type: 'line', data: { labels: @json($ctx['chartApplicantsTrend']['labels'] ?? []), datasets: [
        { label: 'All applicants', data: @json($ctx['chartApplicantsTrend']['applicants'] ?? []), borderColor: '#3b82f6', tension: 0.35 },
        { label: 'Referrals', data: @json($ctx['chartApplicantsTrend']['referrals'] ?? []), borderColor: '#f59e0b', tension: 0.35 }
    ] }, options: base });

    var s = document.getElementById('recruitmentReferralSplitChart');
    if (s) new Chart(s, { type: 'doughnut', data: { labels: @json($ctx['chartReferralSplit']['labels'] ?? []), datasets: [{ data: @json($ctx['chartReferralSplit']['data'] ?? []), backgroundColor: ['#f59e0b', '#64748b'] }] }, options: base });

    var i = document.getElementById('recruitmentInterviewThroughputChart');
    if (i) new Chart(i, { type: 'bar', data: { labels: @json($ctx['chartInterviewThroughput']['labels'] ?? []), datasets: [
        { label: 'Completed', data: @json($ctx['chartInterviewThroughput']['completed'] ?? []), backgroundColor: 'rgba(16,185,129,0.6)' },
        { label: 'Scheduled', data: @json($ctx['chartInterviewThroughput']['scheduled'] ?? []), backgroundColor: 'rgba(99,102,241,0.5)' }
    ] }, options: Object.assign({}, base, { scales: { y: { beginAtZero: true } } }) });
});
</script>
@endpush
