'use client';

import { District, Division, DivisionResult } from '@/lib/db/division';
import { HistoricalPerformance } from '@/lib/db/history';
import { useEffect, useRef, useState } from 'react';

interface DivisionsClientProps {
  divisions: Division[];
  divisionResults: DivisionResult[];
  districtData: { [key: string]: District[] };
  historicalPerformance: HistoricalPerformance;
}

interface Upazila {
  name: string;
  centers: number;
  voters: number;
}

const toBn = (n: string | number): string => {
  const enToBn: { [key: string]: string } = {
    '0': '০',
    '1': '১',
    '2': '২',
    '3': '৩',
    '4': '৪',
    '5': '৫',
    '6': '৬',
    '7': '৭',
    '8': '৮',
    '9': '৯',
    '.': '.',
    '-': '-',
    ',': ',',
  };
  return n
    .toString()
    .split('')
    .map((d) => enToBn[d] || d)
    .join('');
};

declare const Chart: any;

// Common upazila names for generation
const commonUpazilas = [
  'সদর',
  'পূর্ব',
  'পশ্চিম',
  'উত্তর',
  'দক্ষিণ',
  'কালীগঞ্জ',
  'রায়পুর',
  'সোনারগাঁও',
  'রূপগঞ্জ',
  'সাভার',
  'দোহার',
  'নবাবগঞ্জ',
  'কেরানীগঞ্জ',
];

function generateUpazilas(districtName: string, count: number = 5): Upazila[] {
  const upazilas: Upazila[] = [];

  // Always add Sadar first
  upazilas.push({
    name: `${districtName} সদর`,
    centers: 120 + Math.floor(Math.random() * 50),
    voters: 250000 + Math.floor(Math.random() * 50000),
  });

  for (let i = 1; i < count; i++) {
    const name = commonUpazilas[i] || `উপজেলা ${i + 1}`;
    const isGeneric = !commonUpazilas[i];
    const uName = isGeneric ? `${districtName} ${i + 1}` : commonUpazilas[i];

    upazilas.push({
      name: uName,
      centers: 50 + Math.floor(Math.random() * 100),
      voters: 100000 + Math.floor(Math.random() * 100000),
    });
  }

  return upazilas;
}

