Single Choice Easy

QWhat would the following JavaScript code produce?

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() 
{
   var str = "The rain in SPAIN stays mainly in the plain"; 
   var res = str.match(/z/);
   If(res)
      res=</h1>

                    <div class="mcq-info-strip">
                        <span class="info-pill"><i class="fa fa-hashtag"></i> ID: <strong>#5135</strong></span>
                        <span class="info-pill"><i class="fa fa-folder-open"></i> <strong>Javascript DOM &amp; Event Handling MCQ</strong></span>
                        <span class="info-pill"><i class="fa fa-eye"></i> <strong>139</strong> views</span>
                    </div>

                    <details class="mob-info-toggle" style="margin-bottom:14px;">
                        <summary class="btn-outline" style="list-style:none; display:inline-flex;"><i class="fa fa-circle-info"></i> Question Info</summary>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:10px;">
                            <div class="left-stat-box"><span class="left-stat-val">#5135</span><span class="left-stat-lbl">Q ID</span></div>
                            <div class="left-stat-box"><span class="left-stat-val" style="font-size:13px;">Easy</span><span class="left-stat-lbl">Difficulty</span></div>
                            <div class="left-stat-box" style="grid-column:1/-1;"><span class="left-stat-val" style="font-size:13px;">Javascript DOM &amp; Event Handling MCQ</span><span class="left-stat-lbl">Topic</span></div>
                        </div>
                    </details>

                    <div class="mcq-hero-actions">
                        <a href="/quiz/subchapter/347" class="btn-quiz"><i class="fa fa-bolt"></i> Start Quiz on This Topic</a>
                    </div>
                </div>
            </div>

            
            <!-- ═══════════ ANSWER INTERACTION (mode-driven) ═══════════ -->
            <div class="mcq-card" id="answer-interaction-5135">

                                    <div class="section-label"><i class="fa fa-list-check"></i> &nbsp;Your Answer</div>
                    <h2 class="section-title">
                        Choose the Best Option                    </h2>
                    <p class="section-sub">
                        Click any option to instantly check if you're correct.                    </p>
                    <ul class="options-list" data-role="choice-list">
                                                    <li class="options-list-item" data-key="A">
                                                                <span class="option-symbol">A</span>
                                <span class="option-text">True</span>
                                <span class="option-status correct-option">✔</span>
                                <span class="option-status wrong-option">✖</span>
                            </li>
                                                    <li class="options-list-item" data-key="B">
                                                                <span class="option-symbol">B</span>
                                <span class="option-text">False</span>
                                <span class="option-status correct-option">✔</span>
                                <span class="option-status wrong-option">✖</span>
                            </li>
                                                    <li class="options-list-item" data-key="C">
                                                                <span class="option-symbol">C</span>
                                <span class="option-text">Error</span>
                                <span class="option-status correct-option">✔</span>
                                <span class="option-status wrong-option">✖</span>
                            </li>
                                                    <li class="options-list-item" data-key="D">
                                                                <span class="option-symbol">D</span>
                                <span class="option-text">Handling</span>
                                <span class="option-status correct-option">✔</span>
                                <span class="option-status wrong-option">✖</span>
                            </li>
                                            </ul>
                    
                            </div>

            <!-- Payload for JS -->
            <script type="application/json" id="mcq-payload-5135">{"qid":5135,"mode":"single_choice","answer":"B","options":{"A":"True","B":"False","C":"Error","D":"Handling"}}</script>

            <!-- ANSWER / EXPLANATION CARD -->
            <div id="answer-box-5135" class="mcq-card mcq-answer-card">
                                    <div class="answer-badge" data-role="answer-badge">
                        <i class="fa fa-check-circle"></i> <span data-role="answer-badge-text">Correct Answer</span>
                    </div>
                                <h3 class="section-title">Explanation</h3>
                <div class="answer-explanation"><p>The match method searches the given string for matches. The output will be false since the character z is absent from the string.</p></div>
            </div>

            <div class="mcq-card">
                <div class="section-label"><i class="fa fa-arrow-right-arrow-left"></i> &nbsp;Continue Practice</div>
                <div class="mcq-nav-row" style="margin-top:12px;">
                                            <a href="/question/mcq/5134" class="nav-btn"><i class="fa fa-arrow-left"></i> Previous Question</a>
                                                                <a href="/question/mcq/5136" class="nav-btn nav-next">Next Question <i class="fa fa-arrow-right"></i></a>
                                    </div>
            </div>

            <div class="mcq-card">
                <div class="section-label"><i class="fa fa-share-nodes"></i> &nbsp;Share</div>
                <h3 class="section-title" style="margin-bottom:4px;">Share This Question</h3>
                <p class="section-sub">Challenge a friend or share with your study group.</p>
                <div class="share-actions">
                    <a target="_blank" href="https://api.whatsapp.com/send?text=Check+this+MCQ%3A+https%3A%2F%2Fwww.rummanansari.com%2Fquestion%2Fmcq%2F5135" class="share-btn share-btn-wa"><i class="fa-brands fa-whatsapp"></i> WhatsApp</a>
                    <button type="button" class="share-btn" id="copyQuestionLinkBtn"><i class="fa fa-copy"></i> Copy Link</button>
                </div>
            </div>

                        <div class="mcq-card">
                <div class="section-label"><i class="fa fa-circle-question"></i> &nbsp;More from This Topic</div>
                <h2 class="section-title" style="margin-bottom:16px;">Related MCQ Questions</h2>
                <div class="related-q-list">
                                            <a href="/question/mcq/5150" class="related-q-item"><i class="fa fa-chevron-right"></i> Which events are subject to cancellable default actions by event handlers?</a>
                                            <a href="/question/mcq/5157" class="related-q-item"><i class="fa fa-chevron-right"></i> When does the mouseout event occur?</a>
                                            <a href="/question/mcq/5193" class="related-q-item"><i class="fa fa-chevron-right"></i> What is returned by the nodeName of the nodeType Document?</a>
                                            <a href="/question/mcq/5156" class="related-q-item"><i class="fa fa-chevron-right"></i> When does the mouseover event occur?</a>
                                            <a href="/question/mcq/5173" class="related-q-item"><i class="fa fa-chevron-right"></i> How can a user produce numerous keydown events?</a>
                                            <a href="/question/mcq/5211" class="related-q-item"><i class="fa fa-chevron-right"></i> What is the data limitation per cookie?</a>
                                            <a href="/question/mcq/5148" class="related-q-item"><i class="fa fa-chevron-right"></i> The audio and video are property of the</a>
                                            <a href="/question/mcq/5151" class="related-q-item"><i class="fa fa-chevron-right"></i> The events that depict activities taking on within the browser window are</a>
                                            <a href="/question/mcq/5141" class="related-q-item"><i class="fa fa-chevron-right"></i> Which property defines the event&#039;s property?</a>
                                            <a href="/question/mcq/5076" class="related-q-item"><i class="fa fa-chevron-right"></i> What property is used to find out the vendor and version of the browser?</a>
                                    </div>
            </div>
            
        </main>

        <!-- RIGHT COLUMN -->
        <aside class="mcq-right-col">
            <div class="subject-card">
                <div class="subject-card-header">
                    <div class="subject-icon-wrap">
                                                    <i class="fa fa-graduation-cap" style="color:rgba(13,110,253,.7);"></i>
                                            </div>
                    <h3 class="subject-name">Computer Science and Engineering</h3>
                                            <p class="subject-desc">Explore the dynamic field of Computer Science and Engineering with our comprehensive course. Learn about algorithms, dat…</p>
                                    </div>
                <div class="subject-card-body">
                                                                <a href="/payment/enroll/7" class="btn-enroll"><i class="fa fa-plus-circle"></i> Enroll in Subject</a>
                                    </div>
            </div>

                        <div class="mcq-card" style="padding:18px 16px;">
                <div class="section-label" style="margin-bottom:12px;"><i class="fa fa-sitemap"></i> &nbsp;Related Topics</div>
                                    <a href="/article/read/7/333" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Basic JavaScript MCQ                    </a>
                                    <a href="/article/read/7/344" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Client side Databases MCQ                    </a>
                                    <a href="/article/read/7/359" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript and AJAX MCQ                    </a>
                                    <a href="/article/read/7/345" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Blobs MCQ                    </a>
                                    <a href="/article/read/7/340" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Classes MCQ                    </a>
                                    <a href="/article/read/7/338" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Data Types MCQ                    </a>
                                    <a href="/article/read/7/347" class="right-topic-link active">
                        <i class="fa fa-circle-dot"></i>
                        Javascript DOM &amp; Event Handling MCQ                    </a>
                                    <a href="/article/read/7/336" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Functions MCQ                    </a>
                                    <a href="/article/read/7/350" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Graphics and Rendering MCQ                    </a>
                                    <a href="/article/read/7/346" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript loops MCQ                    </a>
                                    <a href="/article/read/7/341" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Modules MCQ                    </a>
                                    <a href="/article/read/7/334" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        JavaScript Operator MCQ                    </a>
                                    <a href="/article/read/7/348" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Scripted HTTP MCQ                    </a>
                                    <a href="/article/read/7/339" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript String MCQ                    </a>
                                    <a href="/article/read/7/342" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Javascript Subsets MCQ                    </a>
                                    <a href="/article/read/7/343" class="right-topic-link ">
                        <i class="fa fa-circle"></i>
                        Scripted Media                    </a>
                            </div>
                    </aside>

    </div>
</div>

<style>
footer.site-footer,
footer.site-footer a,
footer.site-footer li,
footer.site-footer p,
footer.site-footer span,
footer.site-footer h5,
.navbar .dropdown-menu,
.navbar .dropdown-menu a,
.navbar .dropdown-menu li,
.navbar .dropdown-menu p {
    color: var(--text-color) !important;
    background-color: var(--header-footer-bg) !important;
}

footer.site-footer a:hover,
.navbar .dropdown-menu a:hover {
    color: var(--link-hover-color) !important;
}

footer.site-footer hr {
    border-color: var(--shadow-color) !important;
}

footer.site-footer i {
    color: var(--text-color) !important;
}

footer.site-footer i:hover {
    color: var(--link-hover-color) !important;
}

.site-footer {
    padding: 48px 24px 24px;
    margin-top: 40px;
    border-top: 1px solid var(--border-color);
}

.site-footer .footer-inner {
    width: 100%;
    max-width: 100%;
    margin: 0;
}

.site-footer .footer-top {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 32px;
}

.site-footer h5 {
    font-size: 1.2rem;
    font-weight: 700;
    margin-bottom: 16px;
}

.site-footer p,
.site-footer li,
.site-footer a {
    font-size: 0.98rem;
    line-height: 1.7;
    text-decoration: none;
}

.site-footer ul {
    padding-left: 0;
    margin-bottom: 0;
    list-style: none;
}

.site-footer .social-links a {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 14px;
    font-size: 1rem;
}

.site-footer .footer-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    padding-top: 20px;
    margin-top: 28px;
    border-top: 1px solid var(--shadow-color);
}

