'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  LayoutDashboard,
  FileText,
  Eye,
  ThumbsUp,
  CreditCard,
  Plus,
  Search,
  ShieldCheck,
  ShieldAlert,
  ShieldX,
  AlertTriangle,
  Clock,
  ChevronRight,
  Inbox,
  ArrowRight,
  Bookmark,
  BookmarkCheck,
  Trash2,
  Phone,
  Wallet,
  Smartphone,
  Facebook,
  User,
  Activity,
  TrendingUp,
  ArrowUpDown,
  Filter,
  CheckCircle2,
  XCircle,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAppStore } from '@/store/app-store';
import { toast } from 'sonner';
import type { ScamReportType } from '@/types';

// ─── Types ──────────────────────────────────────────────────────────────────

interface BookmarkType {
  id: string;
  userId: string;
  reportId: string | null;
  entityType: string | null;
  entityValue: string | null;
  label: string | null;
  createdAt: string;
  report?: {
    id: string;
    title: string;
    scamType: string;
    status: string;
    riskLevel: string;
    riskScore: number;
    createdAt: string;
  } | null;
}

// ─── Helpers ────────────────────────────────────────────────────────────────

function formatBDT(amount: number): string {
  if (amount >= 10000000) return `৳${(amount / 10000000).toFixed(1)}Cr`;
  if (amount >= 100000) return `৳${(amount / 100000).toFixed(1)}L`;
  if (amount >= 1000) return `৳${(amount / 1000).toFixed(1)}K`;
  return `৳${amount.toLocaleString('en-BD')}`;
}

function timeAgo(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
  if (seconds < 60) return 'Just now';
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `${days}d ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months}mo ago`;
  return `${Math.floor(months / 12)}y ago`;
}

const riskConfig: Record<
  string,
  {
    label: string;
    color: string;
    bg: string;
    border: string;
    icon: React.ElementType;
  }
> = {
  low: {
    label: 'Low',
    color: 'text-emerald-600 dark:text-emerald-400',
    bg: 'bg-emerald-500/10',
    border: 'border-emerald-500/30',
    icon: ShieldCheck,
  },
  medium: {
    label: 'Medium',
    color: 'text-yellow-600 dark:text-yellow-400',
    bg: 'bg-yellow-500/10',
    border: 'border-yellow-500/30',
    icon: ShieldAlert,
  },
  high: {
    label: 'High',
    color: 'text-orange-600 dark:text-orange-400',
    bg: 'bg-orange-500/10',
    border: 'border-orange-500/30',
    icon: ShieldX,
  },
  critical: {
    label: 'Critical',
    color: 'text-red-600 dark:text-red-400',
    bg: 'bg-red-500/10',
    border: 'border-red-500/30',
    icon: AlertTriangle,
  },
};

const statusConfig: Record<
  string,
  { label: string; color: string; bg: string }
> = {
  pending: {
    label: 'Pending',
    color: 'text-yellow-700 dark:text-yellow-300',
    bg: 'bg-yellow-500/15',
  },
  verified: {
    label: 'Verified',
    color: 'text-emerald-700 dark:text-emerald-300',
    bg: 'bg-emerald-500/15',
  },
  suspicious: {
    label: 'Suspicious',
    color: 'text-orange-700 dark:text-orange-300',
    bg: 'bg-orange-500/15',
  },
  rejected: {
    label: 'Rejected',
    color: 'text-red-700 dark:text-red-300',
    bg: 'bg-red-500/15',
  },
};

const entityTypeConfig: Record<string, { label: string; icon: React.ElementType; color: string; bg: string }> = {
  phone: { label: 'Phone', icon: Phone, color: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-500/10' },
  bkash: { label: 'bKash', icon: Wallet, color: 'text-pink-600 dark:text-pink-400', bg: 'bg-pink-500/10' },
  nagad: { label: 'Nagad', icon: Smartphone, color: 'text-orange-600 dark:text-orange-400', bg: 'bg-orange-500/10' },
  facebook: { label: 'Facebook', icon: Facebook, color: 'text-blue-700 dark:text-blue-300', bg: 'bg-blue-500/10' },
  seller: { label: 'Seller', icon: User, color: 'text-purple-600 dark:text-purple-400', bg: 'bg-purple-500/10' },
};

// ─── Animation Variants ─────────────────────────────────────────────────────

const containerVariants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.08 } },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.4, ease: 'easeOut' } },
};

