'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  BarChart3,
  EyeOff,
  Eye,
  Users,
  Vote,
  Trophy,
  Medal,
  TrendingUp,
  Loader2,
  AlertTriangle,
  ChevronRight,
  Building2,
  RefreshCw,
} from 'lucide-react';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import {
  PieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip as RechartsTooltip,
  Label,
} from 'recharts';

import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Separator } from '@/components/ui/separator';
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from '@/components/ui/chart';
import { useAuthStore } from '@/store/auth-store';

// ==================== Types ====================
interface BranchCandidate {
  candidateId: string;
  employeeId: string;
  name: string;
  position: string | null;
  voteCount: number;
}

interface BranchResult {
  branchId: string;
  branchName: string;
  branchCode: string;
  candidates: BranchCandidate[];
}

interface ResultsData {
  visible: boolean;
  branches: BranchResult[];
  totalVotes: number;
  totalVoters: number;
  totalEligibleVoters: number;
}

// ==================== Constants ====================
const EMERALD_PRIMARY = '#10b981';
const TEAL_SECONDARY = '#14b8a6';
const AMBER_ACCENT = '#f59e0b';
const GRAY_MUTED = '#94a3b8';

const PARTICIPATION_CHART_CONFIG: ChartConfig = {
  voters: {
    label: 'ใช้สิทธิ์ลงคะแนน',
    color: EMERALD_PRIMARY,
  },
  nonVoters: {
    label: 'ไม่ใช้สิทธิ์',
    color: GRAY_MUTED,
  },
};

const RANK_STYLES: Record<number, { bg: string; text: string; border: string; icon: string }> = {
  1: {
    bg: 'bg-amber-50 dark:bg-amber-950/30',
    text: 'text-amber-700 dark:text-amber-300',
    border: 'border-amber-200 dark:border-amber-800',
    icon: '🥇',
  },
  2: {
    bg: 'bg-gray-50 dark:bg-gray-900/30',
    text: 'text-gray-600 dark:text-gray-300',
    border: 'border-gray-200 dark:border-gray-700',
    icon: '🥈',
  },
  3: {
    bg: 'bg-orange-50 dark:bg-orange-950/30',
    text: 'text-orange-700 dark:text-orange-300',
    border: 'border-orange-200 dark:border-orange-800',
    icon: '🥉',
  },
};

// ==================== Helpers ====================
function formatNumber(n: number): string {
  return n.toLocaleString('th-TH');
}

function formatPercent(n: number): string {
  return n.toFixed(1);
}

// ==================== Loading Skeleton ====================
function ResultsPanelSkeleton() {
  return (
    <div className="w-full max-w-5xl mx-auto p-4 sm:p-6 space-y-6">
      {/* Header skeleton */}
      <div className="text-center space-y-3">
        <Skeleton className="h-8 w-64 mx-auto" />
        <Skeleton className="h-5 w-80 mx-auto" />
      </div>

      {/* Summary cards skeleton */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <Skeleton key={i} className="h-28 rounded-xl" />
        ))}
      </div>

      {/* Chart skeleton */}
      <Skeleton className="h-64 rounded-xl" />

      {/* Branch accordion skeleton */}
      <div className="space-y-3">
        {Array.from({ length: 3 }).map((_, i) => (
          <Skeleton key={i} className="h-20 rounded-xl" />
        ))}
      </div>
    </div>
  );
}