.site-footer .footer-bottom-links a {
    margin-left: 18px;
}

.site-footer .footer-bottom-links a:first-child {
    margin-left: 0;
}

@media (max-width: 991.98px) {
    .site-footer {
        padding: 36px 16px 20px;
    }

    .site-footer .footer-top {
        grid-template-columns: 1fr;
        gap: 24px;
    }

    .site-footer .footer-bottom {
        flex-direction: column;
        align-items: flex-start;
    }

    .site-footer .footer-bottom-links a {
        margin-left: 0;
        margin-right: 16px;
    }
}
</style>

<footer class="site-footer">
    <div class="footer-inner">
        <div class="footer-top">
            <div>
                <h3>About RummanAnsari</h3>
                <p>Your go-to platform for online courses, GK, blogs, and learning resources.</p>
            </div>

            <div>
                <h3>Quick Links</h3>
                <ul>
                    <li><a href="/">Home</a></li>
                    <li><a href="/blog/">Blog</a></li>
                    <li><a href="https://www.rummanansari.com/course?course_type=paid">Topic</a></li>
                    <li><a href="/course">Courses</a></li>
                </ul>
            </div>

            <div>
                <h3>Courses</h3>
                <ul>
                    <li><a href="https://www.rummanansari.com/course?course_type=free">Free Courses</a></li>
                    <li><a href="https://www.rummanansari.com/course?course_type=paid">Paid Courses</a></li>
                </ul>

                <h3 class="mt-4">Connect with Us</h3>
                <div class="social-links">
                    <a href="https://www.facebook.com/merummanansari/" aria-label="Facebook Profile"><i class="fab fa-facebook-f"></i></a>
                    <a href="https://x.com/merummanansari" aria-label="Twitter Profile"><i class="fab fa-twitter"></i></a>
                    <a href="https://www.linkedin.com/in/rummanansari/" aria-label="LinkedIn Profile"><i class="fab fa-linkedin-in"></i></a>
                    <a href="https://www.instagram.com/instra.ansari/" aria-label="Instagram Profile"><i class="fab fa-instagram"></i></a>
                </div>
            </div>
        </div>

        <div class="footer-bottom">
            <p class="mb-0">&copy; 2026 RummanAnsari. All rights reserved.</p>
            <div class="footer-bottom-links">
                <a href="/about/">About</a>
                <a href="/about/privacy-policy/">Privacy</a>
                <a href="/about/terms-and-conditions/">Terms</a>
            </div>
        </div>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<!--<script src="/assets/js/new-scripts.js"></script>-->

