import React, { useState, useEffect, useRef } from 'react';
import { Link } from '@inertiajs/react';
import { AdminLayout } from './AdminLayout';
import { SEOHead } from '@/Components/SEOHead';
import { playNotificationSound } from '@/lib/sound';
import {
    FileText,
    Briefcase,
    FolderGit2,
    Users,
    Mail,
    MessageSquare,
    Plus,
    ArrowRight,
    Clock,
    MessageCircle,
    Send,
    Monitor,
    Smartphone,
    Tablet,
    Globe,
    TrendingUp,
    BarChart2,
    Eye,
    Layers,
    Sparkles,
} from 'lucide-react';

interface VisitorStats {
    total_views?: number;
    today_views?: number;
    week_views?: number;
    top_pages?: { url: string; views: number }[];
    top_countries?: { country: string; visitors: number }[];
    devices?: { desktop?: number; mobile?: number; tablet?: number };
}

interface DashboardProps {
    stats?: any;
    recentLeads?: any[];
    recentPosts?: any[];
    activeChatSessions?: any[];
    visitorStats?: VisitorStats;
}

const COUNTRY_FLAGS: Record<string, string> = {
    Bangladesh: '🇧🇩',
    'United States': '🇺🇸',
    India: '🇮🇳',
    'United Kingdom': '🇬🇧',
    Canada: '🇨🇦',
    Australia: '🇦🇺',
    Germany: '🇩🇪',
    France: '🇫🇷',
    Pakistan: '🇵🇰',
    Singapore: '🇸🇬',
    Malaysia: '🇲🇾',
    Netherlands: '🇳🇱',
    Japan: '🇯🇵',
    'Saudi Arabia': '🇸🇦',
    UAE: '🇦🇪',
    Local: '🏠',
    Unknown: '🌐',
};

function getFlag(country?: string): string {
    if (!country) return '🌐';
    return COUNTRY_FLAGS[country] ?? '🌐';
}

