@extends('layouts.app')

@push('styles')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" crossorigin="anonymous" />
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
    .sm-hero {
        background: linear-gradient(135deg, #1e1b4b 0%, #3730a3 50%, #4f46e5 100%);
        position: relative; overflow: hidden;
    }
    .sm-hero::before {
        content:''; position:absolute; top:-80px; right:-80px;
        width:320px; height:320px; background:rgba(255,255,255,0.05); border-radius:50%;
    }
    .sm-hero::after {
        content:''; position:absolute; bottom:-50px; left:60px;
        width:200px; height:200px; background:rgba(255,255,255,0.04); border-radius:50%;
    }
    .sm-card {
        background:#fff; border-radius:16px;
        border:1px solid #e2e8f0;
        box-shadow:0 1px 3px rgba(0,0,0,0.06),0 4px 16px rgba(79,70,229,0.04);
        transition:transform 0.22s cubic-bezier(0.34,1.56,0.64,1),box-shadow 0.22s ease;
    }
    .sm-card:hover { transform:translateY(-3px); box-shadow:0 8px 32px rgba(79,70,229,0.12); }
    .kpi-icon { width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0; }
    .sec-title {
        font-size:0.68rem;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;
        color:#64748b;display:flex;align-items:center;gap:8px;margin-bottom:1rem;
    }
    .pbar-wrap { background:#e2e8f0;border-radius:999px;height:8px;overflow:hidden; }
    .pbar-fill  { height:100%;border-radius:999px;transition:width 0.8s cubic-bezier(0.4,0,0.2,1); }
    .qa-btn {
        display:flex;flex-direction:column;align-items:center;gap:8px;
        padding:16px 10px;border-radius:14px;border:1.5px solid #e2e8f0;
        background:#f8fafc;transition:all 0.2s cubic-bezier(0.34,1.56,0.64,1);text-decoration:none;
    }
    .qa-btn:hover { border-color:#4f46e5;background:#eef2ff;transform:translateY(-2px) scale(1.04);box-shadow:0 4px 16px rgba(79,70,229,0.12); }
    .heatmap-cell { width:14px;height:14px;border-radius:3px;display:inline-block; }
    .alert-critical { background:#fef2f2;border:1px solid #fecaca;color:#b91c1c; }
    .alert-warning  { background:#fffbeb;border:1px solid #fde68a;color:#92400e; }
    .alert-info     { background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af; }
    .portal-banner  {
        background:linear-gradient(135deg,#4f46e5 0%,#7c3aed 100%);
        border-radius:16px;padding:1.5rem 2rem;
        display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:1rem;
    }
    .badge-pill { display:inline-flex;align-items:center;padding:2px 10px;border-radius:999px;font-size:0.68rem;font-weight:600; }
    .perm-cell-yes { background:#d1fae5;border-radius:4px;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px; }
    .perm-cell-no  { background:#f1f5f9;border-radius:4px;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px; }
</style>
@endpush

@section('content')
@php
    $totalUsers    = $stats['total_users']   ?? 0;
    $activeUsers   = $stats['active_users']  ?? 0;
    $inactiveUsers = $stats['inactive_users']?? 0;
    $newThisWeek   = $stats['new_this_week'] ?? 0;
    $twoFACount    = $stats['two_factor_enabled_count'] ?? 0;
    $recentLogins  = $stats['recent_logins'] ?? 0;
    $otpEnabled    = $stats['otp_enabled']   ?? false;
    $failedLogins  = $stats['failed_logins_today'] ?? 0;
    $monthlyRev    = $stats['monthly_revenue'] ?? 0;
    $totalMembers  = $stats['total_members'] ?? 0;
    $pendingApprovals = $stats['pending_approvals'] ?? 0;
    $totalTrainingSessions  = $stats['total_training_sessions']  ?? 0;
    $activeTrainingSessions = $stats['active_training_sessions'] ?? 0;
    $totalRegistrations     = $stats['total_registrations']      ?? 0;
    $activeAssignments      = $stats['active_assignments']       ?? 0;
    $totalMentorshipSessions= $stats['total_mentorship_sessions']?? 0;
    $usersByRole   = $stats['users_by_role']  ?? collect();
    $systemAlerts  = $stats['system_alerts']  ?? [];
    $sparklineData = $stats['login_sparkline_data'] ?? [];
    $rolesWithPerms= $stats['roles_with_permissions'] ?? collect();

    $activeRate = $totalUsers > 0 ? round(($activeUsers/$totalUsers)*100) : 0;
    $twoFARate  = $totalUsers > 0 ? round(($twoFACount/$totalUsers)*100) : 0;
    $memberRate = $totalUsers > 0 ? round(($totalMembers/$totalUsers)*100) : 0;
    $trainingRate = $totalUsers > 0 ? min(round(($totalRegistrations/$totalUsers)*100),100) : 0;
    $mentorRate   = $totalUsers > 0 ? min(round(($activeAssignments/$totalUsers)*100),100) : 0;

    $secScore = 0;
    if ($otpEnabled)       $secScore += 30;
    if ($twoFARate >= 50)  $secScore += 30;
    if ($failedLogins < 5) $secScore += 20;
    if ($activeRate >= 70) $secScore += 20;
    $secColor = $secScore >= 80 ? '#10b981' : ($secScore >= 50 ? '#f59e0b' : '#ef4444');
    $secLabel = $secScore >= 80 ? 'Strong' : ($secScore >= 50 ? 'Moderate' : 'Needs Attention');

    $roleLabels  = $usersByRole->keys()->toArray();
    $roleCounts  = $usersByRole->values()->toArray();
    $chartPalette= ['#4f46e5','#10b981','#8b5cf6','#f59e0b','#ec4899','#06b6d4','#ef4444','#6366f1','#14b8a6','#f97316'];
    $sparkValues = array_values($sparklineData);
@endphp

{{-- ═══════════════════════════════════════════════════════════════
     HERO
═══════════════════════════════════════════════════════════════ --}}
<div class="sm-hero px-6 py-8 md:py-10">
    <div class="relative z-10 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="flex items-center gap-3 mb-2">
                <div class="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-shield-alt text-white text-lg"></i>
                </div>
                <span class="text-indigo-200 text-sm font-medium uppercase tracking-widest">Super Manager</span>
            </div>
            <h1 class="text-2xl md:text-3xl font-bold text-white">
                System Control Center
            </h1>
            <p class="text-indigo-300 text-sm mt-1">
                {{ now()->format('l, d F Y') }} &mdash; Full system visibility &amp; security oversight
            </p>
        </div>
        <div class="flex flex-wrap gap-3">
            <a href="{{ route('users.index') }}"
               class="flex items-center gap-2 px-4 py-2 bg-white/15 hover:bg-white/25 text-white text-sm font-medium rounded-xl border border-white/20 transition">
                <i class="fas fa-users text-xs"></i> Users
            </a>
            <a href="{{ route('roles.index') }}"
               class="flex items-center gap-2 px-4 py-2 bg-white text-indigo-700 text-sm font-semibold rounded-xl hover:bg-indigo-50 transition">
                <i class="fas fa-user-shield text-xs"></i> Roles &amp; Permissions
            </a>
        </div>
    </div>
</div>

<div class="px-6 py-6 space-y-8">

{{-- ═══════════════════════════════════════════════════════════════
     SYSTEM ALERTS
═══════════════════════════════════════════════════════════════ --}}
@if(!empty($systemAlerts))
<div class="space-y-2">
    @foreach($systemAlerts as $alert)
    @php
        $cls = match($alert['severity'] ?? 'info') {
            'critical' => 'alert-critical',
            'warning'  => 'alert-warning',
            default    => 'alert-info',
        };
        $icon = match($alert['severity'] ?? 'info') {
            'critical' => 'fa-triangle-exclamation',
            'warning'  => 'fa-exclamation-circle',
            default    => 'fa-info-circle',
        };
    @endphp
    <div class="{{ $cls }} rounded-xl px-4 py-3 flex items-center gap-3" x-data="{show:true}" x-show="show">
        <i class="fas {{ $icon }} flex-shrink-0"></i>
        <p class="text-sm font-medium flex-1">{{ $alert['message'] }}</p>
        <button @click="show=false" class="opacity-60 hover:opacity-100 transition"><i class="fas fa-times text-xs"></i></button>
    </div>
    @endforeach
</div>
@endif

{{-- ═══════════════════════════════════════════════════════════════
     ROW 1 — PRIMARY KPI CARDS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-indigo-50"><i class="fas fa-users text-indigo-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Total Users</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalUsers) }}</p>
            <p class="text-xs text-indigo-500 font-medium mt-0.5"><i class="fas fa-arrow-up text-[9px]"></i> {{ $newThisWeek }} this week</p>
        </div>
    </div>
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-emerald-50"><i class="fas fa-user-check text-emerald-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Active Users</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($activeUsers) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">{{ $activeRate }}% of total</p>
        </div>
    </div>
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-violet-50"><i class="fas fa-id-card text-violet-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Members</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalMembers) }}</p>
            @if($pendingApprovals > 0)
            <p class="text-xs text-amber-600 font-medium mt-0.5"><i class="fas fa-clock text-[9px]"></i> {{ $pendingApprovals }} pending</p>
            @else
            <p class="text-xs text-slate-400 mt-0.5">No pending</p>
            @endif
        </div>
    </div>
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-amber-50"><i class="fas fa-coins text-amber-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Monthly Revenue</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($monthlyRev, 0) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">This month</p>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 2 — SECURITY KPI CARDS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-cyan-50"><i class="fas fa-sign-in-alt text-cyan-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Logins (7d)</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($recentLogins) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Unique sessions</p>
        </div>
    </div>
    <div class="sm-card p-5 flex items-center gap-4 {{ $failedLogins > 10 ? 'border-red-200' : '' }}">
        <div class="kpi-icon {{ $failedLogins > 10 ? 'bg-red-50' : 'bg-slate-50' }}">
            <i class="fas fa-ban {{ $failedLogins > 10 ? 'text-red-500' : 'text-slate-400' }} text-xl"></i>
        </div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Failed Logins</p>
            <p class="text-2xl font-bold {{ $failedLogins > 10 ? 'text-red-600' : 'text-slate-800' }}">{{ number_format($failedLogins) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Today</p>
        </div>
    </div>
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-indigo-50"><i class="fas fa-shield-halved text-indigo-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">2FA Enabled</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($twoFACount) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">{{ $twoFARate }}% adoption</p>
        </div>
    </div>
    <div class="sm-card p-5 flex items-center gap-4">
        <div class="kpi-icon {{ $otpEnabled ? 'bg-emerald-50' : 'bg-red-50' }}">
            <i class="fas fa-key {{ $otpEnabled ? 'text-emerald-600' : 'text-red-500' }} text-xl"></i>
        </div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">OTP System</p>
            <p class="text-lg font-bold text-slate-800">{{ $otpEnabled ? 'Active' : 'Inactive' }}</p>
            <span class="badge-pill {{ $otpEnabled ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700' }}">
                {{ $otpEnabled ? 'Enabled' : 'Disabled' }}
            </span>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 3 — SECURITY POSTURE + USER HEALTH + LOGIN SPARKLINE
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Security Score Card --}}
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-shield-halved text-indigo-500"></i> Security Posture</p>
        <div class="flex flex-col items-center justify-center py-4">
            <div class="relative w-32 h-32 mb-4">
                <canvas id="secGaugeChart" data-score="{{ $secScore }}" data-color="{{ $secColor }}"></canvas>
                <div class="absolute inset-0 flex flex-col items-center justify-center">
                    <span class="text-3xl font-bold text-slate-800">{{ $secScore }}</span>
                    <span class="text-xs text-slate-400">/100</span>
                </div>
            </div>
            <span class="badge-pill text-sm px-4 py-1.5 font-bold"
                  style="background:{{ $secColor }}22; color:{{ $secColor }}">
                {{ $secLabel }}
            </span>
        </div>
        <div class="space-y-3 mt-4 border-t border-slate-100 pt-4">
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-user-check text-emerald-400 w-4"></i> Active Rate</span>
                <span class="font-bold text-slate-700">{{ $activeRate }}%</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-shield-halved text-indigo-400 w-4"></i> 2FA Adoption</span>
                <span class="font-bold text-slate-700">{{ $twoFARate }}%</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-key text-{{ $otpEnabled ? 'emerald' : 'red' }}-400 w-4"></i> OTP System</span>
                <span class="font-bold {{ $otpEnabled ? 'text-emerald-600' : 'text-red-600' }}">{{ $otpEnabled ? 'ON' : 'OFF' }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-ban text-red-400 w-4"></i> Failed Logins</span>
                <span class="font-bold {{ $failedLogins > 10 ? 'text-red-600' : 'text-slate-700' }}">{{ $failedLogins }}</span>
            </div>
        </div>
    </div>

    {{-- User Health Progress --}}
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-heart-pulse text-red-500"></i> User Health Overview</p>
        <div class="space-y-4">
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Active Users</span>
                    <span class="font-bold text-slate-700">{{ $activeUsers }} / {{ $totalUsers }} ({{ $activeRate }}%)</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-emerald-500" style="width:{{ $activeRate }}%"></div></div>
            </div>
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>2FA Adoption</span>
                    <span class="font-bold text-slate-700">{{ $twoFACount }} / {{ $totalUsers }} ({{ $twoFARate }}%)</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-indigo-500" style="width:{{ $twoFARate }}%"></div></div>
            </div>
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Membership Coverage</span>
                    <span class="font-bold text-slate-700">{{ $totalMembers }} / {{ $totalUsers }} ({{ $memberRate }}%)</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-violet-500" style="width:{{ $memberRate }}%"></div></div>
            </div>
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Training Engagement</span>
                    <span class="font-bold text-slate-700">{{ $totalRegistrations }} registrations</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-blue-500" style="width:{{ $trainingRate }}%"></div></div>
            </div>
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Mentorship Reach</span>
                    <span class="font-bold text-slate-700">{{ $activeAssignments }} active pairs</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-teal-500" style="width:{{ $mentorRate }}%"></div></div>
            </div>
        </div>
    </div>

    {{-- Login Sparkline + Summary --}}
    <div class="sm-card p-6 flex flex-col gap-4">
        <p class="sec-title"><i class="fas fa-chart-line text-cyan-500"></i> Login Activity (24h)</p>
        @if(!empty($sparkValues))
        <div class="relative h-28">
            <canvas id="loginSparkline" data-values="{{ json_encode($sparkValues) }}"></canvas>
        </div>
        @else
        <div class="h-28 flex items-center justify-center text-slate-400 text-sm bg-slate-50 rounded-xl">
            <i class="fas fa-chart-line text-2xl text-slate-200 mr-2"></i> No login data yet
        </div>
        @endif
        <div class="border-t border-slate-100 pt-4 space-y-3">
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-sign-in-alt text-cyan-400 w-4"></i> Logins (7d)</span>
                <span class="font-bold text-slate-700">{{ number_format($recentLogins) }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-user-plus text-emerald-400 w-4"></i> New (7d)</span>
                <span class="font-bold text-slate-700">{{ number_format($newThisWeek) }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-ban text-red-400 w-4"></i> Failed today</span>
                <span class="font-bold {{ $failedLogins > 10 ? 'text-red-600' : 'text-slate-700' }}">{{ number_format($failedLogins) }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-user-slash text-amber-400 w-4"></i> Inactive</span>
                <span class="font-bold text-slate-700">{{ number_format($inactiveUsers) }}</span>
            </div>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 4 — USERS BY ROLE CHARTS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Doughnut: Users by Role --}}
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-chart-pie text-indigo-500"></i> Users by Role</p>
        @if($usersByRole->isNotEmpty())
        <div class="relative h-44 flex items-center justify-center">
            <canvas id="roleDonutChart"
                    data-labels="{{ json_encode($roleLabels) }}"
                    data-values="{{ json_encode($roleCounts) }}"
                    data-colors="{{ json_encode(array_slice($chartPalette, 0, count($roleLabels))) }}">
            </canvas>
        </div>
        <div class="mt-3 space-y-1.5">
            @foreach($usersByRole as $role => $count)
            @php $pct = $totalUsers > 0 ? round(($count/$totalUsers)*100) : 0; @endphp
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5 text-slate-600 truncate max-w-[60%]">
                    <span class="w-2 h-2 rounded-full flex-shrink-0" style="background:{{ $chartPalette[$loop->index % count($chartPalette)] }}"></span>
                    {{ $role }}
                </span>
                <span class="font-semibold text-slate-700">{{ $count }} <span class="text-slate-400">({{ $pct }}%)</span></span>
            </div>
            @endforeach
        </div>
        @else
        <div class="flex flex-col items-center justify-center h-40 text-slate-400">
            <i class="fas fa-chart-pie text-3xl mb-2 text-slate-200"></i>
            <p class="text-sm">No role data available.</p>
        </div>
        @endif
    </div>

    {{-- Bar: Role Distribution --}}
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-chart-bar text-violet-500"></i> Role Distribution</p>
        @if($usersByRole->isNotEmpty())
        <div class="relative h-44">
            <canvas id="roleBarChart"
                    data-labels="{{ json_encode($roleLabels) }}"
                    data-values="{{ json_encode($roleCounts) }}"
                    data-colors="{{ json_encode(array_slice($chartPalette, 0, count($roleLabels))) }}">
            </canvas>
        </div>
        <div class="mt-3 space-y-2">
            @foreach($usersByRole as $role => $count)
            @php
                $pct   = $totalUsers > 0 ? round(($count/$totalUsers)*100) : 0;
                $color = $chartPalette[$loop->index % count($chartPalette)];
            @endphp
            <div>
                <div class="flex justify-between text-xs mb-1">
                    <span class="text-slate-600 font-medium">{{ $role }}</span>
                    <span class="text-slate-500">{{ $count }} ({{ $pct }}%)</span>
                </div>
                <div class="pbar-wrap" style="height:6px">
                    <div class="pbar-fill" style="width:{{ $pct }}%;background:{{ $color }}"></div>
                </div>
            </div>
            @endforeach
        </div>
        @else
        <div class="flex flex-col items-center justify-center h-44 text-slate-400">
            <i class="fas fa-chart-bar text-3xl mb-2 text-slate-200"></i>
            <p class="text-sm">No data available.</p>
        </div>
        @endif
    </div>

    {{-- Module Comparison Table --}}
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-table-list text-teal-500"></i> Module Comparison</p>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-slate-100">
                        <th class="text-left text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Module</th>
                        <th class="text-right text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Total</th>
                        <th class="text-right text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Active</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-50">
                    <tr>
                        <td class="py-2.5 text-slate-700 flex items-center gap-2"><i class="fas fa-users text-indigo-400 w-4"></i> Users</td>
                        <td class="py-2.5 text-right font-semibold text-slate-700">{{ number_format($totalUsers) }}</td>
                        <td class="py-2.5 text-right"><span class="badge-pill bg-emerald-100 text-emerald-700">{{ number_format($activeUsers) }}</span></td>
                    </tr>
                    <tr>
                        <td class="py-2.5 text-slate-700 flex items-center gap-2"><i class="fas fa-id-card text-violet-400 w-4"></i> Members</td>
                        <td class="py-2.5 text-right font-semibold text-slate-700">{{ number_format($totalMembers) }}</td>
                        <td class="py-2.5 text-right">
                            @if($pendingApprovals > 0)
                            <span class="badge-pill bg-amber-100 text-amber-700">{{ $pendingApprovals }} pend.</span>
                            @else
                            <span class="badge-pill bg-emerald-100 text-emerald-700">All clear</span>
                            @endif
                        </td>
                    </tr>
                    <tr>
                        <td class="py-2.5 text-slate-700 flex items-center gap-2"><i class="fas fa-chalkboard-user text-blue-400 w-4"></i> Training</td>
                        <td class="py-2.5 text-right font-semibold text-slate-700">{{ number_format($totalTrainingSessions) }}</td>
                        <td class="py-2.5 text-right"><span class="badge-pill bg-blue-100 text-blue-700">{{ number_format($activeTrainingSessions) }}</span></td>
                    </tr>
                    <tr>
                        <td class="py-2.5 text-slate-700 flex items-center gap-2"><i class="fas fa-people-group text-teal-400 w-4"></i> Mentorship</td>
                        <td class="py-2.5 text-right font-semibold text-slate-700">{{ number_format($totalMentorshipSessions) }}</td>
                        <td class="py-2.5 text-right"><span class="badge-pill bg-teal-100 text-teal-700">{{ number_format($activeAssignments) }}</span></td>
                    </tr>
                    <tr>
                        <td class="py-2.5 text-slate-700 flex items-center gap-2"><i class="fas fa-coins text-amber-400 w-4"></i> Revenue</td>
                        <td class="py-2.5 text-right font-semibold text-slate-700" colspan="2">{{ number_format($monthlyRev, 0) }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 5 — SELF-PACED STATISTICS
═══════════════════════════════════════════════════════════════ --}}
@can('view self-paced courses')
@php
    $spCourses   = \App\Models\SelfPaced\Course::count();
    $spEnrolls   = \App\Models\SelfPaced\Enrollment::count();
    $spExams     = \App\Models\SelfPaced\ExamAttempt::where('status','submitted')->count();
    $spCerts     = \App\Models\SelfPaced\SelfPacedCertificate::where('is_revoked',false)->count();
    $spRevenue   = \App\Models\SelfPaced\Enrollment::where('payment_status','paid')->sum('amount') ?? 0;
    $spActive    = \App\Models\SelfPaced\Enrollment::where('status','active')->count();
    $spCompleted = \App\Models\SelfPaced\Enrollment::where('status','completed')->count();
    $spPending   = \App\Models\SelfPaced\Enrollment::where('status','pending')->count();
    $spPassRate  = $spExams > 0 ? round((\App\Models\SelfPaced\ExamAttempt::where('status','submitted')->where('passed',true)->count() / $spExams)*100) : 0;
@endphp
<div>
    <p class="sec-title"><i class="fas fa-graduation-cap text-indigo-500"></i> Self-Paced Learning Statistics</p>
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <div class="sm-card p-4 text-center">
            <i class="fas fa-book-open text-indigo-500 text-2xl mb-2"></i>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spCourses) }}</p>
            <p class="text-xs text-slate-500 mt-0.5">Total Courses</p>
        </div>
        <div class="sm-card p-4 text-center">
            <i class="fas fa-users text-blue-500 text-2xl mb-2"></i>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spEnrolls) }}</p>
            <p class="text-xs text-slate-500 mt-0.5">Enrollments</p>
            <span class="badge-pill bg-blue-100 text-blue-700 mt-1">{{ $spActive }} active</span>
        </div>
        <div class="sm-card p-4 text-center">
            <i class="fas fa-clipboard-question text-violet-500 text-2xl mb-2"></i>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spExams) }}</p>
            <p class="text-xs text-slate-500 mt-0.5">Exams Taken</p>
            <span class="badge-pill bg-violet-100 text-violet-700 mt-1">{{ $spPassRate }}% pass</span>
        </div>
        <div class="sm-card p-4 text-center">
            <i class="fas fa-certificate text-amber-500 text-2xl mb-2"></i>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spCerts) }}</p>
            <p class="text-xs text-slate-500 mt-0.5">Certificates</p>
            <span class="badge-pill bg-amber-100 text-amber-700 mt-1">Issued</span>
        </div>
        <div class="sm-card p-4 text-center">
            <i class="fas fa-check-circle text-emerald-500 text-2xl mb-2"></i>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spCompleted) }}</p>
            <p class="text-xs text-slate-500 mt-0.5">Completed</p>
            <span class="badge-pill bg-emerald-100 text-emerald-700 mt-1">Courses</span>
        </div>
        <div class="sm-card p-4 text-center">
            <i class="fas fa-coins text-red-500 text-2xl mb-2"></i>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spRevenue, 0) }}</p>
            <p class="text-xs text-slate-500 mt-0.5">SP Revenue</p>
            <span class="badge-pill bg-red-100 text-red-600 mt-1">Collected</span>
        </div>
    </div>
