@extends('layouts.app')

@section('title', 'People Dashboard')
@section('heading', 'People Dashboard')

@section('content')
    @include('employees.top-submenu')

    @php
        $roleName = $pageRoleName ?? (auth()->user()->role?->name ?? 'employee');
        $kpis = $kpis ?? [];
        $kpiMeta = $kpiMeta ?? [];
        $attendanceTodaySummary = $attendanceTodaySummary ?? [];
        $chartWeeklyAttendance = $chartWeeklyAttendance ?? ['labels' => [], 'dates' => [], 'present' => []];
        $chartHiringVsExits = $chartHiringVsExits ?? ['labels' => [], 'hires' => [], 'exits' => []];
        $payrollBlock = $payrollBlock ?? [];
        $lifecycle = $lifecycle ?? [];
        $calendarEvents = $calendarEvents ?? ['holidays' => collect(), 'birthdays' => collect(), 'anniversaries' => collect()];
        $aiInsights = $aiInsights ?? [];
        $leaveDistLabels = ($leaveTypeDistribution ?? collect())->pluck('name')->values();
        $leaveDistDays = ($leaveTypeDistribution ?? collect())->pluck('days')->map(function ($d) {
            return (float) $d;
        })->values();
    @endphp
     <div class="mb-5 flex flex-wrap items-center justify-between gap-3">
        <div>
            <h1 class="font-semibold uppercase tracking-[0.18em] text-primary">Workforce cockpit</h1>
            <p class="mt-1 text-sm text-slate-600">Decision-ready snapshot for People operations.</p>
        </div>
     </div>

    <div class="space-y-6 max-w-full overflow-x-hidden">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
            <div class="flex flex-wrap gap-3">
                @if(auth()->user()->hasPermission('users_create'))
                    <a href="{{ route('employees.create') }}" class="inline-flex w-full items-center justify-center gap-2 rounded-full border border-sky-200 bg-sky-50 px-3.5 py-1.5 text-sm font-medium text-sky-800 shadow-sm transition hover:bg-sky-100 sm:w-auto">
                        <i class="bi bi-person-plus text-sm"></i> Add Employee
                    </a>
                @endif
                @if(($isHrStyle ?? false) && ($canViewPayrollAnalytics ?? false))
                    <a href="{{ route('payroll.index', ['tab' => 'run']) }}" class="inline-flex w-full items-center justify-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-3.5 py-1.5 text-sm font-medium text-emerald-800 shadow-sm transition hover:bg-emerald-100 sm:w-auto">
                        <i class="bi bi-currency-dollar text-sm"></i> Run Payroll
                    </a>
                    <a href="{{ route('attendance.index') }}" class="inline-flex w-full items-center justify-center gap-2 rounded-full border border-violet-200 bg-violet-50 px-3.5 py-1.5 text-sm font-medium text-violet-800 shadow-sm transition hover:bg-violet-100 sm:w-auto">
                        <i class="bi bi-clock-history text-sm"></i> Attendance
                    </a>
                @endif
                <a href="{{ route('reports.index') }}" class="inline-flex w-full items-center justify-center gap-2 rounded-full border border-rose-200 bg-rose-50 px-3.5 py-1.5 text-sm font-medium text-rose-800 shadow-sm transition hover:bg-rose-100 sm:w-auto">
                    <i class="bi bi-file-earmark-bar-graph text-sm"></i> Reports
                </a>
            </div>
        </div>

        {{-- KPI strip --}}
        <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
            <x-kpi-card title="Total employees" :value="number_format($kpis['total_employees'] ?? 0)" tone="info" accent="sky" />
            <x-kpi-card title="Present today" :value="number_format($kpis['present_today'] ?? 0)" tone="positive" accent="emerald" />
            <x-kpi-card title="Absent today" :value="number_format($kpis['absent_today'] ?? 0)" :tone="($kpiMeta['absent'] ?? 'positive') === 'critical' ? 'critical' : (($kpiMeta['absent'] ?? '') === 'warning' ? 'warning' : 'positive')" accent="rose" />
            <x-kpi-card title="On leave today" :value="number_format($kpis['on_leave_today'] ?? 0)" tone="warning" accent="amber" />
            <x-kpi-card title="New joiners (MTD)" :value="number_format($kpis['new_joiners_month'] ?? 0)" tone="info" accent="violet" />
            <x-kpi-card
                title="Attrition (MTD)"
                :value="number_format($kpis['attrition_rate'] ?? 0, 2).'%'"
                :tone="($kpiMeta['attrition'] ?? 'positive') === 'critical' ? 'critical' : (($kpiMeta['attrition'] ?? '') === 'warning' ? 'warning' : 'positive')"
                accent="primary"
                subtitle="Exits vs headcount"
            />
        </div>

        <div class="grid gap-6 xl:grid-cols-12">
            <div class="space-y-6 xl:col-span-8 min-w-0">

                @if($isHrStyle ?? false)
                    <x-panel-card title="Attendance" subtitle="Today’s snapshot & 7-day present trend">
                        <x-slot name="actions">
                            <a href="{{ route('attendance.index') }}" class="text-sm font-medium text-primary hover:underline">Open attendance</a>
                        </x-slot>
                        <div class="mb-4 grid gap-3 sm:grid-cols-4">
                            <div class="relative overflow-hidden rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 pl-4 text-center">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-emerald-500" aria-hidden="true"></span>
                                <p class="text-xs text-emerald-700">Present</p>
                                <p class="text-lg font-semibold text-emerald-800">{{ $attendanceTodaySummary['present'] ?? 0 }}</p>
                            </div>
                            <div class="relative overflow-hidden rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 pl-4 text-center">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-rose-500" aria-hidden="true"></span>
                                <p class="text-xs text-rose-700">Absent</p>
                                <p class="text-lg font-semibold text-rose-800">{{ $attendanceTodaySummary['absent'] ?? 0 }}</p>
                            </div>
                            <div class="relative overflow-hidden rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 pl-4 text-center">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-amber-500" aria-hidden="true"></span>
                                <p class="text-xs text-amber-700">On leave</p>
                                <p class="text-lg font-semibold text-amber-800">{{ $attendanceTodaySummary['on_leave'] ?? 0 }}</p>
                            </div>
                            <div class="relative overflow-hidden rounded-xl border border-orange-200 bg-orange-50 px-3 py-2 pl-4 text-center">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-orange-500" aria-hidden="true"></span>
                                <p class="text-xs text-orange-700">Late</p>
                                <p class="text-lg font-semibold text-orange-800">{{ $attendanceTodaySummary['late'] ?? 0 }}</p>
                            </div>
                        </div>
                        <div class="relative h-64 w-full min-w-0 overflow-hidden">
                            <canvas id="weeklyAttendanceChart" class="h-full w-full"></canvas>
                        </div>
                    </x-panel-card>
                @endif

                @if($isHrStyle ?? false)
                    <div class="grid gap-6 lg:grid-cols-2 ">
                        <x-panel-card title="Leave distribution" subtitle="Approved days by type (last 6 months)" class="overflow-hidden">
                            <x-slot name="actions">
                                <a href="{{ route('leaves.index') }}" class="text-sm font-medium text-primary hover:underline">All leaves</a>
                            </x-slot>
                            <div class="relative h-56 w-full min-w-0 overflow-hidden">
                                <canvas id="leaveTypesChart" class="h-full w-full"></canvas>
                            </div>
                        </x-panel-card>

                        <x-panel-card title="Leave balance signals" subtitle="High utilization vs allocation (heuristic)">
                            @if(($leaveBalanceAlerts ?? collect())->isEmpty())
                                <p class="text-sm text-slate-500">No elevated utilization signals for configured leave types.</p>
                            @else
                                <ul class="space-y-2">
                                    @foreach($leaveBalanceAlerts as $row)
                                        <li class="flex items-center justify-between rounded-lg border border-amber-100 bg-amber-50/60 px-3 py-2 text-sm">
                                            <span class="font-medium text-slate-800">{{ $row->leave_type }}</span>
                                            <span class="text-amber-900">{{ number_format($row->pct, 1) }}% utilized</span>
                                        </li>
                                    @endforeach
                                </ul>
                            @endif
                        </x-panel-card>
                    </div>

                    <x-panel-card title="Pending leave requests" subtitle="Approve or reject inline">
                        <div class="overflow-x-auto">
                            <table class="min-w-full text-left text-sm">
                                <thead class="border-b border-slate-200 text-xs uppercase text-slate-500">
                                    <tr>
                                        <th class="pb-2 pr-4">Employee</th>
                                        <th class="pb-2 pr-4">Type</th>
                                        <th class="pb-2 pr-4">Dates</th>
                                        <th class="pb-2 pr-4">Days</th>
                                        <th class="pb-2">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-100">
                                    @forelse(($pendingLeaves ?? collect()) as $leave)
                                        <tr>
                                            <td class="py-2 pr-4 font-medium text-slate-900">{{ $leave->user?->name ?? '—' }}</td>
                                            <td class="py-2 pr-4 text-slate-600">{{ $leave->leaveType?->name ?? '—' }}</td>
                                            <td class="py-2 pr-4 text-slate-600">{{ $leave->start_date?->format('M j') }} – {{ $leave->end_date?->format('M j') }}</td>
                                            <td class="py-2 pr-4">{{ $leave->total_days }}</td>
                                            <td class="py-2">
                                                @can('approve', $leave)
                                                    <form action="{{ route('leaves.update-status', $leave) }}" method="post" class="inline">
                                                        @csrf
                                                        <input type="hidden" name="status" value="approved">
                                                        <button type="submit" class="text-emerald-600 hover:underline text-xs">Approve</button>
                                                    </form>
                                                    <form action="{{ route('leaves.update-status', $leave) }}" method="post" class="inline ms-2">
                                                        @csrf
                                                        <input type="hidden" name="status" value="rejected">
                                                        <button type="submit" class="text-red-600 hover:underline text-xs">Reject</button>
                                                    </form>
                                                @else
                                                    <span class="text-xs text-slate-400">View only</span>
                                                @endif
                                            </td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="5" class="py-6 text-center text-slate-500">No pending leave requests.</td></tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </x-panel-card>
                @endif

                @if(($isHrStyle ?? false) && ($canViewPayrollAnalytics ?? false))
                    <x-panel-card title="Payroll & compliance" subtitle="Current month snapshot">
                        <x-slot name="actions">
                            <a href="{{ route('payroll.index') }}" class="text-sm font-medium text-primary hover:underline">Payroll hub</a>
                        </x-slot>
                        <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                            <div class="relative overflow-hidden rounded-xl border border-slate-200 bg-slate-50 p-3 pl-4">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-slate-400" aria-hidden="true"></span>
                                <p class="text-xs font-medium text-slate-500">Payroll status</p>
                                <p class="mt-1 text-lg font-semibold capitalize text-slate-900">{{ $payrollBlock['status_label'] ?? '—' }}</p>
                                @if(!empty($payrollBlock['v2_cycle_status']))
                                    <p class="text-xs text-slate-500">V2 cycle: {{ $payrollBlock['v2_cycle_status'] }}</p>
                                @endif
                            </div>
                            <div class="relative overflow-hidden rounded-xl border border-emerald-200 bg-emerald-50 p-3 pl-4">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-emerald-500" aria-hidden="true"></span>
                                <p class="text-xs font-medium text-emerald-700">Disbursed (net, paid)</p>
                                <p class="mt-1 text-lg font-semibold text-emerald-900">₹{{ number_format($payrollBlock['total_disbursed'] ?? 0, 2) }}</p>
                            </div>
                            <div class="relative overflow-hidden rounded-xl border border-sky-200 bg-sky-50 p-3 pl-4">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-sky-500" aria-hidden="true"></span>
                                <p class="text-xs font-medium text-sky-700">PF (employer, V2)</p>
                                <p class="mt-1 text-lg font-semibold text-sky-900">₹{{ number_format($payrollBlock['pf_total'] ?? 0, 2) }}</p>
                            </div>
                            <div class="relative overflow-hidden rounded-xl border border-violet-200 bg-violet-50 p-3 pl-4">
                                <span class="absolute inset-y-0 left-0 w-1.5 rounded-l-xl bg-violet-500" aria-hidden="true"></span>
                                <p class="text-xs font-medium text-violet-700">ESI (employer, V2)</p>
                                <p class="mt-1 text-lg font-semibold text-violet-900">₹{{ number_format($payrollBlock['esi_total'] ?? 0, 2) }}</p>
                            </div>
                        </div>
                        <ul class="mt-4 space-y-2">
                            @foreach($payrollBlock['alerts'] ?? [] as $alert)
                                <li class="flex gap-2 rounded-lg border px-3 py-2 text-sm
                                    {{ ($alert['type'] ?? 'info') === 'warning' ? 'border-amber-200 bg-amber-50 text-amber-900' : 'border-sky-200 bg-sky-50 text-sky-900' }}">
                                    <i class="bi bi-info-circle shrink-0"></i>
                                    <span>{{ $alert['message'] ?? '' }}</span>
                                </li>
                            @endforeach
                        </ul>
                    </x-panel-card>
                @endif

                <x-panel-card title="Employee lifecycle" subtitle="Month-to-date movement">
                    <div class="grid gap-3 sm:grid-cols-3">
                        <div class="rounded-xl border border-emerald-100 bg-emerald-50/60 p-4">
                            <p class="text-xs font-medium text-emerald-800">New joiners (MTD)</p>
                            <p class="mt-1 text-xl font-bold text-emerald-900">{{ $lifecycle['new_joiners_mtd'] ?? 0 }}</p>
                        </div>
                        <div class="rounded-xl border border-red-100 bg-red-50/60 p-4">
                            <p class="text-xs font-medium text-red-800">Resignations (MTD)</p>
                            <p class="mt-1 text-xl font-bold text-red-900">{{ $lifecycle['resignations_mtd'] ?? 0 }}</p>
                        </div>
                        <div class="rounded-xl border border-sky-100 bg-sky-50/60 p-4">
                            <p class="text-xs font-medium text-sky-800">Anniversary confirmations</p>
                            <p class="mt-1 text-xl font-bold text-sky-900">{{ $lifecycle['confirmations_due'] ?? 0 }}</p>
                            <p class="mt-1 text-xs text-sky-800">Joining + 1 year in this month</p>
                        </div>
                    </div>
                    <div class="relative mt-6 h-64 w-full min-w-0 overflow-hidden">
                        <canvas id="hiringVsExitsChart" class="h-full w-full"></canvas>
                    </div>
                </x-panel-card>

                @if($isHrStyle ?? false)
                    <x-panel-card title="Department performance" subtitle="Headcount and 7d attendance intensity">
                        <div class="overflow-x-auto">
                            <table class="min-w-full text-left text-sm">
                                <thead class="border-b border-slate-200 text-xs uppercase text-slate-500">
                                    <tr>
                                        <th class="pb-2 pr-4">Department</th>
                                        <th class="pb-2 pr-4">Headcount</th>
                                        <th class="pb-2 pr-4">Attendance %</th>
                                        @if($canViewPayrollAnalytics ?? false)
                                            <th class="pb-2">Avg salary / mo</th>
                                        @endif
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-100">
                                    @forelse(($departmentPerformance ?? collect()) as $row)
                                        <tr>
                                            <td class="py-2 pr-4 font-medium">{{ $row['name'] }}</td>
                                            <td class="py-2 pr-4">{{ $row['headcount'] }}</td>
                                            <td class="py-2 pr-4">{{ $row['attendance_pct'] }}%</td>
                                            @if($canViewPayrollAnalytics ?? false)
                                                <td class="py-2">₹{{ number_format($row['avg_salary'] ?? 0, 2) }}</td>
                                            @endif
                                        </tr>
                                    @empty
                                        <tr><td colspan="{{ ($canViewPayrollAnalytics ?? false) ? 4 : 3 }}" class="py-6 text-center text-slate-500">No department data.</td></tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </x-panel-card>
                @endif

                @if($isHrStyle ?? false)
                    <x-panel-card title="AI insights" subtitle="Rule-based signals (not external AI)">
                        <ul class="space-y-3">
                            @foreach($aiInsights as $insight)
                                <li class="flex gap-3 rounded-xl border px-4 py-3 text-sm
                                    {{ ($insight['type'] ?? '') === 'danger' ? 'border-red-200 bg-red-50 text-red-900' : '' }}
                                    {{ ($insight['type'] ?? '') === 'warning' ? 'border-amber-200 bg-amber-50 text-amber-900' : '' }}
                                    {{ ($insight['type'] ?? '') === 'info' ? 'border-sky-200 bg-sky-50 text-sky-900' : '' }}
                                    {{ ($insight['type'] ?? '') === 'success' ? 'border-emerald-200 bg-emerald-50 text-emerald-900' : '' }}
                                ">
                                    <i class="bi bi-lightning-charge shrink-0"></i>
                                    <div>
                                        <p class="font-semibold">{{ $insight['title'] ?? '' }}</p>
                                        <p class="mt-0.5 text-slate-700">{{ $insight['message'] ?? '' }}</p>
                                    </div>
                                </li>
                            @endforeach
                        </ul>
                    </x-panel-card>
                @endif
            </div>

            {{-- Sticky sidebar --}}
            <aside class="xl:col-span-4">
                <div class="space-y-6 xl:sticky xl:top-20">
                    <x-panel-card title="Tasks & alerts" subtitle="Approvals and risk items">
                        <ul class="space-y-3 text-sm">
                            <li class="flex justify-between gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2">
                                <span class="text-amber-800">Pending leaves</span>
                                <span class="font-semibold text-amber-900">{{ $pending_leave_count ?? 0 }}</span>
                            </li>
                            <li class="flex justify-between gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-2">
                                <span class="text-violet-800">Attendance regularizations</span>
                                <span class="font-semibold text-violet-900">{{ $pending_regularization_count ?? 0 }}</span>
                            </li>
                        </ul>
                        <div class="mt-4 flex flex-wrap gap-3">
                            @if(auth()->user()?->canReviewAttendanceRegularizations())
                            <a href="{{ route('leaves.index', ['status' => 'pending']) }}" class="inline-flex flex-1 items-center justify-center gap-2 rounded-full border border-rose-200 bg-rose-50 px-3.5 py-1.5 text-center text-sm font-medium text-rose-800 shadow-sm transition hover:bg-rose-100">Review leaves</a>
                            <a href="{{ route('attendance-regularizations.index', ['status' => 'pending']) }}" class="inline-flex flex-1 items-center justify-center gap-2 rounded-full border border-violet-200 bg-violet-50 px-3.5 py-1.5 text-center text-sm font-medium text-violet-800 shadow-sm transition hover:bg-violet-100">Review regularizations</a>
                            @endif
                        </div>

                        @if(($probation_soon ?? collect())->isNotEmpty())
                            <div class="mt-4 border-t border-slate-100 pt-4">
                                <p class="text-xs font-semibold uppercase text-slate-500">Probation ending (6 mo window)</p>
                                <ul class="mt-2 space-y-1 text-sm text-slate-700">
                                    @foreach($probation_soon as $u)
                                        <li class="flex justify-between gap-2">
                                            <span>{{ $u->name }}</span>
                                            <span class="text-slate-500">{{ $u->joining_date?->format('M j, Y') }}</span>
                                        </li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        @if(($documentComplianceGaps ?? collect())->isNotEmpty())
                            <div class="mt-4 border-t border-slate-100 pt-4">
                                <p class="text-xs font-semibold uppercase text-slate-500">Document compliance gaps</p>
                                <p class="mt-1 text-xs text-slate-500">6 mandatory types per employee (Aadhaar, PAN, bank proof, education, experience, appointment).</p>
                                <ul class="mt-2 space-y-1 text-sm">
                                    @foreach($documentComplianceGaps as $g)
                                        <li class="flex justify-between gap-2 text-slate-700">
                                            <a href="{{ route('employees.show', ['employee' => $g['user_id'] ?? 0, 'tab' => 'documents']) }}" class="truncate font-medium text-slate-800 hover:text-primary hover:underline">
                                                {{ $g['user'] }}
                                            </a>
                                            <span class="shrink-0 text-amber-700">
                                                {{ ($g['completed'] ?? 0) }}/{{ ($g['total'] ?? 6) }}
                                                <span class="text-xs">({{ $g['missing'] }} missing)</span>
                                            </span>
                                        </li>
                                    @endforeach
                                </ul>
                                <a href="{{ route('employees.index') }}" class="mt-2 block text-center text-xs font-medium text-primary hover:underline">Open employees</a>
                            </div>
                        @endif
                    </x-panel-card>

                    <x-panel-card title="Calendar & events" subtitle="Holidays, birthdays, anniversaries">
                        <div class="space-y-4 text-sm">
                            <div>
                                <p class="flex items-center gap-2 text-xs font-semibold uppercase text-slate-500">
                                    <i class="bi bi-balloon-heart text-base normal-case text-orange-400"></i>
                                    Upcoming holidays
                                </p>
                                @forelse(($calendarEvents['holidays'] ?? collect()) as $h)
                                    <div class="mt-1 flex justify-between gap-2 border-b border-slate-100 py-1.5">
                                        <span class="font-medium text-sky-700">{{ $h->name }}</span>
                                        <span class="text-sky-600">{{ $h->date?->format('M j') }}</span>
                                    </div>
                                @empty
                                    <p class="mt-1 text-slate-500">No upcoming holidays.</p>
                                @endforelse
                            </div>
                            <div>
                                <p class="flex items-center gap-2 text-xs font-semibold uppercase text-slate-500">
                                    <i class="bi bi-cake2 text-base normal-case text-[#F08A8A]"></i>
                                    Birthdays (rolling year)
                                </p>
                                @forelse(($calendarEvents['birthdays'] ?? collect()) as $u)
                                    <div class="mt-1 flex justify-between gap-2 border-b border-slate-100 py-1.5">
                                        <span>{{ $u->name }}</span>
                                        <span class="text-slate-500">{{ $u->dob?->format('M j') }}</span>
                                    </div>
                                @empty
                                    <p class="mt-1 text-slate-500">No birthdays in this pass.</p>
                                @endforelse
                            </div>
                            <div>
                                <p class="flex items-center gap-2 text-xs font-semibold uppercase text-slate-500">
                                    <i class="bi bi-stars text-base normal-case text-[#B9A8DE]"></i>
                                    Work anniversaries
                                </p>
                                @forelse(($calendarEvents['anniversaries'] ?? collect()) as $u)
                                    <div class="mt-1 flex justify-between gap-2 border-b border-slate-100 py-1.5">
                                        <span>{{ $u->name }}</span>
                                        <span class="text-slate-500">{{ $u->joining_date?->format('M j') }}</span>
                                    </div>
                                @empty
                                    <p class="mt-1 text-slate-500">No anniversaries in this pass.</p>
                                @endforelse
                            </div>
                            <a href="{{ route('holidays.index') }}" class="block text-center text-xs font-medium text-primary hover:underline">Manage holidays</a>
                        </div>
                    </x-panel-card>

                    @if($isHrStyle ?? false)
                        <x-panel-card title="Regularization queue" subtitle="Latest pending">
                            @forelse(($pending_regularizations ?? collect()) as $r)
                                <div class="mb-2 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-100 px-3 py-2 text-xs">
                                    <span class="font-medium text-slate-800">{{ $r->user?->name ?? '—' }}</span>
                                    <span class="text-slate-500">{{ $r->date?->format('M j, Y') }}</span>
                                </div>
                            @empty
                                <p class="text-sm text-slate-500">No items in preview.</p>
                            @endforelse
                        </x-panel-card>
                    @endif
                </div>
            </aside>
        </div>
    </div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    if (typeof Chart === 'undefined') return;

    var palette = {
        text: '#334155',
        muted: '#94a3b8',
        grid: 'rgba(148, 163, 184, 0.2)',
    };

    var weeklyLabels = @json($chartWeeklyAttendance['labels'] ?? []);
    var weeklyPresent = @json($chartWeeklyAttendance['present'] ?? []);
    var wctx = document.getElementById('weeklyAttendanceChart');
    if (wctx) {
        var weeklyLineCtx = wctx.getContext('2d');
        var weeklyGradient = weeklyLineCtx.createLinearGradient(0, 0, 0, wctx.clientHeight || 256);
        weeklyGradient.addColorStop(0, 'rgba(16, 185, 129, 0.35)');
        weeklyGradient.addColorStop(1, 'rgba(16, 185, 129, 0.02)');

        new Chart(weeklyLineCtx, {
            type: 'line',
            data: {
                labels: weeklyLabels,
                datasets: [{
                    label: 'Present (distinct employees)',
                    data: weeklyPresent,
                    borderColor: '#10b981',
                    backgroundColor: weeklyGradient,
                    fill: true,
                    tension: 0.35,
                    borderWidth: 2,
                    pointRadius: 3,
                    pointHoverRadius: 5,
                    pointBackgroundColor: '#10b981',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                normalized: true,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            title: function (items) {
                                return items.length ? items[0].label : '';
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: {
                            color: palette.muted,
                            maxRotation: 0,
                            autoSkip: true,
                            maxTicksLimit: 7,
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: { color: palette.muted, precision: 0 },
                        grid: { color: palette.grid }
                    }
                }
            }
        });
    }

    var leaveLabels = @json($leaveDistLabels);
    var leaveData = @json($leaveDistDays);
    var lctx = document.getElementById('leaveTypesChart');
    if (lctx && leaveLabels.length) {
        new Chart(lctx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: leaveLabels,
                datasets: [{
                    data: leaveData,
                    backgroundColor: ['#10b981', '#0ea5e9', '#6366f1', '#f59e0b', '#ef4444', '#14b8a6', '#64748b', '#8b5cf6'],
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                layout: { padding: 0 },
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 10,
                            boxHeight: 10,
                            padding: 10,
                            font: {
                                size: 10
                            }
                        }
                    }
                }
            }
        });
    }

    var hLabels = @json($chartHiringVsExits['labels'] ?? []);
    var hHires = @json($chartHiringVsExits['hires'] ?? []);
    var hExits = @json($chartHiringVsExits['exits'] ?? []);
    var hctx = document.getElementById('hiringVsExitsChart');
    if (hctx) {
        new Chart(hctx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: hLabels,
                datasets: [
                    { label: 'Hires', data: hHires, backgroundColor: 'rgba(16, 185, 129, 0.7)' },
                    { label: 'Exits', data: hExits, backgroundColor: 'rgba(239, 68, 68, 0.65)' },
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
            }
        });
    }
});
</script>
@endpush