// ==================== Not Visible State ====================
function ResultsNotVisible({ onToggleVisibility, isToggling }: { onToggleVisibility: () => void; isToggling: boolean }) {
  const user = useAuthStore((s) => s.user);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
      className="flex flex-col items-center justify-center py-16 px-4"
    >
      <motion.div
        initial={{ scale: 0 }}
        animate={{ scale: 1 }}
        transition={{ type: 'spring', stiffness: 180, damping: 14, delay: 0.15 }}
        className="w-24 h-24 rounded-full bg-amber-50 dark:bg-amber-950/30 flex items-center justify-center mb-8 border-2 border-amber-200 dark:border-amber-800"
      >
        <EyeOff className="size-12 text-amber-500" />
      </motion.div>

      <motion.h2
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.3 }}
        className="text-2xl sm:text-3xl font-bold text-foreground mb-3 text-center"
      >
        ผลการเลือกตั้งยังไม่เปิดเผย
      </motion.h2>

      <motion.p
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.4 }}
        className="text-muted-foreground text-center max-w-md mb-8"
      >
        ผู้ดูแลระบบจะทำการประกาศผลการเลือกตั้งในภายหลัง
        <br />
        กรุณารอการแจ้งเตือน
      </motion.p>

      {user?.isAdmin && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5 }}
          className="space-y-4"
        >
          <Card className="border-amber-200 dark:border-amber-800/50 bg-amber-50/30 dark:bg-amber-950/10 max-w-md">
            <CardContent className="p-4 flex items-center gap-3">
              <div className="shrink-0 w-10 h-10 rounded-full bg-amber-100 dark:bg-amber-900/40 flex items-center justify-center">
                <AlertTriangle className="size-5 text-amber-600 dark:text-amber-400" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
                  สิทธิ์ผู้ดูแลระบบ
                </p>
                <p className="text-xs text-amber-600/70 dark:text-amber-400/70">
                  คุณสามารถเปิดเผยผลการเลือกตั้งได้
                </p>
              </div>
            </CardContent>
          </Card>
          <Button
            onClick={onToggleVisibility}
            disabled={isToggling}
            size="lg"
            className="bg-emerald-600 hover:bg-emerald-700 text-white shadow-lg w-full sm:w-auto min-w-[220px]"
          >
            {isToggling ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                กำลังเปิดเผยผล...
              </>
            ) : (
              <>
                <Eye className="size-4" />
                เปิดเผยผลการเลือกตั้ง
              </>
            )}
          </Button>
        </motion.div>
      )}
    </motion.div>
  );
}

