@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>
    .ct-hero {
        background: linear-gradient(135deg, #4f46e5 0%, #3730a3 60%, #1e1b4b 100%);
        position: relative; overflow: hidden;
    }
    .ct-hero::before {
        content:''; position:absolute; top:-60px; right:-60px;
        width:260px; height:260px; background:rgba(255,255,255,0.06); border-radius:50%;
    }
    .ct-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;
    }
    .ct-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); }
    .badge-pill { display:inline-flex;align-items:center;padding:2px 10px;border-radius:999px;font-size:0.68rem;font-weight:600; }
    .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); }
    .disc-item { display:flex;align-items:flex-start;gap:10px;padding:10px 0;border-bottom:1px solid #f1f5f9; }
    .disc-item:last-child { border-bottom:none; }
    .avatar-sm { width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#4f46e5,#818cf8);display:flex;align-items:center;justify-content:center;color:#fff;font-size:0.7rem;font-weight:700;flex-shrink:0; }
    .heatmap-grid { display:flex;gap:3px;flex-wrap:wrap; }
    .heatmap-cell { width:12px;height:12px;border-radius:2px; }
    .topic-tag { display:inline-flex;align-items:center;padding:4px 12px;border-radius:999px;font-size:0.72rem;font-weight:600;background:#eef2ff;color:#4f46e5;border:1px solid #c7d2fe;margin:2px; }
    .profile-row { display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid #f1f5f9; }
    .profile-row:last-child { border-bottom:none; }
</style>
@endpush

@section('content')
@php
    $totalDiscussions   = $stats['total_discussions'] ?? 0;
    $publishedDiscs     = $stats['published_discussions'] ?? 0;
    $draftDiscs         = $stats['draft_discussions'] ?? 0;
    $totalReplies       = $stats['total_replies'] ?? 0;
    $totalViews         = $stats['total_views'] ?? 0;
    $activityData       = $stats['activity_data'] ?? [];
    $recentDiscussions  = $stats['recent_discussions'] ?? collect();
    $recentPublications = $stats['recent_publications'] ?? collect();
    $topics             = $stats['topics'] ?? collect();

    // Compute engagement rate
    $engagementRate = $totalDiscussions > 0 ? min(round(($totalReplies / max($totalDiscussions,1)) * 10), 100) : 0;
    $publishRate    = $totalDiscussions > 0 ? round(($publishedDiscs/$totalDiscussions)*100) : 0;

    // Discussion status breakdown
    $statusBreakdown = [
        'published'      => $publishedDiscs,
        'draft'          => $draftDiscs,
        'pending_review' => \App\Models\Discussion::where('user_id',$user->id)->where('status','pending_review')->count(),
        'archived'       => \App\Models\Discussion::where('user_id',$user->id)->where('status','archived')->count(),
    ];

    // Monthly discussion trend (last 6 months)
    $discTrend = \App\Models\Discussion::where('user_id',$user->id)
        ->where('created_at','>=',now()->subMonths(6))
        ->selectRaw('MONTH(created_at) as m, COUNT(*) as count')
        ->groupBy('m')->orderBy('m')
        ->pluck('count','m')->toArray();
    $discTrendLabels = collect(range(5,0))->map(fn($m) => now()->subMonths($m)->format('M'))->values()->toArray();
    $discTrendValues = collect(range(5,0))->map(fn($m) => $discTrend[now()->subMonths($m)->month] ?? 0)->values()->toArray();

    // Reply trend (last 6 months)
    $replyTrend = \App\Models\DiscussionReply::where('user_id',$user->id)
        ->where('created_at','>=',now()->subMonths(6))
        ->selectRaw('MONTH(created_at) as m, COUNT(*) as count')
        ->groupBy('m')->orderBy('m')
        ->pluck('count','m')->toArray();
    $replyTrendValues = collect(range(5,0))->map(fn($m) => $replyTrend[now()->subMonths($m)->month] ?? 0)->values()->toArray();

    // Top discussions by views
    $topDiscussions = \App\Models\Discussion::where('user_id',$user->id)
        ->where('status','published')
        ->orderByDesc('view_count')
        ->take(5)->get();
@endphp

{{-- ═══════════════════════════════════════════════════════════════
     HERO
═══════════════════════════════════════════════════════════════ --}}
<div class="ct-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-pen-nib text-white text-lg"></i>
                </div>
                <span class="text-indigo-200 text-sm font-medium uppercase tracking-widest">Contributor Dashboard</span>
            </div>
            <h1 class="text-2xl md:text-3xl font-bold text-white">
                Welcome, {{ $user->name ?? 'Contributor' }}
            </h1>
            <p class="text-indigo-300 text-sm mt-1">
                {{ now()->format('l, d F Y') }} &mdash; Your contributions &amp; knowledge base overview
            </p>
        </div>
        <div class="flex flex-wrap gap-3">
            @can('view discussions')
            <a href="{{ route('contributor.discussions') }}"
               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-file-alt text-xs"></i> My Submissions
            </a>
            @endcan
            <a href="{{ route('profile.edit') }}"
               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-edit text-xs"></i> Edit Profile
            </a>
        </div>
    </div>
</div>

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

{{-- Contextual Notifications --}}
@if($totalDiscussions === 0)
<div class="bg-indigo-50 border border-indigo-200 rounded-xl px-4 py-3 flex items-center gap-3" x-data="{show:true}" x-show="show">
    <i class="fas fa-info-circle text-indigo-500 flex-shrink-0"></i>
    <p class="text-sm font-medium text-indigo-800 flex-1">You haven't started any discussions yet. Start your first discussion to engage with the community!</p>
    <button @click="show=false" class="text-indigo-400 hover:text-indigo-600"><i class="fas fa-times text-xs"></i></button>
</div>
@endif
@if($draftDiscs > 0)
<div class="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-center gap-3" x-data="{show:true}" x-show="show">
    <i class="fas fa-exclamation-circle text-amber-500 flex-shrink-0"></i>
    <p class="text-sm font-medium text-amber-800 flex-1">You have {{ $draftDiscs }} draft discussion(s) waiting to be published.</p>
    <button @click="show=false" class="text-amber-400 hover:text-amber-600"><i class="fas fa-times text-xs"></i></button>
</div>
@endif

{{-- ═══════════════════════════════════════════════════════════════
     ROW 1 — PRIMARY KPI CARDS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="ct-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-indigo-50"><i class="fas fa-comments text-indigo-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Discussions</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalDiscussions) }}</p>
            <p class="text-xs text-indigo-500 font-medium mt-0.5">{{ $publishedDiscs }} published</p>
        </div>
    </div>
    <div class="ct-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-teal-50"><i class="fas fa-reply text-teal-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Replies</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalReplies) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Total responses</p>
        </div>
    </div>
    <div class="ct-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-cyan-50"><i class="fas fa-eye text-cyan-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Total Views</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalViews) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Across all posts</p>
        </div>
    </div>
    <div class="ct-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-red-50"><i class="fas fa-book text-red-500 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Publications</p>
            <p class="text-2xl font-bold text-slate-800">{{ $recentPublications->count() }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Knowledge base</p>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 2 — CONTRIBUTION TREND + STATUS BREAKDOWN
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Contribution Trend Chart --}}
    <div class="ct-card p-6 lg:col-span-2">
        <p class="sec-title"><i class="fas fa-chart-line text-indigo-500"></i> Contribution Trend (6 Months)</p>
        <div class="relative h-52">
            <canvas id="contribTrendChart"
                data-labels="{{ json_encode($discTrendLabels) }}"
                data-discussions="{{ json_encode($discTrendValues) }}"
                data-replies="{{ json_encode($replyTrendValues) }}">
            </canvas>
        </div>
        <div class="flex items-center gap-6 mt-3 text-xs text-slate-500">
            <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-full bg-indigo-500 inline-block"></span> Discussions</span>
            <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-full bg-teal-400 inline-block"></span> Replies</span>
        </div>
    </div>

    {{-- Discussion Status Breakdown --}}
    <div class="ct-card p-6">
        <p class="sec-title"><i class="fas fa-chart-pie text-violet-500"></i> Discussion Status</p>
        <div class="relative h-40 flex items-center justify-center">
            <canvas id="statusPieChart"
                data-published="{{ $statusBreakdown['published'] }}"
                data-draft="{{ $statusBreakdown['draft'] }}"
                data-pending="{{ $statusBreakdown['pending_review'] }}"
                data-archived="{{ $statusBreakdown['archived'] }}">
            </canvas>
        </div>
        <div class="mt-3 space-y-2">
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block"></span> Published</span>
                <span class="font-bold text-slate-700">{{ $statusBreakdown['published'] }}</span>
            </div>
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-slate-400 inline-block"></span> Draft</span>
                <span class="font-bold text-slate-700">{{ $statusBreakdown['draft'] }}</span>
            </div>
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-amber-400 inline-block"></span> Pending Review</span>
                <span class="font-bold text-slate-700">{{ $statusBreakdown['pending_review'] }}</span>
            </div>
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-red-400 inline-block"></span> Archived</span>
                <span class="font-bold text-slate-700">{{ $statusBreakdown['archived'] }}</span>
            </div>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 3 — ENGAGEMENT METRICS + ACTIVITY HEATMAP
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Engagement Metrics --}}
    <div class="ct-card p-6">
        <p class="sec-title"><i class="fas fa-fire text-red-500"></i> Engagement Metrics</p>
        <div class="space-y-4">
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Publication Rate</span>
                    <span class="font-bold text-slate-700">{{ $publishRate }}%</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-indigo-500" style="width:{{ $publishRate }}%"></div></div>
            </div>
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Engagement Score</span>
                    <span class="font-bold text-slate-700">{{ $engagementRate }}%</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-teal-500" style="width:{{ $engagementRate }}%"></div></div>
            </div>
            @php $viewsPerPost = $totalDiscussions > 0 ? round($totalViews/$totalDiscussions) : 0; $viewRate = min($viewsPerPost, 100); @endphp
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Avg Views / Post</span>
                    <span class="font-bold text-slate-700">{{ $viewsPerPost }}</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-cyan-500" style="width:{{ min($viewRate,100) }}%"></div></div>
            </div>
            @php $repliesPerPost = $totalDiscussions > 0 ? round($totalReplies/$totalDiscussions,1) : 0; @endphp
            <div>
                <div class="flex justify-between text-xs text-slate-500 mb-1.5">
                    <span>Avg Replies / Post</span>
                    <span class="font-bold text-slate-700">{{ $repliesPerPost }}</span>
                </div>
                <div class="pbar-wrap"><div class="pbar-fill bg-violet-500" style="width:{{ min($repliesPerPost*10,100) }}%"></div></div>
            </div>
        </div>
        <div class="mt-5 grid grid-cols-2 gap-3">
            <div class="bg-indigo-50 rounded-xl p-3 text-center border border-indigo-100">
                <p class="text-xl font-bold text-indigo-700">{{ $publishedDiscs }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Published</p>
            </div>
            <div class="bg-amber-50 rounded-xl p-3 text-center border border-amber-100">
                <p class="text-xl font-bold text-amber-700">{{ $draftDiscs }}</p>
                <p class="text-xs text-slate-500 mt-0.5">Drafts</p>
            </div>
        </div>
    </div>

    {{-- Activity Heatmap --}}
    @can('view discussions')
    <div class="ct-card p-6 lg:col-span-2">
        <p class="sec-title"><i class="fas fa-calendar-alt text-indigo-500"></i> Contribution Activity (Past Year)</p>
        <x-activity-heatmap :activity-data="$activityData" color="indigo" :weeks="52" />
        <div class="flex items-center gap-3 mt-3 text-xs text-slate-400">
            <span>Less</span>
            <span class="w-3 h-3 rounded-sm bg-slate-100 inline-block"></span>
            <span class="w-3 h-3 rounded-sm bg-indigo-200 inline-block"></span>
            <span class="w-3 h-3 rounded-sm bg-indigo-400 inline-block"></span>
            <span class="w-3 h-3 rounded-sm bg-indigo-600 inline-block"></span>
            <span class="w-3 h-3 rounded-sm bg-indigo-800 inline-block"></span>
            <span>More</span>
        </div>
    </div>
    @endcan
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 4 — TOP DISCUSSIONS + PROFILE
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

    {{-- Top Discussions by Views --}}
    <div class="ct-card p-6">
        <p class="sec-title"><i class="fas fa-star text-amber-500"></i> Top Discussions by Views</p>
        @forelse($topDiscussions as $disc)
        <div class="disc-item">
            <div class="avatar-sm">{{ strtoupper(substr($disc->title ?? 'D', 0, 1)) }}</div>
            <div class="flex-1 min-w-0">
                <p class="text-sm font-semibold text-slate-700 truncate">{{ $disc->title }}</p>
                <div class="flex items-center gap-3 mt-0.5 text-xs text-slate-400">
                    <span><i class="fas fa-eye mr-1"></i>{{ number_format($disc->view_count ?? 0) }}</span>
                    <span><i class="fas fa-reply mr-1"></i>{{ $disc->reply_count ?? 0 }}</span>
                    <span>{{ $disc->created_at?->diffForHumans() }}</span>
                </div>
            </div>
            <span class="badge-pill bg-emerald-100 text-emerald-700 flex-shrink-0">Published</span>
        </div>
        @empty
        <div class="flex flex-col items-center justify-center py-8 text-slate-400">
            <i class="fas fa-star text-3xl text-slate-200 mb-2"></i>
            <p class="text-sm">No published discussions yet.</p>
        </div>
        @endforelse
    </div>

    {{-- Contributor Profile --}}
    <div class="ct-card p-6">
        <p class="sec-title"><i class="fas fa-user-circle text-indigo-500"></i> Contributor Profile</p>
        <div class="space-y-1">
            <div class="profile-row">
                <span class="text-slate-500 text-sm">Email</span>
                <span class="text-slate-800 text-sm font-medium truncate max-w-[60%]">{{ $user->email }}</span>
            </div>
            <div class="profile-row">
                <span class="text-slate-500 text-sm">Contribution Type</span>
                <span class="text-slate-800 text-sm">{{ $user->profile?->contribution_type ?? 'Not Set' }}</span>
            </div>
            <div class="profile-row">
                <span class="text-slate-500 text-sm">Skills</span>
                <span class="text-slate-800 text-sm truncate max-w-[60%]">{{ $user->profile?->skills ?? 'Not Set' }}</span>
            </div>
            <div class="profile-row">
                <span class="text-slate-500 text-sm">Portfolio</span>
                @if($user->profile?->portfolio_url)
                <a href="{{ $user->profile->portfolio_url }}" target="_blank" class="text-indigo-600 text-sm hover:underline truncate max-w-[60%]">
                    {{ Str::limit($user->profile->portfolio_url, 30) }}
                </a>
                @else
                <span class="text-slate-400 text-sm">Not Set</span>
                @endif
            </div>
            <div class="profile-row">
                <span class="text-slate-500 text-sm">Bio</span>
                <span class="text-slate-800 text-sm text-right max-w-[60%]">{{ Str::limit($user->profile?->bio ?? 'Not Set', 50) }}</span>
            </div>
            <div class="profile-row">
                <span class="text-slate-500 text-sm">Member Since</span>
                <span class="text-slate-800 text-sm font-medium">{{ $user->created_at?->format('d M Y') }}</span>
            </div>
        </div>
        <a href="{{ route('profile.edit') }}"
           class="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm rounded-xl transition">
            <i class="fas fa-edit"></i> Edit Profile
        </a>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 5 — RECENT DISCUSSIONS + ACTIVE TOPICS + QUICK ACTIONS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Recent Discussions --}}
    @can('view discussions')
    <div class="ct-card p-6 lg:col-span-2">
        <div class="flex items-center justify-between mb-4">
            <p class="sec-title mb-0"><i class="fas fa-history text-indigo-500"></i> Recent Discussions</p>
            <a href="{{ route('contributor.discussions') }}" class="text-xs text-indigo-600 hover:underline font-medium">View All →</a>
        </div>
        @forelse($recentDiscussions as $discussion)
        @php
            $statusMap = [
                'published'      => 'bg-emerald-100 text-emerald-700',
                'draft'          => 'bg-slate-100 text-slate-600',
                'archived'       => 'bg-red-100 text-red-600',
                'pending_review' => 'bg-amber-100 text-amber-700',
            ];
            $sc = $statusMap[$discussion->status ?? 'draft'] ?? 'bg-slate-100 text-slate-600';
        @endphp
        <div class="disc-item">
            <div class="avatar-sm">{{ strtoupper(substr($discussion->title ?? 'D', 0, 1)) }}</div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2 mb-0.5 flex-wrap">
                    @if($discussion->topic)
                    <span class="badge-pill bg-indigo-100 text-indigo-700">{{ $discussion->topic->name }}</span>
                    @endif
                    <span class="badge-pill {{ $sc }}">{{ ucfirst(str_replace('_',' ',$discussion->status ?? 'draft')) }}</span>
                </div>
                <p class="text-sm font-medium text-slate-800 truncate">{{ $discussion->title }}</p>
                <p class="text-xs text-slate-400 mt-0.5">
                    <i class="fas fa-reply mr-1"></i>{{ $discussion->reply_count ?? 0 }} replies
                    &middot; {{ $discussion->created_at?->diffForHumans() }}
                </p>
            </div>
        </div>
        @empty
        <div class="flex flex-col items-center justify-center py-8 text-slate-400">
            <i class="fas fa-comments text-3xl text-slate-200 mb-2"></i>
            <p class="text-sm">No discussions yet.</p>
        </div>
        @endforelse
    </div>
    @endcan

    {{-- Active Topics + Quick Actions --}}
    <div class="space-y-6">
        @if($topics->isNotEmpty())
        <div class="ct-card p-6">
            <p class="sec-title"><i class="fas fa-tags text-teal-500"></i> Active Topics</p>
            <div class="flex flex-wrap gap-1">
                @foreach($topics->take(10) as $topic)
                <span class="topic-tag">
                    {{ $topic->name }}
                    <span class="ml-1.5 text-indigo-400">({{ $topic->discussions_count }})</span>
                </span>
                @endforeach
            </div>
        </div>
        @endif

        <div class="ct-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 gap-3">
                @can('view discussions')
                <a href="{{ route('contributor.discussions') }}" class="qa-btn">
                    <i class="fas fa-file-alt text-xl text-indigo-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Submissions</span>
                </a>
                @endcan
                @can('view publications')
                <a href="{{ route('research.index') }}" class="qa-btn">
                    <i class="fas fa-book text-xl text-teal-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Publications</span>
                </a>
                @endcan
                <a href="{{ route('profile.edit') }}" class="qa-btn">
                    <i class="fas fa-globe text-xl text-cyan-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Portfolio</span>
                </a>
                @can('view discussions')
                <a href="{{ route('knowledge-sharing.discussions.index') }}" class="qa-btn">
                    <i class="fas fa-comments text-xl text-amber-500"></i>
                    <span class="text-xs text-slate-600 font-medium">All Discussions</span>
                </a>
                @endcan
            </div>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 6 — KNOWLEDGE BASE PUBLICATIONS
═══════════════════════════════════════════════════════════════ --}}
@can('view publications')
@if($recentPublications->isNotEmpty())
<div class="ct-card p-6">
    <div class="flex items-center justify-between mb-4">
        <p class="sec-title mb-0"><i class="fas fa-book-open text-indigo-500"></i> Knowledge Base Contributions</p>
        <a href="{{ route('research.index') }}" class="text-xs text-indigo-600 hover:underline font-medium">View All →</a>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        @foreach($recentPublications->take(6) as $pub)
        <div class="bg-slate-50 rounded-xl p-4 border border-slate-100 hover:border-indigo-200 hover:bg-indigo-50/30 transition">
            <div class="flex items-start gap-3">
                <div class="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-file-alt text-indigo-600"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <p class="text-sm font-semibold text-slate-800 truncate">{{ $pub->title ?? 'Untitled' }}</p>
                    <p class="text-xs text-slate-400 mt-0.5">{{ $pub->approved_at?->format('d M Y') ?? 'Pending' }}</p>
                    @if($pub->category)
                    <span class="badge-pill bg-indigo-100 text-indigo-700 mt-1">{{ $pub->category }}</span>
                    @endif
                </div>
            </div>
        </div>
        @endforeach
    </div>
