import React, { useState, useEffect } from 'react';
import { generateQuizAjax } from '../lib/api';
import { verifyCloudModelAjax } from '../lib/cloud-api';

export default function Quiz({ content, onClose, onVerificationPanelChange }) {
    const [isLoading, setIsLoading] = useState(false);
    const [quizData, setQuizData] = useState([]);
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [selectedOption, setSelectedOption] = useState(null);
    const [showAnswer, setShowAnswer] = useState(false);
    const [correctCount, setCorrectCount] = useState(0);
    const [isLocked, setIsLocked] = useState(false);
    const [allAnswersCorrect, setAllAnswersCorrect] = useState(true);

    const [modelReport, setModelReport] = useState(null);
    const [verifyingModel, setVerifyingModel] = useState(false);
    const [openInfoIndex, setOpenInfoIndex] = useState(null);
    const [openSections, setOpenSections] = useState({});

    const [quizMetadata, setQuizMetadata] = useState({
        verifiedModel: '',
    });

    useEffect(() => {
        loadQuiz();
    }, [content]);

    useEffect(() => {
        if (onVerificationPanelChange && quizData.length > 0) {
            onVerificationPanelChange(renderVerificationPanel());
        }
    }, [quizData, modelReport, verifyingModel, openInfoIndex, openSections, quizMetadata]);

    const loadQuiz = async () => {
        if (!isLoading && content) {
            setIsLoading(true);
            try {
                const response = await generateQuizAjax(content);
                const parsed = JSON.parse(response?.data?.result?.choices[0]?.message?.content);
                if (parsed.quiz) {
                    setQuizData(parsed.quiz);
                    setQuizMetadata({
                        verifiedModel: response?.data?.meta?.model || '',
                    });
                }
            } catch (error) {
                console.error(error);
                setQuizData([]);
            } finally {
                setIsLoading(false);
            }
        }
    };

    const handleVerifyModel = async (modelForVerification) => {
        if (!modelForVerification) return;

        setVerifyingModel(true);
        try {
            const res = await verifyCloudModelAjax({model: modelForVerification});
            const report = res.success ? res.data : {error: "Model verification failed"};
            setModelReport(report);
        } catch {
            setModelReport({error: "Error verifying model"});
        } finally {
            setVerifyingModel(false);
        }
    };

    const toggleSection = (key) => {
        setOpenSections(prev => ({
            ...prev,
            [key]: !prev[key]
        }));
    };

    const verifyModelOnOpenSection = () => {
        toggleSection('verifiedModel');
        if (!modelReport) {
            handleVerifyModel(quizMetadata.verifiedModel);
        }
    };

    const question = quizData[currentQuestion];

    const isComplete = showAnswer && selectedOption === question?.correct_answer && (currentQuestion + 1 === quizData.length);

    const handleOptionClick = (optionKey) => {
        if (isLocked) return;

        setIsLocked(true);
        setSelectedOption(optionKey);
        setShowAnswer(true);

        const isCorrect = optionKey === question.correct_answer;
        if (isCorrect) {
            setCorrectCount(prev => prev + 1);
        } else {
            setAllAnswersCorrect(false);
        }
    };

    const handleTryAgain = () => {
        setSelectedOption(null);
        setShowAnswer(false);
        setIsLocked(false);
    };

    const handleNextQuestion = () => {
        setSelectedOption(null);
        setShowAnswer(false);
        setIsLocked(false);

        if (currentQuestion + 1 >= quizData.length) {
            setCurrentQuestion(quizData.length); // Move past last question to trigger results
        } else {
            setCurrentQuestion(prev => prev + 1);
        }
    };

    const handleRetake = () => {
        setCurrentQuestion(0);
        setSelectedOption(null);
        setShowAnswer(false);
        setCorrectCount(0);
        setIsLocked(false);
        setAllAnswersCorrect(true);
        setModelReport(null);
        setOpenInfoIndex(null);
        setOpenSections({});
    };

    const getPluginImageUrl = (filename) => {
        return `${window?.lnc_ai_quiz_generator?.imageUrl}/${filename}`;
    };

    const renderVerificationPanel = () => {
        return (
            <div style={{ position: 'relative' }}>
                <div
                    className="info-container"
                    onClick={() => setOpenInfoIndex(openInfoIndex ? null : 'quiz')}
                    style={{display: 'inline-flex', alignItems: 'center', gap: '6px', cursor: 'pointer'}}
                >
                    <svg
                        width="20"
                        height="20"
                        viewBox="0 0 20 20"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                        style={{ color: '#10a37f' }}
                    >
                        <path d="M9.89795 0.839478C9.99912 0.82703 10.1022 0.834189 10.2017 0.859009L16.8687 2.52502C17.0077 2.55981 17.1308 2.62904 17.231 2.72131C17.3312 2.81364 17.4083 2.92945 17.4536 3.0592C17.4687 3.1024 17.48 3.14715 17.4878 3.19299C17.4956 3.23887 17.5005 3.28583 17.5005 3.33362V10.0006C17.5005 10.0904 17.4983 10.1796 17.4946 10.2682C17.4654 10.977 17.3213 11.6494 17.0952 12.2819C17.0669 12.361 17.0371 12.4394 17.0063 12.5172C16.9449 12.6727 16.8788 12.8258 16.8081 12.9762C16.2416 14.181 15.3951 15.2214 14.5298 16.0699C14.3137 16.2818 14.0967 16.482 13.8823 16.6696C13.4444 17.0527 13.007 17.3937 12.5981 17.6901C12.1896 17.9862 11.8093 18.2377 11.4839 18.441C11.1575 18.645 10.8835 18.8027 10.6899 18.9098C10.5933 18.9633 10.5163 19.0045 10.4624 19.0328C10.4356 19.0469 10.414 19.0583 10.3989 19.066L10.3765 19.0778L10.3735 19.0787H10.3726C10.2845 19.1228 10.1906 19.1508 10.0952 19.1617C10.032 19.169 9.96803 19.169 9.90479 19.1617C9.80938 19.1508 9.71552 19.1228 9.62744 19.0787H9.62646L9.60107 19.066C9.58605 19.0583 9.56442 19.0469 9.5376 19.0328C9.48369 19.0045 9.40669 18.9633 9.31006 18.9098C9.11654 18.8027 8.84253 18.645 8.51611 18.441C8.19072 18.2377 7.81037 17.9862 7.40186 17.6901C6.99313 17.3938 6.55641 17.0525 6.11865 16.6696C5.90423 16.4819 5.68635 16.2819 5.47021 16.0699C4.60489 15.2214 3.75842 14.181 3.19189 12.9762C3.12118 12.8258 3.05514 12.6727 2.99365 12.5172C2.96286 12.4394 2.93307 12.361 2.90479 12.2819C2.67866 11.6494 2.53464 10.977 2.50537 10.2682C2.50171 10.1796 2.5005 10.0904 2.50049 10.0006V3.33362C2.50049 3.28583 2.50436 3.23886 2.51221 3.19299C2.52003 3.14715 2.53131 3.10239 2.54639 3.0592C2.59174 2.92945 2.66882 2.81364 2.76904 2.72131C2.83574 2.65984 2.9124 2.60837 2.99756 2.57092C3.04022 2.55216 3.08494 2.53664 3.13135 2.52502L9.79834 0.859009L9.89795 0.839478ZM4.1665 3.98401V9.99963C4.1665 12.1275 5.59857 13.9999 7.21533 15.4147C8.00604 16.1065 8.80122 16.6538 9.3999 17.028C9.63544 17.1752 9.84098 17.293 10.0005 17.3834C10.1599 17.293 10.3648 17.175 10.6001 17.028C11.1988 16.6538 11.9939 16.1065 12.7847 15.4147C14.4014 13.9999 15.8335 12.1275 15.8335 9.99963V3.98401L10.0005 2.526L4.1665 3.98401ZM12.062 7.84534C12.3874 7.51991 12.9153 7.51994 13.2407 7.84534C13.5661 8.17078 13.5661 8.69863 13.2407 9.02405L9.70557 12.5592C9.38014 12.8845 8.85227 12.8846 8.52686 12.5592L6.7583 10.7916C6.43327 10.4663 6.4333 9.93828 6.7583 9.61292C7.08374 9.28748 7.61255 9.28748 7.93799 9.61292L9.1167 10.7916L12.062 7.84534Z"
                              fill="currentColor" />
                    </svg>
                </div>

                {openInfoIndex === 'quiz' && (
                    <div
                        className="info-tooltip visible"
                        style={{
                            position: 'absolute',
                            top: '100%',
                            left: '0',
                            marginTop: '8px',
                            zIndex: 1000,
                            minWidth: '400px',
                            maxWidth: '500px',
                            backgroundColor: 'white',
                            border: '1px solid #e5e7eb',
                            borderRadius: '8px',
                            boxShadow: '0 10px 25px rgba(0,0,0,0.1)',
                            padding: '16px'
                        }}
                    >
                        <div style={{marginBottom: '16px'}}>
                            <h4 style={{
                                color: '#10a37f',
                                fontSize: '14px',
                                fontWeight: 600,
                                marginBottom: '12px',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px'
                            }}>
                                <svg
                                    width="20"
                                    height="20"
                                    viewBox="0 0 20 20"
                                    fill="none"
                                    xmlns="http://www.w3.org/2000/svg"
                                >
                                    <path d="M9.89795 0.839478C9.99912 0.82703 10.1022 0.834189 10.2017 0.859009L16.8687 2.52502C17.0077 2.55981 17.1308 2.62904 17.231 2.72131C17.3312 2.81364 17.4083 2.92945 17.4536 3.0592C17.4687 3.1024 17.48 3.14715 17.4878 3.19299C17.4956 3.23887 17.5005 3.28583 17.5005 3.33362V10.0006C17.5005 10.0904 17.4983 10.1796 17.4946 10.2682C17.4654 10.977 17.3213 11.6494 17.0952 12.2819C17.0669 12.361 17.0371 12.4394 17.0063 12.5172C16.9449 12.6727 16.8788 12.8258 16.8081 12.9762C16.2416 14.181 15.3951 15.2214 14.5298 16.0699C14.3137 16.2818 14.0967 16.482 13.8823 16.6696C13.4444 17.0527 13.007 17.3937 12.5981 17.6901C12.1896 17.9862 11.8093 18.2377 11.4839 18.441C11.1575 18.645 10.8835 18.8027 10.6899 18.9098C10.5933 18.9633 10.5163 19.0045 10.4624 19.0328C10.4356 19.0469 10.414 19.0583 10.3989 19.066L10.3765 19.0778L10.3735 19.0787H10.3726C10.2845 19.1228 10.1906 19.1508 10.0952 19.1617C10.032 19.169 9.96803 19.169 9.90479 19.1617C9.80938 19.1508 9.71552 19.1228 9.62744 19.0787H9.62646L9.60107 19.066C9.58605 19.0583 9.56442 19.0469 9.5376 19.0328C9.48369 19.0045 9.40669 18.9633 9.31006 18.9098C9.11654 18.8027 8.84253 18.645 8.51611 18.441C8.19072 18.2377 7.81037 17.9862 7.40186 17.6901C6.99313 17.3938 6.55641 17.0525 6.11865 16.6696C5.90423 16.4819 5.68635 16.2819 5.47021 16.0699C4.60489 15.2214 3.75842 14.181 3.19189 12.9762C3.12118 12.8258 3.05514 12.6727 2.99365 12.5172C2.96286 12.4394 2.93307 12.361 2.90479 12.2819C2.67866 11.6494 2.53464 10.977 2.50537 10.2682C2.50171 10.1796 2.5005 10.0904 2.50049 10.0006V3.33362C2.50049 3.28583 2.50436 3.23886 2.51221 3.19299C2.52003 3.14715 2.53131 3.10239 2.54639 3.0592C2.59174 2.92945 2.66882 2.81364 2.76904 2.72131C2.83574 2.65984 2.9124 2.60837 2.99756 2.57092C3.04022 2.55216 3.08494 2.53664 3.13135 2.52502L9.79834 0.859009L9.89795 0.839478ZM4.1665 3.98401V9.99963C4.1665 12.1275 5.59857 13.9999 7.21533 15.4147C8.00604 16.1065 8.80122 16.6538 9.3999 17.028C9.63544 17.1752 9.84098 17.293 10.0005 17.3834C10.1599 17.293 10.3648 17.175 10.6001 17.028C11.1988 16.6538 11.9939 16.1065 12.7847 15.4147C14.4014 13.9999 15.8335 12.1275 15.8335 9.99963V3.98401L10.0005 2.526L4.1665 3.98401ZM12.062 7.84534C12.3874 7.51991 12.9153 7.51994 13.2407 7.84534C13.5661 8.17078 13.5661 8.69863 13.2407 9.02405L9.70557 12.5592C9.38014 12.8845 8.85227 12.8846 8.52686 12.5592L6.7583 10.7916C6.43327 10.4663 6.4333 9.93828 6.7583 9.61292C7.08374 9.28748 7.61255 9.28748 7.93799 9.61292L9.1167 10.7916L12.062 7.84534Z"
                                          fill="currentColor" />
                                </svg>
                                Quiz is confidential
                            </h4>
                            <p style={{fontSize: '14px', color: '#374151', lineHeight: '1.5', marginBottom: '12px'}}>
                                All models run in TEE (Trusted Execution Environment) — isolated hardware where no one can access your messages.
                            </p>

                            <div style={{marginBottom: '12px'}}>
                                <p style={{fontSize: '13px', color: '#6b7280', marginBottom: '8px'}}>
                                    Hardware attestation:
                                </p>
                                <div style={{display: 'flex', gap: '12px', alignItems: 'center'}}>
                                    <img
                                        src={getPluginImageUrl('nvidia2.svg')}
                                        alt="NVIDIA"
                                        style={{height: '24px'}}
                                    />
                                    <img
                                        src={getPluginImageUrl('intel2.svg')}
                                        alt="Intel"
                                        style={{height: '24px'}}
                                    />
                                </div>
                            </div>

                            <button
                                onClick={verifyModelOnOpenSection}
                                style={{
                                    width: '100%',
                                    padding: '10px 16px',
                                    borderRadius: '6px',
                                    border: '1px solid #d1d5db',
                                    background: '#f9fafb',
                                    color: '#374151',
                                    cursor: 'pointer',
                                    fontSize: '14px',
                                    fontWeight: 500,
                                    marginBottom: '16px'
                                }}
                            >
                                Show Verification Details
                            </button>
                        </div>

                        <div
                            className="accordion-header"
                            onClick={verifyModelOnOpenSection}
                            style={{display: 'none'}}
                        >
                            <strong>Verified Model</strong>
                            <i className={`fas fa-chevron-${openSections['verifiedModel'] ? 'up' : 'down'}`}/>
                        </div>
                        {openSections['verifiedModel'] && (
                            <div className="accordion-content">
                                <div className="bg-white dark:bg-gray-875 rounded-lg border border-gray-200 dark:border-[rgba(255,255,255,0.04)] p-4 mt-3">
                                    <h3 className="text-base text-gray-900 dark:text-white mb-4" style={{fontSize: '16px', fontWeight: 600}}>
                                        Model Verification
                                    </h3>

                                    <div className="mb-4">
                                        <strong>Verified Model:</strong>
                                        <p>{quizMetadata.verifiedModel}</p>
                                    </div>

                                    <div className="mb-4" style={{backgroundColor: "#00000045", padding: "12px"}}>
                                        <strong>Attested by:</strong>
                                        <div style={{display: "flex", alignItems: "center", gap: "8px", marginTop: "8px"}}>
                                            <img
                                                src={getPluginImageUrl('nvidia2.svg')}
                                                alt="NVIDIA"
                                                style={{height: "16px", width: "auto", display: "block"}}/>
                                            <span>And</span>
                                            <img
                                                src={getPluginImageUrl('intel2.svg')}
                                                alt="Intel"
                                                style={{height: "16px", width: "auto", display: "block"}}/>
                                        </div>
                                    </div>

                                    <p className="text-sm text-gray-700 dark:text-gray-300 mb-4">
                                        This automated verification tool lets you independently
                                        confirm that the model is running in the TEE (Trusted
                                        Execution Environment).
                                    </p>

                                    {modelReport && (
                                        <>
                                            {/* GPU Attestation */}
                                            <div
                                                className="accordion-header"
                                                onClick={() => toggleSection('gpuAttestation')}
                                                style={{
                                                    cursor: 'pointer',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'space-between',
                                                    padding: '12px',
                                                    backgroundColor: '#f8f9fa',
                                                    border: '1px solid #dee2e6',
                                                    borderRadius: '4px',
                                                    marginBottom: '8px',
                                                    marginTop: '12px'
                                                }}
                                            >
                                                <strong style={{fontSize: '14px'}}>GPU Attestation</strong>
                                                <i className={`fas fa-chevron-${openSections['gpuAttestation'] ? 'up' : 'down'}`} style={{fontSize: '12px'}}/>
                                            </div>

                                            {openSections['gpuAttestation'] && (
                                                <div className="mt-3 mb-4 p-3 rounded bg-light border">
                                                    <div
                                                        style={{
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            gap: '10px',
                                                            marginBottom: '12px',
                                                            padding: '8px',
                                                            borderRadius: '4px',
                                                            backgroundColor: 'rgba(0,0,0,0.3)'
                                                        }}
                                                    >
                                                        <img
                                                            src={getPluginImageUrl('nvidia2.svg')}
                                                            alt="NVIDIA"
                                                            style={{height: '16x', width: 'auto', display: 'block', flexShrink: 0}}
                                                        />
                                                        <span style={{fontWeight: 600, color: 'white'}}>H100 Confidential Computing</span>
                                                    </div>

                                                    <p className="small text-muted mb-3">
                                                        This verification uses NVIDIA attestation to confirm that
                                                        your model is running on genuine NVIDIA H100 hardware with
                                                        confidential computing enabled. You can verify this
                                                        attestation using NVIDIA's public verification tools.
                                                    </p>
                                                    <ul className="small mb-4 ps-3">
                                                        <li>
                                                            <a href="https://nras.attestation.nvidia.com/"
                                                               target="_blank" rel="noreferrer">
                                                                Verify attestation at NVIDIA NRAS
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a
                                                                href="https://docs.nvidia.com/attestation/index.html#overview"
                                                                target="_blank"
                                                                rel="noreferrer"
                                                            >
                                                                Learn about NVIDIA Attestation
                                                            </a>
                                                        </li>
                                                    </ul>

                                                    {(() => {
                                                        try {
                                                            const nvidiaPayload = JSON.parse(modelReport?.report?.nvidia_payload);
                                                            return (
                                                                <>
                                                                    <div className="mb-3">
                                                                        <label className="form-label fw-semibold small">Nonce:</label>
                                                                        <textarea
                                                                            readOnly
                                                                            className="form-control form-control-sm"
                                                                            style={{
                                                                                fontFamily: 'monospace',
                                                                                minHeight: '120px',
                                                                                width: '100%',
                                                                                resize: 'vertical',
                                                                            }}
                                                                            value={nvidiaPayload.nonce || 'N/A'}
                                                                        />
                                                                    </div>

                                                                    <div className="mb-4">
                                                                        <label className="form-label fw-semibold small">Evidence List:</label>
                                                                        <textarea
                                                                            readOnly
                                                                            className="form-control form-control-sm"
                                                                            style={{
                                                                                fontFamily: 'monospace',
                                                                                minHeight: '200px',
                                                                                width: '100%',
                                                                                resize: 'vertical',
                                                                            }}
                                                                            value={JSON.stringify(nvidiaPayload.evidence_list || [], null, 2)}
                                                                        />
                                                                    </div>

                                                                    <div style={{marginBottom: '16px', marginTop: '10px'}}>
                                                                        <label className="form-label fw-semibold small">Architecture:</label>
                                                                        <input
                                                                            type="text"
                                                                            readOnly
                                                                            className="form-control form-control-sm"
                                                                            style={{
                                                                                fontFamily: 'monospace',
                                                                            }}
                                                                            value={nvidiaPayload.arch || 'N/A'}
                                                                        />
                                                                    </div>
                                                                </>
                                                            );
                                                        } catch (e) {
                                                            return (
                                                                <div className="alert alert-warning small mb-0">
                                                                    Error parsing nvidia_payload: {e.message}
                                                                </div>
                                                            );
                                                        }
                                                    })()}
                                                </div>
                                            )}

                                            {/* TDX Attestation */}
                                            <div
                                                className="accordion-header"
                                                onClick={() => toggleSection('tdxAttestation')}
                                                style={{
                                                    cursor: 'pointer',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'space-between',
                                                    padding: '12px',
                                                    backgroundColor: '#f8f9fa',
                                                    border: '1px solid #dee2e6',
                                                    borderRadius: '4px',
                                                    marginBottom: '8px'
                                                }}
                                            >
                                                <strong style={{fontSize: '14px'}}>TDX Attestation</strong>
                                                <i className={`fas fa-chevron-${openSections['tdxAttestation'] ? 'up' : 'down'}`} style={{fontSize: '12px'}}/>
                                            </div>

                                            {openSections['tdxAttestation'] && (
                                                <div className="mt-3 mb-4 p-3 rounded bg-light border">
                                                    <div
                                                        style={{
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            gap: '10px',
                                                            marginBottom: '12px',
                                                            padding: '8px',
                                                            borderRadius: '4px',
                                                            backgroundColor: 'rgba(0,0,0,0.3)'
                                                        }}
                                                    >
                                                        <img
                                                            src={getPluginImageUrl('intel2.svg')}
                                                            alt="Intel"
                                                            style={{height: '16px', width: 'auto', display: 'block', flexShrink: 0}}
                                                        />
                                                        <span style={{fontWeight: 600, color: 'white'}}>Trust Domain Extensions</span>
                                                    </div>

                                                    <p className="small text-muted mb-3">
                                                        This verification uses Intel TDX attestation to confirm that your
                                                        model is running in a trusted execution environment. You can verify
                                                        this attestation quote using Intel's public verification tools.
                                                    </p>
                                                    <ul className="small mb-4 ps-3">
                                                        <li>
                                                            <a href="https://proof.t16z.com/" target="_blank" rel="noreferrer">
                                                                Verify TDX quote at TEE Explorer
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a
                                                                href="https://www.intel.com/content/www/us/en/developer/tools/trust-domain-extensions/overview.html"
                                                                target="_blank"
                                                                rel="noreferrer"
                                                            >
                                                                Learn about Intel TDX
                                                            </a>
                                                        </li>
                                                    </ul>

                                                    <label className="form-label fw-semibold small">Intel Quote:</label>
                                                    <textarea
                                                        readOnly
                                                        className="form-control form-control-sm"
                                                        style={{
                                                            fontFamily: 'monospace',
                                                            minHeight: '150px',
                                                            width: '100%',
                                                            resize: 'vertical',
                                                        }}
                                                        value={modelReport?.report?.intel_quote || ''}
                                                    />
                                                </div>
                                            )}
                                        </>
                                    )}

                                    <div style={{marginTop: '15px', textAlign: 'center'}}>
                                        <button
                                            onClick={() => handleVerifyModel(quizMetadata.verifiedModel)}
                                            disabled={verifyingModel}
                                            style={{
                                                padding: '8px 16px',
                                                borderRadius: '4px',
                                                border: '1px solid #00c08b',
                                                background: verifyingModel ? '#a0f0d9' : '#00c08b',
                                                color: '#fff',
                                                cursor: verifyingModel ? 'not-allowed' : 'pointer',
                                                fontSize: '13px',
                                                fontWeight: 500,
                                            }}
                                        >
                                            {verifyingModel ? 'Verifying...' : (modelReport ? 'Verify Again' : 'Verify Model')}
                                        </button>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </div>
        );
    };

    if (isLoading) {
        return (
            <div className="lncqp-loading">
                <div className="lncqp-spinner" aria-hidden="true"></div>
                <div>Generating quiz…</div>
            </div>
        );
    }

    if (!question && quizData.length === 0) {
        return (
            <div className="lncqp-card">
                <div className="lncqp-msg"><strong>Couldn't generate a quiz.</strong></div>
                <div className="lncqp-muted">Please try again or check your content.</div>
                <div className="lncqp-actions">
                    <button type="button" className="lncqp-btn" onClick={onClose}>Close</button>
                </div>
            </div>
        );
    }

    if (!question && quizData.length > 0) {
        return (
            <div className="lncqp-card">
                <div className="lncqp-done-title">Done 🎉</div>
                <div className="lncqp-done-sub">
                    You got <strong>{correctCount}</strong> / <strong>{quizData.length}</strong> correct.
                </div>

                <div className="lncqp-actions" style={{marginTop: '20px'}}>
                    {allAnswersCorrect ? (
                        <button type="button" className="lncqp-btn lncqp-primary" onClick={onClose}>
                            Continue Reading
                        </button>
                    ) : (
                        <button type="button" className="lncqp-btn lncqp-primary" onClick={handleRetake}>
                            🔄 Try Again
                        </button>
                    )}
                </div>
            </div>
        );
    }

    return (
        <div>
            <div className="lncqp-toprow">
                <div className="lncqp-progress">
                    Question {currentQuestion + 1} / {quizData.length}
                </div>
            </div>

            <div className="lncqp-q">
                {question.question}
            </div>

            <div className="lncqp-options" role="group" aria-label="Answer choices">
                {Object.entries(question.options).map(([key, value]) => {
                    let optionClass = 'lncqp-option';
                    const isCorrect = key === question.correct_answer;
                    const isSelected = key === selectedOption;

                    if (showAnswer) {
                        if (isCorrect) {
                            optionClass += ' is-correct';
                        } else if (isSelected) {
                            optionClass += ' is-wrong';
                        } else {
                            optionClass += ' is-disabled';
                        }
                    }

                    return (
                        <button
                            key={key}
                            type="button"
                            className={optionClass}
                            onClick={() => handleOptionClick(key)}
                            disabled={isLocked}
                        >
                            <span className="lncqp-option-text">{value}</span>
                            {showAnswer && isCorrect && <span className="lncqp-check">✓</span>}
                            {showAnswer && isSelected && !isCorrect && <span className="lncqp-cross">✕</span>}
                        </button>
                    );
                })}
            </div>

            <div className="lncqp-feedback" aria-live="polite">
                {showAnswer && (
                    <div className={`lncqp-fb ${selectedOption === question.correct_answer ? 'lncqp-fb-correct' : 'lncqp-fb-wrong'}`}>
                        <div className="lncqp-fb-text">
                            {question.correct_answer_explanation || 'Review the content for more details.'}
                        </div>
                    </div>
                )}
            </div>

            <div className={`lncqp-actions${isComplete ? ' is-complete' : ''}`}>
                {isComplete && (
                    <div className="lncqp-complete-label">
                        Quiz complete: {correctCount}/{quizData.length} 🎉
                    </div>
                )}

                {showAnswer && (
                    <>
                        {selectedOption === question.correct_answer ? (
                            <button
                                type="button"
                                className="lncqp-btn lncqp-primary"
                                onClick={currentQuestion + 1 === quizData.length ? onClose : handleNextQuestion}
                            >
                                {currentQuestion + 1 === quizData.length ? 'Continue Reading' : 'Next'}
                            </button>
                        ) : (
                            <button
                                type="button"
                                className="lncqp-btn lncqp-primary"
                                onClick={handleTryAgain}
                            >
                                🔄 Try Again
                            </button>
                        )}
                    </>
                )}
            </div>
        </div>
    );
}