import { Quiz as QuizType, QuizQuestion } from 'utils/quiz' import { useState } from 'react' import Button, { IconButton } from '@components/shared/Button' import { useRouter } from 'next/router' import { ArrowLeftIcon, CheckCircleIcon, ChevronDownIcon, InformationCircleIcon, XCircleIcon, } from '@heroicons/react/20/solid' import { Disclosure } from '@headlessui/react' import Image from 'next/image' import { useWallet } from '@solana/wallet-adapter-react' import useMangoAccount from 'hooks/useMangoAccount' import { bs58 } from '@project-serum/anchor/dist/cjs/utils/bytes' import { useQueryClient } from '@tanstack/react-query' import { useCompletedQuizzes } from 'hooks/useQuiz' type RESULT = { correctAnswers: number wrongAnswers: QuizQuestion[] } const DEFAULT_RESULT = { correctAnswers: 0, wrongAnswers: [], } const Quiz = ({ quiz }: { quiz: QuizType }) => { const router = useRouter() const queryClient = useQueryClient() const { connected, publicKey, signMessage } = useWallet() const { mangoAccountAddress } = useMangoAccount() const { data: solved } = useCompletedQuizzes(publicKey?.toBase58()) const [currentQuestion, setCurrentQuestion] = useState(0) const [answerIndex, setAnswerIndex] = useState(null) const [isCorrectAnswer, setIsCorrectAnswer] = useState(null) const [result, setResult] = useState(DEFAULT_RESULT) const [showIntro, setShowIntro] = useState(true) const [showResult, setShowResult] = useState(false) const { questions, intro } = quiz const { question, choices, description, correctAnswer } = questions[currentQuestion] const handleAnswer = (answer: string, index: number) => { setAnswerIndex(index) if (answer === correctAnswer) { setIsCorrectAnswer(true) } else { setIsCorrectAnswer(false) } } const handleNext = () => { setAnswerIndex(null) setResult((prev) => isCorrectAnswer ? { ...prev, correctAnswers: prev.correctAnswers + 1, } : { ...prev, wrongAnswers: [...prev.wrongAnswers, questions[currentQuestion]], }, ) if (currentQuestion !== questions.length - 1) { setCurrentQuestion((prev) => prev + 1) } else { setCurrentQuestion(0) setShowResult(true) } } const handleTryAgain = () => { setResult(DEFAULT_RESULT) setShowResult(false) } const getResultsHeadingText = (score: number) => { if (!score) { return 'Whoops 😲' } else if (score < 50) { return 'Try Again' } else if (score < 100) { return 'Almost There...' } else return 'Congratulations 🎉' } const completeQuiz = async () => { const message = new TextEncoder().encode(mangoAccountAddress) const signature = await signMessage!(message) const rawResponse = await fetch( 'https://api.mngo.cloud/data/v4/user-data/complete-quiz', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ wallet_pk: publicKey?.toBase58(), quiz_id: quiz.id, mango_account: mangoAccountAddress, signature: bs58.encode(signature), }), }, ) await rawResponse.json() queryClient.invalidateQueries(['completed-quizzes', publicKey?.toBase58()]) router.push('/learn', undefined, { shallow: true }) } const canClaimPoints = connected && mangoAccountAddress return ( <>
router.push('/learn', undefined, { shallow: true })} >

{quiz.name} Quiz

{showIntro || showResult ? null : (
{currentQuestion + 1} /{quiz.questions.length}
)}
{showIntro ? ( <> {quiz.imagePath ? ( Quiz Image ) : null}

{intro.title}

{intro.description}

{intro?.docs ? ( {intro.docs.linkText} ) : null}

{!connected ? 'Connect wallet to earn rewards points' : solved?.find((x) => x.quiz_id === quiz.id) ? 'Rewards Points Claimed' : mangoAccountAddress ? `Score ${quiz.questions.length}/${quiz.questions.length} to earn rewards points` : 'Create a Mango Account to earn rewards points'}

) : !showResult ? ( <>

{question}

{description ?

: null}
{choices.map((choice, index) => ( ))}
) : ( <>

{getResultsHeadingText( (result.correctAnswers / questions.length) * 100, )}

You scored

{((result.correctAnswers / questions.length) * 100).toFixed()}% {result.correctAnswers !== questions.length ? (

Try again to earn rewards points.

) : null}

Correct Answers

{result.correctAnswers}

{result.wrongAnswers?.length ? ( {({ open }) => ( <>

Wrong Answers

{result.wrongAnswers.length}

{result.wrongAnswers.map((answer) => (
{({ open }) => ( <>

{answer.question}

{open ? 'Hide Answer' : 'Reveal Answer'}
{answer.explanation ? (

{answer.explanation}

) : null} {answer.choices.map((choice, index) => (
{String.fromCharCode( 97 + index, ).toUpperCase()}
{choice}
))} )}
))}
)}
) : (

Wrong Answers

0

)}
{solved?.find((x) => x.quiz_id === quiz.id) || !canClaimPoints ? ( ) : result.correctAnswers === questions.length ? ( ) : ( <> )}
)}
) } export default Quiz