// ─── Sparkline Component ────────────────────────────────────────────────────

function MiniSparkline({ data, maxVal }: { data: number[]; maxVal: number }) {
  const safeMax = Math.max(maxVal, 1);
  return (
    <div className="flex items-end gap-[3px] h-8">
      {data.map((val, i) => {
        const height = Math.max(3, (val / safeMax) * 100);
        return (
          <div
            key={i}
            className="w-2 rounded-t-sm bg-emerald-500/60 hover:bg-emerald-400 transition-colors min-h-[3px]"
            style={{
              height: `${height}%`,
              animation: `sparkline-grow 0.3s ease-out ${i * 0.05}s both`,
            }}
            title={`${val} reports`}
          />
        );
      })}
    </div>
  );
}

// ─── Activity Timeline Component ────────────────────────────────────────────

function ActivityTimeline({ reports }: { reports: ScamReportType[] }) {
  const activities = useMemo(() => {
    const items: { id: string; type: string; label: string; time: string; icon: React.ElementType; iconColor: string; iconBg: string }[] = [];

    for (const report of reports.slice(0, 8)) {
      items.push({
        id: `submit-${report.id}`,
        type: 'submit',
        label: `Report submitted: ${report.title}`,
        time: report.createdAt,
        icon: FileText,
        iconColor: 'text-emerald-500',
        iconBg: 'bg-emerald-500/10',
      });

      if (report.status === 'verified') {
        items.push({
          id: `verify-${report.id}`,
          type: 'verify',
          label: `Report verified: ${report.title}`,
          time: report.updatedAt,
          icon: CheckCircle2,
          iconColor: 'text-emerald-500',
          iconBg: 'bg-emerald-500/10',
        });
      }

      if (report.status === 'rejected') {
        items.push({
          id: `reject-${report.id}`,
          type: 'reject',
          label: `Report rejected: ${report.title}`,
          time: report.updatedAt,
          icon: XCircle,
          iconColor: 'text-red-500',
          iconBg: 'bg-red-500/10',
        });
      }
    }

    // Sort by most recent first
    items.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
    return items.slice(0, 6);
  }, [reports]);

  if (activities.length === 0) {
    return (
      <div className="text-center py-8">
        <Activity className="h-10 w-10 text-muted-foreground/30 mx-auto mb-3" />
        <p className="text-sm text-muted-foreground">No recent activity</p>
      </div>
    );
  }

  return (
    <div className="space-y-0 max-h-72 overflow-y-auto custom-scrollbar">
      {activities.map((activity, idx) => {
        const Icon = activity.icon;
        return (
          <motion.div
            key={activity.id}
            initial={{ opacity: 0, x: -10 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: idx * 0.05, duration: 0.25 }}
            className="flex gap-3 py-2.5 group"
          >
            <div className="flex flex-col items-center">
              <div className={`p-1.5 rounded-lg ${activity.iconBg} shrink-0`}>
                <Icon className={`h-3.5 w-3.5 ${activity.iconColor}`} />
              </div>
              {idx < activities.length - 1 && (
                <div className="w-px flex-1 bg-border mt-1.5" />
              )}
            </div>
            <div className="flex-1 min-w-0 pb-1">
              <p className="text-sm line-clamp-1 group-hover:text-emerald-500 transition-colors">
                {activity.label}
              </p>
              <p className="text-xs text-muted-foreground flex items-center gap-1">
                <Clock className="h-3 w-3" />
                {timeAgo(activity.time)}
              </p>
            </div>
          </motion.div>
        );
      })}
    </div>
  );
}

// ─── Main Component ─────────────────────────────────────────────────────────