</div>
@endif
@endcan

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

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Contribution Trend
    const trendCanvas = document.getElementById('contribTrendChart');
    if (trendCanvas) {
        const labels      = JSON.parse(trendCanvas.dataset.labels || '[]');
        const discussions = JSON.parse(trendCanvas.dataset.discussions || '[]');
        const replies     = JSON.parse(trendCanvas.dataset.replies || '[]');
        new Chart(trendCanvas, {
            type: 'line',
            data: {
                labels,
                datasets: [
                    {
                        label: 'Discussions',
                        data: discussions,
                        borderColor: '#4f46e5',
                        backgroundColor: 'rgba(79,70,229,0.08)',
                        borderWidth: 2.5,
                        pointRadius: 4,
                        pointBackgroundColor: '#4f46e5',
                        tension: 0.4,
                        fill: true,
                    },
                    {
                        label: 'Replies',
                        data: replies,
                        borderColor: '#14b8a6',
                        backgroundColor: 'rgba(20,184,166,0.06)',
                        borderWidth: 2.5,
                        pointRadius: 4,
                        pointBackgroundColor: '#14b8a6',
                        tension: 0.4,
                        fill: true,
                    }
                ]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { size: 11 }, color: '#94a3b8' } },
                    y: { grid: { color: '#f1f5f9' }, ticks: { font: { size: 10 }, color: '#94a3b8' }, beginAtZero: true }
                }
            }
        });
    }

    // Status Pie
    const pieCanvas = document.getElementById('statusPieChart');
    if (pieCanvas) {
        const published = parseInt(pieCanvas.dataset.published || 0);
        const draft     = parseInt(pieCanvas.dataset.draft || 0);
        const pending   = parseInt(pieCanvas.dataset.pending || 0);
        const archived  = parseInt(pieCanvas.dataset.archived || 0);
        new Chart(pieCanvas, {
            type: 'doughnut',
            data: {
                labels: ['Published', 'Draft', 'Pending', 'Archived'],
                datasets: [{
                    data: [published, draft, pending, archived],
                    backgroundColor: ['#10b981', '#94a3b8', '#f59e0b', '#ef4444'],
                    borderWidth: 2,
                    borderColor: '#fff',
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '60%',
                plugins: { legend: { display: false } }
            }
        });
    }
});
</script>
@endpush