export function DivisionsClient({
  divisions,
  divisionResults,
  districtData,
  historicalPerformance,
}: DivisionsClientProps) {
  const [selectedDivision, setSelectedDivision] = useState<string | null>(null);
  const [selectedDistrict, setSelectedDistrict] = useState<{
    name: string;
    nameEn: string;
    district: District;
  } | null>(null);
  const [chartLoaded, setChartLoaded] = useState(false);
  const [upazilas, setUpazilas] = useState<Upazila[]>([]);

  const divisionChartRef = useRef<HTMLCanvasElement>(null);
  const demographicsChartRef = useRef<HTMLCanvasElement>(null);
  const historicalChartRef = useRef<HTMLCanvasElement>(null);

  const divisionChartInstance = useRef<any>(null);
  const demographicsChartInstance = useRef<any>(null);
  const historicalChartInstance = useRef<any>(null);

  // Load Chart.js
  useEffect(() => {
    const chartOnWindow =
      typeof window !== 'undefined' ? (window as Window & { Chart?: unknown }).Chart : undefined;
    if (!chartOnWindow) {
      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/chart.js';
      script.onload = () => setChartLoaded(true);
      document.head.appendChild(script);
    } else {
      setChartLoaded(true);
    }
  }, []);

  // Initialize Historical Chart (Always visible)
  useEffect(() => {
    if (!chartLoaded || !historicalChartRef.current || typeof Chart === 'undefined') return;

    if (historicalChartInstance.current) {
      historicalChartInstance.current.destroy();
    }

    const ctx = historicalChartRef.current.getContext('2d');
    if (!ctx) return;

    historicalChartInstance.current = new Chart(ctx, {
      type: 'line',
      data: {
        labels: historicalPerformance.years.map((y) => toBn(y)),
        datasets: [
          {
            label: 'আওয়ামী লীগ',
            data: historicalPerformance.awamiLeague.seats,
            borderColor: '#006A4E',
            backgroundColor: 'rgba(0, 106, 78, 0.1)',
            borderWidth: 3,
            tension: 0.3,
            fill: true,
          },
          {
            label: 'বিএনপি',
            data: historicalPerformance.bnp.seats,
            borderColor: '#ED1B24',
            backgroundColor: 'rgba(237, 27, 36, 0.1)',
            borderWidth: 3,
            tension: 0.3,
            fill: true,
          },
          {
            label: 'জাতীয় পার্টি',
            data: historicalPerformance.jatiyaParty.seats,
            borderColor: '#9333EA',
            backgroundColor: 'rgba(147, 51, 234, 0.1)',
            borderWidth: 3,
            tension: 0.3,
            fill: true,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top',
            labels: {
              font: { family: "'Hind Siliguri', sans-serif", size: 14 },
              usePointStyle: true,
            },
          },
          tooltip: {
            mode: 'index',
            intersect: false,
            callbacks: {
              label: (ctx: any) => ` ${ctx.dataset.label}: ${toBn(ctx.raw)} আসন`,
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
        scales: {
          y: {
            beginAtZero: true,
            title: {
              display: true,
              text: 'আসন সংখ্যা',
              font: { family: "'Hind Siliguri', sans-serif", size: 14 },
            },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif" },
              callback: (value: any) => toBn(value),
            },
          },
          x: {
            grid: { display: false },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif" },
            },
          },
        },
      },
    });

    return () => {
      if (historicalChartInstance.current) {
        historicalChartInstance.current.destroy();
      }
    };
  }, [chartLoaded, historicalPerformance]);

  // Update Division Chart when division is selected
  useEffect(() => {
    if (
      !chartLoaded ||
      !divisionChartRef.current ||
      !selectedDivision ||
      typeof Chart === 'undefined'
    )
      return;

    const resultIndex = divisions.findIndex((d) => d.id === selectedDivision);
    const result = divisionResults[resultIndex];
    if (!result) return;

    if (divisionChartInstance.current) {
      divisionChartInstance.current.destroy();
    }

    const ctx = divisionChartRef.current.getContext('2d');
    if (!ctx) return;

    divisionChartInstance.current = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['আওয়ামী লীগ', 'জাতীয় পার্টি', 'স্বতন্ত্র'],
        datasets: [
          {
            data: [result.AL, result.JP, result.IND],
            backgroundColor: ['#006A4E', '#DC2626', '#6B7280'],
            borderRadius: 8,
            barThickness: 40,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: (ctx: any) => ` আসন: ${toBn(ctx.raw)}`,
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: { color: '#f3f4f6' },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif" },
              callback: (value: any) => toBn(value),
            },
          },
          x: {
            grid: { display: false },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif", size: 12 },
            },
          },
        },
      },
    });

    return () => {
      if (divisionChartInstance.current) {
        divisionChartInstance.current.destroy();
      }
    };
  }, [chartLoaded, selectedDivision, divisions, divisionResults]);

  // Update Demographics Chart when division is selected
  useEffect(() => {
    if (
      !chartLoaded ||
      !demographicsChartRef.current ||
      !selectedDivision ||
      typeof Chart === 'undefined'
    )
      return;

    if (demographicsChartInstance.current) {
      demographicsChartInstance.current.destroy();
    }

    const ctx = demographicsChartRef.current.getContext('2d');
    if (!ctx) return;

    // Simulate demographics (48-52% male)
    const malePct = 48 + Math.random() * 4;
    const femalePct = 100 - malePct;

    demographicsChartInstance.current = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ['পুরুষ ভোটার', 'মহিলা ভোটার'],
        datasets: [
          {
            data: [malePct.toFixed(1), femalePct.toFixed(1)],
            backgroundColor: ['#2563EB', '#DB2777'],
            borderWidth: 0,
            hoverOffset: 4,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              font: { family: "'Hind Siliguri', sans-serif" },
              usePointStyle: true,
            },
          },
          tooltip: {
            callbacks: {
              label: (ctx: any) => ` ${ctx.label}: ${toBn(ctx.raw)}%`,
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
      },
    });

    return () => {
      if (demographicsChartInstance.current) {
        demographicsChartInstance.current.destroy();
      }
    };
  }, [chartLoaded, selectedDivision]);

  const handleSelectDivision = (divisionId: string) => {
    setSelectedDivision(divisionId);
    setSelectedDistrict(null);
  };

  const handleSelectDistrict = (
    districtName: string,
    districtNameEn: string,
    district: District,
  ) => {
    setSelectedDistrict({ name: districtName, nameEn: districtNameEn, district });

    // Generate upazilas
    const count = 4 + Math.floor(Math.random() * 4);
    const generatedUpazilas = generateUpazilas(districtName, count);
    setUpazilas(generatedUpazilas);
  };

  const selectedDivisionData = selectedDivision
    ? divisions.find((d) => d.id === selectedDivision)
    : null;
  const selectedDivisionResult = selectedDivision
    ? divisionResults[divisions.findIndex((d) => d.id === selectedDivision)]
    : null;
  const selectedDivisionDistricts = selectedDivision ? districtData[selectedDivision] : [];

  // Calculate stats for selected district
  const districtStats = selectedDistrict
    ? {
        totalVoters: upazilas.reduce((sum, u) => sum + u.voters, 0),
        totalCenters: upazilas.reduce((sum, u) => sum + u.centers, 0),
        maleVoters: Math.floor(
          upazilas.reduce((sum, u) => sum + u.voters, 0) * (0.48 + Math.random() * 0.04),
        ),
        femaleVoters: 0,
      }
    : null;

  if (districtStats) {
    districtStats.femaleVoters = districtStats.totalVoters - districtStats.maleVoters;
  }

  return (
    <>
      <div className="relative bg-linear-to-r from-purple-800 to-indigo-900 text-white py-10 sm:py-16 overflow-hidden">
        <div className="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/cubes.png')] opacity-10"></div>
        <div className="absolute -top-24 -right-24 w-96 h-96 bg-purple-500 rounded-full blur-[128px] opacity-20"></div>
        <div className="absolute -bottom-24 -left-24 w-72 h-72 bg-indigo-400 rounded-full blur-[100px] opacity-20"></div>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10 text-center">
          <h1 className="text-3xl sm:text-4xl md:text-5xl font-bold mb-4 leading-tight">
            বিভাগভিত্তিক <span className="text-yellow-400">নির্বাচনী তথ্য</span>
          </h1>
          <p className="text-purple-100 text-sm sm:text-base md:text-lg max-w-2xl mx-auto font-light">
            ৮টি বিভাগের নির্বাচনী ফলাফল, আসন বণ্টন ও পরিসংখ্যান একনজরে দেখুন।
          </p>
        </div>
      </div>

      <main className="max-w-7xl mx-auto px-3 sm:px-4 lg:px-8 py-4 sm:py-6 md:py-8">
        {/* Division Cards Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 gap-2 sm:gap-3 md:gap-4 mb-6 sm:mb-8">
          {divisions.map((div, index) => {
            const result = divisionResults[index];
            const isSelected = selectedDivision === div.id;

            return (
              <div
                key={div.id}
                onClick={() => handleSelectDivision(div.id)}
                className={`bg-white rounded-xl shadow-sm border-2 cursor-pointer transition-all hover:shadow-lg hover:-translate-y-1 ${
                  isSelected ? 'border-purple-500 ring-2 ring-purple-200' : 'border-gray-200'
                }`}
              >
                <div className="p-4">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 rounded" style={{ backgroundColor: div.color }}></div>
                      <span className="font-bold text-gray-800">{div.nameBn}</span>
                    </div>
                    {isSelected ? (
                      <span className="material-symbols-outlined text-purple-600">
                        check_circle
                      </span>
                    ) : (
                      <span className="text-xs text-gray-500">{toBn(div.seats)} আসন</span>
                    )}
                  </div>
                  <div className="flex items-center justify-between text-xs text-gray-500">
                    <span>আওয়ামী: {toBn(result.AL)}</span>
                    <span>জাপা: {toBn(result.JP)}</span>
                    <span>স্বতন্ত্র: {toBn(result.IND)}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Selection Hint */}
        {!selectedDivision && (
          <div className="text-center py-6 sm:py-8 text-gray-500">
            <span className="material-symbols-outlined text-3xl sm:text-4xl text-gray-300">
              touch_app
            </span>
            <p className="mt-2 text-sm sm:text-base">
              উপরে থেকে একটি বিভাগ নির্বাচন করতে ক্লিক করুন
            </p>
          </div>
        )}

        {/* District Selection Section */}
        {selectedDivision && !selectedDistrict && (
          <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-6 sm:mb-8">
            <div className="bg-linear-to-r from-purple-600 to-purple-800 text-white px-3 sm:px-4 md:px-6 py-2.5 sm:py-3 md:py-4">
              <h3 className="text-base sm:text-lg font-bold flex items-center gap-2">
                <span className="material-symbols-outlined">map</span>
                জেলা নির্বাচন করুন
              </h3>
            </div>
            <div className="p-4 sm:p-6">
              <p className="text-gray-500 mb-4 text-sm sm:text-base">
                বিস্তারিত তথ্য দেখতে নিচে থেকে একটি জেলা নির্বাচন করুন:
              </p>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 md:gap-4">
                {selectedDivisionDistricts.map((district, index) => {
                  const winningParty =
                    district.al > district.jp && district.al > district.ind
                      ? 'AL'
                      : district.jp > district.ind
                        ? 'JP'
                        : 'IND';
                  const winningColor =
                    winningParty === 'AL'
                      ? 'bg-green-500'
                      : winningParty === 'JP'
                        ? 'bg-red-500'
                        : 'bg-gray-500';

                  return (
                    <div
                      key={index}
                      onClick={() => handleSelectDistrict(district.name, district.nameEn, district)}
                      className="bg-white border hover:shadow-md cursor-pointer rounded-xl p-3 sm:p-4 transition-all hover:-translate-y-1 relative overflow-hidden group"
                    >
                      <div className="flex justify-between items-start mb-2">
                        <h4 className="font-bold text-gray-800 text-lg group-hover:text-purple-700 transition-colors">
                          {district.name}
                        </h4>
                        <span className="text-xs font-bold px-2 py-1 rounded bg-white border shadow-sm">
                          {toBn(district.al + district.jp + district.ind)} আসন
                        </span>
                      </div>
                      <div className="space-y-1 text-xs text-gray-600">
                        <div className="flex justify-between">
                          <span>আওয়ামী লীগ:</span>
                          <span className="font-bold">{toBn(district.al)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span>জাতীয় পার্টি:</span>
                          <span className="font-bold">{toBn(district.jp)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span>স্বতন্ত্র:</span>
                          <span className="font-bold">{toBn(district.ind)}</span>
                        </div>
                      </div>
                      <div className={`absolute bottom-0 left-0 h-1 w-full ${winningColor}`}></div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {/* Selected District View */}
        {selectedDistrict && districtStats && (
          <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-6 sm:mb-8 scroll-mt-20">
            {/* District Header */}
            <div className="bg-teal-50 border-b border-teal-100 p-4 sm:p-6 flex justify-between items-start sm:items-center flex-col sm:flex-row gap-4">
              <div>
                <h3 className="text-xl sm:text-2xl font-bold text-teal-900 flex items-center gap-2">
                  <span className="material-symbols-outlined text-teal-600">map</span>
                  {selectedDistrict.name} জেলা
                </h3>
                <div className="flex flex-wrap gap-2 mt-2">
                  <span className="px-2 py-1 rounded-md bg-purple-100 text-purple-700 text-xs font-bold border border-purple-200">
                    {toBn(
                      selectedDistrict.district.al +
                        selectedDistrict.district.jp +
                        selectedDistrict.district.ind,
                    )}
                    টি আসন
                  </span>
                  <span className="px-2 py-1 rounded-md bg-blue-100 text-blue-700 text-xs font-bold border border-blue-200">
                    বিভাগ: {selectedDivisionData?.nameBn}
                  </span>
                </div>
              </div>
              <button
                onClick={() => setSelectedDistrict(null)}
                className="text-teal-600 hover:bg-teal-100 px-3 py-1 rounded-lg text-sm font-medium transition flex items-center gap-1"
              >
                <span className="material-symbols-outlined text-lg">close</span> বন্ধ করুন
              </button>
            </div>

            {/* District Stats */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 sm:p-6 border-b border-gray-100">
              <div className="bg-blue-50 p-4 rounded-xl text-center">
                <p className="text-blue-600 text-xs font-bold uppercase mb-1">মোট ভোটার</p>
                <p className="text-xl font-bold text-gray-800">
                  {toBn(districtStats.totalVoters.toLocaleString())}
                </p>
              </div>
              <div className="bg-pink-50 p-4 rounded-xl text-center">
                <p className="text-pink-600 text-xs font-bold uppercase mb-1">নারী ভোটার</p>
                <p className="text-xl font-bold text-gray-800">
                  {toBn(districtStats.femaleVoters.toLocaleString())}
                </p>
              </div>
              <div className="bg-indigo-50 p-4 rounded-xl text-center">
                <p className="text-indigo-600 text-xs font-bold uppercase mb-1">পুরুষ ভোটার</p>
                <p className="text-xl font-bold text-gray-800">
                  {toBn(districtStats.maleVoters.toLocaleString())}
                </p>
              </div>
              <div className="bg-green-50 p-4 rounded-xl text-center">
                <p className="text-green-600 text-xs font-bold uppercase mb-1">মোট কেন্দ্র</p>
                <p className="text-xl font-bold text-gray-800">
                  {toBn(districtStats.totalCenters)}
                </p>
              </div>
            </div>

            {/* Upazila Breakdown Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-xs sm:text-sm">
                <thead className="bg-gray-50 border-b border-gray-200">
                  <tr>
                    <th className="px-4 py-3 text-left font-bold text-gray-600">উপজেলা/থানা</th>
                    <th className="px-4 py-3 text-center font-bold text-gray-600">কেন্দ্র</th>
                    <th className="px-4 py-3 text-center font-bold text-gray-600">ভোটার</th>
                    <th className="px-4 py-3 text-center font-bold text-blue-600">পুরুষ (%)</th>
                    <th className="px-4 py-3 text-center font-bold text-pink-600">মহিলা (%)</th>
                    <th className="px-4 py-3 text-center font-bold text-purple-600">
                      বিজয়ী (সম্ভাব্য)
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {upazilas.map((upazila, index) => {
                    const malePct = 48 + Math.random() * 4;
                    const femalePct = 100 - malePct;
                    const maleCnt = Math.round(upazila.voters * (malePct / 100));
                    const femaleCnt = Math.round(upazila.voters * (femalePct / 100));

                    // Random winner
                    const r = Math.random();
                    const winner =
                      r > 0.4
                        ? {
                            name: 'আওয়ামী লীগ',
                            class: 'text-green-700 bg-green-50 border-green-200',
                          }
                        : r > 0.2
                          ? {
                              name: 'জাতীয় পার্টি',
                              class: 'text-red-700 bg-red-50 border-red-200',
                            }
                          : {
                              name: 'স্বতন্ত্র',
                              class: 'text-gray-700 bg-gray-50 border-gray-200',
                            };

                    return (
                      <tr
                        key={index}
                        className="hover:bg-gray-50 transition border-b border-gray-50 last:border-0"
                      >
                        <td className="px-4 py-3 font-bold text-gray-800">{upazila.name}</td>
                        <td className="px-4 py-3 text-center text-gray-600">
                          {toBn(upazila.centers)}
                        </td>
                        <td className="px-4 py-3 text-center font-bold text-gray-800">
                          {toBn(upazila.voters.toLocaleString())}
                        </td>
                        <td className="px-4 py-3 text-center">
                          <div className="text-xs text-blue-600 font-bold">
                            {toBn(malePct.toFixed(1))}%
                          </div>
                          <div className="text-[10px] text-gray-400">
                            ({toBn(maleCnt.toLocaleString())})
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <div className="text-xs text-pink-600 font-bold">
                            {toBn(femalePct.toFixed(1))}%
                          </div>
                          <div className="text-[10px] text-gray-400">
                            ({toBn(femaleCnt.toLocaleString())})
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <span
                            className={`inline-flex items-center gap-1 px-2 py-1 rounded-full border text-[11px] font-bold ${winner.class}`}
                          >
                            {winner.name}
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Division Details Grid */}
        {selectedDivision && !selectedDistrict && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-3 sm:gap-4 md:gap-6 mb-6 sm:mb-8">
            {/* Division Info */}
            <div className="lg:col-span-1 bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 p-3 sm:p-4 md:p-6">
              <h3 className="font-bold text-gray-800 mb-3 sm:mb-4 flex items-center gap-2">
                <span className="material-symbols-outlined text-purple-600">location_on</span>
                {selectedDivisionData?.nameBn} বিভাগ
              </h3>
              <div className="space-y-3">
                <div className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                  <span className="text-gray-600">জেলা</span>
                  <span className="font-bold text-gray-800">
                    {toBn(selectedDivisionData?.districts || 0)}টি
                  </span>
                </div>
                <div className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                  <span className="text-gray-600">সংসদীয় আসন</span>
                  <span className="font-bold text-gray-800">
                    {toBn(selectedDivisionData?.seats || 0)}টি
                  </span>
                </div>
                <div className="p-3 bg-green-50 rounded-lg">
                  <div className="flex justify-between items-center mb-1">
                    <span className="text-gray-600">আওয়ামী লীগ</span>
                    <span className="font-bold text-green-700">
                      {toBn(selectedDivisionResult?.AL || 0)}
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-lg h-2">
                    <div
                      className="bg-green-600 h-2 rounded-lg"
                      style={{
                        width: `${(((selectedDivisionResult?.AL || 0) / (selectedDivisionData?.seats || 1)) * 100).toFixed(1)}%`,
                      }}
                    ></div>
                  </div>
                </div>
                <div className="p-3 bg-red-50 rounded-lg">
                  <div className="flex justify-between items-center mb-1">
                    <span className="text-gray-600">জাতীয় পার্টি</span>
                    <span className="font-bold text-red-700">
                      {toBn(selectedDivisionResult?.JP || 0)}
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-lg h-2">
                    <div
                      className="bg-red-600 h-2 rounded-lg"
                      style={{
                        width: `${(((selectedDivisionResult?.JP || 0) / (selectedDivisionData?.seats || 1)) * 100).toFixed(1)}%`,
                      }}
                    ></div>
                  </div>
                </div>
                <div className="p-3 bg-gray-100 rounded-lg">
                  <div className="flex justify-between items-center mb-1">
                    <span className="text-gray-600">স্বতন্ত্র</span>
                    <span className="font-bold text-gray-700">
                      {toBn(selectedDivisionResult?.IND || 0)}
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-lg h-2">
                    <div
                      className="bg-gray-600 h-2 rounded-lg"
                      style={{
                        width: `${(((selectedDivisionResult?.IND || 0) / (selectedDivisionData?.seats || 1)) * 100).toFixed(1)}%`,
                      }}
                    ></div>
                  </div>
                </div>
              </div>
            </div>

            {/* Party Distribution Chart */}
            <div className="lg:col-span-1 bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 p-3 sm:p-4 md:p-6">
              <h3 className="font-bold text-gray-800 mb-3 sm:mb-4 flex items-center gap-2 text-sm sm:text-base">
                <span className="material-symbols-outlined text-blue-600">bar_chart</span>
                আসন বিন্যাস
              </h3>
              <div className="h-48 sm:h-56 md:h-64">
                <canvas ref={divisionChartRef}></canvas>
              </div>
            </div>

            {/* Demographics Chart */}
            <div className="lg:col-span-1 bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 p-3 sm:p-4 md:p-6">
              <h3 className="font-bold text-gray-800 mb-3 sm:mb-4 flex items-center gap-2 text-sm sm:text-base">
                <span className="material-symbols-outlined text-green-600">pie_chart</span>
                ভোটার পরিসংখ্যান (পুরুষ ও মহিলা)
              </h3>
              <div className="h-48 sm:h-56 md:h-64 relative">
                <canvas ref={demographicsChartRef}></canvas>
              </div>
            </div>
          </div>
        )}

        {/* Historical Data Section */}
        <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-6 sm:mb-8">
          <div className="bg-linear-to-r from-indigo-600 to-indigo-800 text-white px-3 sm:px-4 md:px-6 py-2.5 sm:py-3 md:py-4">
            <h3 className="text-base sm:text-lg font-bold flex items-center gap-2">
              <span className="material-symbols-outlined">history</span>
              ঐতিহাসিক নির্বাচনী ফলাফল (১৯৯১ - ২০২৪)
            </h3>
          </div>
          <div className="p-4 sm:p-6 h-64 sm:h-80 md:h-96">
            <canvas ref={historicalChartRef}></canvas>
          </div>
        </div>

        {/* All Divisions Comparison Table */}
        <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
          <div className="bg-linear-to-r from-gray-700 to-gray-800 text-white px-3 sm:px-4 md:px-6 py-2.5 sm:py-3 md:py-4">
            <h3 className="text-base sm:text-lg font-bold flex items-center gap-2">
              <span className="material-symbols-outlined">table_chart</span>
              সকল বিভাগের তুলনা
            </h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-xs sm:text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-2 sm:px-3 md:px-4 py-2 sm:py-3 text-left text-xs font-bold text-gray-600 uppercase">
                    বিভাগ
                  </th>
                  <th className="px-2 sm:px-3 md:px-4 py-2 sm:py-3 text-center text-xs font-bold text-gray-600 uppercase">
                    জেলা
                  </th>
                  <th className="px-2 sm:px-3 md:px-4 py-2 sm:py-3 text-center text-xs font-bold text-gray-600 uppercase">
                    আসন
                  </th>
                  <th className="px-2 sm:px-3 md:px-4 py-2 sm:py-3 text-center text-xs font-bold text-green-700 uppercase">
                    আওয়ামী লীগ
                  </th>
                  <th className="px-2 sm:px-3 md:px-4 py-2 sm:py-3 text-center text-xs font-bold text-purple-700 uppercase">
                    জাতীয় পার্টি
                  </th>
                  <th className="px-2 sm:px-3 md:px-4 py-2 sm:py-3 text-center text-xs font-bold text-gray-700 uppercase">
                    স্বতন্ত্র
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {divisions.map((div, index) => {
                  const result = divisionResults[index];
                  return (
                    <tr
                      key={div.id}
                      onClick={() => handleSelectDivision(div.id)}
                      className="hover:bg-gray-50 transition cursor-pointer"
                    >
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div
                            className="w-3 h-3 rounded"
                            style={{ backgroundColor: div.color }}
                          ></div>
                          <span className="font-medium text-gray-800">{div.nameBn}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-center text-gray-600">{toBn(div.districts)}</td>
                      <td className="px-4 py-3 text-center font-bold text-gray-800">
                        {toBn(div.seats)}
                      </td>
                      <td className="px-4 py-3 text-center font-bold text-green-700">
                        {toBn(result.AL)}
                      </td>
                      <td className="px-4 py-3 text-center font-bold text-purple-700">
                        {toBn(result.JP)}
                      </td>
                      <td className="px-4 py-3 text-center font-bold text-gray-700">
                        {toBn(result.IND)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </main>
    </>
  );
}
