@extends('layouts.app')

@section('title', 'Performance Dashboard')

@section('content')
    @include('performance.top-submenu')
     <div class="mb-5 flex flex-wrap items-center justify-between gap-3">
     <div>
        <h1 class="font-semibold uppercase tracking-[0.18em] text-primary">Performance Dashboard</h1>
        <p class="text-sm text-slate-500">Goals, review pipeline, and recent activity in one place.</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-start lg:justify-between">
            
            <div class="flex flex-wrap gap-2">
                @if(auth()->user()->hasPermission('performance_create'))
                    <a href="{{ route('goals.create') }}" class="inline-flex w-full items-center justify-center rounded-lg border border-indigo-200 bg-white px-4 py-2 text-sm font-medium text-indigo-800 shadow-sm hover:bg-indigo-50 sm:w-auto">
                        <i class="bi bi-bullseye me-2"></i> New goal
                    </a>
                    <a href="{{ route('performance-reviews.create') }}" class="inline-flex w-full items-center justify-center rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-500 sm:w-auto">
                        <i class="bi bi-clipboard-check me-2"></i> New review
                    </a>
                @endif
                @if(auth()->user()->hasPermission('performance_view'))
                    <a href="{{ route('goals.index') }}" class="inline-flex w-full items-center justify-center rounded-lg bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200 sm:w-auto">All goals</a>
                    <a href="{{ route('performance-reviews.index') }}" class="inline-flex w-full items-center justify-center rounded-lg bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200 sm:w-auto">All reviews</a>
                @endif
            </div>
        </div>

        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <x-kpi-card title="Total goals" :value="$kpis['total_goals']" accent="slate" subtitle="All tracked goals" />
            <x-kpi-card title="Active goals" :value="$kpis['goals_active']" accent="sky" subtitle="Not yet completed" />
            <x-kpi-card title="On track" :value="$kpis['goals_on_track']" accent="emerald" subtitle="Healthy progress" />
            <x-kpi-card
                title="At risk / behind"
                :value="$kpis['goals_at_risk']"
                tone="{{ ($kpis['goals_at_risk'] ?? 0) > 0 ? 'warning' : 'positive' }}"
                accent="amber"
                subtitle="Needs attention"
            />
            <x-kpi-card title="Completed goals" :value="$kpis['goals_completed']" accent="primary" subtitle="Done" />
            <x-kpi-card
                title="Overdue goals"
                :value="$kpis['goals_overdue']"
                tone="{{ ($kpis['goals_overdue'] ?? 0) > 0 ? 'critical' : 'positive' }}"
                accent="rose"
                subtitle="Past due date, not complete"
            />
            <x-kpi-card title="Due in 14 days" :value="$kpis['goals_due_soon']" tone="warning" accent="amber" subtitle="Upcoming deadlines" />
            <x-kpi-card
                title="Reviews pending"
                :value="$kpis['reviews_pending']"
                tone="{{ ($kpis['reviews_pending'] ?? 0) > 0 ? 'warning' : 'positive' }}"
                accent="violet"
                subtitle="Awaiting completion"
            />
            <x-kpi-card title="Reviews done (MTD)" :value="$kpis['reviews_completed_mtd']" accent="emerald" subtitle="Completed this month" />
            <x-kpi-card title="Avg review rating" :value="$kpis['avg_rating'] > 0 ? number_format($kpis['avg_rating'], 1) : '—'" accent="sky" subtitle="Where rated (0–5)" />
        </div>

        <div class="grid gap-5 lg:grid-cols-2">
            <x-card class="overflow-hidden">
                <x-slot name="header">
                    <h2 class="text-sm font-semibold text-slate-700">Goals by status</h2>
                </x-slot>
                <div class="h-64 w-full p-2">
                    <canvas id="performanceGoalsStatusChart"></canvas>
                </div>
            </x-card>
            <x-card class="overflow-hidden">
                <x-slot name="header">
                    <h2 class="text-sm font-semibold text-slate-700">Reviews completed (6 months)</h2>
                </x-slot>
                <div class="h-64 w-full p-2">
                    <canvas id="performanceReviewsTrendChart"></canvas>
                </div>
            </x-card>
        </div>

        <div class="grid gap-5 lg:grid-cols-2">
            <x-card class="overflow-hidden">
                <x-slot name="header">
                    <div class="flex flex-wrap items-center justify-between gap-2">
                        <h2 class="text-sm font-semibold text-slate-700">Recent goals</h2>
                        <a href="{{ route('goals.index') }}" class="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline">
                            View all <i class="bi bi-chevron-right text-[10px]"></i>
                        </a>
                    </div>
                </x-slot>
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Goal</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Owner</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Progress</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                            <th class="px-4 py-3 text-right text-xs font-medium uppercase text-slate-500"></th>
                        </tr>
                    </x-slot>
                    @forelse($recentGoals as $g)
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium text-slate-900">{{ \Illuminate\Support\Str::limit($g->title, 42) }}</td>
                            <td class="px-4 py-3 text-sm text-slate-600">{{ $g->user?->name ?? '—' }}</td>
                            <td class="px-4 py-3 text-sm tabular-nums text-slate-700">{{ $g->progress }}%</td>
                            <td class="px-4 py-3 text-sm whitespace-nowrap">
                                <x-badge :status="$g->status">{{ str_replace('_', ' ', ucfirst((string) ($g->status ?? ''))) }}</x-badge>
                            </td>
                            <td class="px-4 py-3 text-right">
                                @if(auth()->user()->hasPermission('performance_edit'))
                                    <a href="{{ route('goals.edit', $g) }}" class="btn-icon-action btn-icon-action--edit" title="Edit" aria-label="Edit"><i class="bi bi-pencil-square"></i></a>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="5" class="px-4 py-8 text-center text-sm text-slate-500">No goals yet.</td>
                        </tr>
                    @endforelse
                </x-table>
            </x-card>

            <x-card class="overflow-hidden">
                <x-slot name="header">
                    <div class="flex flex-wrap items-center justify-between gap-2">
                        <h2 class="text-sm font-semibold text-slate-700">Recent reviews</h2>
                        <a href="{{ route('performance-reviews.index') }}" class="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline">
                            View all <i class="bi bi-chevron-right text-[10px]"></i>
                        </a>
                    </div>
                </x-slot>
                <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">Reviewer</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Rating</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                            <th class="px-4 py-3 text-right text-xs font-medium uppercase text-slate-500"></th>
                        </tr>
                    </x-slot>
                    @forelse($recentReviews as $r)
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium text-slate-900">{{ $r->user?->name ?? '—' }}</td>
                            <td class="px-4 py-3 text-sm text-slate-600">{{ $r->reviewer?->name ?? '—' }}</td>
                            <td class="px-4 py-3 text-sm text-slate-700">{{ $r->rating !== null ? number_format($r->rating, 1) : '—' }}</td>
                            <td class="px-4 py-3 text-sm">
                                <x-badge :status="$r->status">{{ ucfirst($r->status) }}</x-badge>
                            </td>
                            <td class="px-4 py-3 text-right">
                                @if(auth()->user()->hasPermission('performance_edit'))
                                    <a href="{{ route('performance-reviews.edit', $r) }}" class="btn-icon-action btn-icon-action--edit" title="Edit" aria-label="Edit"><i class="bi bi-pencil-square"></i></a>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="5" class="px-4 py-8 text-center text-sm text-slate-500">No reviews yet.</td>
                        </tr>
                    @endforelse
                </x-table>
            </x-card>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            if (typeof Chart === 'undefined') return;

            var muted = '#94a3b8';
            var grid = 'rgba(148, 163, 184, 0.2)';

            var gEl = document.getElementById('performanceGoalsStatusChart');
            if (gEl) {
                new Chart(gEl.getContext('2d'), {
                    type: 'bar',
                    data: {
                        labels: @json($chartGoalsByStatus['labels'] ?? []),
                        datasets: [{
                            label: 'Goals',
                            data: @json($chartGoalsByStatus['data'] ?? []),
                            backgroundColor: [
                                'rgba(99, 102, 241, 0.65)',
                                'rgba(245, 158, 11, 0.65)',
                                'rgba(239, 68, 68, 0.6)',
                                'rgba(16, 185, 129, 0.65)',
                            ],
                            borderRadius: 6,
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { ticks: { color: muted }, grid: { display: false } },
                            y: { ticks: { color: muted }, grid: { color: grid }, beginAtZero: true }
                        }
                    }
                });
            }

            var rEl = document.getElementById('performanceReviewsTrendChart');
            if (rEl) {
                new Chart(rEl.getContext('2d'), {
                    type: 'line',
                    data: {
                        labels: @json($chartReviewsTrend['labels'] ?? []),
                        datasets: [{
                            label: 'Completed',
                            data: @json($chartReviewsTrend['completed'] ?? []),
                            borderColor: 'rgb(79, 70, 229)',
                            backgroundColor: 'rgba(79, 70, 229, 0.12)',
                            fill: true,
                            tension: 0.35,
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { ticks: { color: muted }, grid: { display: false } },
                            y: { ticks: { color: muted }, grid: { color: grid }, beginAtZero: true }
                        }
                    }
                });
            }
        });
    </script>
@endpush
