import { confirmAction } from '@/lib/confirm-action';
import { Link, router, usePage } from '@inertiajs/react';
import { Users, Vote, Lock, CheckCircle2, Eye, EyeOff, Plus, Trash2, Crown, UserPlus, AlertTriangle, MessageSquare } from 'lucide-react';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';
import { useState } from 'react';
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal';

interface Student {
    id: number;
    full_name: string;
    gender: 'L' | 'P' | null;
}

interface Position {
    id: number;
    name: string;
    sort_order: number;
    candidates: Array<{
        id: number;
        student_id: number | null;
        label: string | null;
        nomination_count: number;
        source: string;
        student: Student | null;
        final_votes_count?: number;
    }>;
}

interface NominationEntry {
    nominee_student_id: number | null;
    nominee_label: string | null;
    votes: number;
    nominee: Student | null;
}

interface Props extends PageProps {
    session: {
        id: number;
        title: string;
        type: 'class_election' | 'quick_poll';
        mode: string;
        current_phase: string;
        min_votes_threshold: number;
        results_visible: boolean;
        synced_class: { id: number; name: string; students: Student[] };
        positions: Position[];
        started_at: string | null;
        end_at: string | null;
    };
    totalStudents: number;
    nominationProgress: number;
    finalVoteProgress: number;
    nominationTally: Record<number, NominationEntry[]>;
    finalVoteTally: Record<number, Array<{ id: number; student: Student | null; label: string | null; final_votes_count: number }>>;
    students: Student[];
}

const phaseSteps = [
    { key: 'nomination', label: 'Nominasi', icon: Users },
    { key: 'review', label: 'Review', icon: Eye },
    { key: 'final_vote', label: 'Pemilihan', icon: Vote },
    { key: 'completed', label: 'Selesai', icon: CheckCircle2 },
];