</div>
@endcan

{{-- ═══════════════════════════════════════════════════════════════
     ROW 6 — KNOWLEDGE BASE + CHAT STATS
═══════════════════════════════════════════════════════════════ --}}
@php
    $kbArticles    = \App\Models\Discussion::count();
    $kbPublished   = \App\Models\Discussion::where('status','published')->count();
    $kbReplies     = \App\Models\DiscussionReply::count();
    $chatMessages  = class_exists(\App\Models\ChatMessage::class) ? \App\Models\ChatMessage::count() : 0;
    $chatRooms     = class_exists(\App\Models\ChatRoom::class) ? \App\Models\ChatRoom::count() : 0;
@endphp
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-book text-indigo-500"></i> Knowledge Base</p>
        <div class="grid grid-cols-3 gap-4">
            <div class="bg-indigo-50 rounded-xl p-4 text-center border border-indigo-100">
                <i class="fas fa-file-alt text-indigo-500 text-xl mb-2"></i>
                <p class="text-2xl font-bold text-slate-800">{{ number_format($kbArticles) }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Total Articles</p>
            </div>
            <div class="bg-emerald-50 rounded-xl p-4 text-center border border-emerald-100">
                <i class="fas fa-check-circle text-emerald-500 text-xl mb-2"></i>
                <p class="text-2xl font-bold text-slate-800">{{ number_format($kbPublished) }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Published</p>
            </div>
            <div class="bg-blue-50 rounded-xl p-4 text-center border border-blue-100">
                <i class="fas fa-reply text-blue-500 text-xl mb-2"></i>
                <p class="text-2xl font-bold text-slate-800">{{ number_format($kbReplies) }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Replies</p>
            </div>
        </div>
        <div class="mt-4">
            <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                <span>Publication Rate</span>
                @php $pubRate = $kbArticles > 0 ? round(($kbPublished/$kbArticles)*100) : 0; @endphp
                <span class="font-bold text-slate-700">{{ $pubRate }}%</span>
            </div>
            <div class="pbar-wrap"><div class="pbar-fill bg-indigo-500" style="width:{{ $pubRate }}%"></div></div>
        </div>
    </div>
    <div class="sm-card p-6">
        <p class="sec-title"><i class="fas fa-comments text-teal-500"></i> Chat &amp; Communication</p>
        <div class="grid grid-cols-2 gap-4">
            <div class="bg-teal-50 rounded-xl p-4 text-center border border-teal-100">
                <i class="fas fa-comment-dots text-teal-500 text-xl mb-2"></i>
                <p class="text-2xl font-bold text-slate-800">{{ number_format($chatMessages) }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Total Messages</p>
            </div>
            <div class="bg-cyan-50 rounded-xl p-4 text-center border border-cyan-100">
                <i class="fas fa-door-open text-cyan-500 text-xl mb-2"></i>
                <p class="text-2xl font-bold text-slate-800">{{ number_format($chatRooms) }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Chat Rooms</p>
            </div>
        </div>
        <div class="mt-4 space-y-2">
            @if(Route::has('chat.index'))
            <a href="{{ route('chat.index') }}" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-teal-50 transition group">
                <i class="fas fa-comments text-teal-400 w-4 group-hover:text-teal-600"></i>
                <span class="text-sm text-slate-600 group-hover:text-slate-800">Open Live Chat</span>
                <i class="fas fa-chevron-right text-slate-300 text-xs ml-auto"></i>
            </a>
            @endif
            @if(Route::has('emails.compose'))
            <a href="{{ route('emails.compose') }}" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-blue-50 transition group">
                <i class="fas fa-envelope text-blue-400 w-4 group-hover:text-blue-600"></i>
                <span class="text-sm text-slate-600 group-hover:text-slate-800">Compose Email</span>
                <i class="fas fa-chevron-right text-slate-300 text-xs ml-auto"></i>
            </a>
            @endif
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 7 — USER MANAGEMENT TABLE
═══════════════════════════════════════════════════════════════ --}}
<div class="sm-card p-6">
    <div class="flex items-center justify-between mb-4">
        <p class="sec-title mb-0"><i class="fas fa-users-gear text-indigo-500"></i> User Management Overview</p>
        <a href="{{ route('users.index') }}" class="text-xs text-indigo-600 hover:underline font-medium">View All →</a>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="border-b border-slate-100">
                    <th class="text-left text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Metric</th>
                    <th class="text-right text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Count</th>
                    <th class="text-right text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Rate</th>
                    <th class="text-right text-xs text-slate-400 font-medium pb-2 uppercase tracking-wide">Status</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
                <tr>
                    <td class="py-3 text-slate-700 flex items-center gap-2"><i class="fas fa-users text-indigo-400 w-4"></i> Total Users</td>
                    <td class="py-3 text-right font-bold text-slate-800">{{ number_format($totalUsers) }}</td>
                    <td class="py-3 text-right text-slate-500">100%</td>
                    <td class="py-3 text-right"><span class="badge-pill bg-indigo-100 text-indigo-700">Baseline</span></td>
                </tr>
                <tr>
                    <td class="py-3 text-slate-700 flex items-center gap-2"><i class="fas fa-user-check text-emerald-400 w-4"></i> Active Users</td>
                    <td class="py-3 text-right font-bold text-slate-800">{{ number_format($activeUsers) }}</td>
                    <td class="py-3 text-right text-slate-500">{{ $activeRate }}%</td>
                    <td class="py-3 text-right"><span class="badge-pill bg-emerald-100 text-emerald-700">Healthy</span></td>
                </tr>
                <tr>
                    <td class="py-3 text-slate-700 flex items-center gap-2"><i class="fas fa-user-slash text-amber-400 w-4"></i> Inactive Users</td>
                    <td class="py-3 text-right font-bold text-slate-800">{{ number_format($inactiveUsers) }}</td>
                    <td class="py-3 text-right text-slate-500">{{ $totalUsers > 0 ? round(($inactiveUsers/$totalUsers)*100) : 0 }}%</td>
                    <td class="py-3 text-right"><span class="badge-pill bg-amber-100 text-amber-700">Monitor</span></td>
                </tr>
                <tr>
                    <td class="py-3 text-slate-700 flex items-center gap-2"><i class="fas fa-shield-halved text-indigo-400 w-4"></i> 2FA Enabled</td>
                    <td class="py-3 text-right font-bold text-slate-800">{{ number_format($twoFACount) }}</td>
                    <td class="py-3 text-right text-slate-500">{{ $twoFARate }}%</td>
                    <td class="py-3 text-right"><span class="badge-pill {{ $twoFARate >= 50 ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700' }}">{{ $twoFARate >= 50 ? 'Good' : 'Low' }}</span></td>
                </tr>
                <tr>
                    <td class="py-3 text-slate-700 flex items-center gap-2"><i class="fas fa-user-plus text-blue-400 w-4"></i> New This Week</td>
                    <td class="py-3 text-right font-bold text-slate-800">{{ number_format($newThisWeek) }}</td>
                    <td class="py-3 text-right text-slate-500">—</td>
                    <td class="py-3 text-right"><span class="badge-pill bg-blue-100 text-blue-700">Growth</span></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 8 — PERMISSION HEATMAP
═══════════════════════════════════════════════════════════════ --}}
@if($rolesWithPerms->isNotEmpty())
<div class="sm-card p-6">
    <div class="flex items-center justify-between mb-4">
        <p class="sec-title mb-0"><i class="fas fa-th text-indigo-500"></i> Permission Heatmap</p>
        <span class="text-xs text-slate-400">
            {{ $rolesWithPerms->flatMap(fn($r)=>$r->permissions)->unique('id')->count() }} permissions &times; {{ $rolesWithPerms->count() }} roles
        </span>
    </div>
    @php
        $allPerms = $rolesWithPerms->flatMap(fn($r)=>$r->permissions)->unique('id')->sortBy('name');
        $rolePermMap = [];
        foreach($rolesWithPerms as $role) {
            $rolePermMap[$role->id] = $role->permissions->pluck('name')->flip()->toArray();
        }
    @endphp
    <div class="overflow-auto max-h-72 rounded-xl border border-slate-100">
        <table class="w-full text-xs border-collapse">
            <thead class="sticky top-0 z-10 bg-slate-50">
                <tr>
                    <th class="text-left text-slate-500 font-medium px-3 py-2 border-b border-slate-100 min-w-[180px]">Permission</th>
                    @foreach($rolesWithPerms as $role)
                    <th class="text-center text-slate-600 font-medium px-2 py-2 border-b border-slate-100 min-w-[80px] whitespace-nowrap">{{ $role->name }}</th>
                    @endforeach
                </tr>
            </thead>
            <tbody>
                @foreach($allPerms as $perm)
                <tr class="odd:bg-white even:bg-slate-50/50 hover:bg-indigo-50/30 transition-colors border-b border-slate-50 last:border-0">
                    <td class="text-slate-600 px-3 py-1.5 font-mono text-[11px]">{{ $perm->name }}</td>
                    @foreach($rolesWithPerms as $role)
                    @php $granted = isset($rolePermMap[$role->id][$perm->name]); @endphp
                    <td class="text-center px-2 py-1.5">
                        @if($granted)
                        <span class="perm-cell-yes" title="Granted to {{ $role->name }}">
                            <i class="fas fa-check text-emerald-500" style="font-size:9px"></i>
                        </span>
                        @else
                        <span class="perm-cell-no" title="Not granted to {{ $role->name }}">
                            <i class="fas fa-minus text-slate-300" style="font-size:9px"></i>
                        </span>
                        @endif
                    </td>
                    @endforeach
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
    <div class="flex items-center gap-4 mt-3 text-xs text-slate-400">
        <span class="flex items-center gap-1.5">
            <span class="perm-cell-yes"><i class="fas fa-check text-emerald-500" style="font-size:8px"></i></span> Granted
        </span>
        <span class="flex items-center gap-1.5">
            <span class="perm-cell-no"><i class="fas fa-minus text-slate-300" style="font-size:8px"></i></span> Not granted
        </span>
    </div>
</div>
@endif

{{-- ═══════════════════════════════════════════════════════════════
     ROW 9 — QUICK ACTIONS
═══════════════════════════════════════════════════════════════ --}}
<div class="sm-card p-6">
    <p class="sec-title"><i class="fas fa-bolt text-amber-500"></i> Quick Actions</p>
    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3">
        <a href="{{ route('users.index') }}" class="qa-btn">
            <i class="fas fa-users text-2xl text-indigo-500"></i>
            <span class="text-xs text-slate-600 font-medium text-center">Manage Users</span>
        </a>
        <a href="{{ route('roles.index') }}" class="qa-btn">
            <i class="fas fa-user-shield text-2xl text-emerald-500"></i>
            <span class="text-xs text-slate-600 font-medium text-center">Roles &amp; Perms</span>
        </a>
        <a href="{{ route('otp.settings') }}" class="qa-btn">
            <i class="fas fa-key text-2xl text-violet-500"></i>
            <span class="text-xs text-slate-600 font-medium text-center">OTP Settings</span>
        </a>
        <a href="{{ route('admin.members.applications.index') }}" class="qa-btn">
            <i class="fas fa-id-card text-2xl text-amber-500"></i>
            <span class="text-xs text-slate-600 font-medium text-center">Membership</span>
        </a>
        <a href="{{ route('admin.themes.index') }}" class="qa-btn">
            <i class="fas fa-palette text-2xl text-pink-500"></i>
            <span class="text-xs text-slate-600 font-medium text-center">Themes</span>
        </a>
        <a href="/telescope" class="qa-btn">
            <i class="fas fa-magnifying-glass-chart text-2xl text-slate-500"></i>
            <span class="text-xs text-slate-600 font-medium text-center">Audit Log</span>
        </a>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     SELF-PACED PORTAL BANNER
═══════════════════════════════════════════════════════════════ --}}
@can('view self-paced courses')
<div class="portal-banner">
    <div class="flex items-center gap-4">
        <div class="w-14 h-14 bg-white/20 rounded-2xl flex items-center justify-center flex-shrink-0">
            <i class="fas fa-graduation-cap text-white text-2xl"></i>
        </div>
        <div>
            <h3 class="text-lg font-bold text-white">Self-Paced Learning Portal</h3>
            <p class="text-indigo-200 text-sm">Manage courses, exams, enrollments and certificates</p>
        </div>
    </div>
    <a href="{{ route('self-paced.dashboard.index') }}"
       class="flex items-center gap-2 px-5 py-2.5 bg-white text-indigo-700 font-semibold rounded-xl hover:bg-indigo-50 transition text-sm flex-shrink-0">
        <i class="fas fa-arrow-right"></i> Open Portal
    </a>