<!--  below two for editor-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-lite.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-lite.min.js"></script>
<!--<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>-->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const body = document.body;
    const toggleBtn = document.getElementById('sidebarToggleBtn');
    const closeBtn = document.getElementById('closeSidebarBtn');
    const overlay = document.getElementById('sidebarOverlay');
    const mobileBreakpoint = 992;

    function isMobile() {
        return window.innerWidth < mobileBreakpoint;
    }

    function applySidebarState() {
        const saved = localStorage.getItem('sidebarCollapsed');

        if (isMobile()) {
            body.classList.remove('sidebar-collapsed');
            body.classList.remove('sidebar-mobile-open');
        } else {
            body.classList.remove('sidebar-mobile-open');

            if (saved === 'true') {
                body.classList.add('sidebar-collapsed');
            } else {
                body.classList.remove('sidebar-collapsed');
            }
        }
    }

    if (toggleBtn) {
        toggleBtn.addEventListener('click', function () {
            if (isMobile()) {
                body.classList.toggle('sidebar-mobile-open');
            } else {
                body.classList.toggle('sidebar-collapsed');
                localStorage.setItem(
                    'sidebarCollapsed',
                    body.classList.contains('sidebar-collapsed') ? 'true' : 'false'
                );
            }
        });
    }

    if (closeBtn) {
        closeBtn.addEventListener('click', function () {
            body.classList.remove('sidebar-mobile-open');
        });
    }

    if (overlay) {
        overlay.addEventListener('click', function () {
            body.classList.remove('sidebar-mobile-open');
        });
    }

    window.addEventListener('resize', applySidebarState);
    applySidebarState();
});