export function DashboardPage() {
  const user = useAppStore((s) => s.user);
  const navigate = useAppStore((s) => s.navigate);
  const setSelectedReportId = useAppStore((s) => s.setSelectedReportId);

  const [reports, setReports] = useState<ScamReportType[]>([]);
  const [bookmarks, setBookmarks] = useState<BookmarkType[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingBookmarks, setIsLoadingBookmarks] = useState(true);
  const [sortBy, setSortBy] = useState<string>('date-desc');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [activeTab, setActiveTab] = useState('reports');

  // Redirect if not logged in (with hydration delay to prevent flash redirect)
  useEffect(() => {
    if (!user) {
      // Check localStorage first - the Zustand store may not be hydrated yet
      const savedUser = localStorage.getItem('scamchecker_user');
      if (!savedUser) {
        const timer = setTimeout(() => {
          // Double-check after a brief delay
          const savedUser2 = localStorage.getItem('scamchecker_user');
          if (!savedUser2) {
            navigate('login');
          }
        }, 300);
        return () => clearTimeout(timer);
      }
    }
  }, [user, navigate]);

  // Fetch user's reports
  useEffect(() => {
    if (!user) return;
    let cancelled = false;
    fetch(`/api/reports?reporterId=${user.id}`)
      .then((res) => {
        if (!res.ok) throw new Error('Network error');
        return res.json();
      })
      .then((data) => {
        if (cancelled) return;
        if (data.success) {
          setReports(data.data.reports || data.data || []);
        } else {
          toast.error('Failed to load reports');
        }
        setIsLoading(false);
      })
      .catch(() => {
        if (!cancelled) {
          setIsLoading(false);
          toast.error('Failed to load reports. Please try again.');
        }
      });
    return () => { cancelled = true; };
  }, [user]);

  // Fetch bookmarks
  useEffect(() => {
    if (!user) return;
    let cancelled = false;
    fetch(`/api/bookmarks?userId=${user.id}`)
      .then((res) => {
        if (!res.ok) throw new Error('Network error');
        return res.json();
      })
      .then((data) => {
        if (cancelled) return;
        if (data.success) {
          setBookmarks(data.data || []);
        } else {
          toast.error('Failed to load bookmarks');
        }
        setIsLoadingBookmarks(false);
      })
      .catch(() => {
        if (!cancelled) {
          setIsLoadingBookmarks(false);
          toast.error('Failed to load bookmarks. Please try again.');
        }
      });
    return () => { cancelled = true; };
  }, [user]);

  const handleReportClick = useCallback(
    (reportId: string) => {
      setSelectedReportId(reportId);
      navigate('report-detail');
    },
    [setSelectedReportId, navigate]
  );

  const handleDeleteBookmark = useCallback(async (bookmarkId: string) => {
    try {
      const res = await fetch(`/api/bookmarks/${bookmarkId}`, { method: 'DELETE' });
      const data = await res.json();
      if (data.success) {
        setBookmarks((prev) => prev.filter((b) => b.id !== bookmarkId));
        toast.success('Bookmark removed');
      } else {
        toast.error('Failed to remove bookmark');
      }
    } catch {
      toast.error('Failed to remove bookmark');
    }
  }, []);

  // Compute stats
  const totalViews = reports.reduce((sum, r) => sum + r.views, 0);
  const totalUpvotes = reports.reduce((sum, r) => sum + r.upvotes, 0);
  const totalAmountLost = reports.reduce((sum, r) => sum + r.amountLost, 0);

  // Sparkline data: reports per day for last 7 days
  const sparklineData = useMemo(() => {
    const days: number[] = [];
    const now = new Date();
    for (let i = 6; i >= 0; i--) {
      const dayStart = new Date(now);
      dayStart.setDate(dayStart.getDate() - i);
      dayStart.setHours(0, 0, 0, 0);
      const dayEnd = new Date(dayStart);
      dayEnd.setDate(dayEnd.getDate() + 1);
      const count = reports.filter((r) => {
        const d = new Date(r.createdAt);
        return d >= dayStart && d < dayEnd;
      }).length;
      days.push(count);
    }
    return days;
  }, [reports]);

  const sparklineMax = Math.max(...sparklineData, 1);

  // Trend indicators
  const thisWeekCount = useMemo(() => {
    const weekAgo = new Date();
    weekAgo.setDate(weekAgo.getDate() - 7);
    return reports.filter((r) => new Date(r.createdAt) >= weekAgo).length;
  }, [reports]);

  // Filtered & sorted reports
  const filteredReports = useMemo(() => {
    let result = [...reports];

    if (filterStatus !== 'all') {
      result = result.filter((r) => r.status === filterStatus);
    }

    switch (sortBy) {
      case 'date-asc':
        result.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
        break;
      case 'risk-desc':
        result.sort((a, b) => b.riskScore - a.riskScore);
        break;
      case 'risk-asc':
        result.sort((a, b) => a.riskScore - b.riskScore);
        break;
      case 'views-desc':
        result.sort((a, b) => b.views - a.views);
        break;
      case 'date-desc':
      default:
        result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        break;
    }

    return result;
  }, [reports, sortBy, filterStatus]);

  if (!user) return null;

  const statCards = [
    {
      icon: FileText,
      label: 'My Reports',
      value: reports.length.toString(),
      color: 'text-emerald-500',
      bgIcon: 'bg-emerald-500/10',
      trend: thisWeekCount > 0 ? `+${thisWeekCount} this week` : 'No new reports',
      trendUp: thisWeekCount > 0,
    },
    {
      icon: Eye,
      label: 'Total Views',
      value: totalViews.toLocaleString(),
      color: 'text-teal-500',
      bgIcon: 'bg-teal-500/10',
      trend: reports.length > 0 ? `Avg ${Math.round(totalViews / reports.length)} per report` : 'No data yet',
      trendUp: totalViews > 0,
    },
    {
      icon: ThumbsUp,
      label: 'Total Upvotes',
      value: totalUpvotes.toLocaleString(),
      color: 'text-cyan-500',
      bgIcon: 'bg-cyan-500/10',
      trend: totalUpvotes > 0 ? `${((totalUpvotes / Math.max(reports.length, 1)) ).toFixed(1)} avg` : 'No upvotes yet',
      trendUp: totalUpvotes > 0,
    },
    {
      icon: CreditCard,
      label: 'Amount Lost',
      value: formatBDT(totalAmountLost),
      color: 'text-red-500',
      bgIcon: 'bg-red-500/10',
      trend: totalAmountLost > 0 ? `Avg ${formatBDT(totalAmountLost / Math.max(reports.length, 1))}` : 'No losses recorded',
      trendUp: false,
    },
  ];

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
      <motion.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
      >
        {/* ─── Welcome Header ──────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mb-8">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 rounded-xl bg-emerald-500/10">
              <LayoutDashboard className="h-6 w-6 text-emerald-500" />
            </div>
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold">
                Welcome back, {user.name || user.email.split('@')[0]}
              </h1>
              <p className="text-muted-foreground text-sm sm:text-base">
                Manage your reports and track scam activity
              </p>
            </div>
          </div>
        </motion.div>

        {/* ─── Stats Cards Row ─────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mb-8">
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
            {statCards.map((stat, idx) => (
              <motion.div
                key={stat.label}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 + idx * 0.08, duration: 0.4 }}
              >
                <Card className="glass border-0 shadow-lg hover:shadow-xl hover:shadow-emerald-500/5 transition-all duration-300 group">
                  <CardContent className="p-4 sm:p-6">
                    <div className="flex items-center justify-between mb-3">
                      <div className={`${stat.bgIcon} p-2.5 sm:p-3 rounded-xl group-hover:scale-110 transition-transform duration-300`}>
                        <stat.icon
                          className={`h-5 w-5 sm:h-6 sm:w-6 ${stat.color}`}
                        />
                      </div>
                      {/* Sparkline for first card */}
                      {idx === 0 && sparklineData.some((v) => v > 0) && (
                        <MiniSparkline data={sparklineData} maxVal={sparklineMax} />
                      )}
                    </div>
                    <div className="min-w-0">
                      <div className="text-xl sm:text-2xl font-bold truncate">
                        {isLoading ? (
                          <Skeleton className="h-7 w-16" />
                        ) : (
                          stat.value
                        )}
                      </div>
                      <p className="text-xs sm:text-sm text-muted-foreground">
                        {stat.label}
                      </p>
                      <p className={`text-xs mt-1 flex items-center gap-1 ${stat.trendUp ? 'text-emerald-500' : 'text-muted-foreground'}`}>
                        {stat.trendUp && <TrendingUp className="h-3 w-3" />}
                        {stat.trend}
                      </p>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            ))}
          </div>
        </motion.div>

        {/* ─── Quick Actions ───────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mb-8">
          <div className="flex flex-col sm:flex-row gap-3">
            <Button
              size="lg"
              onClick={() => navigate('report')}
              className="h-12 px-6 text-base rounded-xl bg-emerald-600 hover:bg-emerald-700 dark:bg-emerald-500 dark:hover:bg-emerald-600 shadow-lg shadow-emerald-500/20"
            >
              <Plus className="h-5 w-5" />
              Report a Scam
            </Button>
            <Button
              size="lg"
              variant="outline"
              onClick={() => navigate('search')}
              className="h-12 px-6 text-base rounded-xl border-emerald-500/30 hover:bg-emerald-500/10 hover:text-emerald-600 dark:hover:text-emerald-400"
            >
              <Search className="h-5 w-5" />
              Search Database
            </Button>
          </div>
        </motion.div>

        {/* ─── Two-Column Layout: Reports + Activity ──────────────────────── */}
        <motion.div variants={itemVariants}>
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Left Column - Reports & Bookmarks */}
            <div className="lg:col-span-2">
              <Tabs value={activeTab} onValueChange={setActiveTab}>
                <div className="flex items-center justify-between mb-4">
                  <TabsList>
                    <TabsTrigger value="reports" className="gap-1.5">
                      <FileText className="h-4 w-4" />
                      My Reports
                    </TabsTrigger>
                    <TabsTrigger value="bookmarks" className="gap-1.5">
                      <Bookmark className="h-4 w-4" />
                      Saved Items
                      {bookmarks.length > 0 && (
                        <Badge variant="secondary" className="text-[10px] h-4 px-1 ml-1">
                          {bookmarks.length}
                        </Badge>
                      )}
                    </TabsTrigger>
                  </TabsList>
                  {activeTab === 'reports' && reports.length > 0 && (
                    <span className="text-sm text-muted-foreground hidden sm:block">
                      {reports.length} report{reports.length !== 1 ? 's' : ''}
                    </span>
                  )}
                </div>

                {/* ─── Reports Tab ──────────────────────────────────────────── */}
                <TabsContent value="reports">
                  {/* Filter & Sort Controls */}
                  {reports.length > 1 && (
                    <div className="flex flex-col sm:flex-row gap-2 mb-4">
                      <div className="flex items-center gap-2">
                        <Filter className="h-4 w-4 text-muted-foreground shrink-0" />
                        <Select value={filterStatus} onValueChange={setFilterStatus}>
                          <SelectTrigger className="w-[140px] h-9 text-sm">
                            <SelectValue placeholder="Filter status" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">All Status</SelectItem>
                            <SelectItem value="pending">Pending</SelectItem>
                            <SelectItem value="verified">Verified</SelectItem>
                            <SelectItem value="suspicious">Suspicious</SelectItem>
                            <SelectItem value="rejected">Rejected</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="flex items-center gap-2">
                        <ArrowUpDown className="h-4 w-4 text-muted-foreground shrink-0" />
                        <Select value={sortBy} onValueChange={setSortBy}>
                          <SelectTrigger className="w-[160px] h-9 text-sm">
                            <SelectValue placeholder="Sort by" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="date-desc">Newest First</SelectItem>
                            <SelectItem value="date-asc">Oldest First</SelectItem>
                            <SelectItem value="risk-desc">Highest Risk</SelectItem>
                            <SelectItem value="risk-asc">Lowest Risk</SelectItem>
                            <SelectItem value="views-desc">Most Viewed</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  )}

                  {isLoading ? (
                    <div className="space-y-3">
                      {[1, 2, 3].map((i) => (
                        <Card key={i} className="glass border-0 shadow-lg">
                          <CardContent className="p-4 sm:p-5">
                            <div className="flex items-start justify-between gap-3">
                              <div className="flex-1 space-y-2">
                                <Skeleton className="h-5 w-3/4" />
                                <Skeleton className="h-4 w-1/2" />
                                <Skeleton className="h-4 w-1/3" />
                              </div>
                              <Skeleton className="h-5 w-5 rounded" />
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  ) : filteredReports.length === 0 ? (
                    <Card className="border-dashed">
                      <CardContent className="py-16 text-center">
                        <motion.div
                          initial={{ opacity: 0, scale: 0.9 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ duration: 0.4 }}
                        >
                          {filterStatus !== 'all' ? (
                            <>
                              <Filter className="h-16 w-16 text-muted-foreground/40 mx-auto mb-4" />
                              <h3 className="text-lg font-semibold mb-2">
                                No Matching Reports
                              </h3>
                              <p className="text-muted-foreground mb-6 max-w-sm mx-auto">
                                No reports match the current filter. Try changing your filter criteria.
                              </p>
                              <Button
                                variant="outline"
                                onClick={() => setFilterStatus('all')}
                                className="border-emerald-500/30 hover:bg-emerald-500/10"
                              >
                                Clear Filter
                              </Button>
                            </>
                          ) : (
                            <>
                              <Inbox className="h-16 w-16 text-muted-foreground/40 mx-auto mb-4" />
                              <h3 className="text-lg font-semibold mb-2">
                                No Reports Yet
                              </h3>
                              <p className="text-muted-foreground mb-6 max-w-sm mx-auto">
                                You haven&apos;t submitted any scam reports yet. Help protect the
                                community by reporting scammers.
                              </p>
                              <Button
                                onClick={() => navigate('report')}
                                className="bg-emerald-600 hover:bg-emerald-700"
                              >
                                <Plus className="h-4 w-4" />
                                Report a Scam
                              </Button>
                            </>
                          )}
                        </motion.div>
                      </CardContent>
                    </Card>
                  ) : (
                    <div className="space-y-3 max-h-[600px] overflow-y-auto pr-1 custom-scrollbar">
                      {filteredReports.map((report, idx) => {
                        const risk = riskConfig[report.riskLevel] || riskConfig.low;
                        const RiskIcon = risk.icon;
                        const status = statusConfig[report.status] || statusConfig.pending;
                        return (
                          <motion.div
                            key={report.id}
                            initial={{ opacity: 0, x: -20 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ delay: idx * 0.04, duration: 0.3 }}
                          >
                            <Card
                              className="group cursor-pointer glass border-0 shadow-lg hover:shadow-xl hover:shadow-emerald-500/10 transition-all duration-300"
                              onClick={() => handleReportClick(report.id)}
                            >
                              <CardContent className="p-4 sm:p-5">
                                <div className="flex items-start justify-between gap-3">
                                  <div className="flex-1 min-w-0">
                                    <div className="flex flex-wrap items-center gap-2 mb-1.5">
                                      <Badge
                                        variant="outline"
                                        className={`text-xs ${risk.color} ${risk.border} ${risk.bg}`}
                                      >
                                        <RiskIcon className="h-3 w-3" />
                                        {risk.label}
                                      </Badge>
                                      <Badge
                                        variant="secondary"
                                        className={`text-xs ${status.color} ${status.bg}`}
                                      >
                                        {status.label}
                                      </Badge>
                                    </div>
                                    <h3 className="font-semibold text-base sm:text-lg group-hover:text-emerald-500 transition-colors line-clamp-1">
                                      {report.title}
                                    </h3>
                                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-sm text-muted-foreground">
                                      {report.amountLost > 0 && (
                                        <span className="flex items-center gap-1 text-red-500 dark:text-red-400">
                                          <CreditCard className="h-3.5 w-3.5" />
                                          {formatBDT(report.amountLost)}
                                        </span>
                                      )}
                                      <span className="flex items-center gap-1">
                                        <Eye className="h-3.5 w-3.5" />
                                        {report.views} views
                                      </span>
                                      <span className="flex items-center gap-1">
                                        <ThumbsUp className="h-3.5 w-3.5" />
                                        {report.upvotes}
                                      </span>
                                      <span className="flex items-center gap-1">
                                        <Clock className="h-3.5 w-3.5" />
                                        {timeAgo(report.createdAt)}
                                      </span>
                                    </div>
                                  </div>
                                  <ChevronRight className="h-5 w-5 text-muted-foreground group-hover:text-emerald-500 transition-colors shrink-0 mt-1" />
                                </div>
                              </CardContent>
                            </Card>
                          </motion.div>
                        );
                      })}
                    </div>
                  )}
                </TabsContent>

                {/* ─── Bookmarks Tab ────────────────────────────────────────── */}
                <TabsContent value="bookmarks">
                  {isLoadingBookmarks ? (
                    <div className="space-y-3">
                      {[1, 2, 3].map((i) => (
                        <Card key={i} className="glass border-0 shadow-lg">
                          <CardContent className="p-4">
                            <div className="flex items-center gap-3">
                              <Skeleton className="h-10 w-10 rounded-lg" />
                              <div className="flex-1 space-y-2">
                                <Skeleton className="h-4 w-3/4" />
                                <Skeleton className="h-3 w-1/2" />
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  ) : bookmarks.length === 0 ? (
                    <Card className="border-dashed">
                      <CardContent className="py-16 text-center">
                        <motion.div
                          initial={{ opacity: 0, scale: 0.9 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ duration: 0.4 }}
                        >
                          <Bookmark className="h-16 w-16 text-muted-foreground/40 mx-auto mb-4" />
                          <h3 className="text-lg font-semibold mb-2">
                            No Saved Items
                          </h3>
                          <p className="text-muted-foreground mb-6 max-w-sm mx-auto">
                            Bookmark suspicious phone numbers, bKash accounts, or Facebook profiles for quick access.
                          </p>
                          <Button
                            variant="outline"
                            onClick={() => navigate('search')}
                            className="border-emerald-500/30 hover:bg-emerald-500/10"
                          >
                            <Search className="h-4 w-4" />
                            Search to Bookmark
                          </Button>
                        </motion.div>
                      </CardContent>
                    </Card>
                  ) : (
                    <div className="space-y-3 max-h-[600px] overflow-y-auto pr-1 custom-scrollbar">
                      {bookmarks.map((bookmark, idx) => {
                        const entityConf = bookmark.entityType
                          ? entityTypeConfig[bookmark.entityType] || entityTypeConfig.phone
                          : null;
                        const EntityIcon = entityConf?.icon || Bookmark;
                        const risk = bookmark.report
                          ? riskConfig[bookmark.report.riskLevel] || riskConfig.low
                          : null;

                        return (
                          <motion.div
                            key={bookmark.id}
                            initial={{ opacity: 0, x: -20 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ delay: idx * 0.05, duration: 0.3 }}
                          >
                            <Card className="glass border-0 shadow-lg hover:shadow-xl hover:shadow-emerald-500/5 transition-all duration-300 group">
                              <CardContent className="p-4">
                                <div className="flex items-start gap-3">
                                  <div className={`p-2.5 rounded-lg ${entityConf?.bg || 'bg-muted'}`}>
                                    <EntityIcon className={`h-4 w-4 ${entityConf?.color || 'text-muted-foreground'}`} />
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 mb-0.5">
                                      {entityConf && (
                                        <Badge variant="secondary" className="text-[10px] h-5">
                                          {entityConf.label}
                                        </Badge>
                                      )}
                                      {risk && (
                                        <Badge
                                          variant="outline"
                                          className={`text-[10px] h-5 ${risk.color} ${risk.border} ${risk.bg}`}
                                        >
                                          {risk.label}
                                        </Badge>
                                      )}
                                    </div>
                                    {bookmark.entityValue && (
                                      <p className="font-medium text-sm truncate">
                                        {bookmark.entityValue}
                                      </p>
                                    )}
                                    {bookmark.report && (
                                      <p className="text-xs text-muted-foreground truncate mt-0.5">
                                        {bookmark.report.title}
                                      </p>
                                    )}
                                    {bookmark.label && (
                                      <p className="text-xs text-muted-foreground mt-0.5">
                                        {bookmark.label}
                                      </p>
                                    )}
                                    <p className="text-xs text-muted-foreground mt-1 flex items-center gap-1">
                                      <Clock className="h-3 w-3" />
                                      Saved {timeAgo(bookmark.createdAt)}
                                    </p>
                                  </div>
                                  <div className="flex items-center gap-1 shrink-0">
                                    {bookmark.report && (
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => handleReportClick(bookmark.report!.id)}
                                        className="h-8 w-8 p-0 text-emerald-500 hover:bg-emerald-500/10"
                                      >
                                        <Eye className="h-4 w-4" />
                                      </Button>
                                    )}
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      onClick={() => handleDeleteBookmark(bookmark.id)}
                                      className="h-8 w-8 p-0 text-red-500 hover:bg-red-500/10"
                                    >
                                      <Trash2 className="h-4 w-4" />
                                    </Button>
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          </motion.div>
                        );
                      })}
                    </div>
                  )}
                </TabsContent>
              </Tabs>
            </div>

            {/* Right Column - Recent Activity & Quick Stats */}
            <div className="space-y-6">
              {/* Recent Activity Timeline */}
              <Card className="glass border-0 shadow-lg">
                <CardHeader className="pb-3">
                  <CardTitle className="text-base flex items-center gap-2">
                    <Activity className="h-4 w-4 text-emerald-500" />
                    Recent Activity
                  </CardTitle>
                  <CardDescription className="text-xs">
                    Your latest report actions
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <ActivityTimeline reports={reports} />
                </CardContent>
              </Card>

              {/* Quick Stats Chart */}
              <Card className="glass border-0 shadow-lg">
                <CardHeader className="pb-3">
                  <CardTitle className="text-base flex items-center gap-2">
                    <TrendingUp className="h-4 w-4 text-teal-500" />
                    Reports This Week
                  </CardTitle>
                  <CardDescription className="text-xs">
                    Last 7 days activity
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <MiniSparkline data={sparklineData} maxVal={sparklineMax} />
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span>7 days ago</span>
                      <span className="font-medium text-foreground">
                        {sparklineData.reduce((a, b) => a + b, 0)} total
                      </span>
                      <span>Today</span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Quick Links */}
              <Card className="glass border-0 shadow-lg">
                <CardHeader className="pb-3">
                  <CardTitle className="text-base">Quick Links</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1.5">
                  {[
                    { label: 'AI Scam Detector', page: 'ai-detect' as const, icon: ShieldAlert },
                    { label: 'Analytics Dashboard', page: 'analytics' as const, icon: TrendingUp },
                  ].map((link) => (
                    <button
                      key={link.page}
                      onClick={() => navigate(link.page)}
                      className="w-full flex items-center gap-3 p-2.5 rounded-lg hover:bg-emerald-500/5 transition-colors text-left group"
                    >
                      <div className="p-1.5 rounded-lg bg-muted group-hover:bg-emerald-500/10 transition-colors">
                        <link.icon className="h-4 w-4 text-muted-foreground group-hover:text-emerald-500 transition-colors" />
                      </div>
                      <span className="text-sm font-medium group-hover:text-emerald-500 transition-colors">
                        {link.label}
                      </span>
                      <ArrowRight className="h-3.5 w-3.5 text-muted-foreground group-hover:text-emerald-500 ml-auto transition-colors" />
                    </button>
                  ))}
                </CardContent>
              </Card>
            </div>
          </div>
        </motion.div>
      </motion.div>
    </div>
  );
}