// ==================== Summary Card ====================
function SummaryCard({
  icon,
  label,
  value,
  subValue,
  colorClass,
  delay,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  subValue?: string;
  colorClass: string;
  delay: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4, delay }}
    >
      <Card className="h-full overflow-hidden">
        <CardContent className="p-4 sm:p-5">
          <div className="flex items-start gap-3">
            <div
              className={`shrink-0 w-11 h-11 rounded-xl ${colorClass} flex items-center justify-center`}
            >
              {icon}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs sm:text-sm text-muted-foreground leading-tight">
                {label}
              </p>
              <p className="text-xl sm:text-2xl font-bold text-foreground mt-1">
                {value}
              </p>
              {subValue && (
                <p className="text-xs text-muted-foreground mt-0.5">
                  {subValue}
                </p>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}

// ==================== Participation Donut Chart ====================
function ParticipationChart({
  totalVoters,
  totalEligibleVoters,
}: {
  totalVoters: number;
  totalEligibleVoters: number;
}) {
  const nonVoters = Math.max(0, totalEligibleVoters - totalVoters);
  const participationRate = totalEligibleVoters > 0 ? (totalVoters / totalEligibleVoters) * 100 : 0;

  const data = [
    { name: 'voters', value: totalVoters, fill: 'var(--color-voters)' },
    { name: 'nonVoters', value: nonVoters, fill: 'var(--color-nonVoters)' },
  ];

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.5, delay: 0.3 }}
    >
      <Card className="overflow-hidden">
        <CardHeader className="pb-2">
          <CardTitle className="text-base sm:text-lg flex items-center gap-2">
            <TrendingUp className="size-5 text-emerald-600 dark:text-emerald-400" />
            ภาพรวมการมีสิทธิ์ใช้เสียง
          </CardTitle>
          <CardDescription>
            สัดส่วนผู้ใช้สิทธิ์ลงคะแนนทั้งหมด
          </CardDescription>
        </CardHeader>
        <CardContent className="pb-4">
          <div className="flex flex-col sm:flex-row items-center gap-6">
            <div className="w-full sm:w-1/2 max-w-[280px] mx-auto sm:mx-0">
              <ChartContainer config={PARTICIPATION_CHART_CONFIG} className="aspect-square w-full">
                <PieChart>
                  <ChartTooltip content={<ChartTooltipContent hideLabel />} />
                  <Pie
                    data={data}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    innerRadius="60%"
                    outerRadius="85%"
                    paddingAngle={2}
                    strokeWidth={2}
                    stroke="hsl(var(--background))"
                  >
                    {data.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.fill} />
                    ))}
                    <Label
                      content={({ viewBox }) => {
                        if (viewBox && 'cx' in viewBox && 'cy' in viewBox) {
                          return (
                            <text
                              x={viewBox.cx}
                              y={viewBox.cy}
                              textAnchor="middle"
                              dominantBaseline="middle"
                            >
                              <tspan
                                x={viewBox.cx}
                                y={(viewBox.cy || 0) - 8}
                                className="fill-foreground text-2xl sm:text-3xl font-bold"
                              >
                                {formatPercent(participationRate)}%
                              </tspan>
                              <tspan
                                x={viewBox.cx}
                                y={(viewBox.cy || 0) + 16}
                                className="fill-muted-foreground text-xs"
                              >
                                อัตราการใช้สิทธิ์
                              </tspan>
                            </text>
                          );
                        }
                        return null;
                      }}
                    />
                  </Pie>
                </PieChart>
              </ChartContainer>
            </div>
            <div className="flex-1 space-y-4 w-full sm:w-auto">
              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <div className="w-3 h-3 rounded-full bg-emerald-500 shrink-0" />
                  <div className="flex-1">
                    <p className="text-sm text-muted-foreground">ใช้สิทธิ์ลงคะแนน</p>
                    <div className="flex items-baseline gap-2">
                      <span className="text-lg font-bold text-foreground">
                        {formatNumber(totalVoters)}
                      </span>
                      <span className="text-xs text-muted-foreground">คน</span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <div className="w-3 h-3 rounded-full bg-slate-400 shrink-0" />
                  <div className="flex-1">
                    <p className="text-sm text-muted-foreground">ไม่ใช้สิทธิ์</p>
                    <div className="flex items-baseline gap-2">
                      <span className="text-lg font-bold text-foreground">
                        {formatNumber(nonVoters)}
                      </span>
                      <span className="text-xs text-muted-foreground">คน</span>
                    </div>
                  </div>
                </div>
              </div>
              <Separator />
              <div>
                <p className="text-sm text-muted-foreground mb-1">
                  อัตราการมีสิทธิ์ใช้เสียง
                </p>
                <div className="flex items-center gap-3">
                  <Progress
                    value={participationRate}
                    className="flex-1 h-3 bg-emerald-100 dark:bg-emerald-950/40 [&>[data-slot=progress-indicator]]:bg-emerald-500"
                  />
                  <span className="text-sm font-bold text-emerald-600 dark:text-emerald-400 min-w-[3rem] text-right">
                    {formatPercent(participationRate)}%
                  </span>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}