document.addEventListener('DOMContentLoaded', function () {
    const body = document.body;
    const themeButtons = document.querySelectorAll('[data-theme-button]');
});
</script>

<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import { getAuth, GoogleAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";

const firebaseConfig = {
    apiKey: "AIzaSyCNteyUk6yYXnx275jqn09fGPtjpnir5pY",
    authDomain: "rummanansari-01.firebaseapp.com",
    projectId: "rummanansari-01",
    storageBucket: "rummanansari-01.firebasestorage.app",
    messagingSenderId: "958581859518",
    appId: "1:958581859518:web:ea2b17c10640eb8747eaef"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();

const googleLoginButtons = document.querySelectorAll('.googleLoginBtn');

googleLoginButtons.forEach(function (googleLoginBtn) {
    googleLoginBtn.addEventListener('click', async function () {
        try {
            const result = await signInWithPopup(auth, provider);
            const user = result.user;

            const response = await fetch('/login/google', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    email: user.email || '',
                    first_name: user.displayName ? user.displayName.split(' ')[0] : '',
                    last_name: user.displayName ? user.displayName.split(' ').slice(1).join(' ') : '',
                    profile_image: user.photoURL || '',
                    google_uid: user.uid
                })
            });

            const rawText = await response.text();
            console.log('Server response:', rawText);

            let data;
            try {
                data = JSON.parse(rawText);
            } catch (e) {
                alert('Server is not returning valid JSON. Check console.');
                return;
            }

            if (data.status === 'success') {
                window.location.href = data.redirect || '/dashboard';
            } else {
                alert(data.message || 'Google login failed.');
            }

        } catch (error) {
            console.error('Google login error:', error);
            alert(error.message || 'Unable to login with Google.');
        }
    });
});
</script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/php.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/json.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/csharp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/sql.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/java.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.article-content pre code').forEach(function (block) {
        if (window.hljs) {
            hljs.highlightElement(block);
        }
    });
});
</script>