export default function Dashboard({
    stats = {},
    recentLeads = [],
    recentPosts = [],
    activeChatSessions = [],
    visitorStats = {},
}: DashboardProps) {
    const [sessions, setSessions] = useState<any[]>(Array.isArray(activeChatSessions) ? activeChatSessions : []);
    const [unreadTotal, setUnreadTotal] = useState<number>(stats?.unread_chat_count || 0);
    const [inlineReplies, setInlineReplies] = useState<Record<number, string>>({});
    const [sendingId, setSendingId] = useState<number | null>(null);

    const prevUnreadRef = useRef<number>(stats?.unread_chat_count || 0);

    useEffect(() => {
        if (Array.isArray(activeChatSessions)) {
            setSessions(activeChatSessions);
        }
    }, [activeChatSessions]);

    // Live auto-polling every 4 seconds for new chat messages on dashboard
    useEffect(() => {
        const pollChats = async () => {
            try {
                const res = await fetch('/admin/dashboard/api/active-chats');
                if (!res.ok) return;
                const data = await res.json();
                if (data?.success) {
                    const newUnread: number = data.unread_chat_count || 0;
                    if (newUnread > prevUnreadRef.current && prevUnreadRef.current >= 0) {
                        playNotificationSound();
                    }
                    prevUnreadRef.current = newUnread;
                    setUnreadTotal(newUnread);
                    setSessions(data.active_chat_sessions || []);
                }
            } catch (e) {
                // Silently catch polling issues
            }
        };

        const interval = setInterval(pollChats, 4000);
        return () => clearInterval(interval);
    }, []);

    const handleSendInlineReply = async (sessionId: number, e: React.FormEvent) => {
        e.preventDefault();
        const text = inlineReplies[sessionId]?.trim();
        if (!text) return;

        setSendingId(sessionId);
        try {
            const res = await fetch(`/admin/chat/${sessionId}/reply`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
                body: JSON.stringify({ message: text }),
            });
            const data = await res.json();
            if (data?.success) {
                setInlineReplies((prev) => ({ ...prev, [sessionId]: '' }));
                const refreshRes = await fetch('/admin/dashboard/api/active-chats');
                const refreshData = await refreshRes.json();
                if (refreshData?.success) {
                    setSessions(refreshData.active_chat_sessions || []);
                    setUnreadTotal(refreshData.unread_chat_count || 0);
                }
            }
        } catch (e) {
            console.error('Error sending inline reply', e);
        } finally {
            setSendingId(null);
        }
    };

    // Safe stats resolution
    const safeStats = {
        total_pages: stats?.total_pages ?? 0,
        total_services: stats?.total_services ?? 0,
        total_projects: stats?.total_projects ?? 0,
        total_blog_posts: stats?.total_blog_posts ?? 0,
        contact_messages: stats?.contact_messages ?? 0,
        subscribers: stats?.subscribers ?? 0,
        total_team: stats?.total_team ?? 0,
    };

    const safeVisitorStats = {
        total_views: visitorStats?.total_views ?? 0,
        today_views: visitorStats?.today_views ?? 0,
        week_views: visitorStats?.week_views ?? 0,
        top_pages: Array.isArray(visitorStats?.top_pages) ? visitorStats.top_pages : [],
        top_countries: Array.isArray(visitorStats?.top_countries) ? visitorStats.top_countries : [],
        devices: {
            desktop: visitorStats?.devices?.desktop ?? 0,
            mobile: visitorStats?.devices?.mobile ?? 0,
            tablet: visitorStats?.devices?.tablet ?? 0,
        },
    };

    const totalDevices = (safeVisitorStats.devices.desktop + safeVisitorStats.devices.mobile + safeVisitorStats.devices.tablet) || 1;
    const desktopPct = Math.round((safeVisitorStats.devices.desktop / totalDevices) * 100);
    const mobilePct = Math.round((safeVisitorStats.devices.mobile / totalDevices) * 100);
    const tabletPct = Math.max(0, 100 - desktopPct - mobilePct);

    const maxCountryVisitors = safeVisitorStats.top_countries[0]?.visitors || 1;
    const maxPageViews = safeVisitorStats.top_pages[0]?.views || 1;

    const leadsList = Array.isArray(recentLeads) ? recentLeads : [];
    const postsList = Array.isArray(recentPosts) ? recentPosts : [];

    return (
        <AdminLayout title="Admin Overview & Dashboard">
            <SEOHead title="Admin Dashboard | Tech in Soul" description="Tech in Soul administrative control center and real-time metrics." />

            <div className="space-y-8">
                {/* Welcome / Header Banner */}
                <div className="rounded-2xl bg-gradient-to-r from-[#0B132B] via-[#0F1D40] to-[#0B132B] border border-[#00F2FE]/20 p-6 shadow-xl relative overflow-hidden">
                    <div className="absolute top-0 right-0 w-96 h-96 bg-[#00F2FE]/5 rounded-full blur-3xl pointer-events-none" />
                    <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-4">
                        <div>
                            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#00F2FE]/10 border border-[#00F2FE]/30 text-[#00F2FE] text-xs font-semibold mb-2">
                                <Sparkles className="w-3.5 h-3.5" />
                                <span>Overview Control Center</span>
                            </div>
                            <h2 className="text-2xl font-extrabold text-white tracking-tight">Welcome back to Tech in Soul</h2>
                            <p className="text-xs text-slate-300 mt-1">Here is a real-time summary of your website traffic, client leads, and live customer inquiries.</p>
                        </div>
                        <div className="flex flex-wrap items-center gap-3">
                            <Link href="/admin/chat" className="btn-aqua px-4 py-2.5 rounded-xl text-xs font-bold flex items-center gap-2 shadow-lg shadow-[#00F2FE]/20">
                                <MessageSquare className="w-4 h-4" /> Live Chat Inbox
                            </Link>
                            <Link href="/" target="_blank" className="px-4 py-2.5 rounded-xl bg-[#0B132B] border border-slate-700 text-xs font-bold text-slate-200 hover:text-white hover:border-[#00F2FE] transition-colors flex items-center gap-2">
                                <Globe className="w-4 h-4 text-[#00F2FE]" /> View Public Site
                            </Link>
                        </div>
                    </div>
                </div>

                {/* Stats Cards Grid */}
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 lg:gap-5">
                    {/* CMS Pages */}
                    <div className="bg-[#0B132B]/90 border border-[#38BDF8]/15 rounded-2xl p-5 space-y-3 shadow-lg hover:border-[#00F2FE]/40 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">CMS Pages</span>
                            <div className="p-2 rounded-xl bg-[#00F2FE]/10 text-[#00F2FE]">
                                <FileText className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-white">{safeStats.total_pages}</div>
                        <Link href="/admin/pages" className="text-[11px] font-semibold text-[#00F2FE] hover:underline flex items-center gap-1">
                            Manage Pages <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* Services */}
                    <div className="bg-[#0B132B]/90 border border-[#38BDF8]/15 rounded-2xl p-5 space-y-3 shadow-lg hover:border-[#00F2FE]/40 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Services</span>
                            <div className="p-2 rounded-xl bg-[#00F2FE]/10 text-[#00F2FE]">
                                <Briefcase className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-white">{safeStats.total_services}</div>
                        <Link href="/admin/services" className="text-[11px] font-semibold text-[#00F2FE] hover:underline flex items-center gap-1">
                            Manage Services <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* Projects */}
                    <div className="bg-[#0B132B]/90 border border-[#38BDF8]/15 rounded-2xl p-5 space-y-3 shadow-lg hover:border-[#00F2FE]/40 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Projects</span>
                            <div className="p-2 rounded-xl bg-cyan-500/10 text-cyan-400">
                                <FolderGit2 className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-white">{safeStats.total_projects}</div>
                        <Link href="/admin/projects" className="text-[11px] font-semibold text-cyan-400 hover:underline flex items-center gap-1">
                            View Case Studies <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* Blog Posts */}
                    <div className="bg-[#0B132B]/90 border border-[#38BDF8]/15 rounded-2xl p-5 space-y-3 shadow-lg hover:border-[#00F2FE]/40 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Blog Articles</span>
                            <div className="p-2 rounded-xl bg-sky-500/10 text-sky-400">
                                <Layers className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-white">{safeStats.total_blog_posts}</div>
                        <Link href="/admin/blog" className="text-[11px] font-semibold text-sky-400 hover:underline flex items-center gap-1">
                            Manage Blog <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* Unread Live Chats */}
                    <div className="bg-[#0B132B]/90 border border-[#00F2FE]/40 rounded-2xl p-5 space-y-3 shadow-lg shadow-[#00F2FE]/10 relative overflow-hidden">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-300 uppercase tracking-wider">Unread Chats</span>
                            <div className="p-2 rounded-xl bg-[#00F2FE]/20 text-[#00F2FE]">
                                <MessageCircle className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-[#00F2FE]">{unreadTotal}</div>
                        {unreadTotal > 0 && (
                            <span className="absolute top-3 right-3 flex h-3 w-3">
                                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[#00F2FE] opacity-75"></span>
                                <span className="relative inline-flex rounded-full h-3 w-3 bg-[#00F2FE]"></span>
                            </span>
                        )}
                        <Link href="/admin/chat" className="text-[11px] font-bold text-[#00F2FE] hover:underline flex items-center gap-1">
                            Open Chat Inbox <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* New Leads */}
                    <div className="bg-[#0B132B]/90 border border-emerald-500/30 rounded-2xl p-5 space-y-3 shadow-lg hover:border-emerald-500/50 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Client Leads</span>
                            <div className="p-2 rounded-xl bg-emerald-500/10 text-emerald-400">
                                <Mail className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-emerald-400">{safeStats.contact_messages}</div>
                        <Link href="/admin/contacts" className="text-[11px] font-semibold text-emerald-400 hover:underline flex items-center gap-1">
                            View Inquiries <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* Subscribers */}
                    <div className="bg-[#0B132B]/90 border border-[#38BDF8]/15 rounded-2xl p-5 space-y-3 shadow-lg hover:border-[#00F2FE]/40 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Subscribers</span>
                            <div className="p-2 rounded-xl bg-violet-500/10 text-violet-400">
                                <Users className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-white">{safeStats.subscribers}</div>
                        <Link href="/admin/newsletter" className="text-[11px] font-semibold text-violet-400 hover:underline flex items-center gap-1">
                            View Subscribers <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    {/* Team Members */}
                    <div className="bg-[#0B132B]/90 border border-[#38BDF8]/15 rounded-2xl p-5 space-y-3 shadow-lg hover:border-[#00F2FE]/40 transition-all duration-200">
                        <div className="flex items-center justify-between">
                            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Team Members</span>
                            <div className="p-2 rounded-xl bg-amber-500/10 text-amber-400">
                                <Users className="w-4 h-4" />
                            </div>
                        </div>
                        <div className="text-3xl font-extrabold text-white">{safeStats.total_team}</div>
                        <Link href="/admin/team" className="text-[11px] font-semibold text-amber-400 hover:underline flex items-center gap-1">
                            Manage Team <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>
                </div>

                {/* Main two-column: Live Chat LEFT + Visitor Analytics RIGHT */}
                <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
                    {/* LEFT — Live Chat Active & Unread Conversations (2/3 width) */}
                    <div className="xl:col-span-2 bg-[#0B132B]/90 border border-[#38BDF8]/20 rounded-2xl p-6 space-y-5 shadow-xl">
                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-slate-800">
                            <div className="flex items-center gap-3">
                                <div className="w-10 h-10 rounded-xl bg-[#00F2FE]/10 border border-[#00F2FE]/30 flex items-center justify-center text-[#00F2FE]">
                                    <MessageSquare className="w-5 h-5" />
                                </div>
                                <div>
                                    <h3 className="text-base font-bold text-white flex items-center gap-2">
                                        Live Chat Visitor Conversations
                                        <span className="relative flex h-2.5 w-2.5">
                                            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                            <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
                                        </span>
                                    </h3>
                                    <p className="text-xs text-slate-400">Auto-refreshing visitor chats with one-click quick reply.</p>
                                </div>
                            </div>
                            <Link href="/admin/chat" className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5 self-start sm:self-auto shrink-0">
                                Full Inbox <ArrowRight className="w-3.5 h-3.5" />
                            </Link>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {sessions.length > 0 ? (
                                sessions.slice(0, 4).map((session) => {
                                    const lastMsg = session?.messages?.[0];

                                    const isUnread = (session?.unread_count || 0) > 0;
                                    return (
                                        <div
                                            key={session.id}
                                            className={`p-4 rounded-2xl bg-[#060B18]/90 border transition-all flex flex-col justify-between space-y-3 ${
                                                isUnread ? 'border-[#00F2FE]/60 shadow-lg shadow-[#00F2FE]/10' : 'border-slate-800 hover:border-slate-700'
                                            }`}
                                        >
                                            <div className="space-y-2">
                                                <div className="flex items-center justify-between">
                                                    <div className="flex items-center gap-2 min-w-0">
                                                        <div className="w-8 h-8 rounded-full bg-[#00F2FE]/10 border border-[#00F2FE]/30 flex items-center justify-center text-[#00F2FE] text-xs font-bold shrink-0">
                                                            {session.visitor_name?.charAt(0)?.toUpperCase() || 'V'}
                                                        </div>
                                                        <div className="min-w-0">
                                                            <h4 className="text-xs font-bold text-white truncate">{session.visitor_name || 'Visitor'}</h4>
                                                            <p className="text-[10px] text-slate-400 truncate">{session.visitor_email || 'No email'}</p>
                                                        </div>
                                                    </div>
                                                    {isUnread ? (
                                                        <span className="px-2 py-0.5 rounded-full bg-[#00F2FE] text-[#060B18] text-[10px] font-extrabold shrink-0">
                                                            {session.unread_count} New
                                                        </span>
                                                    ) : (
                                                        <span className="text-[10px] text-slate-400 bg-[#0F172A] px-2 py-0.5 rounded-full border border-slate-800 capitalize shrink-0">
                                                            {session.status || 'Active'}
                                                        </span>
                                                    )}
                                                </div>
                                                {lastMsg && (
                                                    <div className="bg-[#0F172A] p-2.5 rounded-xl border border-slate-800/90 text-xs text-slate-200">
                                                        <span className="text-[10px] font-bold text-[#00F2FE] block mb-0.5">{lastMsg.sender_name || 'Visitor'}</span>
                                                        <p className="line-clamp-2 leading-relaxed">"{lastMsg.message}"</p>
                                                    </div>
                                                )}
                                            </div>

                                            <div className="space-y-2 pt-2 border-t border-slate-800/80">
                                                <form onSubmit={(e) => handleSendInlineReply(session.id, e)} className="flex items-center gap-2">
                                                    <input
                                                        type="text"
                                                        value={inlineReplies[session.id] || ''}
                                                        onChange={(e) => setInlineReplies((prev) => ({ ...prev, [session.id]: e.target.value }))}
                                                        placeholder="Quick reply..."
                                                        className="flex-grow bg-[#0F172A] border border-slate-800 rounded-xl px-3 py-1.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#00F2FE]"
                                                    />
                                                    <button
                                                        type="submit"
                                                        disabled={!inlineReplies[session.id]?.trim() || sendingId === session.id}
                                                        className="p-2 bg-[#00F2FE] text-[#060B18] rounded-xl font-bold hover:bg-cyan-300 disabled:opacity-30 transition-all shrink-0"
                                                    >
                                                        <Send className="w-3.5 h-3.5" />
                                                    </button>
                                                </form>
                                                <div className="flex items-center justify-between text-[10px] text-slate-400">
                                                    <span className="flex items-center gap-1">
                                                        <Clock className="w-3 h-3 text-slate-500" />
                                                        {session.last_activity_at ? new Date(session.last_activity_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : 'Recent'}
                                                    </span>
                                                    <Link href="/admin/chat" className="text-xs font-bold text-[#00F2FE] hover:underline flex items-center gap-1">
                                                        Full Thread <ArrowRight className="w-3 h-3" />
                                                    </Link>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })
                            ) : (
                                <div className="col-span-full py-12 text-center text-slate-400 text-xs space-y-2 bg-[#060B18]/50 rounded-2xl border border-slate-800/60">
                                    <MessageSquare className="w-8 h-8 text-[#00F2FE]/40 mx-auto" />
                                    <p className="font-semibold text-slate-300">No active visitor chats at the moment.</p>
                                    <p className="text-[11px] text-slate-500">Live conversations from website visitors will appear here automatically.</p>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* RIGHT — Visitor Analytics Panel (1/3 width) */}
                    <div className="xl:col-span-1 flex flex-col gap-5">
                        {/* Summary box */}
                        <div className="bg-[#0B132B]/90 border border-[#38BDF8]/20 rounded-2xl p-5 space-y-4 shadow-xl">
                            <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
                                <div className="w-8 h-8 rounded-xl bg-[#00F2FE]/10 border border-[#00F2FE]/30 flex items-center justify-center text-[#00F2FE]">
                                    <BarChart2 className="w-4 h-4" />
                                </div>
                                <h3 className="text-sm font-bold text-white">Traffic Analytics</h3>
                            </div>

                            <div className="grid grid-cols-3 gap-2 sm:gap-3">
                                <div className="bg-[#060B18] rounded-xl p-3 text-center border border-slate-800">
                                    <Eye className="w-4 h-4 text-[#00F2FE] mx-auto mb-1" />
                                    <div className="text-lg font-extrabold text-white">{safeVisitorStats.total_views.toLocaleString()}</div>
                                    <div className="text-[10px] text-slate-400 font-medium">Total</div>
                                </div>
                                <div className="bg-[#060B18] rounded-xl p-3 text-center border border-emerald-900/50">
                                    <TrendingUp className="w-4 h-4 text-emerald-400 mx-auto mb-1" />
                                    <div className="text-lg font-extrabold text-emerald-400">{safeVisitorStats.today_views.toLocaleString()}</div>
                                    <div className="text-[10px] text-slate-400 font-medium">Today</div>
                                </div>
                                <div className="bg-[#060B18] rounded-xl p-3 text-center border border-slate-800">
                                    <BarChart2 className="w-4 h-4 text-cyan-400 mx-auto mb-1" />
                                    <div className="text-lg font-extrabold text-cyan-400">{safeVisitorStats.week_views.toLocaleString()}</div>
                                    <div className="text-[10px] text-slate-400 font-medium">7 Days</div>
                                </div>
                            </div>

                            {/* Device Breakdown */}
                            <div className="space-y-2.5 pt-2">
                                <h4 className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">Device Breakdown</h4>
                                <div className="space-y-2">
                                    <div className="flex items-center gap-2">
                                        <Monitor className="w-3.5 h-3.5 text-[#00F2FE] shrink-0" />
                                        <div className="flex-grow">
                                            <div className="flex justify-between text-[11px] mb-1">
                                                <span className="text-slate-300 font-medium">Desktop</span>
                                                <span className="text-[#00F2FE] font-bold">{desktopPct}%</span>
                                            </div>
                                            <div className="h-1.5 bg-[#060B18] rounded-full overflow-hidden">
                                                <div className="h-full bg-[#00F2FE] rounded-full transition-all" style={{ width: `${desktopPct}%` }} />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Smartphone className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
                                        <div className="flex-grow">
                                            <div className="flex justify-between text-[11px] mb-1">
                                                <span className="text-slate-300 font-medium">Mobile</span>
                                                <span className="text-emerald-400 font-bold">{mobilePct}%</span>
                                            </div>
                                            <div className="h-1.5 bg-[#060B18] rounded-full overflow-hidden">
                                                <div className="h-full bg-emerald-400 rounded-full transition-all" style={{ width: `${mobilePct}%` }} />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Tablet className="w-3.5 h-3.5 text-violet-400 shrink-0" />
                                        <div className="flex-grow">
                                            <div className="flex justify-between text-[11px] mb-1">
                                                <span className="text-slate-300 font-medium">Tablet</span>
                                                <span className="text-violet-400 font-bold">{tabletPct}%</span>
                                            </div>
                                            <div className="h-1.5 bg-[#060B18] rounded-full overflow-hidden">
                                                <div className="h-full bg-violet-400 rounded-full transition-all" style={{ width: `${tabletPct}%` }} />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Top Countries */}
                        <div className="bg-[#0B132B]/90 border border-slate-800 rounded-2xl p-5 space-y-3 shadow-xl">
                            <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
                                <Globe className="w-4 h-4 text-[#00F2FE]" />
                                <h3 className="text-sm font-bold text-white">Top Countries</h3>
                            </div>
                            {safeVisitorStats.top_countries.length > 0 ? (
                                <div className="space-y-2.5">
                                    {safeVisitorStats.top_countries.map((c, idx) => (
                                        <div key={idx} className="space-y-1">
                                            <div className="flex items-center justify-between text-[11px]">
                                                <span className="text-slate-200 font-medium flex items-center gap-1.5">
                                                    <span>{getFlag(c.country)}</span>
                                                    {c.country}
                                                </span>
                                                <span className="text-slate-400">{c.visitors.toLocaleString()}</span>
                                            </div>
                                            <div className="h-1.5 bg-[#060B18] rounded-full overflow-hidden">
                                                <div
                                                    className="h-full rounded-full transition-all"
                                                    style={{
                                                        width: `${Math.round((c.visitors / maxCountryVisitors) * 100)}%`,
                                                        background: `hsl(${180 + idx * 30}, 80%, 55%)`,
                                                    }}
                                                />
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <p className="text-xs text-slate-500 py-3 text-center">No visitor location data yet.</p>
                            )}
                        </div>

                        {/* Top Pages */}
                        <div className="bg-[#0B132B]/90 border border-slate-800 rounded-2xl p-5 space-y-3 shadow-xl">
                            <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
                                <FileText className="w-4 h-4 text-[#00F2FE]" />
                                <h3 className="text-sm font-bold text-white">Top Viewed Pages</h3>
                            </div>
                            {safeVisitorStats.top_pages.length > 0 ? (
                                <div className="space-y-2.5">
                                    {safeVisitorStats.top_pages.map((p, idx) => (
                                        <div key={idx} className="space-y-1">
                                            <div className="flex items-center justify-between text-[11px]">
                                                <span className="text-slate-200 font-medium truncate max-w-[140px]">{p.url}</span>
                                                <span className="text-[#00F2FE] font-bold shrink-0 ml-2">{p.views.toLocaleString()} views</span>
                                            </div>
                                            <div className="h-1.5 bg-[#060B18] rounded-full overflow-hidden">
                                                <div
                                                    className="h-full bg-[#00F2FE] rounded-full transition-all"
                                                    style={{ width: `${Math.round((p.views / maxPageViews) * 100)}%`, opacity: 0.6 + idx * 0.1 }}
                                                />
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <p className="text-xs text-slate-500 py-3 text-center">No page view data yet.</p>
                            )}
                        </div>
                    </div>
                </div>

                {/* Bottom row: Recent Leads + Recent Blog Posts */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div className="bg-[#0B132B]/90 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-xl">
                        <div className="flex items-center justify-between">
                            <h3 className="text-base font-bold text-white">Recent Client Inquiries</h3>
                            <Link href="/admin/contacts" className="text-xs text-[#00F2FE] hover:underline font-semibold">View All Leads →</Link>
                        </div>
                        <div className="space-y-3">
                            {leadsList.length > 0 ? (
                                leadsList.map((lead) => (
                                    <div key={lead.id} className="p-3.5 rounded-xl bg-[#060B18] border border-slate-800 flex items-center justify-between">
                                        <div>
                                            <span className="text-xs font-bold text-white block">{lead.name}</span>
                                            <span className="text-[11px] text-slate-400 block">{lead.email}</span>
                                        </div>
                                        <span className="text-[10px] font-semibold px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 capitalize">
                                            {lead.status}
                                        </span>
                                    </div>
                                ))
                            ) : (
                                <p className="text-xs text-slate-500 py-4 text-center">No contact submissions yet.</p>
                            )}
                        </div>
                    </div>

                    <div className="bg-[#0B132B]/90 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-xl">
                        <div className="flex items-center justify-between">
                            <h3 className="text-base font-bold text-white">Recent Blog Articles</h3>
                            <Link href="/admin/blog" className="text-xs text-[#00F2FE] hover:underline font-semibold">Manage Posts →</Link>
                        </div>
                        <div className="space-y-3">
                            {postsList.length > 0 ? (
                                postsList.map((post) => (
                                    <div key={post.id} className="p-3.5 rounded-xl bg-[#060B18] border border-slate-800 flex items-center justify-between">
                                        <div className="truncate max-w-xs">
                                            <span className="text-xs font-bold text-white block truncate">{post.title}</span>
                                            <span className="text-[11px] text-slate-400 block">{post.category?.name || 'General'}</span>
                                        </div>
                                        <span className="text-[10px] font-semibold px-2 py-0.5 rounded bg-[#00F2FE]/10 text-[#00F2FE] border border-[#00F2FE]/20">
                                            {post.views} views
                                        </span>
                                    </div>
                                ))
                            ) : (
                                <p className="text-xs text-slate-500 py-4 text-center">No blog posts found.</p>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