export default function VotingShow() {
    const { session, totalStudents, nominationProgress, finalVoteProgress, nominationTally, finalVoteTally, students } = usePage<Props>().props;
    const [addingToPosition, setAddingToPosition] = useState<number | null>(null);
    const [selectedStudent, setSelectedStudent] = useState<string>('');
    const [newLabel, setNewLabel] = useState<string>('');
    const [deleteConfig, setDeleteConfig] = useState<{isOpen: boolean, url: string, message: string, title: string, keyword?: string} | null>(null);

    const currentPhaseIndex = phaseSteps.findIndex(s => s.key === session.current_phase);
    const isQuickPoll = session.type === 'quick_poll';

    const handleProcessNominations = async () => {
        const msg = isQuickPoll 
            ? 'Proses usulan dan tentukan daftar pilihan final? Pastikan semua siswa sudah selesai mengirimkan usulan.' 
            : 'Proses nominasi dan tentukan kandidat? Pastikan semua siswa sudah selesai menominasikan.';
        if ((await confirmAction(msg))) {
            router.post(`/voting/${session.id}/process-nominations`);
        }
    };

    const handleLockCandidates = async () => {
        const msg = isQuickPoll
            ? 'Kunci daftar pilihan dan buka sesi pemilihan final? Pastikan semua pilihan sudah siap.'
            : 'Kunci kandidat dan buka sesi pemilihan final? Pastikan semua posisi sudah terisi.';
        if ((await confirmAction(msg))) {
            router.post(`/voting/${session.id}/lock-candidates`);
        }
    };

    const handleComplete = async () => {
        if ((await confirmAction('Tutup voting dan publikasikan hasil?'))) {
            router.post(`/voting/${session.id}/complete`);
        }
    };

    const handleToggleResults = () => {
        router.post(`/voting/${session.id}/toggle-results`);
    };

    const handleAddCandidate = (positionId: number) => {
        if (isQuickPoll) {
            if (!newLabel.trim()) return;
            router.post(`/voting/${session.id}/add-candidate`, {
                position_id: positionId,
                label: newLabel,
            }, {
                onSuccess: () => {
                    setAddingToPosition(null);
                    setNewLabel('');
                },
            });
        } else {
            if (!selectedStudent) return;
            router.post(`/voting/${session.id}/add-candidate`, {
                position_id: positionId,
                student_id: parseInt(selectedStudent),
            }, {
                onSuccess: () => {
                    setAddingToPosition(null);
                    setSelectedStudent('');
                },
            });
        }
    };

    const handleRemoveCandidate = (candidateId: number) => {
        setDeleteConfig({
            isOpen: true,
            url: `/voting/${session.id}/remove-candidate/${candidateId}`,
            title: isQuickPoll ? 'Hapus Pilihan' : 'Hapus Kandidat',
            message: isQuickPoll ? 'Yakin ingin menghapus pilihan ini? Data suara untuk pilihan ini mungkin akan hilang.' : 'Yakin ingin menghapus kandidat ini? Data suara untuk kandidat ini mungkin akan hilang.',
            keyword: 'HAPUS'
        });
    };

    // Get already-assigned student IDs (can't be assigned to another position)
    const assignedStudentIds = session.positions.flatMap(p => p.candidates.filter(c => c.student_id).map(c => c.student_id));

    const now = new Date();
    const serverTimeBuffer = 5 * 60 * 1000; // 5 menit toleransi waktu server vs client
    const nowWithBuffer = new Date(now.getTime() + serverTimeBuffer);

    const isLive = session.started_at && new Date(session.started_at) <= nowWithBuffer && (!session.end_at || new Date(session.end_at) > now);
    const isDraft = !session.started_at;
    const isScheduled = session.started_at && new Date(session.started_at) > nowWithBuffer;
    const isPastEnd = session.end_at && new Date(session.end_at) <= now;

    return (
        <AuthenticatedLayout title={session.title} backHref="/voting">
            {/* Header / Actions */}
            <div className="flex items-center justify-between mb-6">
                <button
                    onClick={() => {
                        setDeleteConfig({
                            isOpen: true,
                            url: `/voting/${session.id}`,
                            title: 'Hapus Sesi Voting',
                            message: 'Semua data suara akan ikut terhapus secara permanen.',
                            keyword: 'HAPUS'
                        });
                    }}
                    className="inline-flex items-center gap-2 rounded-lg bg-rose-500/10 px-3 py-1.5 text-xs font-semibold text-rose-500 hover:bg-rose-500/20 transition-colors"
                >
                    <Trash2 className="h-3.5 w-3.5" />
                    Hapus Sesi
                </button>
            </div>

            {/* Banner Penjadwalan */}
            {(!isLive || isPastEnd) && (
                <div className={cn(
                    "rounded-xl md:rounded-2xl border p-4 mb-4 md:mb-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4 backdrop-blur-sm shadow-sm",
                    isDraft && "border-amber-500/20 bg-amber-500/5 text-amber-400",
                    isScheduled && "border-sky-500/20 bg-sky-500/5 text-sky-400",
                    isPastEnd && "border-rose-500/20 bg-rose-500/5 text-rose-400"
                )}>
                    <div>
                        <h4 className="font-semibold text-sm sm:text-base">
                            {isDraft && "Status Sesi: Draft (Belum Aktif)"}
                            {isScheduled && "Status Sesi: Terjadwal"}
                            {isPastEnd && "Status Sesi: Selesai (Otomatis)"}
                        </h4>
                        <p className="text-xs text-text-muted mt-1">
                            {isDraft && "Siswa belum dapat melihat atau mengisi sesi voting ini. Klik tombol untuk mengaktifkannya sekarang."}
                            {isScheduled && `Sesi voting akan dimulai secara otomatis pada ${new Date(session.started_at!).toLocaleString('id-ID')} sampai ${session.end_at ? new Date(session.end_at).toLocaleString('id-ID') : 'selesai'}.`}
                            {isPastEnd && `Sesi voting telah ditutup secara otomatis berdasarkan jadwal (${new Date(session.end_at!).toLocaleString('id-ID')}).`}
                        </p>
                    </div>
                    {(!isLive && !isPastEnd) && (
                        <button
                            onClick={async () => {
                                if ((await confirmAction('Mulai sesi voting ini sekarang?'))) {
                                    router.post(`/voting/${session.id}/start`);
                                }
                            }}
                            className="shrink-0 inline-flex items-center gap-1.5 rounded-lg bg-primary-500 px-4 py-2 text-xs font-semibold text-white shadow-lg shadow-primary-500/25 transition-all hover:bg-primary-600 hover:shadow-primary-500/40"
                        >
                            Mulai Sekarang
                        </button>
                    )}
                </div>
            )}

            {/* Phase Progress Bar */}
            <div className="rounded-xl md:rounded-2xl border border-border/50 bg-linear-to-br from-surface/80 to-surface/40 backdrop-blur-md p-4 md:p-6 mb-4 md:mb-6 shadow-sm overflow-x-hidden">
                <div className="flex items-center justify-between w-full">
                    {phaseSteps.map((step, i) => {
                        const StepIcon = step.icon;
                        const isActive = i === currentPhaseIndex;
                        const isDone = i < currentPhaseIndex;
                        // Ganti label untuk quick poll
                        let stepLabel = step.label;
                        if (isQuickPoll && step.key === 'nomination') stepLabel = 'Usulan';
                        if (isQuickPoll && step.key === 'review') stepLabel = 'Review Pilihan';

                        return (
                            <div key={step.key} className="flex items-center flex-1">
                                <div className="flex flex-col items-center flex-1">
                                    <div className={cn(
                                        'w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 rounded-full flex items-center justify-center transition-all duration-300',
                                        isActive && 'bg-linear-to-br from-primary-500 to-primary-600 text-white shadow-lg shadow-primary-500/30 scale-[1.15]',
                                        isDone && 'bg-linear-to-br from-emerald-500 to-emerald-600 text-white shadow-md shadow-emerald-500/20',
                                        !isActive && !isDone && 'bg-surface-hover/80 text-text-muted border border-border/50'
                                    )}>
                                        {isDone ? <CheckCircle2 className="h-4 w-4 sm:h-5 sm:w-5" /> : <StepIcon className="h-4 w-4 sm:h-5 sm:w-5" />}
                                    </div>
                                    <span className={cn(
                                        'text-[9px] sm:text-[11px] md:text-xs mt-2 font-medium transition-colors text-center leading-tight',
                                        isActive ? 'text-primary-400 font-bold' : isDone ? 'text-emerald-400' : 'text-text-muted'
                                    )}>
                                        {stepLabel}
                                    </span>
                                </div>
                                {i < phaseSteps.length - 1 && (
                                    <div className={cn(
                                        'h-0.5 md:h-1 flex-1 mx-1 md:mx-3 rounded-full transition-all duration-500',
                                        i < currentPhaseIndex ? 'bg-linear-to-r from-emerald-500 to-emerald-400 shadow-[0_0_8px_rgba(16,185,129,0.5)]' : 'bg-surface-hover border-y border-border/50'
                                    )} />
                                )}
                            </div>
                        );
                    })}
                </div>
            </div>

            {/* Stats Row */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 md:gap-4 mb-6">
                <div className="rounded-2xl border border-border/50 bg-linear-to-br from-surface/80 to-surface/40 backdrop-blur-sm p-4 md:p-5 hover:-translate-y-1 hover:shadow-lg transition-all duration-300">
                    <p className="text-[10px] md:text-xs text-text-muted uppercase tracking-wider font-semibold">Total Siswa</p>
                    <p className="text-xl md:text-2xl font-bold mt-1.5">{totalStudents}</p>
                </div>
                <div className="rounded-2xl border border-amber-500/20 bg-linear-to-br from-amber-500/10 to-surface/40 backdrop-blur-sm p-4 md:p-5 hover:-translate-y-1 hover:shadow-lg transition-all duration-300">
                    <p className="text-[10px] md:text-xs text-amber-500/80 uppercase tracking-wider font-semibold">
                        {isQuickPoll ? 'Siswa Mengusulkan' : 'Sudah Nominasi'}
                    </p>
                    <p className="text-xl md:text-2xl font-bold mt-1.5 flex items-baseline gap-1">
                        <span className={nominationProgress === totalStudents ? 'text-emerald-400' : 'text-amber-400'}>
                            {nominationProgress}
                        </span>
                        <span className="text-xs md:text-sm text-text-muted font-normal">/{totalStudents}</span>
                    </p>
                </div>
                <div className="rounded-2xl border border-sky-500/20 bg-linear-to-br from-sky-500/10 to-surface/40 backdrop-blur-sm p-4 md:p-5 hover:-translate-y-1 hover:shadow-lg transition-all duration-300">
                    <p className="text-[10px] md:text-xs text-sky-500/80 uppercase tracking-wider font-semibold">Sudah Memilih</p>
                    <p className="text-xl md:text-2xl font-bold mt-1.5 flex items-baseline gap-1">
                        <span className={finalVoteProgress === totalStudents ? 'text-emerald-400' : 'text-sky-400'}>
                            {finalVoteProgress}
                        </span>
                        <span className="text-xs md:text-sm text-text-muted font-normal">/{totalStudents}</span>
                    </p>
                </div>
                <div className="rounded-2xl border border-border/50 bg-linear-to-br from-surface/80 to-surface/40 backdrop-blur-sm p-4 md:p-5 hover:-translate-y-1 hover:shadow-lg transition-all duration-300">
                    <p className="text-[10px] md:text-xs text-text-muted uppercase tracking-wider font-semibold">
                        {isQuickPoll ? 'Tipe' : 'Posisi'}
                    </p>
                    {isQuickPoll ? (
                        <p className="text-lg md:text-xl font-bold mt-1.5 text-primary-400 truncate">Quick Poll</p>
                    ) : (
                        <p className="text-xl md:text-2xl font-bold mt-1.5">{session.positions.length}</p>
                    )}
                </div>
            </div>

            {/* Phase-specific Content */}
            {session.current_phase === 'nomination' && (
                <div className="space-y-4">
                    <div className="flex items-center justify-between">
                        <h3 className="text-sm md:text-lg font-semibold">Sesi 1: {isQuickPoll ? 'Usulan' : 'Nominasi'} Berlangsung</h3>
                        <button
                            onClick={handleProcessNominations}
                            className="inline-flex items-center gap-1.5 md:gap-2 rounded-lg md:rounded-xl bg-amber-500 px-3 md:px-5 py-2 md:py-2.5 text-[10px] md:text-sm font-semibold text-white shadow-lg shadow-amber-500/25 transition-all hover:bg-amber-600 hover:shadow-amber-500/40"
                        >
                            <Lock className="h-3 w-3 md:h-4 md:w-4" />
                            Tutup & Proses
                        </button>
                    </div>

                    {/* Nomination Tally per Position */}
                    {session.positions.map(pos => (
                        <div key={pos.id} className="rounded-lg md:rounded-xl border border-border/50 bg-surface/60 backdrop-blur-sm p-4 md:p-5">
                            {!isQuickPoll && (
                                <h4 className="font-semibold text-xs md:text-base mb-2 md:mb-3 flex items-center gap-1.5 md:gap-2">
                                    <Crown className="h-3.5 w-3.5 md:h-4 md:w-4 text-amber-400" />
                                    {pos.name}
                                </h4>
                            )}
                            {(nominationTally[pos.id] || []).length === 0 ? (
                                <p className="text-[10px] md:text-sm text-text-muted italic">Belum ada {isQuickPoll ? 'usulan pilihan' : 'nominasi'}</p>
                            ) : (
                                <div className="space-y-1.5 md:space-y-2 mt-2">
                                    {(nominationTally[pos.id] || []).map((entry: any, i: number) => {
                                        const label = entry.nominee_label || (entry.nominee?.full_name || `Siswa #${entry.nominee_student_id}`);
                                        return (
                                            <div key={i} className="flex items-center gap-2 md:gap-3">
                                                <span className="w-4 md:w-6 text-[10px] md:text-xs text-text-muted text-right">{i + 1}.</span>
                                                <span className="flex-1 text-[11px] md:text-sm font-medium truncate capitalize">{label}</span>
                                                <div className="flex items-center gap-1.5 md:gap-2">
                                                    <div className="w-20 md:w-32 h-1.5 md:h-2 rounded-full bg-surface-hover overflow-hidden">
                                                        <div
                                                            className={cn(
                                                                'h-full rounded-full transition-all',
                                                                entry.votes >= session.min_votes_threshold ? 'bg-emerald-500' : 'bg-amber-500'
                                                            )}
                                                            style={{ width: `${Math.min(100, (entry.votes / totalStudents) * 100)}%` }}
                                                        />
                                                    </div>
                                                    <span className={cn(
                                                        'text-[10px] md:text-xs font-semibold min-w-[24px] md:min-w-8 text-right',
                                                        entry.votes >= session.min_votes_threshold ? 'text-emerald-400' : 'text-amber-400'
                                                    )}>
                                                        {entry.votes}
                                                    </span>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            )}

            {session.current_phase === 'review' && (
                <div className="space-y-4">
                    <div className="flex items-center justify-between">
                        <h3 className="text-sm md:text-lg font-semibold">Review {isQuickPoll ? 'Daftar Pilihan' : 'Kandidat'}</h3>
                        <button
                            onClick={handleLockCandidates}
                            className="inline-flex items-center gap-1.5 md:gap-2 rounded-lg md:rounded-xl bg-emerald-500 px-3 md:px-5 py-2 md:py-2.5 text-[10px] md:text-sm font-semibold text-white shadow-lg shadow-emerald-500/25 transition-all hover:bg-emerald-600 hover:shadow-emerald-500/40"
                        >
                            <Lock className="h-3 w-3 md:h-4 md:w-4" />
                            <span className="hidden sm:inline">Kunci & Buka Sesi 2</span>
                            <span className="sm:hidden">Buka Sesi 2</span>
                        </button>
                    </div>

                    {session.positions.map(pos => {
                        const hasCandidates = pos.candidates.length > 0;
                        return (
                            <div key={pos.id} className={cn(
                                'rounded-lg md:rounded-xl border bg-surface/60 backdrop-blur-sm p-4 md:p-5',
                                !hasCandidates ? 'border-amber-500/50' : 'border-border/50'
                            )}>
                                <div className="flex items-center justify-between mb-2 md:mb-3">
                                    {!isQuickPoll ? (
                                        <h4 className="font-semibold text-xs md:text-base flex items-center gap-1.5 md:gap-2">
                                            <Crown className="h-3.5 w-3.5 md:h-4 md:w-4 text-amber-400" />
                                            {pos.name}
                                            {!hasCandidates && (
                                                <span className="inline-flex items-center gap-1 text-[9px] md:text-xs text-amber-400 bg-amber-500/10 px-1.5 md:px-2 py-0.5 rounded-md">
                                                    <AlertTriangle className="h-3 w-3" />
                                                    Butuh kandidat
                                                </span>
                                            )}
                                        </h4>
                                    ) : (
                                        <h4 className="font-semibold text-xs md:text-base flex items-center gap-1.5 md:gap-2">
                                            <MessageSquare className="h-3.5 w-3.5 md:h-4 md:w-4 text-amber-400" />
                                            Daftar Pilihan Voting
                                        </h4>
                                    )}
                                    <button
                                        onClick={() => setAddingToPosition(addingToPosition === pos.id ? null : pos.id)}
                                        className="inline-flex items-center gap-1 text-[10px] md:text-xs text-primary-400 hover:text-primary-300 transition-colors"
                                    >
                                        {isQuickPoll ? <Plus className="h-3 w-3 md:h-3.5 md:w-3.5" /> : <UserPlus className="h-3 w-3 md:h-3.5 md:w-3.5" />}
                                        Tambah {isQuickPoll ? 'Pilihan' : 'Kandidat'}
                                    </button>
                                </div>

                                {/* Add candidate form */}
                                {addingToPosition === pos.id && (
                                    <div className="flex items-center gap-2 mb-3 p-2.5 md:p-3 rounded-lg bg-surface-hover/50">
                                        {isQuickPoll ? (
                                            <input
                                                type="text"
                                                value={newLabel}
                                                onChange={(e) => setNewLabel(e.target.value)}
                                                placeholder="Ketik pilihan baru..."
                                                className="flex-1 rounded-lg border border-border bg-surface px-2.5 md:px-3 py-1.5 md:py-2 text-[11px] md:text-sm"
                                            />
                                        ) : (
                                            <select
                                                value={selectedStudent}
                                                onChange={(e) => setSelectedStudent(e.target.value)}
                                                className="flex-1 rounded-lg border border-border bg-surface px-2.5 md:px-3 py-1.5 md:py-2 text-[11px] md:text-sm"
                                            >
                                                <option value="">Pilih siswa...</option>
                                                {students
                                                    .filter(s => !assignedStudentIds.includes(s.id))
                                                    .map(s => (
                                                        <option key={s.id} value={s.id}>{s.full_name}</option>
                                                    ))}
                                            </select>
                                        )}
                                        <button
                                            onClick={() => handleAddCandidate(pos.id)}
                                            disabled={isQuickPoll ? !newLabel.trim() : !selectedStudent}
                                            className="rounded-lg bg-primary-500 px-3 md:px-4 py-1.5 md:py-2 text-[11px] md:text-sm font-medium text-white disabled:opacity-50 hover:bg-primary-600 transition-colors"
                                        >
                                            Tambah
                                        </button>
                                    </div>
                                )}

                                {/* Candidate list */}
                                {pos.candidates.length === 0 ? (
                                    <p className="text-[10px] md:text-sm text-text-muted italic">Tidak ada pilihan yang tersedia</p>
                                ) : (
                                    <div className="space-y-1.5 md:space-y-2">
                                        {pos.candidates.map((c) => {
                                            const label = c.label || c.student?.full_name;
                                            const initial = label ? label.charAt(0).toUpperCase() : '?';
                                            return (
                                                <div key={c.id} className="flex items-center justify-between p-2.5 md:p-3 rounded-lg bg-surface-hover/30">
                                                    <div className="flex items-center gap-2.5 md:gap-3">
                                                        <div className="w-6 h-6 md:w-8 md:h-8 rounded-full bg-primary-500/20 flex items-center justify-center text-[10px] md:text-xs font-bold text-primary-300">
                                                            {initial}
                                                        </div>
                                                        <div>
                                                            <p className="text-[11px] md:text-sm font-medium capitalize">{label}</p>
                                                            <p className="text-[9px] md:text-xs text-text-muted">
                                                                {c.source === 'nomination' 
                                                                    ? `${c.nomination_count} usulan / nominasi` 
                                                                    : 'Ditambahkan guru'}
                                                            </p>
                                                        </div>
                                                    </div>
                                                    <button
                                                        onClick={() => handleRemoveCandidate(c.id)}
                                                        className="p-1.5 rounded-lg text-text-muted hover:text-rose-400 hover:bg-rose-500/10 transition-colors"
                                                    >
                                                        <Trash2 className="h-3 w-3 md:h-3.5 md:w-3.5" />
                                                    </button>
                                                </div>
                                            );
                                        })}
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            )}

            {session.current_phase === 'final_vote' && (
                <div className="space-y-4">
                    <div className="flex items-center justify-between">
                        <h3 className="text-sm md:text-lg font-semibold">Sesi 2: Pemilihan Final Berlangsung</h3>
                        <button
                            onClick={handleComplete}
                            className="inline-flex items-center gap-1.5 md:gap-2 rounded-lg md:rounded-xl bg-emerald-500 px-3 md:px-5 py-2 md:py-2.5 text-[10px] md:text-sm font-semibold text-white shadow-lg shadow-emerald-500/25 transition-all hover:bg-emerald-600 hover:shadow-emerald-500/40"
                        >
                            <CheckCircle2 className="h-3 w-3 md:h-4 md:w-4" />
                            <span className="hidden sm:inline">Tutup & Publikasikan</span>
                            <span className="sm:hidden">Tutup</span>
                        </button>
                    </div>

                    {/* Live Tally (guru can see) */}
                    {session.positions.map(pos => (
                        <div key={pos.id} className="rounded-lg md:rounded-xl border border-border/50 bg-surface/60 backdrop-blur-sm p-4 md:p-5">
                            {!isQuickPoll && (
                                <h4 className="font-semibold text-xs md:text-base mb-2 md:mb-3 flex items-center gap-1.5 md:gap-2">
                                    <Crown className="h-3.5 w-3.5 md:h-4 md:w-4 text-emerald-400" />
                                    {pos.name}
                                </h4>
                            )}
                            <div className="space-y-1.5 md:space-y-2 mt-2">
                                {(finalVoteTally[pos.id] || []).map((c: any) => {
                                    const label = c.label || c.student?.full_name;
                                    const initial = label ? label.charAt(0).toUpperCase() : '?';
                                    return (
                                        <div key={c.id} className="flex items-center gap-2 md:gap-3">
                                            <div className="w-6 h-6 md:w-8 md:h-8 rounded-full bg-primary-500/20 flex items-center justify-center text-[10px] md:text-xs font-bold text-primary-300">
                                                {initial}
                                            </div>
                                            <span className="flex-1 text-[11px] md:text-sm font-medium truncate capitalize">{label}</span>
                                            <div className="flex items-center gap-1.5 md:gap-2">
                                                <div className="w-20 md:w-32 h-1.5 md:h-2 rounded-full bg-surface-hover overflow-hidden">
                                                    <div
                                                        className="h-full rounded-full bg-emerald-500 transition-all"
                                                        style={{ width: `${Math.min(100, (c.final_votes_count / totalStudents) * 100)}%` }}
                                                    />
                                                </div>
                                                <span className="text-[10px] md:text-xs font-semibold text-emerald-400 min-w-[24px] md:min-w-8 text-right">
                                                    {c.final_votes_count}
                                                </span>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {session.current_phase === 'completed' && (
                <div className="text-center py-8">
                    <CheckCircle2 className="h-16 w-16 text-emerald-400 mx-auto mb-4" />
                    <h3 className="text-xl font-semibold mb-2">Voting Selesai!</h3>
                    <p className="text-text-muted mb-6">Hasil telah dipublikasikan kepada siswa.</p>
                    <Link
                        href={`/voting/${session.id}/results`}
                        className="inline-flex items-center gap-2 rounded-xl bg-primary-500 px-6 py-3 text-sm font-semibold text-white shadow-lg shadow-primary-500/25"
                    >
                        <Eye className="h-4 w-4" />
                        Lihat Hasil Lengkap
                    </Link>
                </div>
            )}

            {deleteConfig && (
                <ConfirmDeleteModal
                    isOpen={deleteConfig.isOpen}
                    onClose={() => setDeleteConfig(null)}
                    onConfirm={() => router.delete(deleteConfig.url)}
                    title={deleteConfig.title}
                    message={deleteConfig.message}
                    confirmKeyword={deleteConfig.keyword}
                />
            )}
        </AuthenticatedLayout>
    );
}