</body>
</html>
<script>
document.addEventListener("DOMContentLoaded", function () {

    const qid = 5135;
    const payloadEl = document.getElementById("mcq-payload-" + qid);
    const payload = payloadEl ? JSON.parse(payloadEl.textContent) : { mode: "single_choice" };
    const answerBox = document.getElementById("answer-box-" + qid);
    const interactionBox = document.getElementById("answer-interaction-" + qid);

    function revealAnswer() {
        if (answerBox) {
            answerBox.style.display = "block";
            setTimeout(function () {
                window.scrollTo({ top: answerBox.offsetTop - 90, behavior: "smooth" });
            }, 120);
        }
    }

    function setFeedback(isCorrect, textOk, textBad) {
        const el = interactionBox.querySelector('[data-role="feedback"]');
        if (!el) return;
        el.classList.remove("ok", "bad");
        el.classList.add("show", isCorrect ? "ok" : "bad");
        el.textContent = isCorrect ? (textOk || "Correct! 🎉") : (textBad || "Not quite — check the explanation below.");
    }

    /* ── SINGLE CHOICE ── */
    if (payload.mode === "single_choice") {
        const items = interactionBox.querySelectorAll(".options-list-item");
        items.forEach(function (item) {
            item.addEventListener("click", function () {
                const selectedKey = this.dataset.key;
                const correct = (payload.answer || "").trim().toUpperCase();

                items.forEach(function (li) {
                    li.classList.remove("correct-selected", "wrong-selected");
                    const ok = li.querySelector(".correct-option");
                    const bad = li.querySelector(".wrong-option");
                    if (ok) ok.style.display = "none";
                    if (bad) bad.style.display = "none";
                });

                if (selectedKey === correct) {
                    this.classList.add("correct-selected");
                    const ok = this.querySelector(".correct-option");
                    if (ok) ok.style.display = "inline";
                } else {
                    this.classList.add("wrong-selected");
                    const bad = this.querySelector(".wrong-option");
                    if (bad) bad.style.display = "inline";
                }
                revealAnswer();
            });
        });
    }

    /* ── MULTIPLE CHOICE ── */
    if (payload.mode === "multi_choice") {
        const checkboxes = interactionBox.querySelectorAll(".option-check");
        const items = interactionBox.querySelectorAll(".options-list-item");

        items.forEach(function (item) {
            item.addEventListener("click", function (e) {
                if (e.target.tagName.toLowerCase() === "input") return;
                const cb = this.querySelector(".option-check");
                cb.checked = !cb.checked;
                this.classList.toggle("picked", cb.checked);
            });
        });
        checkboxes.forEach(function (cb) {
            cb.addEventListener("change", function () {
                cb.closest(".options-list-item").classList.toggle("picked", cb.checked);
            });
        });

        const btn = interactionBox.querySelector('[data-role="check-btn"]');
        if (btn) btn.addEventListener("click", function () {
            const correctSet = new Set((payload.answer || "").split(",").map(s => s.trim().toUpperCase()).filter(Boolean));
            let allCorrect = true;

            items.forEach(function (li) {
                const key = li.dataset.key;
                const cb = li.querySelector(".option-check");
                const isPicked = cb.checked;
                const shouldBePicked = correctSet.has(key);

                li.classList.remove("correct-selected", "wrong-selected");
                const ok = li.querySelector(".correct-option");
                const bad = li.querySelector(".wrong-option");
                if (ok) ok.style.display = "none";
                if (bad) bad.style.display = "none";

                if (shouldBePicked) {
                    li.classList.add("correct-selected");
                    if (ok) ok.style.display = "inline";
                    if (!isPicked) allCorrect = false;
                } else if (isPicked) {
                    li.classList.add("wrong-selected");
                    if (bad) bad.style.display = "inline";
                    allCorrect = false;
                }
            });

            setFeedback(allCorrect);
            revealAnswer();
        });
    }

    /* ── TEXT INPUT (short answer / fill blank / one word) ── */
    if (payload.mode === "text_input") {
        const btn = interactionBox.querySelector('[data-role="check-btn"]');
        const input = interactionBox.querySelector('[data-role="text-input"]');
        const wrap = interactionBox.querySelector('[data-role="text-wrap"]');

        if (btn) btn.addEventListener("click", function () {
            const val = (input.value || "").trim().toLowerCase();
            const accepted = payload.accepted || [];
            const isCorrect = accepted.includes(val) && val !== "";

            wrap.classList.remove("correct", "incorrect");
            wrap.classList.add(isCorrect ? "correct" : "incorrect");
            setFeedback(isCorrect);
            revealAnswer();
        });

        if (input) input.addEventListener("keydown", function (e) {
            if (e.key === "Enter") btn.click();
        });
    }

    /* ── ORDER (drag & drop / ranking, tap-to-order) ── */
    if (payload.mode === "order") {
        const poolItems = interactionBox.querySelectorAll('[data-role="order-pool"] .order-item');
        const slots = interactionBox.querySelectorAll('[data-role="order-slots"] .order-slot');
        const checkBtn = interactionBox.querySelector('[data-role="check-btn"]');
        let filledCount = 0;

        function firstEmptySlot() {
            for (const s of slots) if (!s.classList.contains("filled")) return s;
            return null;
        }

        poolItems.forEach(function (item) {
            item.addEventListener("click", function () {
                if (this.classList.contains("used")) return;
                const slot = firstEmptySlot();
                if (!slot) return;

                slot.classList.add("filled");
                slot.dataset.key = this.dataset.key;
                slot.querySelector('[data-role="slot-text"]').textContent = this.dataset.key + ". " + this.textContent.replace(this.dataset.key + ".", "").trim();
                this.classList.add("used");
                filledCount++;
                checkBtn.disabled = (filledCount !== slots.length);
            });
        });

        slots.forEach(function (slot) {
            slot.addEventListener("click", function () {
                if (!this.classList.contains("filled")) return;
                const key = this.dataset.key;
                const poolItem = interactionBox.querySelector('[data-role="order-pool"] .order-item[data-key="' + key + '"]');
                if (poolItem) poolItem.classList.remove("used");

                this.classList.remove("filled", "correct", "incorrect");
                this.removeAttribute("data-key");
                this.querySelector('[data-role="slot-text"]').textContent = "Empty";
                filledCount--;
                checkBtn.disabled = (filledCount !== slots.length);
            });
        });

        checkBtn.addEventListener("click", function () {
            const correctOrder = payload.correctOrder || [];
            let allCorrect = true;

            slots.forEach(function (slot, idx) {
                const expected = correctOrder[idx];
                const actual = slot.dataset.key;
                slot.classList.remove("correct", "incorrect");
                if (actual === expected) {
                    slot.classList.add("correct");
                } else {
                    slot.classList.add("incorrect");
                    allCorrect = false;
                }
            });

            setFeedback(allCorrect, "Perfect order! 🎉", "Order isn't quite right — see the correct sequence below.");
            revealAnswer();
        });
    }

    /* ── MATCHING ── */
    if (payload.mode === "matching") {
        const rows = interactionBox.querySelectorAll('[data-role="match-rows"] .match-row');
        const btn = interactionBox.querySelector('[data-role="check-btn"]');
        const pairs = payload.pairs || {};

        btn.addEventListener("click", function () {
            let allCorrect = true;
            rows.forEach(function (row) {
                const key = row.dataset.key;
                const select = row.querySelector(".match-select");
                const chosen = select.value.trim();
                const correctRight = (pairs[key] || {}).right || "";

                row.classList.remove("correct", "incorrect");
                if (chosen !== "" && chosen === correctRight) {
                    row.classList.add("correct");
                } else {
                    row.classList.add("incorrect");
                    allCorrect = false;
                }
            });
            setFeedback(allCorrect);
            revealAnswer();
        });
    }

    /* ── HOTSPOT ── */
    if (payload.mode === "hotspot") {
        const markers = interactionBox.querySelectorAll(".hotspot-marker");
        markers.forEach(function (marker) {
            marker.addEventListener("click", function () {
                const key = this.dataset.key;
                const correct = (payload.correct || "").trim().toUpperCase();

                markers.forEach(function (m) { m.classList.remove("correct", "wrong"); });

                if (key === correct) {
                    this.classList.add("correct");
                } else {
                    this.classList.add("wrong");
                    const correctMarker = interactionBox.querySelector('.hotspot-marker[data-key="' + correct + '"]');
                    if (correctMarker) correctMarker.classList.add("correct");
                }
                setFeedback(key === correct);
                revealAnswer();
            });
        });
    }

    /* ── FREE TEXT / MEDIA RESPONSE (no auto-grading) ── */
    if (payload.mode === "free_text" || payload.mode === "media_response") {
        const btn = interactionBox.querySelector('[data-role="reveal-btn"]');
        if (btn) btn.addEventListener("click", revealAnswer);
    }

    /* ── Copy link ── */
    const copyBtn = document.getElementById("copyQuestionLinkBtn");
    if (copyBtn) {
        copyBtn.addEventListener("click", function () {
            navigator.clipboard.writeText(window.location.href).then(function () {
                const orig = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fa fa-check"></i> Copied!';
                setTimeout(function () { copyBtn.innerHTML = orig; }, 1400);
            });
        });
    }

    document.querySelectorAll(".right-topic-link.active").forEach(function (el) {
        el.style.borderColor = "rgba(13,110,253,.35)";
        el.style.background = "rgba(13,110,253,.07)";
        el.style.color = "var(--link-color)";
    });
});
</script>