// ==================== Branch Results Card ====================
function BranchResultCard({
  branch,
  index,
  totalVotesInBranch,
}: {
  branch: BranchResult;
  index: number;
  totalVotesInBranch: number;
}) {
  const maxVoteCount = Math.max(...branch.candidates.map((c) => c.voteCount), 1);
  const winner = branch.candidates[0];

  // Chart config for this branch
  const barChartConfig: ChartConfig = {};
  const barChartData = branch.candidates.map((c, i) => {
    const key = `candidate${i}`;
    barChartConfig[key] = {
      label: c.name,
      color: i === 0 ? EMERALD_PRIMARY : i === 1 ? TEAL_SECONDARY : AMBER_ACCENT,
    };
    return {
      name: c.name.length > 15 ? c.name.slice(0, 15) + '...' : c.name,
      fullName: c.name,
      votes: c.voteCount,
      [`candidate${i}`]: c.voteCount,
      fill: `var(--color-candidate${i})`,
    };
  });

  return (
    <AccordionItem
      value={branch.branchId}
      className="border border-border/50 rounded-xl overflow-hidden data-[state=open]:border-emerald-200 dark:data-[state=open]:border-emerald-800/50 transition-colors"
    >
      <AccordionTrigger className="px-4 sm:px-6 py-4 hover:no-underline hover:bg-muted/30 transition-colors">
        <div className="flex items-center gap-3 flex-1 min-w-0 text-left">
          <div className="shrink-0 w-10 h-10 rounded-xl bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center">
            <Building2 className="size-5 text-emerald-600 dark:text-emerald-400" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-semibold text-foreground text-sm sm:text-base">
                {branch.branchName}
              </span>
              <Badge
                variant="secondary"
                className="text-[10px] bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800"
              >
                {branch.candidates.length} ผู้สมัคร
              </Badge>
            </div>
            <p className="text-xs text-muted-foreground mt-0.5">
              รวม {formatNumber(totalVotesInBranch)} คะแนน
            </p>
          </div>
          {winner && (
            <Badge className="hidden sm:flex shrink-0 bg-emerald-100 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800 text-xs">
              <Trophy className="size-3 mr-1" />
              {winner.name}
            </Badge>
          )}
        </div>
      </AccordionTrigger>
      <AccordionContent className="px-4 sm:px-6 pb-6">
        <div className="space-y-6">
          {/* Bar Chart */}
          <div>
            <h4 className="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
              <BarChart3 className="size-4" />
              จำนวนคะแนนเสียง
            </h4>
            <ChartContainer config={barChartConfig} className="h-[max(250px,5rem*var(--chart-count))] w-full" style={{ '--chart-count': branch.candidates.length } as React.CSSProperties}>
              <BarChart
                data={barChartData}
                layout="vertical"
                margin={{ top: 5, right: 30, left: 10, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                <XAxis type="number" tick={{ fontSize: 12 }} />
                <YAxis
                  dataKey="name"
                  type="category"
                  width={120}
                  tick={{ fontSize: 11 }}
                />
                <ChartTooltip
                  content={
                    <ChartTooltipContent
                      formatter={(value, name, item) => (
                        <span className="font-mono font-medium">
                          {formatNumber(Number(value))} คะแนน
                        </span>
                      )}
                    />
                  }
                />
                {branch.candidates.map((_, i) => (
                  <Bar
                    key={`candidate${i}`}
                    dataKey={`candidate${i}`}
                    radius={[0, 6, 6, 0]}
                    maxBarSize={36}
                  />
                ))}
              </BarChart>
            </ChartContainer>
          </div>

          <Separator />

          {/* Results Table */}
          <div>
            <h4 className="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
              <Medal className="size-4" />
              ตารางคะแนน
            </h4>
            <div className="rounded-lg border overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="w-16 text-center">อันดับ</TableHead>
                    <TableHead>ชื่อ-นามสกุล</TableHead>
                    <TableHead className="hidden sm:table-cell">ตำแหน่ง</TableHead>
                    <TableHead className="text-right w-24">คะแนน</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {branch.candidates.map((candidate, rank) => {
                    const rankStyle = RANK_STYLES[rank + 1];
                    const isWinner = rank === 0;
                    const votePercent = totalVotesInBranch > 0
                      ? (candidate.voteCount / totalVotesInBranch) * 100
                      : 0;

                    return (
                      <TableRow
                        key={candidate.candidateId}
                        className={isWinner ? 'bg-emerald-50/50 dark:bg-emerald-950/20' : ''}
                      >
                        <TableCell className="text-center">
                          {rankStyle ? (
                            <div
                              className={`inline-flex items-center justify-center w-8 h-8 rounded-full ${rankStyle.bg} ${rankStyle.border} border ${rankStyle.text} text-sm font-bold`}
                            >
                              {rank + 1}
                            </div>
                          ) : (
                            <span className="text-sm text-muted-foreground font-medium">
                              {rank + 1}
                            </span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <div
                              className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold ${
                                isWinner
                                  ? 'bg-emerald-500 text-white'
                                  : 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300'
                              }`}
                            >
                              {candidate.name.charAt(0)}
                            </div>
                            <div className="min-w-0">
                              <div className="flex items-center gap-2 flex-wrap">
                                <span
                                  className={`text-sm font-medium ${
                                    isWinner
                                      ? 'text-emerald-700 dark:text-emerald-300'
                                      : 'text-foreground'
                                  }`}
                                >
                                  {candidate.name}
                                </span>
                                {isWinner && (
                                  <Badge className="bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800 text-[10px] px-1.5 py-0">
                                    <Trophy className="size-2.5 mr-0.5" />
                                    ตัวแทนที่ได้รับเลือก
                                  </Badge>
                                )}
                                {rankStyle && rank < 3 && (
                                  <span className="text-xs" title={`อันดับที่ ${rank + 1}`}>
                                    {rankStyle.icon}
                                  </span>
                                )}
                              </div>
                              {/* Mobile-only position */}
                              <p className="text-xs text-muted-foreground sm:hidden">
                                {candidate.position || '—'}
                              </p>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">
                          <span className="text-sm text-muted-foreground">
                            {candidate.position || '—'}
                          </span>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex flex-col items-end gap-1">
                            <span
                              className={`text-sm font-bold ${
                                isWinner
                                  ? 'text-emerald-600 dark:text-emerald-400'
                                  : 'text-foreground'
                              }`}
                            >
                              {formatNumber(candidate.voteCount)}
                            </span>
                            <div className="w-16">
                              <Progress
                                value={votePercent}
                                className={`h-1.5 ${
                                  isWinner
                                    ? 'bg-emerald-100 dark:bg-emerald-950/40 [&>[data-slot=progress-indicator]]:bg-emerald-500'
                                    : 'bg-muted [&>[data-slot=progress-indicator]]:bg-muted-foreground/40'
                                }`}
                              />
                            </div>
                            <span className="text-[10px] text-muted-foreground">
                              {formatPercent(votePercent)}%
                            </span>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          </div>
        </div>
      </AccordionContent>
    </AccordionItem>
  );
}

// ==================== Main Component ====================
export default function ResultsPanel() {
  const [results, setResults] = useState<ResultsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isToggling, setIsToggling] = useState(false);

  const user = useAuthStore((s) => s.user);

  // Fetch results
  const fetchResults = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch('/api/results');
      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || 'ไม่สามารถโหลดข้อมูลได้');
      }
      const data: ResultsData = await res.json();
      setResults(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'เกิดข้อผิดพลาดในระบบ');
      toast.error('ไม่สามารถโหลดผลการเลือกตั้งได้', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchResults();
  }, [fetchResults]);

  // Admin toggle visibility
  const handleToggleVisibility = useCallback(async () => {
    setIsToggling(true);
    try {
      const res = await fetch('/api/admin/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ settings: { resultsVisible: 'true' } }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok || data?.success === false) {
        throw new Error(data?.error || 'ไม่สามารถเปิดเผยผลได้');
      }
      toast.success('เปิดเผยผลการเลือกตั้งสำเร็จ');
      fetchResults();
    } catch (err) {
      toast.error('เกิดข้อผิดพลาด', {
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setIsToggling(false);
    }
  }, [fetchResults]);

  // ==================== Render ====================

  // Loading
  if (loading) {
    return <ResultsPanelSkeleton />;
  }

  // Error
  if (error || !results) {
    return (
      <div className="w-full max-w-5xl mx-auto p-4 sm:p-6">
        <Alert variant="destructive">
          <AlertTriangle className="size-4" />
          <AlertTitle>เกิดข้อผิดพลาด</AlertTitle>
          <AlertDescription>
            {error || 'ไม่สามารถโหลดข้อมูลได้ กรุณาลองใหม่อีกครั้ง'}
          </AlertDescription>
        </Alert>
        <Button
          onClick={fetchResults}
          variant="outline"
          className="mt-4 w-full border-emerald-300 dark:border-emerald-700 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
        >
          <RefreshCw className="size-4" />
          ลองใหม่อีกครั้ง
        </Button>
      </div>
    );
  }

  // Not visible
  if (!results.visible) {
    return (
      <ResultsNotVisible
        onToggleVisibility={handleToggleVisibility}
        isToggling={isToggling}
      />
    );
  }

  // Visible — show results
  const participationRate =
    results.totalEligibleVoters > 0
      ? (results.totalVoters / results.totalEligibleVoters) * 100
      : 0;

  return (
    <div className="w-full max-w-5xl mx-auto p-4 sm:p-6 space-y-6">
      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
        className="text-center space-y-3"
      >
        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800">
          <BarChart3 className="size-5 text-emerald-600 dark:text-emerald-400" />
          <span className="font-semibold text-emerald-700 dark:text-emerald-300">
            ประกาศผลการเลือกตั้ง
          </span>
        </div>
        <h1 className="text-2xl sm:text-3xl font-bold text-foreground">
          ผลการเลือกตั้งตัวแทนพนักงาน
        </h1>
        <p className="text-sm text-muted-foreground">
          ผลการนับคะแนนอย่างเป็นทางการ
        </p>
      </motion.div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
        <SummaryCard
          icon={<Users className="size-5 text-emerald-600 dark:text-emerald-400" />}
          label="จำนวนผู้มีสิทธิ์ลงคะแนน"
          value={formatNumber(results.totalEligibleVoters)}
          subValue="คน"
          colorClass="bg-emerald-100 dark:bg-emerald-900/40"
          delay={0.1}
        />
        <SummaryCard
          icon={<Vote className="size-5 text-teal-600 dark:text-teal-400" />}
          label="จำนวนผู้ใช้สิทธิ์ลงคะแนน"
          value={formatNumber(results.totalVoters)}
          subValue="คน"
          colorClass="bg-teal-100 dark:bg-teal-900/40"
          delay={0.15}
        />
        <SummaryCard
          icon={<BarChart3 className="size-5 text-amber-600 dark:text-amber-400" />}
          label="จำนวนคะแนนเสียงทั้งหมด"
          value={formatNumber(results.totalVotes)}
          subValue="คะแนน"
          colorClass="bg-amber-100 dark:bg-amber-900/40"
          delay={0.2}
        />
        <SummaryCard
          icon={<TrendingUp className="size-5 text-emerald-600 dark:text-emerald-400" />}
          label="อัตราการมีสิทธิ์ใช้เสียง"
          value={`${formatPercent(participationRate)}%`}
          subValue={`จาก ${formatNumber(results.totalEligibleVoters)} คน`}
          colorClass="bg-emerald-100 dark:bg-emerald-900/40"
          delay={0.25}
        />
      </div>

      {/* Participation Donut Chart */}
      <ParticipationChart
        totalVoters={results.totalVoters}
        totalEligibleVoters={results.totalEligibleVoters}
      />

      {/* Branch Results */}
      {results.branches.length === 0 ? (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.4 }}
        >
          <Card className="py-12">
            <CardContent className="flex flex-col items-center justify-center text-center p-6">
              <Building2 className="size-16 text-muted-foreground/30 mb-4" />
              <h3 className="text-lg font-medium text-muted-foreground mb-2">
                ยังไม่มีข้อมูลผลการเลือกตั้ง
              </h3>
              <p className="text-sm text-muted-foreground">
                ขณะนี้ยังไม่มีข้อมูลสาขาที่มีผู้สมัครหรือคะแนนเสียง
              </p>
            </CardContent>
          </Card>
        </motion.div>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4, delay: 0.35 }}
          className="space-y-2"
        >
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
              <Building2 className="size-5 text-emerald-600 dark:text-emerald-400" />
              ผลการเลือกตั้งตามสาขา
            </h2>
            <Badge
              variant="secondary"
              className="bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800"
            >
              {results.branches.length} สาขา
            </Badge>
          </div>

          <Accordion type="multiple" defaultValue={[results.branches[0]?.branchId]} className="space-y-3">
            {results.branches.map((branch, index) => {
              const totalVotesInBranch = branch.candidates.reduce(
                (sum, c) => sum + c.voteCount,
                0
              );
              return (
                <BranchResultCard
                  key={branch.branchId}
                  branch={branch}
                  index={index}
                  totalVotesInBranch={totalVotesInBranch}
                />
              );
            })}
          </Accordion>
        </motion.div>
      )}

      {/* Footer note */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.6 }}
        className="text-center pt-4 pb-2"
      >
        <p className="text-xs text-muted-foreground">
          ผลการเลือกตั้งนี้เป็นผลการนับคะแนนอย่างเป็นทางการ • การลงคะแนนเป็นความลับ
        </p>
      </motion.div>
    </div>
  );
}
