"use client";

import { use, useState, useTransition, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { 
  ChevronLeft, 
  ChevronRight, 
  Globe,
  Flag,
  Award,
  Download,
  Mail,
  User,
  AlertCircle,
  FileJson,
  Lock,
  KeyRound,
  CheckCircle2
} from "lucide-react";
import { Button } from "@workspace/ui/components/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@workspace/ui/components/card";
import { Input } from "@workspace/ui/components/input";
import { Label } from "@workspace/ui/components/label";

import idMessages from "../../../../messages/id.json";
import enMessages from "../../../../messages/en.json";
import jaMessages from "../../../../messages/ja.json";
import koMessages from "../../../../messages/ko.json";

import dynamicQuestionsPool from "./questionsData.json";

const dictionaries: Record<string, any> = {
  id: idMessages,
  en: enMessages,
  ja: jaMessages,
  ko: koMessages,
};

export default function JlptN5QuizPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = use(params);
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const [isMounted, setIsMounted] = useState(false);
  useEffect(() => {
    setIsMounted(true);
  }, []);

  const currentLocale = dictionaries[locale] ? locale : "id";

  const [screen, setScreen] = useState<'home' | 'quiz' | 'result'>('home');
  const [userName, setUserName] = useState('');
  const [userEmail, setUserEmail] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [studentRecord, setStudentRecord] = useState<any>(null);

  // State untuk Modal Password Download data-student.json
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [passwordInput, setPasswordInput] = useState("");
  const [passwordError, setPasswordError] = useState("");

  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [userAnswers, setUserAnswers] = useState<Record<number, number>>({});
  const [flaggedQuestions, setFlaggedQuestions] = useState<Record<number, boolean>>({});
  const [expiredQuestions, setExpiredQuestions] = useState<Record<number, boolean>>({});
  const [score, setScore] = useState(0);
  const [examDate, setExamDate] = useState('');

  const activeQuestions = dynamicQuestionsPool["N5"] || [];
  const currentQ = activeQuestions[currentQuestionIndex];
  const questionDuration = currentQ?.duration || 20;
  const [timeLeft, setTimeLeft] = useState(questionDuration);

  const certificateRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (screen !== 'quiz' || !currentQ) return;

    if (expiredQuestions[currentQuestionIndex]) {
      setTimeLeft(0);
      return;
    }

    setTimeLeft(currentQ.duration || 20);
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev > 1) return prev - 1;
        clearInterval(timer);
        setExpiredQuestions(exp => ({ ...exp, [currentQuestionIndex]: true }));
        
        if (currentQuestionIndex + 1 < activeQuestions.length) {
          setCurrentQuestionIndex(idx => idx + 1);
        }
        return 0;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [currentQuestionIndex, screen]);

  const handleLocaleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newLocale = e.target.value;
    startTransition(() => {
      router.push(`/${newLocale}/jlpt-n5`);
    });
  };

  const handleStartQuiz = () => {
    if (!userName.trim() || !userEmail.trim()) {
      setErrorMessage('Nama lengkap dan Email wajib diisi! Jika kosong, Anda tidak bisa masuk ujian.');
      return;
    }
    
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(userEmail)) {
      setErrorMessage('Format alamat email tidak valid!');
      return;
    }

    setErrorMessage('');
    setScreen('quiz');
    setCurrentQuestionIndex(0);
    setUserAnswers({});
    setFlaggedQuestions({});
    setExpiredQuestions({});
  };

  const handleSelectAnswer = (optIdx: number) => {
    if (expiredQuestions[currentQuestionIndex]) return;
    setUserAnswers(prev => ({ ...prev, [currentQuestionIndex]: optIdx }));
  };

  const toggleFlag = () => {
    if (expiredQuestions[currentQuestionIndex]) return;
    setFlaggedQuestions(prev => ({ ...prev, [currentQuestionIndex]: !prev[currentQuestionIndex] }));
  };

  const handleGoToQuestion = (idx: number) => {
    if (expiredQuestions[idx]) return;
    setCurrentQuestionIndex(idx);
  };

  const handleNextOrSubmit = () => {
    if (currentQuestionIndex + 1 < activeQuestions.length) {
      setCurrentQuestionIndex(prev => prev + 1);
    } else {
      handleSubmitQuiz();
    }
  };

  const handlePrevQuestion = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  const handleSubmitQuiz = () => {
    let correctCount = 0;
    activeQuestions.forEach((q: any, idx: number) => {
      if (userAnswers[idx] === q.c) {
        correctCount++;
      }
    });
    const calculatedScore = Math.round((correctCount / activeQuestions.length) * 100);
    setScore(calculatedScore);
    const formattedDate = new Date().toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' });
    setExamDate(formattedDate);

    // Menyimpan data record peserta
    const record = {
      name: userName,
      email: userEmail,
      exam_level: "JLPT N5",
      score: calculatedScore,
      status: calculatedScore >= 60 ? "LULUS (PASSED)" : "BELUM LULUS",
      exam_date: formattedDate,
      submitted_at: new Date().toISOString()
    };

    setStudentRecord(record);
    setScreen('result');
  };

  // Trigger klik download (memicu pop-up password)
  const handleTriggerDownloadJson = () => {
    setPasswordInput("");
    setPasswordError("");
    setShowPasswordModal(true);
  };

  // Verifikasi password dan eksekusi download file data-student.json
  const handleVerifyAndDownload = (e: React.FormEvent) => {
    e.preventDefault();

    if (passwordInput !== "AslanAsilon") {
      setPasswordError("Password salah! Hanya ***** yang diizinkan mengunduh file ini.");
      return;
    }

    setPasswordError("");
    setShowPasswordModal(false);

    if (!studentRecord) return;

    // Perbaikan: Gunakan Blob agar kompatibel di Mozilla Firefox dan semua browser modern
    const jsonString = JSON.stringify(studentRecord, null, 2);
    const blob = new Blob([jsonString], { type: "application/json;charset=utf-8" });
    const url = URL.createObjectURL(blob);

    const downloadAnchor = document.createElement('a');
    downloadAnchor.href = url;
    downloadAnchor.download = "data-student.json";
    
    // Firefox memerlukan elemen anchor agar terpasang di dalam DOM body saat diklik
    document.body.appendChild(downloadAnchor);
    downloadAnchor.click();

    // Cleanup memori setelah download diproses
    setTimeout(() => {
      document.body.removeChild(downloadAnchor);
      URL.revokeObjectURL(url);
    }, 100);
  };

  const handleDownloadCertificate = () => {
    window.print();
  };

  const handleResetQuiz = () => {
    setScreen('home');
    setUserName('');
    setUserEmail('');
    setUserAnswers({});
    setFlaggedQuestions({});
    setExpiredQuestions({});
    setCurrentQuestionIndex(0);
    setScore(0);
    setStudentRecord(null);
  };

  if (!isMounted) return null;

  return (
    <div className="w-full max-w-7xl mx-auto p-0 overflow-x-hidden select-none font-sans bg-white min-h-screen text-gray-900 relative">
      
      {/* 1. HOME SCREEN & REGISTRASI DATA */}
      {screen === 'home' && (
        <div className="p-4 bg-white min-h-screen flex items-center justify-center">
          <Card className="border-2 border-gray-200 shadow-2xl rounded-none bg-white max-w-xl w-full text-gray-900">
            <CardHeader className="text-center pb-2">
              <div className="flex justify-center mb-2">
                <div className="p-3 bg-gray-50 rounded-full border border-gray-200 shadow-sm flex items-center justify-center">
                  <Image 
                    src="/images/eduverse-dark.png" 
                    alt="Eduverse Logo" 
                    width={40} 
                    height={40} 
                    className="object-contain" 
                    onError={(e) => { e.currentTarget.style.display = 'none'; }}
                  />
                </div>
              </div>
              <CardTitle className="text-xl font-bold text-gray-900">Eduverse CBT - JLPT N5 Simulator</CardTitle>
              <CardDescription className="text-xs text-gray-500 mt-1">
                Registrasi Data Peserta untuk Memulai Ujian & Klaim Sertifikat
              </CardDescription>
            </CardHeader>

            <CardContent className="space-y-4 pt-4">
              {errorMessage && (
                <div className="bg-red-50 border-l-4 border-red-500 text-red-700 p-3 text-xs flex items-center gap-2">
                  <AlertCircle className="w-4 h-4 flex-shrink-0" />
                  <span>{errorMessage}</span>
                </div>
              )}

              <div className="bg-amber-50 border border-amber-200 p-3 text-xs text-amber-900 flex gap-2 items-start">
                <AlertCircle className="w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5" />
                <p className="leading-relaxed">
                  <strong>Perhatian:</strong> Pengisian <strong>Nama Lengkap</strong> dan <strong>Email</strong> wajib diisi. Jika tidak memasukkannya, sistem menolak akses masuk ujian dan sertifikat kelulusan resmi tidak dapat diterbitkan.
                </p>
              </div>

              <div className="space-y-3">
                <div>
                  <Label className="text-xs font-bold mb-1 flex items-center gap-1.5">
                    <User className="w-3.5 h-3.5 text-gray-600" /> Nama Lengkap Peserta
                  </Label>
                  <Input 
                    value={userName}
                    onChange={(e) => setUserName(e.target.value)}
                    placeholder="Contoh: Aslan Asilon"
                    className="border-gray-300 focus-visible:ring-gray-900 rounded-none text-sm"
                  />
                </div>

                <div>
                  <Label className="text-xs font-bold mb-1 flex items-center gap-1.5">
                    <Mail className="w-3.5 h-3.5 text-gray-600" /> Alamat Email Aktif
                  </Label>
                  <Input 
                    type="email"
                    value={userEmail}
                    onChange={(e) => setUserEmail(e.target.value)}
                    placeholder="Contoh: aslan@eduverse.com"
                    className="border-gray-300 focus-visible:ring-gray-900 rounded-none text-sm"
                  />
                </div>
              </div>

              <div className="pt-2">
                <Button 
                  onClick={handleStartQuiz}
                  className="bg-gray-900 hover:bg-black text-white border-none w-full font-bold uppercase tracking-widest rounded-none shadow-md h-11 cursor-pointer"
                >
                  試験開始 (Mulai Ujian N5)
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 2. QUIZ SCREEN */}
      {screen === 'quiz' && currentQ && (
        <div className="w-full bg-white text-gray-900 min-h-[600px] flex flex-col justify-between font-sans border-b-2 border-black">
          
          <div className="bg-black text-white px-4 py-2 flex justify-between items-center text-sm">
            <div className="leading-tight">
              <div className="text-xs sm:text-sm font-semibold">Question: {currentQuestionIndex + 1} / {activeQuestions.length}</div>
              <div className="text-xs sm:text-sm font-bold">Section: {currentQ.section_name}</div>
            </div>
            
            <div className="flex items-center space-x-2">
              <div className="bg-gray-800 text-white px-2 py-1 rounded font-bold text-xs border border-gray-600">EV</div>
              <span className="font-bold tracking-wider text-xs sm:text-sm">EDUVERSE CBT ENGINE</span>
            </div>

            <div>
              <button 
                onClick={handleSubmitQuiz} 
                className="bg-amber-400 hover:bg-amber-500 text-black font-bold px-6 py-1 rounded-sm text-xs sm:text-sm transition-colors border-none cursor-pointer"
              >
                finish
              </button>
            </div>
          </div>

          <div className="bg-gray-900 text-white px-4 py-1 text-xs sm:text-sm font-bold flex justify-between items-center">
            <span>Test: JLPT (Bahasa Jepang) (N5) - Candidate: {userName} ({userEmail})</span>
            <div className="flex items-center gap-1">
              <Globe className="w-3.5 h-3.5 text-white" />
              <select
                value={currentLocale}
                onChange={handleLocaleChange}
                disabled={isPending}
                className="text-xs bg-transparent text-white font-bold cursor-pointer focus:outline-none"
              >
                <option value="id" className="text-black">ID</option>
                <option value="en" className="text-black">EN</option>
                <option value="ja" className="text-black">JA</option>
                <option value="ko" className="text-black">KO</option>
              </select>
            </div>
          </div>

          <div className="p-4 sm:p-6 flex-1 flex flex-col justify-between bg-white">
            
            {currentQ.instruction && (
              <div className="bg-gray-50 border-l-4 border-gray-900 text-gray-800 px-4 py-2 text-xs sm:text-base mb-4 font-normal">
                {currentQ.instruction}
                {expiredQuestions[currentQuestionIndex] && (
                  <span className="ml-3 text-red-600 font-bold text-xs">[ Waktu Habis: Soal Terkunci ]</span>
                )}
              </div>
            )}

            <div className="grid grid-cols-12 gap-4 items-start flex-1 my-2">
              
              <div className="col-span-2 sm:col-span-1 space-y-1.5 pr-1">
                {activeQuestions.map((_: any, idx: number) => {
                  const isAnswered = userAnswers[idx] !== undefined;
                  const isCurrent = currentQuestionIndex === idx;
                  const isExpired = expiredQuestions[idx];
                  const isFlagged = flaggedQuestions[idx];

                  let btnStyle = "bg-gray-200 text-gray-800";
                  if (isCurrent) btnStyle = "bg-gray-900 text-white font-bold ring-2 ring-black";
                  else if (isAnswered) btnStyle = "bg-gray-700 text-white";
                  if (isExpired) btnStyle = "bg-gray-300 text-gray-500 cursor-not-allowed opacity-60";

                  return (
                    <button 
                      key={idx}
                      onClick={() => handleGoToQuestion(idx)}
                      disabled={isExpired}
                      className={`w-full text-center py-1 text-xs sm:text-sm font-bold border border-gray-400 transition-all relative cursor-pointer ${btnStyle}`}
                      title={isExpired ? "Durasi habis" : `Soal ${idx + 1}`}
                    >
                      {idx + 1}
                      {isFlagged && !isExpired && (
                        <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-amber-500 rounded-full border border-black" />
                      )}
                    </button>
                  );
                })}
              </div>

              <div className="col-span-10 sm:col-span-11 grid grid-cols-1 lg:grid-cols-12 gap-6 items-center pl-2">
                
                <div className="lg:col-span-5 flex flex-col justify-center space-y-3">
                  {currentQ.is_image === true && currentQ.image_banner && (
                    <div className="w-full bg-gray-50 border-2 border-dashed border-gray-300 p-4 rounded flex items-center justify-center relative min-h-[160px] shadow-sm">
                      <Image 
                        src={currentQ.image_banner}
                        alt="Ilustrasi Banner Soal"
                        width={150}
                        height={110}
                        className="object-contain max-h-[140px]"
                        priority
                      />
                    </div>
                  )}

                  {currentQ.image_icon && (
                    <div className="w-full bg-amber-50 border border-amber-200 p-2 rounded flex items-center gap-3 shadow-xs">
                      <div className="relative w-10 h-10 flex-shrink-0 bg-white border border-amber-300 p-1 rounded flex items-center justify-center">
                        <Image 
                          src={currentQ.image_icon}
                          alt="icon"
                          width={32}
                          height={32}
                          className="object-contain"
                        />
                      </div>
                      <span className="text-[11px] font-medium text-amber-900 leading-tight">
                        (Soal #{currentQuestionIndex + 1})
                      </span>
                    </div>
                  )}

                  {currentQ.passage && (
                    <div className="p-3 bg-gray-50 border border-gray-300 rounded text-xs sm:text-sm w-full font-semibold">
                      {currentQ.passage}
                    </div>
                  )}
                  <div className="text-base sm:text-lg font-bold text-gray-900">
                    {currentQ.q}
                  </div>
                </div>

                <div className="lg:col-span-4 space-y-3 w-full">
                  {currentQ.a.map((optText: string, optIdx: number) => {
                    const selector = userAnswers[currentQuestionIndex] === optIdx;
                    const isDisabled = expiredQuestions[currentQuestionIndex];

                    return (
                      <button
                        key={optIdx}
                        type="button"
                        disabled={isDisabled}
                        onClick={() => handleSelectAnswer(optIdx)}
                        className={`w-full text-left px-3 py-2.5 border-2 border-black transition-all flex items-center gap-2 bg-white text-gray-900 text-base sm:text-lg font-medium rounded-none ${
                          isDisabled ? 'cursor-not-allowed opacity-70 bg-gray-50' : 'cursor-pointer hover:bg-gray-50'
                        } ${selector ? 'bg-gray-100 font-bold border-gray-900 ring-2 ring-gray-900' : ''}`}
                      >
                        <span className="font-bold text-lg min-w-[28px]">{String.fromCharCode(65 + optIdx)}.</span>
                        <span className="tracking-wide">{optText}</span>
                      </button>
                    );
                  })}
                </div>

                <div className="lg:col-span-3 flex flex-col items-center justify-center text-center my-4 lg:my-0 space-y-3">
                  <div>
                    <span className="text-xs sm:text-sm font-semibold text-gray-900 mb-1 block">
                      Answer in <span className="font-bold text-red-600">{timeLeft}</span> Seconds!
                    </span>
                    
                    <div className="relative w-16 h-16 sm:w-20 sm:h-20 flex items-center justify-center mx-auto">
                      <svg className="w-full h-full -rotate-90 transform" viewBox="0 0 36 36">
                        <path className="text-gray-200" strokeWidth="3.5" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                        <path 
                          className="text-gray-900 transition-all duration-1000 ease-linear" 
                          strokeWidth="18" 
                          strokeDasharray={`${(timeLeft / questionDuration) * 100}, 100`} 
                          stroke="currentColor" 
                          fill="none" 
                          d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" 
                        />
                      </svg>
                    </div>
                  </div>

                  <Button
                    onClick={toggleFlag}
                    disabled={expiredQuestions[currentQuestionIndex]}
                    variant={flaggedQuestions[currentQuestionIndex] ? "default" : "outline"}
                    className={`text-xs gap-1.5 h-8 w-full rounded-none ${
                      flaggedQuestions[currentQuestionIndex] 
                        ? 'bg-amber-500 hover:bg-amber-600 text-black font-bold' 
                        : 'border-black text-gray-900 hover:bg-gray-100'
                    }`}
                  >
                    <Flag className="w-3.5 h-3.5" />
                    {flaggedQuestions[currentQuestionIndex] ? "Ragu-ragu (Ditandai)" : "Tandai Ragu-ragu"}
                  </Button>
                </div>

              </div>
            </div>

            <div className="mt-8 pt-2 flex justify-between items-end bg-white border-t border-gray-100">
              <div className="flex flex-col text-[10px] sm:text-xs leading-tight font-sans text-gray-500">
                <span className="font-bold text-gray-700">JAPAN FOUNDATION / EDUVERSE</span>
                <span className="font-black text-gray-900 text-xs">CBT Simulator Engine</span>
              </div>

              <div className="flex items-center gap-2">
                <Button 
                  onClick={handlePrevQuestion}
                  disabled={currentQuestionIndex === 0}
                  className="bg-gray-900 hover:bg-black disabled:opacity-40 text-white font-bold px-4 py-1 text-xs sm:text-sm rounded-none border-none shadow-none cursor-pointer"
                >
                  <ChevronLeft className="w-4 h-4 mr-1" /> Back
                </Button>

                <Button 
                  onClick={handleNextOrSubmit}
                  className="bg-gray-900 hover:bg-black text-white font-bold px-4 py-1 text-xs sm:text-sm rounded-none border-none shadow-none cursor-pointer"
                >
                  {currentQuestionIndex + 1 === activeQuestions.length ? 'Finish' : 'Next'} <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              </div>
            </div>

          </div>
        </div>
      )}

      {/* 3. RESULT SCREEN & SERTIFIKAT KELULUSAN */}
      {screen === 'result' && (
        <div className="p-4 bg-gray-100 min-h-screen flex flex-col items-center justify-center space-y-6">
          
          {/* Panel Tombol Download Terproteksi Password Admin */}
          <div className="w-full max-w-3xl bg-amber-50 border border-amber-300 text-amber-900 px-4 py-3 text-xs flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Lock className="w-4 h-4 text-amber-700 flex-shrink-0" />
              <span>Area Khusus Admin/Developer: Unduh file <strong>data-student.json</strong></span>
            </div>
            <Button 
              onClick={handleTriggerDownloadJson}
              className="bg-gray-900 hover:bg-black text-white text-xs h-7 px-3 rounded-none gap-1.5 cursor-pointer font-bold"
            >
              <FileJson className="w-3.5 h-3.5" /> Download data-student.json
            </Button>
          </div>

          <div 
            ref={certificateRef}
            className="w-full max-w-3xl bg-white border-8 border-gray-900 p-8 sm:p-12 text-center shadow-2xl relative font-serif text-gray-900"
          >
            <div className="flex justify-between items-center border-b-2 border-gray-200 pb-4 mb-6">
              <div className="flex items-center gap-2">
                <div className="bg-gray-900 text-white p-2 font-bold text-sm">EV</div>
                <span className="font-sans font-bold text-sm tracking-widest text-gray-700">EDUVERSE CERTIFICATION</span>
              </div>
              <span className="font-sans text-xs text-gray-500">Certificate No: EV-CERT-{Math.floor(100000 + Math.random() * 900000)}</span>
            </div>

            <div className="space-y-4 my-6">
              <h3 className="font-sans text-xs uppercase tracking-widest text-gray-700 font-bold">Sertifikat Kelulusan Resmi</h3>
              <h1 className="text-3xl sm:text-4xl font-bold tracking-wide text-gray-900">Certificate of Completion</h1>
              <p className="font-sans text-xs sm:text-sm text-gray-500">Sertifikat ini diberikan dengan bangga kepada:</p>
              
              <div className="text-2xl sm:text-3xl font-bold text-gray-900 border-b-2 border-dashed border-gray-400 inline-block px-8 py-1 my-2">
                {userName}
              </div>

              <div className="font-sans text-xs text-gray-500">
                Email: <span className="font-bold text-gray-700">{userEmail}</span>
              </div>

              <p className="font-sans text-xs sm:text-sm text-gray-600 max-w-lg mx-auto leading-relaxed">
                Atas keberhasilannya menyelesaikan simulasi ujian <strong className="text-black">JLPT (Bahasa Jepang)</strong> untuk level <strong className="text-black">N5</strong> dengan pencapaian nilai akhir:
              </p>

              <div className="inline-block bg-gray-50 border border-gray-300 px-6 py-3 my-2">
                <span className="font-sans text-[10px] uppercase font-bold text-gray-700 tracking-wider block">Total Skor Ujian</span>
                <div className="font-sans text-4xl font-black text-gray-900">{score} <span className="text-lg font-normal text-gray-600">/ 100</span></div>
              </div>
            </div>

            <div className="flex justify-between items-end pt-12 mt-8 border-t-2 border-gray-200 text-xs font-sans">
              <div className="text-left text-gray-500">
                <p>Tanggal Ujian: <strong className="text-black">{examDate}</strong></p>
                <p>Status: <strong className={score >= 60 ? "text-green-600" : "text-amber-600"}>{score >= 60 ? "LULUS (PASSED)" : "BELUM LULUS"}</strong></p>
              </div>
              <div className="text-center">
                <div className="font-serif italic text-lg font-bold text-gray-800 mb-1">Eduverse Director</div>
                <div className="border-t border-black pt-1 px-4 font-bold text-gray-700">Official Board</div>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-4">
            <Button 
              onClick={handleDownloadCertificate}
              className="bg-blue-600 hover:bg-blue-700 text-white font-bold px-6 py-2 rounded-none gap-2 shadow-lg cursor-pointer"
            >
              <Download className="w-4 h-4" /> Cetak / Print Sertifikat Saya
            </Button>

            <Button 
              onClick={handleResetQuiz}
              className="bg-gray-900 hover:bg-black text-white font-bold px-6 py-2 rounded-none gap-2 shadow-lg cursor-pointer"
            >
              <Award className="w-4 h-4" /> Ulangi Ujian / Menu Utama
            </Button>
          </div>

        </div>
      )}

      {/* MODAL PASSWORD DOWNLOAD data-student.json */}
      {showPasswordModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-xs flex items-center justify-center z-50 p-4">
          <Card className="w-full max-w-md bg-white border-2 border-black rounded-none shadow-2xl">
            <CardHeader className="border-b border-gray-100 pb-3">
              <CardTitle className="text-base font-bold flex items-center gap-2 text-gray-900">
                <KeyRound className="w-4 h-4 text-amber-600" /> Verifikasi Password Admin
              </CardTitle>
              <CardDescription className="text-xs text-gray-500">
                Masukkan password admin/developer untuk mengunduh <code className="bg-gray-100 px-1 py-0.5 text-black font-bold">data-student.json</code>.
              </CardDescription>
            </CardHeader>

            <form onSubmit={handleVerifyAndDownload}>
              <CardContent className="space-y-4 pt-4">
                {passwordError && (
                  <div className="bg-red-50 border-l-4 border-red-500 text-red-700 p-2.5 text-xs flex items-center gap-2">
                    <AlertCircle className="w-4 h-4 flex-shrink-0" />
                    <span>{passwordError}</span>
                  </div>
                )}

                <div>
                  <Label className="text-xs font-bold mb-1.5 block">Password (*****************)</Label>
                  <Input 
                    type="password"
                    autoFocus
                    value={passwordInput}
                    onChange={(e) => setPasswordInput(e.target.value)}
                    placeholder="Masukkan password..."
                    className="border-gray-300 focus-visible:ring-gray-900 rounded-none text-sm"
                  />
                </div>

                <div className="flex items-center justify-end gap-2 pt-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setShowPasswordModal(false)}
                    className="border-gray-300 text-xs rounded-none h-9 cursor-pointer"
                  >
                    Batal
                  </Button>

                  <Button
                    type="submit"
                    className="bg-gray-900 hover:bg-black text-white text-xs h-9 px-4 rounded-none font-bold cursor-pointer"
                  >
                    Konfirmasi & Download
                  </Button>
                </div>
              </CardContent>
            </form>
          </Card>
        </div>
      )}

    </div>
  );
}