</div>
@endcan

</div>{{-- end px-6 --}}
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Security Gauge (Doughnut)
    const gaugeCanvas = document.getElementById('secGaugeChart');
    if (gaugeCanvas) {
        const score = parseInt(gaugeCanvas.dataset.score || 0);
        const color = gaugeCanvas.dataset.color || '#4f46e5';
        new Chart(gaugeCanvas, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [score, 100 - score],
                    backgroundColor: [color, '#f1f5f9'],
                    borderWidth: 0,
                    circumference: 270,
                    rotation: 225,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                cutout: '78%',
                plugins: { legend: { display: false }, tooltip: { enabled: false } }
            }
        });
    }

    // Role Donut Chart
    const donutCanvas = document.getElementById('roleDonutChart');
    if (donutCanvas) {
        const labels = JSON.parse(donutCanvas.dataset.labels || '[]');
        const values = JSON.parse(donutCanvas.dataset.values || '[]');
        const colors = JSON.parse(donutCanvas.dataset.colors || '[]');
        new Chart(donutCanvas, {
            type: 'doughnut',
            data: { labels, datasets: [{ data: values, backgroundColor: colors, borderWidth: 2, borderColor: '#fff' }] },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '65%',
                plugins: { legend: { display: false } }
            }
        });
    }

    // Role Bar Chart
    const barCanvas = document.getElementById('roleBarChart');
    if (barCanvas) {
        const labels = JSON.parse(barCanvas.dataset.labels || '[]');
        const values = JSON.parse(barCanvas.dataset.values || '[]');
        const colors = JSON.parse(barCanvas.dataset.colors || '[]');
        new Chart(barCanvas, {
            type: 'bar',
            data: { labels, datasets: [{ data: values, backgroundColor: colors, borderRadius: 6, borderSkipped: false }] },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { size: 9 }, color: '#94a3b8' } },
                    y: { grid: { color: '#f1f5f9' }, ticks: { font: { size: 9 }, color: '#94a3b8' }, beginAtZero: true }
                }
            }
        });
    }

    // Login Sparkline
    const sparkCanvas = document.getElementById('loginSparkline');
    if (sparkCanvas) {
        const values = JSON.parse(sparkCanvas.dataset.values || '[]');
        const labels = values.map((_, i) => i + 'h');
        new Chart(sparkCanvas, {
            type: 'line',
            data: {
                labels,
                datasets: [{
                    data: values,
                    borderColor: '#06b6d4',
                    backgroundColor: 'rgba(6,182,212,0.1)',
                    borderWidth: 2,
                    pointRadius: 0,
                    tension: 0.4,
                    fill: true,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { display: false },
                    y: { display: false, beginAtZero: true }
                }
            }
        });
    }
});
</script>
@endpush
