




<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Uncategorized Archives &#187; GyanXp</title>
	<atom:link href="https://gyanxp.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>https://gyanxp.com/category/uncategorized/</link>
	<description>अपनी Online Class</description>
	<lastBuildDate>Thu, 01 Oct 2026 13:39:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://gyanxp.com/wp-content/uploads/2025/02/image-1.webp</url>
	<title>Uncategorized Archives &#187; GyanXp</title>
	<link>https://gyanxp.com/category/uncategorized/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>tool</title>
		<link>https://gyanxp.com/tool/</link>
					<comments>https://gyanxp.com/tool/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Thu, 24 Sep 2026 16:49:49 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=6447</guid>

					<description><![CDATA[<p>GyanXp Master Portal &#8211; Unified Tool Suite G GyanXp Master Suite Enter your secure credentials to access the tools portal Login ID Password Invalid Login ID or Password! Access Portal G GyanXp Unified Master Portal High-performance production tool suite for educational content Tool 1: MCQ Format Converter Tool 2: GyanXp Document Generator MCQ Format Converter [&#8230;]</p>
<p>The post <a href="https://gyanxp.com/tool/">tool</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[		<div data-elementor-type="wp-post" data-elementor-id="6447" class="elementor elementor-6447">
						<section class="elementor-section elementor-top-section elementor-element elementor-element-4959ccc elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="4959ccc" data-element_type="section" data-e-type="section">
						<div class="elementor-container elementor-column-gap-default">
					<div class="elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-7832d19" data-id="7832d19" data-element_type="column" data-e-type="column">
			<div class="elementor-widget-wrap elementor-element-populated">
						<div class="elementor-element elementor-element-a9fbfb3 elementor-widget elementor-widget-html" data-id="a9fbfb3" data-element_type="widget" data-e-type="widget" data-widget_type="html.default">
				<div class="elementor-widget-container">
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GyanXp Master Portal - Unified Tool Suite</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Mammoth.js for robust .docx file parsing -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Fira+Code:wght@450;600&family=Noto+Sans+Devanagari:wght@600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-orange: #FF6B00;
            --primary-orange-hover: #e56000;
            --dark-slate: #1e293b;
            --bg-main: #f8fafc;
            --card-bg: #ffffff;
            --border-color: #cbd5e1;
            --text-main: #0f172a;
            --text-muted: #64748b;
        }
        
        body {
            background-color: var(--bg-main) !important;
            color: var(--text-main) !important;
            font-family: 'Inter', 'Noto Sans Devanagari', sans-serif;
        }

        .portal-tool-section { display: none !important; }
        .portal-tool-section.active-portal-tool { display: flex !important; flex-direction: column !important; flex-grow: 1 !important; }
        
        .portal-card { background: var(--card-bg); border: 1.5px solid var(--border-color); border-radius: 16px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02); }
        
        #portalContainerTool2 .analysis-dashboard { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 5px; }
        #portalContainerTool2 .dashboard-metric-card { background: var(--card-bg); border: 1.5px solid var(--border-color); border-radius: 12px; padding: 16px 20px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02); display: flex; flex-direction: column; justify-content: center; }
        #portalContainerTool2 .dashboard-metric-title { font-size: 12px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; }
        #portalContainerTool2 .dashboard-metric-value { font-size: 22px; font-weight: 800; color: var(--dark-slate); }
        #portalContainerTool2 .card { background: var(--card-bg); padding: 35px; border-radius: 16px; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05); border: 1.5px solid var(--border-color); }
        #portalContainerTool2 .brand-header { display: flex; align-items: center; gap: 15px; margin-bottom: 25px; border-bottom: 2px solid #f1f5f9; padding-bottom: 20px; }
        #portalContainerTool2 .brand-logo-circle { width: 50px; height: 50px; background: var(--dark-slate); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary-orange); font-weight: 800; font-size: 26px; box-shadow: 0 4px 12px rgba(255, 107, 0, 0.2); }
        #portalContainerTool2 h2 { margin: 0; color: var(--dark-slate); font-size: 24px; font-weight: 700; letter-spacing: -0.025em; }
        #portalContainerTool2 .category-section { background: #f8fafc; border: 1.5px solid var(--border-color); border-radius: 12px; padding: 20px; margin-bottom: 20px; }
        #portalContainerTool2 .category-title { font-size: 14px; font-weight: 700; color: var(--primary-orange); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
        #portalContainerTool2 .form-group { margin-bottom: 16px; }
        #portalContainerTool2 .form-group:last-child { margin-bottom: 0; }
        #portalContainerTool2 label { font-weight: 600; display: block; margin-bottom: 6px; font-size: 13px; color: var(--dark-slate); }
        #portalContainerTool2 input[type="file"], #portalContainerTool2 select, #portalContainerTool2 input[type="number"], #portalContainerTool2 input[type="text"], #portalContainerTool2 input[type="password"] { width: 100%; padding: 12px 14px; border: 1.5px solid var(--border-color); border-radius: 10px; box-sizing: border-box; font-family: inherit; font-size: 14px; color: var(--text-main); background: #ffffff; transition: all 0.2s ease; }
        #portalContainerTool2 input[type="file"]:focus, #portalContainerTool2 select:focus, #portalContainerTool2 input[type="number"]:focus, #portalContainerTool2 input[type="text"]:focus, #portalContainerTool2 input[type="password"]:focus { outline: none; border-color: var(--primary-orange); box-shadow: 0 0 0 3px rgba(255, 107, 0, 0.15); }
        #portalContainerTool2 .color-picker-wrapper { display: flex; align-items: center; gap: 12px; background: #ffffff; padding: 8px 12px; border: 1.5px solid var(--border-color); border-radius: 10px; }
        #portalContainerTool2 .color-picker-wrapper span { font-size: 12px; font-weight: 600; color: var(--text-muted); }
        #portalContainerTool2 input[type="color"].sm-picker { width: 34px; height: 34px; border: none; padding: 0; background: none; cursor: pointer; border-radius: 6px; }
        #portalContainerTool2 .row { display: flex; gap: 16px; }
        #portalContainerTool2 .row > div { flex: 1; }
        #portalContainerTool2 .grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
        #portalContainerTool2 .btn-group { display: flex; gap: 12px; margin-top: 25px; }
        #portalContainerTool2 button { background: var(--primary-orange); color: white; border: none; padding: 14px 28px; border-radius: 10px; font-weight: 600; font-size: 15px; cursor: pointer; transition: all 0.2s ease; box-shadow: 0 4px 12px rgba(255, 107, 0, 0.25); width: 100%; }
        #portalContainerTool2 button:hover { background: var(--primary-orange-hover); transform: translateY(-1px); box-shadow: 0 6px 16px rgba(255, 107, 0, 0.35); }
        #portalContainerTool2 button.secondary { background: var(--dark-slate); box-shadow: 0 4px 12px rgba(30, 41, 59, 0.2); width: auto; color: #ffffff; }
        #portalContainerTool2 button.secondary:hover { background: #0f172a; box-shadow: 0 6px 16px rgba(30, 41, 59, 0.3); }
        #portalContainerTool2 button.reset-btn { background: #ef4444; padding: 6px 12px; font-size: 11px; margin-left: auto; width: auto; box-shadow: none; color: #ffffff; }
        #portalContainerTool2 button.reset-btn:hover { background: #dc2626; }
        #portalContainerTool2 button.nav-btn { background: #475569; padding: 10px 16px; font-size: 13px; width: auto; box-shadow: none; color: #ffffff; }
        #portalContainerTool2 button.nav-btn:hover { background: #334155; }
        #portalContainerTool2 #t2PreviewContainer { display: none; }
        #portalContainerTool2 .slide-viewport { width: 100%; height: 520px; border: 2px solid #e2e8f0; border-radius: 12px; margin-top: 15px; background: #0f172a; display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; box-shadow: inset 0 2px 8px rgba(0,0,0,0.2); }
        #portalContainerTool2 .slide-canvas { background: white; background-size: 100% 100% !important; background-position: center !important; background-repeat: no-repeat !important; box-shadow: 0 20px 35px -10px rgba(0,0,0,0.3); box-sizing: border-box; display: flex; flex-direction: column; justify-content: flex-start; overflow: hidden; position: relative; transition: all 0.2s ease; }
        #portalContainerTool2 .set-divider-title { font-size: 64px; font-weight: 900; text-align: center; margin: auto; letter-spacing: 2px; text-transform: uppercase; z-index: 2; }
        #portalContainerTool2 .q-hindi, #portalContainerTool2 .q-english, #portalContainerTool2 .stmt-item, #portalContainerTool2 .opt-item { box-sizing: border-box; z-index: 2; word-break: break-word; overflow-wrap: break-word; white-space: normal; width: 100%; }
        #portalContainerTool2 .question-row-container { display: flex; flex-direction: row; align-items: flex-start; justify-content: space-between; gap: 20px; width: 100%; box-sizing: border-box; z-index: 2; }
        #portalContainerTool2 .question-text-side { flex: 1; display: flex; flex-direction: column; box-sizing: border-box; min-width: 0; }
        #portalContainerTool2 .question-image-side { flex-shrink: 0; display: flex; align-items: flex-start; justify-content: flex-end; }
        #portalContainerTool2 .question-image-box { object-fit: contain; border: none !important; background: transparent !important; display: block; box-shadow: none !important; }
        #portalContainerTool2 .code-preview-box { font-family: 'Fira Code', monospace; padding: 6px 10px; margin: 6px 0; font-size: 0.8em; line-height: 1.4; white-space: pre; z-index: 2; box-sizing: border-box; display: inline-block; }
        #portalContainerTool2 .syntax-keyword { color: #2563eb; font-weight: bold; }
        #portalContainerTool2 .syntax-function { color: #7c3aed; font-weight: bold; }
        #portalContainerTool2 .syntax-string { color: #16a34a; }
        #portalContainerTool2 .syntax-number { color: #d97706; }
        #portalContainerTool2 .ak-container { width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: flex-start; box-sizing: border-box; overflow: hidden; z-index: 2; padding: 15px; }
        #portalContainerTool2 .ak-title { text-align: center; font-size: 20px; font-weight: 800; letter-spacing: 1px; margin-bottom: 12px; text-transform: uppercase; color: #cc0000; }
        #portalContainerTool2 .pro-ak-table { width: 100%; border-collapse: collapse; border: 1.5px solid #000000; background: #ffffff; table-layout: fixed; }
        #portalContainerTool2 .pro-ak-table td { padding: 5px 2px; font-size: 11px; font-weight: bold; text-align: center; border: 1px solid #000000; color: #000000; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        #portalContainerTool2 .pro-ak-table tr:nth-child(even) td { background-color: #d1d5db; }
        #portalContainerTool2 .preview-controls { display: flex; justify-content: space-between; align-items: center; margin-top: 15px; background: #f8fafc; padding: 12px 18px; border-radius: 10px; border: 1.5px solid var(--border-color); flex-wrap: wrap; gap: 12px; }
        #portalContainerTool2 .badge { background: #fff7ed; color: var(--primary-orange); padding: 3px 6px; border-radius: 6px; font-size: 11px; font-weight: 700; border: 1px solid #fed7aa; }
        #portalContainerTool2 .section-title { font-size: 13px; font-weight: 700; margin-bottom: 12px; display: flex; align-items: center; color: var(--dark-slate); text-transform: uppercase; letter-spacing: 0.025em; }
        #portalContainerTool2 .checkbox-card { display: flex; align-items: center; gap: 12px; background: #ffffff; padding: 12px 16px; border-radius: 10px; border: 1.5px solid var(--border-color); cursor: pointer; height: 100%; box-sizing: border-box; }
        #portalContainerTool2 .checkbox-card input[type="checkbox"] { width: 20px; height: 20px; accent-color: var(--primary-orange); cursor: pointer; }
        #portalContainerTool2 .checkbox-card label { margin-bottom: 0; cursor: pointer; font-weight: 600; color: var(--dark-slate); text-transform: none; font-size: 14px; }
        #portalContainerTool2 .file-info-badge { margin-top: 8px; font-size: 13px; font-weight: 600; color: var(--primary-orange); }
    </style>
</head>
<body class="min-h-screen flex flex-col selection:bg-orange-500 selection:text-white">

    <!-- GLOBAL SECURE LOGIN OVERLAY -->
    <div id="masterLoginOverlay" class="fixed inset-0 bg-slate-900/80 backdrop-blur-md flex items-center justify-center z-[999999] px-4">
        <div class="portal-card bg-white p-8 rounded-3xl w-full max-w-md shadow-2xl text-center relative overflow-hidden">
            <div class="absolute -top-12 -right-12 w-32 h-32 bg-orange-600/15 rounded-full blur-2xl"></div>
            <div class="w-16 h-16 bg-gradient-to-tr from-orange-600 to-amber-500 text-white rounded-2xl flex items-center justify-center text-3xl font-black mx-auto mb-6 shadow-lg shadow-orange-600/30">G</div>
            <h2 class="text-xl font-extrabold text-slate-900 tracking-tight mb-1">GyanXp Master Suite</h2>
            <p class="text-slate-500 text-xs mb-8">Enter your secure credentials to access the tools portal</p>
            
            <div class="space-y-4 text-left">
                <div>
                    <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Login ID</label>
                    <input type="text" id="masterLoginId" placeholder="Enter Login ID" class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-3 text-sm text-slate-900 focus:outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500 transition-all">
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Password</label>
                    <input type="password" id="masterLoginPass" placeholder="Enter Password" onkeypress="handleMasterLoginKey(event)" class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-3 text-sm text-slate-900 focus:outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500 transition-all">
                </div>
            </div>

            <div id="masterLoginError" class="text-rose-600 text-xs font-semibold mt-3 hidden">Invalid Login ID or Password!</div>

            <button onclick="verifyMasterLogin()" class="w-full mt-6 bg-gradient-to-r from-orange-600 to-amber-600 hover:from-orange-500 hover:to-amber-500 text-white font-bold py-3 px-4 rounded-xl shadow-lg shadow-orange-600/25 transition-all text-sm tracking-wide cursor-pointer">
                Access Portal
            </button>
        </div>
    </div>

    <!-- Global Portal Selector Navigation Header -->
    <header class="bg-white/90 backdrop-blur-md border-b border-slate-200 shadow-sm sticky top-0 z-[99999]">
        <div class="max-w-7xl mx-auto px-4 py-3.5 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-gradient-to-tr from-orange-600 to-amber-500 text-white rounded-xl flex items-center justify-center text-lg font-black shadow-md shadow-orange-600/30">G</div>
                <div>
                    <h1 class="text-base font-extrabold tracking-tight text-slate-900 flex items-center gap-2">
                        GyanXp Unified Master Portal
                    </h1>
                    <p class="text-slate-500 text-xs">High-performance production tool suite for educational content</p>
                </div>
            </div>
            <div class="flex items-center gap-2 bg-slate-100 p-1.5 rounded-2xl border border-slate-200 shadow-inner">
                <button onclick="switchPortalTool(1)" id="portalNavBtn1" class="px-5 py-2.5 text-xs font-bold rounded-xl transition-all bg-orange-600 text-white shadow-lg shadow-orange-600/25 cursor-pointer">
                    Tool 1: MCQ Format Converter
                </button>
                <button onclick="switchPortalTool(2)" id="portalNavBtn2" class="px-5 py-2.5 text-xs font-bold rounded-xl transition-all text-slate-600 hover:text-slate-900 hover:bg-slate-200 cursor-pointer">
                    Tool 2: GyanXp Document Generator
                </button>
            </div>
        </div>
    </header>

    <!-- ================================================================= -->
    <!-- TOOL 1 CONTAINER (WITH CLIPBOARD PERMISSION ERROR FALLBACK)       -->
    <!-- ================================================================= -->
    <div id="portalContainerTool1" class="portal-tool-section active-portal-tool bg-slate-50 text-slate-800">
        <header class="bg-gradient-to-r from-orange-600 via-orange-500 to-amber-600 text-white shadow-md border-b border-orange-700/30">
            <div class="max-w-7xl mx-auto px-6 py-6 flex flex-col sm:flex-row justify-between items-center">
                <div>
                    <h2 class="text-2xl font-black tracking-tight text-white">MCQ Format Converter</h2>
                    <p class="text-orange-100 text-xs mt-1">Instant, error-free parsing and standardized export tool</p>
                </div>
                <div class="mt-3 sm:mt-0 bg-white/25 border border-white/30 px-4 py-1.5 rounded-full text-xs font-semibold text-white">
                    Version 4.6 Pro
                </div>
            </div>
        </header>

        <main class="max-w-7xl mx-auto px-6 py-8 flex-grow w-full grid grid-cols-1 lg:grid-cols-2 gap-8">
            <section class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6 flex flex-col">
                <h3 class="text-base font-bold text-slate-800 mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
                    Upload & Input Questions
                </h3>
                <div class="mb-6">
                    <label class="block text-xs font-semibold text-slate-600 mb-2 uppercase tracking-wider">Upload Word Document (.docx) or Text File (.txt)</label>
                    <div class="border-2 border-dashed border-slate-300 rounded-xl p-6 text-center hover:border-orange-500 transition-colors bg-slate-50 cursor-pointer relative group" id="dropzone">
                        <input type="file" id="fileInput" accept=".docx,.txt" class="absolute inset-0 opacity-0 cursor-pointer w-full h-full">
                        <svg class="mx-auto h-12 w-12 text-slate-400 group-hover:text-orange-500 transition-colors mb-2" stroke="currentColor" fill="none" viewBox="0 0 48 48"><path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                        <p class="text-sm text-slate-700 font-medium" id="fileNameDisplay">Drag & drop your file here, or <span class="text-orange-600 underline">browse</span></p>
                        <p class="text-xs text-slate-400 mt-1">Supports .docx and .txt formats</p>
                    </div>
                </div>

                <div id="t1StatsAndSelectionContainer" class="mb-4 p-4 bg-slate-50 border border-slate-200 rounded-xl hidden">
                    <div class="flex flex-wrap justify-between items-center gap-2 mb-3">
                        <div class="text-xs font-bold text-slate-700">
                            Uploaded Questions: <span id="t1TotalUploadedCount" class="text-orange-600 font-black text-sm">0</span> | 
                            Selected: <span id="t1SelectedCount" class="text-emerald-600 font-black text-sm">0</span>
                        </div>
                        <div class="flex gap-2">
                            <button type="button" onclick="t1ToggleSelectAll(true)" class="text-xs bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold px-2.5 py-1 rounded-lg">Select All</button>
                            <button type="button" onclick="t1ToggleSelectAll(false)" class="text-xs bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold px-2.5 py-1 rounded-lg">Deselect All</button>
                        </div>
                    </div>
                    <div id="t1CheckboxesGrid" class="flex flex-wrap gap-1.5 max-h-36 overflow-y-auto bg-white p-2.5 border border-slate-200 rounded-lg">
                        <!-- Checkboxes injected dynamically -->
                    </div>
                </div>

                <div class="flex-grow flex flex-col mb-4">
                    <div class="flex justify-between items-center mb-2">
                        <label for="rawInput" class="text-xs font-semibold text-slate-600 uppercase tracking-wider">Or Paste Raw Questions Text</label>
                        <button id="clearBtn" class="text-xs text-rose-600 hover:text-rose-700 font-semibold transition-colors cursor-pointer">Clear Text</button>
                    </div>
                    <textarea id="rawInput" rows="6" class="w-full flex-grow p-4 bg-slate-50 border border-slate-300 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-orange-500 text-sm font-mono leading-relaxed text-slate-800 placeholder-slate-400" placeholder="Q5. round(4.576)&#10;(A) 4.5&#10;(B) 4.6&#10;(C) 5&#10;(D) 4&#10;Answer: (C)"></textarea>
                </div>

                <button id="convertBtn" class="w-full bg-orange-600 hover:bg-orange-500 text-white font-bold py-3 px-4 rounded-xl transition-all shadow-lg shadow-orange-600/25 flex items-center justify-center gap-2 text-sm cursor-pointer">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"/></svg>
                    Convert to Standard Format
                </button>
            </section>

            <section class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6 flex flex-col">
                <h3 class="text-base font-bold text-slate-800 mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    Converted Output Format
                </h3>
                <div class="flex-grow flex flex-col mb-4">
                    <textarea id="outputArea" readonly rows="12" class="w-full flex-grow p-4 bg-slate-50 border border-slate-300 rounded-xl text-sm font-mono leading-relaxed text-slate-700 placeholder-slate-400" placeholder="Converted output will appear here..."></textarea>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <button id="copyBtn" class="bg-slate-800 hover:bg-slate-900 text-white font-semibold py-3 px-4 rounded-xl transition-all flex items-center justify-center gap-2 text-sm shadow-md border border-slate-700 cursor-pointer">
                        <svg class="w-4 h-4 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"/></svg>
                        Copy to Clipboard
                    </button>
                    <button id="downloadWordBtn" class="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-3 px-4 rounded-xl transition-all flex items-center justify-center gap-2 text-sm shadow-lg shadow-emerald-600/25 cursor-pointer">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                        Download as Word (.docx)
                    </button>
                </div>
                <div id="toast" class="mt-3 text-center text-xs text-emerald-600 font-semibold h-4 transition-opacity opacity-0"></div>
            </section>
        </main>

        <footer class="bg-white border-t border-slate-200 py-4 text-center text-xs text-slate-500 mt-auto">
            MCQ Format Converter &bull; Native Compatible Word Document Generator
        </footer>
    </div>


    <!-- ================================================================= -->
    <!-- TOOL 2 CONTAINER (EXACTLY UNCHANGED & PRESERVED)                  -->
    <!-- ================================================================= -->
    <div id="portalContainerTool2" class="portal-tool-section bg-slate-50 text-slate-900" style="padding: 30px 20px;">
        <div id="t2ScopedRoot" style="width: 100%; max-width: 1050px; margin: auto;">
            <div id="t2AppContent" style="display: flex; flex-direction: column; gap: 24px;">
                <div class="analysis-dashboard">
                    <div class="dashboard-metric-card">
                        <div class="dashboard-metric-title">Total Questions</div>
                        <div class="dashboard-metric-value" id="t2DashTotalQ">0</div>
                    </div>
                    <div class="dashboard-metric-card">
                        <div class="dashboard-metric-title">Selected Questions</div>
                        <div class="dashboard-metric-value" id="t2DashSelectedQ">0</div>
                    </div>
                    <div class="dashboard-metric-card">
                        <div class="dashboard-metric-title">Generated Sets</div>
                        <div class="dashboard-metric-value" id="t2DashTotalSets">1</div>
                    </div>
                    <div class="dashboard-metric-card">
                        <div class="dashboard-metric-title">Total Slides / Pages</div>
                        <div class="dashboard-metric-value" id="t2DashTotalSlides">0</div>
                    </div>
                </div>

                <div class="card">
                    <div class="brand-header">
                        <div class="brand-logo-circle">G</div>
                        <div>
                            <h2>GyanXp Unified Document Generator</h2>
                            <div style="font-size: 12px; color: var(--text-muted); font-weight: 500;">अपनी Online Class - Pro Programming & Test Series Suite with Smart Auto-Option Parser</div>
                        </div>
                    </div>

                    <div class="category-section">
                        <div class="category-title">📁 File & Assets Upload</div>
                        <div class="row">
                            <div class="form-group">
                                <label>Upload Word File (.docx with Tables & Images)</label>
                                <input type="file" id="t2DocFileInput" accept=".docx" onchange="t2HandleFileUploaded(event)">
                                <div id="t2FileInfoBadge" class="file-info-badge" style="display: none;"></div>
                            </div>
                            <div class="form-group">
                                <label>Background Image <span class="badge">Optional</span></label>
                                <input type="file" id="t2BgImageInput" accept="image/*">
                            </div>
                        </div>
                        
                        <div class="row" style="margin-top: 16px; display: none;" id="t2ManualSelectionWrapper">
                            <div class="form-group" style="flex: 1;">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                                    <label style="margin-bottom: 0;">Select Specific Questions (<span id="t2SelectedCountDisplay">0</span> Selected)</label>
                                    <div style="display: flex; gap: 8px;">
                                        <button type="button" class="nav-btn" onclick="t2ToggleSelectAllManual(true)" style="padding: 4px 10px; font-size: 11px;">Select All</button>
                                        <button type="button" class="nav-btn" onclick="t2ToggleSelectAllManual(false)" style="padding: 4px 10px; font-size: 11px;">Deselect All</button>
                                    </div>
                                </div>
                                <div id="t2QuestionCheckboxesGrid" style="display: flex; flex-wrap: wrap; gap: 8px; max-height: 160px; overflow-y: auto; background: #fff; padding: 12px; border: 1.5px solid var(--border-color); border-radius: 10px; box-sizing: border-box;">
                                    <span style="font-size: 13px; color: var(--text-muted);">Please upload a word file first to view question numbers.</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="category-section">
                        <div class="category-title">🎯 Document Output Formatting Mode</div>
                        <div class="row">
                            <div class="form-group">
                                <label>Select Output Format Style</label>
                                <select id="t2FormattingMode" onchange="t2RenderSlidePreview()">
                                    <option value="standard" selected>Standard MCQ & Programming Presentation</option>
                                    <option value="test_series">Test Series Format (With Detailed Solution)</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="category-section">
                        <div class="category-title">💻 Programming Code Block Styling</div>
                        <div class="row">
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2EnableCodeHighlight" checked onchange="t2RenderSlidePreview()">
                                    <label for="t2EnableCodeHighlight">Enable Code Highlight</label>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2EnableSyntaxHighlighter" checked onchange="t2RenderSlidePreview()">
                                    <label for="t2EnableSyntaxHighlighter">Enable Syntax Highlighter</label>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2EnableCodeBorder" checked onchange="t2RenderSlidePreview()">
                                    <label for="t2EnableCodeBorder">Enable Code Block Border</label>
                                </div>
                            </div>
                        </div>
                        <div class="row" style="margin-top: 16px;">
                            <div class="form-group">
                                <label>Code Border Corner Style</label>
                                <select id="t2CodeBorderShape" onchange="t2RenderSlidePreview()">
                                    <option value="rounded" selected>Rounded Corners</option>
                                    <option value="rectangle">Rectangle (Sharp Corners)</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Code Block Color</label>
                                <input type="color" id="t2CodeBlockBgColor" class="sm-picker" value="#f8fafc" style="width: 100%; height: 44px;" onchange="t2RenderSlidePreview()">
                            </div>
                            <div class="form-group">
                                <label>Code Block Opacity (0.0 to 1.0)</label>
                                <input type="number" id="t2CodeBlockOpacity" value="1.0" step="0.05" min="0" max="1" oninput="t2RenderSlidePreview()">
                            </div>
                        </div>
                    </div>

                    <div class="category-section">
                        <div class="category-title">⚙️ Structure & Sets Configuration</div>
                        <div class="row">
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2EnableSetWise" onchange="t2RenderSlidePreview()">
                                    <label for="t2EnableSetWise">Create Set-wise Questions</label>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Questions Per Set</label>
                                <input type="number" id="t2QuestionsPerSet" value="10" min="1" max="500" oninput="t2RenderSlidePreview()">
                            </div>
                        </div>
                        <div class="row" style="margin-top: 16px;">
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2HideOptions" onchange="t2RenderSlidePreview()">
                                    <label for="t2HideOptions">hide questions's option</label>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2IncludeAnswerKey" checked onchange="t2RenderSlidePreview()">
                                    <label for="t2IncludeAnswerKey">Include Answer Key at the end (Max 100 Q/Table)</label>
                                </div>
                            </div>
                        </div>
                        <div class="row" style="margin-top: 16px;">
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2ShowAnswerOnSlide" onchange="t2RenderSlidePreview()">
                                    <label for="t2ShowAnswerOnSlide">Show Answer After Question</label>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="checkbox-card">
                                    <input type="checkbox" id="t2ShowSolutionOnSlide" checked onchange="t2RenderSlidePreview()">
                                    <label for="t2ShowSolutionOnSlide">Show Detailed Solution</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="category-section">
                        <div class="category-title">📐 Layout & Pagination Settings</div>
                        <div class="row">
                            <div class="form-group">
                                <label>Target Questions Per Page</label>
                                <select id="t2QuestionsPerPage" onchange="t2RenderSlidePreview()">
                                    <option value="auto">Auto (Smart Fit based on Font Size)</option>
                                    <option value="1" selected>1 Question Per Page</option>
                                    <option value="2">2 Questions Per Page</option>
                                    <option value="3">3 Questions Per Page</option>
                                    <option value="4">4 Questions Per Page</option>
                                    <option value="5">5 Questions Per Page</option>
                                    <option value="6">6 Questions Per Page</option>
                                    <option value="7">7 Questions Per Page</option>
                                    <option value="8">8 Questions Per Page</option>
                                    <option value="9">9 Questions Per Page</option>
                                    <option value="10">10 Questions Per Page</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Page Columns Layout</label>
                                <select id="t2ColumnLayout" onchange="t2RenderSlidePreview()">
                                    <option value="1" selected>1 Column (Single View)</option>
                                    <option value="2">2 Columns (Continuous Flow)</option>
                                    <option value="3">3 Columns (Continuous Flow)</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Question Spacing (Line Space, px/pt)</label>
                                <input type="number" id="t2QuestionSpacing" value="12" min="0" max="100" oninput="t2RenderSlidePreview()">
                            </div>
                        </div>
                        <div class="row" style="margin-top: 16px;">
                            <div class="form-group">
                                <label>Page Size Format</label>
                                <select id="t2PageSize" onchange="t2RenderSlidePreview()">
                                    <option value="hd" selected>Full HD / Presentation (16:9 / 9:16)</option>
                                    <option value="a4">A4 Size</option>
                                    <option value="a3">A3 Size</option>
                                    <option value="letter">US Letter</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Page Orientation</label>
                                <select id="t2Orientation" onchange="t2HandleOrientationChange()">
                                    <option value="landscape" selected>Landscape (Horizontal)</option>
                                    <option value="portrait">Portrait (Vertical)</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Resolution Quality (HD Mode)</label>
                                <select id="t2ResolutionQuality" onchange="t2RenderSlidePreview()">
                                    <option value="1080p" selected>Full HD (1080p)</option>
                                    <option value="720p">Standard (720p)</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="category-section">
                        <div class="category-title">🎨 Typography & Styling Preferences</div>
                        <div class="row">
                            <div class="form-group">
                                <label>Font Type Selection</label>
                                <select id="t2FontFamily" onchange="t2RenderSlidePreview()">
                                    <option value="Noto Sans Devanagari" selected>Noto Sans Devanagari (Best Hindi Support)</option>
                                    <option value="Arial">Arial</option>
                                    <option value="Helvetica">Helvetica</option>
                                    <option value="Roboto">Roboto</option>
                                    <option value="Poppins">Poppins</option>
                                    <option value="Montserrat">Montserrat</option>
                                    <option value="Times New Roman">Times New Roman</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Question Font Size (pt)</label>
                                <input type="number" id="t2BaseFontSize" value="45" min="8" max="120" oninput="t2RenderSlidePreview()">
                            </div>
                            <div class="form-group">
                                <label>Bold Style Mode</label>
                                <select id="t2BoldStyleMode" onchange="t2RenderSlidePreview()">
                                    <option value="all" selected>Bold All (Default)</option>
                                    <option value="questions_only">Bold Questions Only</option>
                                    <option value="questions_and_options">Bold Questions & Options Both</option>
                                </select>
                            </div>
                        </div>

                        <div class="row" style="margin-top: 16px;">
                            <div class="form-group">
                                <label>Color Theme Preset</label>
                                <select id="t2ColorThemePreset" onchange="t2ApplyColorPreset()">
                                    <option value="custom" selected>Custom Colors</option>
                                    <option value="light">Light Theme Preset (For Dark BG)</option>
                                    <option value="dark">Dark Theme Preset (For Light BG)</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group" style="margin-top: 16px;">
                            <div class="section-title" style="margin-bottom: 8px;">
                                Text Color Palette
                                <button class="reset-btn" onclick="t2ResetDefaultColors()">Reset Colors</button>
                            </div>
                            <div class="grid-4">
                                <div class="color-picker-wrapper">
                                    <input type="color" id="t2HindiColor" class="sm-picker" value="#FF6B00" onchange="t2OnColorInputChanged()">
                                    <span>Hindi Q</span>
                                </div>
                                <div class="color-picker-wrapper">
                                    <input type="color" id="t2EnglishColor" class="sm-picker" value="#000000" onchange="t2OnColorInputChanged()">
                                    <span>English Q</span>
                                </div>
                                <div class="color-picker-wrapper">
                                    <input type="color" id="t2OptionsColor" class="sm-picker" value="#000000" onchange="t2OnColorInputChanged()">
                                    <span>Options</span>
                                </div>
                                <div class="color-picker-wrapper">
                                    <input type="color" id="t2AnswerKeyColor" class="sm-picker" value="#1e293b" onchange="t2OnColorInputChanged()">
                                    <span>Answer Key</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="category-section" style="margin-bottom: 0;">
                        <div class="category-title">📏 Range & Page Margins</div>
                        <div class="row">
                            <div class="form-group">
                                <label>Question Range (Start - End)</label>
                                <div class="row">
                                    <input type="number" id="t2QStart" placeholder="From (e.g. 1)" min="1">
                                    <input type="number" id="t2QEnd" placeholder="To (e.g. 136)" min="1">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Page Margins (px/pt) <span class="badge" id="t2MarginNotice">Synchronized</span></label>
                                <div class="grid-4">
                                    <div><label style="font-size:10px; margin-bottom:2px;">Top</label><input type="number" id="t2MarginTop" value="120" min="0" oninput="t2RenderSlidePreview()"></div>
                                    <div><label style="font-size:10px; margin-bottom:2px;">Right</label><input type="number" id="t2MarginRight" value="30" min="0" oninput="t2RenderSlidePreview()"></div>
                                    <div><label style="font-size:10px; margin-bottom:2px;">Bottom</label><input type="number" id="t2MarginBottom" value="30" min="0" oninput="t2RenderSlidePreview()"></div>
                                    <div><label style="font-size:10px; margin-bottom:2px;">Left</label><input type="number" id="t2MarginLeft" value="120" min="0" oninput="t2RenderSlidePreview()"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="btn-group">
                        <button onclick="t2GenerateSlides()">Generate Presentation & Preview</button>
                    </div>
                </div>

                <div class="card" id="t2PreviewContainer">
                    <h2>Slide Document Interactive Preview</h2>
                    <div class="slide-viewport">
                        <div id="t2SlideStage" class="slide-canvas"></div>
                    </div>
                    <div class="preview-controls">
                        <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                            <button class="nav-btn" onclick="t2PrevSlide()">Previous</button>
                            <span id="t2SlideIndicator" style="font-weight: 600; font-size: 13px;">Slide 1 of 1</span>
                            <button class="nav-btn" onclick="t2NextSlide()">Next</button>
                            <div style="display: flex; align-items: center; gap: 4px; margin-left: 8px;">
                                <span style="font-size: 12px; font-weight: 600; color: var(--text-muted);">Go to:</span>
                                <input type="number" id="t2JumpPageInput" min="1" value="1" style="width: 55px; padding: 7px; text-align: center; border: 1.5px solid var(--border-color); border-radius: 8px; font-size: 13px;" title="Jump to slide">
                                <button class="nav-btn" onclick="t2JumpToSlide()" style="padding: 7px 14px;">Go</button>
                            </div>
                        </div>
                        <div style="display: flex; gap: 10px; flex-wrap: wrap;" id="t2DownloadActionButtons">
                            <button class="secondary" onclick="t2DownloadPDF()">Download PDF File</button>
                            <button class="secondary" onclick="t2DownloadDOCX(false)">Download Word File (Normal)</button>
                            <button class="secondary" onclick="t2DownloadDOCX(true)">Download Word File (Compatibility)</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div id="t2PrintSection" style="display: none;"></div>
    </div>


    <!-- Master Portal Switcher & Global Login Handler Script -->
    <script>
        function verifyMasterLogin() {
            const enteredId = document.getElementById('masterLoginId').value.trim();
            const enteredPass = document.getElementById('masterLoginPass').value.trim();
            const errorMsg = document.getElementById('masterLoginError');

            if (enteredId === 'gxpmcq' && enteredPass === 'mcq@gxp') {
                document.getElementById('masterLoginOverlay').style.display = 'none';
                t2HandleOrientationChange();
            } else {
                errorMsg.classList.remove('hidden');
            }
        }

        function handleMasterLoginKey(e) {
            if (e.key === 'Enter') {
                verifyMasterLogin();
            }
        }

        function switchPortalTool(toolNumber) {
            const t1Div = document.getElementById('portalContainerTool1');
            const t2Div = document.getElementById('portalContainerTool2');
            const btn1 = document.getElementById('portalNavBtn1');
            const btn2 = document.getElementById('portalNavBtn2');

            if (toolNumber === 1) {
                t1Div.classList.add('active-portal-tool');
                t2Div.classList.remove('active-portal-tool');
                btn1.className = "px-5 py-2.5 text-xs font-bold rounded-xl transition-all bg-orange-600 text-white shadow-lg shadow-orange-600/25 cursor-pointer";
                btn2.className = "px-5 py-2.5 text-xs font-bold rounded-xl transition-all text-slate-600 hover:text-slate-900 hover:bg-slate-200 cursor-pointer";
            } else {
                t2Div.classList.add('active-portal-tool');
                t1Div.classList.remove('active-portal-tool');
                btn2.className = "px-5 py-2.5 text-xs font-bold rounded-xl transition-all bg-orange-600 text-white shadow-lg shadow-orange-600/25 cursor-pointer";
                btn1.className = "px-5 py-2.5 text-xs font-bold rounded-xl transition-all text-slate-600 hover:text-slate-900 hover:bg-slate-200 cursor-pointer";
            }
        }
    </script>


    <!-- ================================================================= -->
    <!-- TOOL 1 SCRIPT LOGIC (WITH SAFE CLIPBOARD FALLBACK)                -->
    <!-- ================================================================= -->
    <script>
        const fileInput = document.getElementById('fileInput');
        const fileNameDisplay = document.getElementById('fileNameDisplay');
        const rawInput = document.getElementById('rawInput');
        const outputArea = document.getElementById('outputArea');
        const convertBtn = document.getElementById('convertBtn');
        const clearBtn = document.getElementById('clearBtn');
        const copyBtn = document.getElementById('copyBtn');
        const downloadWordBtn = document.getElementById('downloadWordBtn');
        const toast = document.getElementById('toast');

        let t1GlobalQuestionsList = [];

        function showToast(message) {
            toast.textContent = message;
            toast.classList.remove('opacity-0');
            setTimeout(() => {
                toast.classList.add('opacity-0');
            }, 3000);
        }

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            fileNameDisplay.textContent = `Selected: ${file.name}`;
            const fileExtension = file.name.split('.').pop().toLowerCase();

            if (fileExtension === 'txt') {
                const reader = new FileReader();
                reader.onload = (event) => {
                    rawInput.value = event.target.result;
                    processTextForTool1(event.target.result);
                    showToast('Text file loaded successfully!');
                };
                reader.readAsText(file);
            } else if (fileExtension === 'docx') {
                const reader = new FileReader();
                reader.onload = async (event) => {
                    try {
                        const arrayBuffer = event.target.result;
                        const result = await mammoth.extractRawText({ arrayBuffer: arrayBuffer });
                        rawInput.value = result.value;
                        processTextForTool1(result.value);
                        showToast('Word (.docx) loaded successfully!');
                    } catch (err) {
                        console.error(err);
                        alert('Error parsing Word document. Please ensure it is a valid .docx file.');
                    }
                };
                reader.readAsArrayBuffer(file);
            } else {
                alert('Unsupported file format. Please upload .docx or .txt files.');
            }
        });

        rawInput.addEventListener('input', () => {
            if (rawInput.value.trim()) {
                processTextForTool1(rawInput.value);
            } else {
                document.getElementById('t1StatsAndSelectionContainer').classList.add('hidden');
                t1GlobalQuestionsList = [];
            }
        });

        clearBtn.addEventListener('click', () => {
            rawInput.value = '';
            outputArea.value = '';
            fileInput.value = '';
            fileNameDisplay.innerHTML = `Drag & drop your file here, or <span class="text-orange-600 underline">browse</span>`;
            document.getElementById('t1StatsAndSelectionContainer').classList.add('hidden');
            t1GlobalQuestionsList = [];
        });

        function parseQuestionsToObjects(text) {
            if (!text.trim()) return [];
            const rawLines = text.split(/\r?\n/).map(l => l.replace(/\t/g, '    '));
            let questions = [];
            let currentQ = null;

            const qRegex = /^(?:Q\.?\s*|Question\s*)(\d+)[\.\)]\s*(.*)$/i;
            const explicitOptRegex = /^\(?([A-D])\)?[\.\)]\s*(.*)$/i;
            const answerRegex = /^(?:Answer|Ans)[:\s\-]*\(?([A-D])\)?(.*)$/i;

            for (let i = 0; i < rawLines.length; i++) {
                let line = rawLines[i];
                let trimmedLine = line.trim();
                if (!trimmedLine) continue;

                let qMatch = trimmedLine.match(qRegex);
                if (qMatch) {
                    if (currentQ) questions.push(currentQ);
                    currentQ = {
                        number: qMatch[1],
                        linesPool: [qMatch[2]],
                        explicitAnswer: ''
                    };
                    continue;
                }

                let ansMatch = trimmedLine.match(answerRegex);
                if (ansMatch && currentQ) {
                    currentQ.explicitAnswer = ansMatch[1].toUpperCase();
                    continue;
                }

                if (currentQ) {
                    if (!currentQ.explicitAnswer && /^ans/i.test(trimmedLine)) {
                        let cleanAns = trimmedLine.replace(/[^A-D]/gi, '').toUpperCase();
                        if (cleanAns) currentQ.explicitAnswer = cleanAns[0];
                        continue;
                    }
                    currentQ.linesPool.push(line);
                } else {
                    currentQ = {
                        number: '1',
                        linesPool: [line],
                        explicitAnswer: ''
                    };
                }
            }
            if (currentQ) questions.push(currentQ);
            return questions;
        }

        function processTextForTool1(text) {
            t1GlobalQuestionsList = parseQuestionsToObjects(text);
            const container = document.getElementById('t1StatsAndSelectionContainer');
            const totalCountEl = document.getElementById('t1TotalUploadedCount');
            const grid = document.getElementById('t1CheckboxesGrid');

            if (t1GlobalQuestionsList.length > 0) {
                container.classList.remove('hidden');
                totalCountEl.innerText = t1GlobalQuestionsList.length;

                let gridHtml = '';
                t1GlobalQuestionsList.forEach((q, idx) => {
                    let qNum = idx + 1;
                    gridHtml += `
                        <label class="inline-flex items-center gap-1 bg-white px-2 py-1 border border-slate-200 rounded text-xs font-semibold cursor-pointer">
                            <input type="checkbox" class="t1-q-cb" value="${idx}" checked onchange="t1UpdateSelectedCount()" style="accent-color: var(--primary-orange);">
                            Q${qNum}
                        </label>
                    `;
                });
                grid.innerHTML = gridHtml;
                t1UpdateSelectedCount();
            } else {
                container.classList.add('hidden');
            }
        }

        function t1UpdateSelectedCount() {
            const checkedBoxes = document.querySelectorAll('.t1-q-cb:checked');
            const countEl = document.getElementById('t1SelectedCount');
            if (countEl) countEl.innerText = checkedBoxes.length;
        }

        function t1ToggleSelectAll(state) {
            const checkboxes = document.querySelectorAll('.t1-q-cb');
            checkboxes.forEach(cb => cb.checked = state);
            t1UpdateSelectedCount();
        }

        function parseAndConvertMCQs(text) {
            let allParsedQs = parseQuestionsToObjects(text);
            if (allParsedQs.length === 0) return '';

            const checkedBoxes = document.querySelectorAll('.t1-q-cb');
            let allowedIndices = [];
            if (checkedBoxes.length > 0) {
                checkedBoxes.forEach(cb => {
                    if (cb.checked) allowedIndices.push(parseInt(cb.value));
                });
            } else {
                allowedIndices = allParsedQs.map((_, idx) => idx);
            }

            let questions = allParsedQs.filter((_, idx) => allowedIndices.includes(idx));
            if (questions.length === 0) return '';

            let formattedOutput = [];
            questions.forEach((q, idx) => {
                let qNum = idx + 1;
                let pool = q.linesPool;

                let parsedOptions = [];
                let tempLines = [...pool];
                const explicitOptRegex = /^\(?([A-D])\)?[\.\)]\s*(.*)$/i;

                while (tempLines.length > 0) {
                    let lastLine = tempLines[tempLines.length - 1].trim();
                    let optM = lastLine.match(explicitOptRegex);
                    if (optM) {
                        parsedOptions.unshift({ letter: optM[1].toUpperCase(), text: optM[2].trim() });
                        tempLines.pop();
                    } else {
                        break;
                    }
                }

                if (parsedOptions.length > 0) {
                    pool = tempLines;
                } else if (pool.length >= 5) {
                    let potentialOpts = pool.splice(pool.length - 4, 4);
                    const letters = ['A', 'B', 'C', 'D'];
                    parsedOptions = potentialOpts.map((o, oIdx) => ({
                        letter: letters[oIdx],
                        text: o.trim().replace(/^\(?([A-D])\)?[\.\)]\s*/i, '')
                    }));
                }

                let questionTextLines = pool;

                if (questionTextLines.length > 0) {
                    formattedOutput.push(`${qNum}. ${questionTextLines[0].trim()}`);
                    for (let i = 1; i < questionTextLines.length; i++) {
                        formattedOutput.push(questionTextLines[i]);
                    }
                } else {
                    formattedOutput.push(`${qNum}. Question text missing`);
                }

                ['A', 'B', 'C', 'D'].forEach((optKey) => {
                    let foundOpt = parsedOptions.find(o => o.letter === optKey);
                    let optText = foundOpt ? foundOpt.text : `Option ${optKey}`;
                    formattedOutput.push(`${optKey}. ${optText}`);
                });

                let finalAns = q.explicitAnswer ? q.explicitAnswer : 'A';
                formattedOutput.push(`Answer ${finalAns}`);
                formattedOutput.push('');
            });

            return formattedOutput.join('\n').trim();
        }

        convertBtn.addEventListener('click', () => {
            const rawText = rawInput.value;
            if (!rawText.trim()) {
                alert('Please paste some text or upload a file first.');
                return;
            }
            const converted = parseAndConvertMCQs(rawText);
            outputArea.value = converted;
            showToast('Converted successfully!');
        });

        // FIXED CLIPBOARD COPY WITH FALLBACK (NO PERMISSION ERROR)
        copyBtn.addEventListener('click', () => {
            const textToCopy = outputArea.value;
            if (!textToCopy.trim()) {
                alert('No output to copy!');
                return;
            }

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(textToCopy).then(() => {
                    showToast('Copied to clipboard!');
                }).catch(() => {
                    fallbackCopyTextToClipboard(textToCopy);
                });
            } else {
                fallbackCopyTextToClipboard(textToCopy);
            }
        });

        function fallbackCopyTextToClipboard(text) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.position = "fixed";  // Avoid scrolling to bottom
            textArea.style.top = "0";
            textArea.style.left = "0";
            textArea.style.opacity = "0";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showToast('Copied to clipboard!');
                } else {
                    alert('Unable to copy. Please select and copy manually.');
                }
            } catch (err) {
                alert('Browser does not support automatic copying.');
            }
            document.body.removeChild(textArea);
        }

        downloadWordBtn.addEventListener('click', async () => {
            const text = outputArea.value;
            if (!text.trim()) {
                alert('No converted output available to download.');
                return;
            }

            try {
                if (window.docx) {
                    const { Document, Packer, Paragraph, TextRun } = window.docx;
                    const lines = text.split('\n');
                    const children = lines.map(line => {
                        if (line.trim() === '') {
                            return new Paragraph({ spacing: { after: 120 } });
                        }
                        return new Paragraph({
                            children: [
                                new TextRun({
                                    text: line,
                                    font: "Calibri",
                                    size: 22 // 11pt
                                })
                            ],
                            spacing: { after: 80 }
                        });
                    });

                    const doc = new Document({
                        sections: [{
                            properties: {},
                            children: children
                        }]
                    });

                    const blob = await Packer.toBlob(doc);
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'Converted_MCQs.docx';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    showToast('Word document downloaded successfully!');
                    return;
                }
            } catch (e) {
                console.warn('Native docx fallback triggered:', e);
            }

            const htmlContent = `
                <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
                <head><meta charset='utf-8'><title>Converted MCQs</title></head>
                <body style='font-family: Calibri, sans-serif; font-size: 11pt;'>
                ${text.split('\n').map(line => line.trim() === '' ? '<br/>' : `<p style='margin: 0 0 4pt 0;'>${line}</p>`).join('')}
                </body>
                </html>
            `;
            const blob = new Blob(['\ufeff' + htmlContent], { type: 'application/msword' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'Converted_MCQs.doc';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            showToast('Word document downloaded successfully!');
        });
    </script>


    <!-- ================================================================= -->
    <!-- TOOL 2 SCRIPT LOGIC (EXACTLY UNCHANGED & PRESERVED)                  -->
    <!-- ================================================================= -->
    <script>
        let t2ActiveBgJpegDataUrl = null;
        let t2RawBgData = null;
        let t2MasterSlides = [];
        let t2CurrentSlideIndex = 0;
        let t2CurrentFilteredQuestions = [];
        let t2GlobalParsedQuestions = [];

        function t2UnescapeHtml(str) {
            if (!str) return '';
            const parser = new DOMParser();
            return parser.parseFromString(str, 'text/html').body.textContent;
        }

        function t2EscapeHtml(str) {
            if (!str) return '';
            let unescaped = t2UnescapeHtml(str);
            return unescaped
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function t2UpdateDashboardMetrics() {
            const totalQEl = document.getElementById('t2DashTotalQ');
            const selectedQEl = document.getElementById('t2DashSelectedQ');
            const totalSetsEl = document.getElementById('t2DashTotalSets');
            const totalSlidesEl = document.getElementById('t2DashTotalSlides');

            if (totalQEl) totalQEl.innerText = t2GlobalParsedQuestions.length || 0;
            if (selectedQEl) selectedQEl.innerText = t2CurrentFilteredQuestions.length || 0;

            const enableSetWise = document.getElementById('t2EnableSetWise').checked;
            const questionsPerSet = parseInt(document.getElementById('t2QuestionsPerSet').value) || 10;
            
            let totalSets = 1;
            if (enableSetWise && t2CurrentFilteredQuestions.length > 0) {
                totalSets = Math.ceil(t2CurrentFilteredQuestions.length / questionsPerSet);
            }
            if (totalSetsEl) totalSetsEl.innerText = totalSets;
            if (totalSlidesEl) totalSlidesEl.innerText = t2MasterSlides.length || 0;
        }

        function t2HandleOrientationChange() {
            t2RenderSlidePreview();
        }

        function t2ApplyColorPreset() {
            const preset = document.getElementById('t2ColorThemePreset').value;
            if (preset === 'light') {
                document.getElementById('t2HindiColor').value = "#FFFFFF";
                document.getElementById('t2EnglishColor').value = "#FFFFFF";
                document.getElementById('t2OptionsColor').value = "#FFFFFF";
                document.getElementById('t2AnswerKeyColor').value = "#FFFFFF";
            } else if (preset === 'dark') {
                document.getElementById('t2HindiColor').value = "#000000";
                document.getElementById('t2EnglishColor').value = "#000000";
                document.getElementById('t2OptionsColor').value = "#000000";
                document.getElementById('t2AnswerKeyColor').value = "#000000";
            }
            const previewContainer = document.getElementById('t2PreviewContainer');
            if (previewContainer && previewContainer.style.display === 'block') {
                t2RenderSlidePreview();
            }
        }

        function t2OnColorInputChanged() {
            document.getElementById('t2ColorThemePreset').value = 'custom';
            t2RenderSlidePreview();
        }

        function t2ResetDefaultColors() {
            document.getElementById('t2ColorThemePreset').value = 'custom';
            document.getElementById('t2HindiColor').value = "#FF6B00";
            document.getElementById('t2EnglishColor').value = "#000000";
            document.getElementById('t2OptionsColor').value = "#000000";
            document.getElementById('t2AnswerKeyColor').value = "#1e293b";
            const previewContainer = document.getElementById('t2PreviewContainer');
            if (previewContainer && previewContainer.style.display === 'block') {
                t2RenderSlidePreview();
            }
        }

        document.getElementById('t2BgImageInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(evt) {
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);
                        t2ActiveBgJpegDataUrl = canvas.toDataURL('image/jpeg', 0.95);
                        t2RawBgData = {
                            base64: t2ActiveBgJpegDataUrl.split(',')[1],
                            width: img.width,
                            height: img.height
                        };
                        const previewContainer = document.getElementById('t2PreviewContainer');
                        if (previewContainer && previewContainer.style.display === 'block') {
                            t2RenderSlidePreview();
                        }
                    };
                    img.src = evt.target.result;
                };
                reader.readAsDataURL(file);
            } else {
                t2ActiveBgJpegDataUrl = null;
                t2RawBgData = null;
            }
        });

        function t2GetActiveDimensions() {
            const pageSize = document.getElementById('t2PageSize').value;
            const orientation = document.getElementById('t2Orientation').value;
            const isLandscape = (orientation === 'landscape');

            if (pageSize === 'a4') {
                return isLandscape ? { width: 842, height: 595 } : { width: 595, height: 842 };
            } else if (pageSize === 'a3') {
                return isLandscape ? { width: 1190, height: 842 } : { width: 842, height: 1190 };
            } else if (pageSize === 'letter') {
                return isLandscape ? { width: 792, height: 612 } : { width: 612, height: 792 };
            } else {
                const res = document.getElementById('t2ResolutionQuality').value;
                if (isLandscape) {
                    return res === '720p' ? { width: 1280, height: 720 } : { width: 1920, height: 1080 };
                } else {
                    return res === '720p' ? { width: 720, height: 1280 } : { width: 1080, height: 1920 };
                }
            }
        }

        function t2GetPortraitBaseDimensions() {
            const pageSize = document.getElementById('t2PageSize').value;
            if (pageSize === 'a4') return { width: 595, height: 842 };
            if (pageSize === 'a3') return { width: 842, height: 1190 };
            if (pageSize === 'letter') return { width: 612, height: 792 };
            const res = document.getElementById('t2ResolutionQuality').value;
            return res === '720p' ? { width: 720, height: 1280 } : { width: 1080, height: 1920 };
        }

        function t2CreateDefaultBgCanvas(width, height) {
            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, width, height);
            ctx.strokeStyle = '#e2e8f0';
            ctx.lineWidth = 4;
            ctx.strokeRect(40, 40, width - 80, height - 80);
            ctx.fillStyle = '#FF6B00';
            ctx.font = 'bold 36px Inter, sans-serif';
            ctx.fillText('GyanXp Academy', 80, 100);
            ctx.fillStyle = '#64748b';
            ctx.font = '24px Inter, sans-serif';
            ctx.fillText('GyanXp. All Rights Reserved.', 80, height - 60);
            return canvas.toDataURL('image/jpeg', 0.92);
        }

        function t2ParseDocx(file) {
            return file.arrayBuffer().then(arrayBuffer => {
                let currentImgBase64 = null;
                const options = {
                    convertImage: mammoth.images.imgElement(function(image) {
                        return image.read("base64").then(function(imageBuffer) {
                            currentImgBase64 = `data:${image.contentType};base64,${imageBuffer}`;
                            return { src: currentImgBase64 };
                        });
                    })
                };
                return mammoth.convertToHtml({ arrayBuffer: arrayBuffer }, options).then(result => {
                    const html = result.value;
                    const parser = new DOMParser();
                    const docHtml = parser.parseFromString(html, 'text/html');

                    const elements = Array.from(docHtml.querySelectorAll('p, td, li, pre'));
                    let qMap = {};
                    let activeQNum = null;

                    elements.forEach(el => {
                        let txt = t2UnescapeHtml(el.textContent || '').trim();
                        let match = txt.match(/^Q(\d+)\./i);
                        if (match) {
                            activeQNum = parseInt(match[1]);
                            if (!qMap[activeQNum]) {
                                qMap[activeQNum] = { images: [] };
                            }
                        }
                        if (activeQNum) {
                            let imgs = el.querySelectorAll('img');
                            imgs.forEach(img => {
                                if (img.src && !qMap[activeQNum].images.includes(img.src)) {
                                    qMap[activeQNum].images.push(img.src);
                                }
                            });
                        }
                    });

                    const rawLines = [];
                    elements.forEach(el => {
                        let inner = el.innerHTML || '';
                        inner = inner.replace(/<br\s*[\/]?>/gi, '\n');
                        const tmpDiv = document.createElement('div');
                        tmpDiv.innerHTML = inner;
                        
                        let textContent = tmpDiv.textContent || tmpDiv.innerText || '';
                        let linesArr = textContent.split(/\r?\n/);
                        linesArr.forEach(l => {
                            rawLines.push(l);
                        });
                    });

                    const filteredLines = rawLines.filter(l => l.trim().length > 0);

                    const rawQuestions = [];
                    let currentQ = null;
                    let currentLines = [];

                    filteredLines.forEach(l => {
                        const qMatch = l.trim().match(/^Q(\d+)\.\s*(.*)/i);
                        if (qMatch) {
                            if (currentQ) {
                                currentQ.rawLines = currentLines;
                                rawQuestions.push(currentQ);
                            }
                            const qNum = parseInt(qMatch[1]);
                            currentQ = {
                                num: qNum,
                                hindiQ: '',
                                englishQ: '',
                                codeBlock: '',
                                statements: [],
                                options: [],
                                answer: '',
                                image: (qMap[qNum] && qMap[qNum].images && qMap[qNum].images.length > 0) ? qMap[qNum].images[0] : null
                            };
                            currentLines = [qMatch[2]];
                        } else if (currentQ) {
                            currentLines.push(l);
                        }
                    });
                    if (currentQ) {
                        currentQ.rawLines = currentLines;
                        rawQuestions.push(currentQ);
                    }

                    const questions = [];

                    rawQuestions.forEach(q => {
                        let linesList = q.rawLines;
                        let ansIndex = -1;
                        for (let i = 0; i < linesList.length; i++) {
                            if (/^(?:Answer|उत्तर)\s*[:\-]?\s*(.*)/i.test(linesList[i].trim())) {
                                ansIndex = i;
                                const m = linesList[i].match(/^(?:Answer|उत्तर)\s*[:\-]?\s*(.*)/i);
                                q.answer = m[1].trim();
                                break;
                            }
                        }

                        if (ansIndex === -1) ansIndex = linesList.length;
                        let preAnswerLines = linesList.slice(0, ansIndex).filter(l => l.trim().length > 0);

                        let explicitOptions = [];
                        let remainingLines = [];

                        preAnswerLines.forEach(l => {
                            const optMatch = l.trim().match(/^(?:\(?([A-Ea-e])\)?[\.\)]+)\s*(.*)/i);
                            if (optMatch) {
                                let ltr = optMatch[1].toUpperCase();
                                let textVal = optMatch[2] || '';
                                explicitOptions.push({ prefix: `(${ltr})`, text: textVal, letter: ltr });
                            } else {
                                remainingLines.push(l);
                            }
                        });

                        if (explicitOptions.length >= 2) {
                            q.options = explicitOptions;
                        } else {
                            if (remainingLines.length >= 5) {
                                let potentialOpts = remainingLines.slice(-4);
                                remainingLines = remainingLines.slice(0, remainingLines.length - 4);
                                const letters = ['A', 'B', 'C', 'D', 'E'];
                                potentialOpts.forEach((optText, idx) => {
                                    let ltr = letters[idx] || 'A';
                                    q.options.push({ prefix: `(${ltr})`, text: optText.trim(), letter: ltr });
                                });
                            } else if (remainingLines.length === 4) {
                                let potentialOpts = remainingLines;
                                remainingLines = [];
                                const letters = ['A', 'B', 'C', 'D', 'E'];
                                potentialOpts.forEach((optText, idx) => {
                                    let ltr = letters[idx] || 'A';
                                    q.options.push({ prefix: `(${ltr})`, text: optText.trim(), letter: ltr });
                                });
                            }
                        }

                        let statements = [];
                        let nonOptLines = [];

                        remainingLines.forEach(l => {
                            const stmtMatch = l.trim().match(/^(\d+[\.\)])\s*(.*)/);
                            if (stmtMatch) {
                                statements.push(l);
                            } else {
                                nonOptLines.push(l);
                            }
                        });

                        q.statements = statements;
                        q.hindiQ = nonOptLines[0] ? nonOptLines[0].trim() : '';
                        q.englishQ = nonOptLines[1] ? nonOptLines[1].trim() : '';
                        
                        if (nonOptLines.length > 2) {
                            q.codeBlock = nonOptLines.slice(2).join('\n');
                        }

                        questions.push(q);
                    });

                    return questions;
                });
            });
        }

        function t2HandleFileUploaded(event) {
            const file = event.target.files[0];
            const badge = document.getElementById('t2FileInfoBadge');
            const wrapper = document.getElementById('t2ManualSelectionWrapper');
            const grid = document.getElementById('t2QuestionCheckboxesGrid');

            if (!file) {
                badge.style.display = 'none';
                wrapper.style.display = 'none';
                t2GlobalParsedQuestions = [];
                t2UpdateDashboardMetrics();
                return;
            }

            t2ParseDocx(file).then(questions => {
                t2GlobalParsedQuestions = questions;
                badge.style.display = 'block';
                badge.innerText = `✔ Uploaded successfully! Total questions found: ${questions.length}`;
                
                wrapper.style.display = 'flex';
                let gridHTML = '';
                questions.forEach((q) => {
                    gridHTML += `
                        <label style="display: inline-flex; align-items: center; gap: 4px; background: #f8fafc; padding: 4px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer;">
                            <input type="checkbox" class="t2-q-checkbox-item" value="${q.num}" checked onchange="t2UpdateManualSelectedCount()" style="width: 14px; height: 14px; accent-color: var(--primary-orange);">
                            Q${q.num}
                        </label>
                    `;
                });
                grid.innerHTML = gridHTML;
                t2UpdateManualSelectedCount();
                t2UpdateDashboardMetrics();
            }).catch(err => {
                badge.style.display = 'block';
                badge.style.color = '#ef4444';
                badge.innerText = `Error parsing file: ${err.message}`;
                t2GlobalParsedQuestions = [];
                t2UpdateDashboardMetrics();
                wrapper.style.display = 'none';
            });
        }

        function t2UpdateManualSelectedCount() {
            const checkboxes = document.querySelectorAll('.t2-q-checkbox-item:checked');
            const countDisplay = document.getElementById('t2SelectedCountDisplay');
            if (countDisplay) {
                countDisplay.innerText = checkboxes.length;
            }
            t2UpdateDashboardMetrics();
        }

        function t2ToggleSelectAllManual(selectState) {
            const checkboxes = document.querySelectorAll('.t2-q-checkbox-item');
            checkboxes.forEach(cb => cb.checked = selectState);
            t2UpdateManualSelectedCount();
        }

        function t2HighlightSyntax(code) {
            const escaped = t2EscapeHtml(code);
            const keywords = /\b(def|return|import|from|as|for|in|if|else|elif|while|class|try|except|with|print|range|bin|max|min|round|type)\b/g;
            const strings = /(["'])(?:(?=(\\?))\2.)*?\1/g;
            const numbers = /\b\d+\b/g;

            return escaped
                .replace(strings, '<span class="syntax-string">$&</span>')
                .replace(keywords, '<span class="syntax-keyword">$&</span>')
                .replace(numbers, '<span class="syntax-number">$&</span>');
        }

        function t2TokenizeCodeForDocxLine(lineText, size) {
            const regex = /(\b(?:def|return|import|from|as|for|in|if|else|elif|while|class|try|except|with|print|range|bin|max|min|round|type)\b)|(["'].*?["'])|(\b\d+\b)/g;
            
            let runs = [];
            let lastIndex = 0;
            let match;

            while ((match = regex.exec(lineText)) !== null) {
                if (match.index > lastIndex) {
                    runs.push(new window.docx.TextRun({ text: lineText.substring(lastIndex, match.index), font: "Fira Code", size: size, color: "0F172A" }));
                }

                if (match[1]) {
                    runs.push(new window.docx.TextRun({ text: match[1], font: "Fira Code", size: size, color: "2563EB", bold: true }));
                } else if (match[2]) {
                    runs.push(new window.docx.TextRun({ text: match[2], font: "Fira Code", size: size, color: "16A34A" }));
                } else if (match[3]) {
                    runs.push(new window.docx.TextRun({ text: match[3], font: "Fira Code", size: size, color: "D97706" }));
                }
                lastIndex = regex.lastIndex;
            }

            if (lastIndex < lineText.length) {
                runs.push(new window.docx.TextRun({ text: lineText.substring(lastIndex), font: "Fira Code", size: size, color: "0F172A" }));
            }

            return runs;
        }

        function t2BuildSingleAnswerKeyTableHTML(chunkQuestions, setNum) {
            const totalQ = Math.min(100, chunkQuestions ? chunkQuestions.length : 0);
            const colsCount = Math.ceil(totalQ / 10);
            const rowsPerCol = 10;
            
            let titleText = setNum ? `Answer Key Set-${setNum}` : `ANSWER KEY`;
            let html = `<div class="ak-container"><div class="ak-title">${titleText}</div>`;
            html += `<table class="pro-ak-table"><tbody>`;

            for (let r = 0; r < rowsPerCol; r++) {
                html += `<tr>`;
                for (let c = 0; c < colsCount; c++) {
                    const localIndex = r + (c * rowsPerCol);
                    if (localIndex < totalQ) {
                        const qNum = localIndex + 1;
                        let ansRaw = chunkQuestions[localIndex].answer || '-';
                        let cleanAns = ansRaw.replace(/[\(\)]/g, '').trim().charAt(0).toUpperCase();
                        html += `<td>${qNum}</td><td>${cleanAns}</td>`;
                    } else {
                        html += `<td></td><td></td>`;
                    }
                }
                html += `</tr>`;
            }
            html += `</tbody></table></div>`;
            return html;
        }

        function t2GetSmartQuestionsPerSlide() {
            const qPerSlideSetting = document.getElementById('t2QuestionsPerPage').value;
            if (qPerSlideSetting !== 'auto') {
                return parseInt(qPerSlideSetting) || 1;
            }
            return 1; 
        }

        function t2BuildMasterSlides(questions) {
            if (!questions || questions.length === 0) return [];
            const slides = [];
            const enableSetWise = document.getElementById('t2EnableSetWise').checked;
            const questionsPerSet = parseInt(document.getElementById('t2QuestionsPerSet').value) || 10;
            const qPerSlide = t2GetSmartQuestionsPerSlide();
            const includeAK = document.getElementById('t2IncludeAnswerKey').checked;

            if (enableSetWise) {
                const sets = [];
                for (let i = 0; i < questions.length; i += questionsPerSet) {
                    sets.push(questions.slice(i, i + questionsPerSet));
                }

                sets.forEach((setQuestions, setIdx) => {
                    const setNum = setIdx + 1;
                    
                    slides.push({
                        type: 'divider',
                        setNumber: setNum
                    });

                    const renumberedSetQuestions = setQuestions.map((q, qIndex) => ({
                        ...q,
                        displayNum: qIndex + 1
                    }));

                    for (let i = 0; i < renumberedSetQuestions.length; i += qPerSlide) {
                        slides.push({
                            type: 'question',
                            setNumber: setNum,
                            questions: renumberedSetQuestions.slice(i, i + qPerSlide)
                        });
                    }

                    if (includeAK) {
                        for (let i = 0; i < renumberedSetQuestions.length; i += 100) {
                            slides.push({
                                type: 'answerkey',
                                setNumber: setNum,
                                questions: renumberedSetQuestions.slice(i, i + 100)
                            });
                        }
                    }
                });
            } else {
                const renumberedQuestions = questions.map((q, qIndex) => ({
                    ...q,
                    displayNum: qIndex + 1
                }));

                for (let i = 0; i < renumberedQuestions.length; i += qPerSlide) {
                    slides.push({
                        type: 'normal-question',
                        questions: renumberedQuestions.slice(i, i + qPerSlide)
                    });
                }

                if (includeAK) {
                    for (let i = 0; i < renumberedQuestions.length; i += 100) {
                        slides.push({
                            type: 'normal-answerkey',
                            questions: renumberedQuestions.slice(i, i + 100)
                        });
                    }
                }
            }

            return slides;
        }

        function t2GetActivePtForQuestion(q, baseFontSize) {
            return baseFontSize;
        }

        function t2GetDynamicImageDimensions(q, scale) {
            return { width: Math.round(380 * scale), height: Math.round(270 * scale) };
        }

        function t2HexToRgba(hex, opacity) {
            let c = hex.replace('#','');
            if(c.length===3) c = c.split('').map(x=>x+x).join('');
            const num = parseInt(c,16);
            return `rgba(${num>>16},${(num>>8)&255},${num&255},${opacity})`;
        }

        function t2GenerateSlides() {
            const fileInput = document.getElementById('t2DocFileInput');
            if (!fileInput.files[0]) {
                alert("Please select a Word (.docx) file first.");
                return;
            }

            t2ParseDocx(fileInput.files[0]).then(parsedQuestions => {
                t2GlobalParsedQuestions = parsedQuestions;
                
                const checkedBoxes = document.querySelectorAll('.t2-q-checkbox-item:checked');
                const allowedNums = Array.from(checkedBoxes).map(cb => parseInt(cb.value));

                let processedQuestions = parsedQuestions.filter(q => allowedNums.includes(q.num));

                const start = parseInt(document.getElementById('t2QStart').value) || 1;
                const end = parseInt(document.getElementById('t2QEnd').value) || 9999;
                
                processedQuestions = processedQuestions.filter(q => q.num >= start && q.num <= end);

                t2CurrentFilteredQuestions = processedQuestions.map((q, index) => ({
                    ...q,
                    num: index + 1
                }));

                if (t2CurrentFilteredQuestions.length === 0) {
                    alert("No questions selected or found matching your criteria.");
                    return;
                }

                t2MasterSlides = t2BuildMasterSlides(t2CurrentFilteredQuestions);
                t2CurrentSlideIndex = 0;
                t2RenderSlidePreview();
                t2UpdateDownloadButtonsUI();
                t2UpdateDashboardMetrics();
                const previewContainer = document.getElementById('t2PreviewContainer');
                if (previewContainer) {
                    previewContainer.style.display = 'block';
                    previewContainer.scrollIntoView({ behavior: 'smooth' });
                }
            }).catch(err => {
                alert("Error reading file: " + err.message);
            });
        }

        function t2UpdateDownloadButtonsUI() {
            const container = document.getElementById('t2DownloadActionButtons');
            if (!container) return;
            
            const enableSetWise = document.getElementById('t2EnableSetWise').checked;
            
            let html = `<button class="secondary" onclick="t2DownloadPDF()">Download PDF File</button>`;
            html += `<button class="secondary" onclick="t2DownloadDOCX(false)">Download Word File (Normal)</button>`;
            html += `<button class="secondary" onclick="t2DownloadDOCX(true)">Download Word File (Compatibility)</button>`;

            if (enableSetWise && t2CurrentFilteredQuestions.length > 0) {
                const questionsPerSet = parseInt(document.getElementById('t2QuestionsPerSet').value) || 10;
                const sets = [];
                for (let i = 0; i < t2CurrentFilteredQuestions.length; i += questionsPerSet) {
                    sets.push(t2CurrentFilteredQuestions.slice(i, i + questionsPerSet));
                }

                sets.forEach((_, setIdx) => {
                    const setNum = setIdx + 1;
                    html += `<button class="secondary" onclick="t2DownloadSpecificSetDOCX(${setNum}, false)">Download Set-${setNum} DOCX</button>`;
                });
            }

            container.innerHTML = html;
        }

        function t2RenderSlidePreview() {
            const stage = document.getElementById('t2SlideStage');
            if (!stage) return;

            if (t2CurrentFilteredQuestions && t2CurrentFilteredQuestions.length > 0) {
                t2MasterSlides = t2BuildMasterSlides(t2CurrentFilteredQuestions) || [];
                if (t2CurrentSlideIndex >= t2MasterSlides.length) {
                    t2CurrentSlideIndex = Math.max(0, t2MasterSlides.length - 1);
                }
            } else {
                t2MasterSlides = [];
            }

            t2UpdateDownloadButtonsUI();
            t2UpdateDashboardMetrics();

            const fontFamily = document.getElementById('t2FontFamily').value;
            const baseFontSize = parseInt(document.getElementById('t2BaseFontSize').value) || 20;
            const boldStyleMode = document.getElementById('t2BoldStyleMode').value;
            const hindiColor = document.getElementById('t2HindiColor').value;
            const englishColor = document.getElementById('t2EnglishColor').value;
            const optionsColor = document.getElementById('t2OptionsColor').value;
            const answerKeyColor = document.getElementById('t2AnswerKeyColor').value;
            const showAns = document.getElementById('t2ShowAnswerOnSlide').checked;
            const hideOpts = document.getElementById('t2HideOptions').checked;
            const columns = parseInt(document.getElementById('t2ColumnLayout').value) || 1;
            const questionSpacing = parseInt(document.getElementById('t2QuestionSpacing').value) || 12;

            const enableCodeHighlight = document.getElementById('t2EnableCodeHighlight').checked;
            const enableSyntaxHighlighter = document.getElementById('t2EnableSyntaxHighlighter').checked;
            const enableCodeBorder = document.getElementById('t2EnableCodeBorder').checked;
            const codeBorderShape = document.getElementById('t2CodeBorderShape').value;
            const codeBlockBgColor = document.getElementById('t2CodeBlockBgColor').value;
            const codeBlockOpacity = parseFloat(document.getElementById('t2CodeBlockOpacity').value) || 1.0;
            
            const dims = t2GetActiveDimensions();
            const maxBoxWidth = 750;
            const maxBoxHeight = 480;
            const aspect = dims.width / dims.height;
            let previewWidth, previewHeight;
            if (aspect >= 1) {
                previewWidth = maxBoxWidth;
                previewHeight = Math.round(maxBoxWidth / aspect);
            } else {
                previewHeight = maxBoxHeight;
                previewWidth = Math.round(maxBoxHeight * aspect);
            }
            
            stage.style.width = `${previewWidth}px`;
            stage.style.height = `${previewHeight}px`;

            const scale = previewWidth / dims.width;
            const mTop = Math.round((parseInt(document.getElementById('t2MarginTop').value) || 30) * scale);
            const mRight = Math.round((parseInt(document.getElementById('t2MarginRight').value) || 30) * scale);
            const mBottom = Math.round((parseInt(document.getElementById('t2MarginBottom').value) || 30) * scale);
            const mLeft = Math.round((parseInt(document.getElementById('t2MarginLeft').value) || 30) * scale);
            const scaledSpacing = Math.round(questionSpacing * scale);

            stage.style.fontFamily = `"${fontFamily}", "Noto Sans Devanagari", sans-serif`;
            stage.style.padding = `${mTop}px ${mRight}px ${mBottom}px ${mLeft}px`;
            
            const bgToDraw = t2ActiveBgJpegDataUrl || t2CreateDefaultBgCanvas(dims.width, dims.height);
            stage.style.background = `url("${bgToDraw}")`;

            const totalSlides = t2MasterSlides.length || 1;
            const slideIndicator = document.getElementById('t2SlideIndicator');
            if (slideIndicator) {
                slideIndicator.innerText = `Slide ${t2CurrentSlideIndex + 1} of ${totalSlides}`;
            }

            const jumpInput = document.getElementById('t2JumpPageInput');
            if (jumpInput) {
                jumpInput.value = t2CurrentSlideIndex + 1;
                jumpInput.max = totalSlides;
            }

            if (t2MasterSlides.length > 0 && t2CurrentSlideIndex < t2MasterSlides.length) {
                const slide = t2MasterSlides[t2CurrentSlideIndex];
                let html = '';

                if (slide.type === 'divider') {
                    html += `<div class="set-divider-title" style="color: ${hindiColor}; font-size: ${Math.round(64 * scale)}px;">SET-${slide.setNumber}</div>`;
                    stage.innerHTML = html;
                } else if (slide.type === 'question' || slide.type === 'normal-question') {
                    html += `<div style="column-count: ${columns}; column-gap: 15px; column-fill: auto; width: 100%; height: 100%; overflow: hidden; box-sizing: border-box;">`;
                    
                    slide.questions.forEach((q, idx) => {
                        const activePt = t2GetActivePtForQuestion(q, baseFontSize);
                        const pxFontSize = Math.max(10, Math.round(activePt * scale * 1.15));
                        const qNum = q.displayNum !== undefined ? q.displayNum : q.num;
                        const bottomMargin = (idx < slide.questions.length - 1) ? scaledSpacing : 0;

                        const qFontWeight = (boldStyleMode === 'all' || boldStyleMode === 'questions_only' || boldStyleMode === 'questions_and_options') ? 'bold' : 'normal';
                        const optFontWeight = (boldStyleMode === 'all' || boldStyleMode === 'questions_and_options') ? 'bold' : 'normal';

                        html += `<div class="q-item-block" style="margin-bottom: ${bottomMargin}px;">`;
                        html += `<div class="question-row-container">`;
                        html += `<div class="question-text-side">`;

                        if (q.hindiQ) {
                            html += `<div class="q-hindi" style="font-size: ${pxFontSize}px; color: ${hindiColor}; font-weight: ${qFontWeight}; line-height: 1.25;">Q${qNum}. ${t2EscapeHtml(q.hindiQ)}</div>`;
                        }
                        if (q.englishQ) {
                            html += `<div class="q-english" style="font-size: ${pxFontSize}px; color: ${englishColor}; margin-top: 4px; font-weight: ${qFontWeight}; line-height: 1.25;">${t2EscapeHtml(q.englishQ)}</div>`;
                        }

                        if (q.statements && q.statements.length > 0) {
                            q.statements.forEach(stmt => {
                                html += `<div class="stmt-item" style="font-size: ${Math.round(pxFontSize * 0.9)}px; color: ${englishColor}; margin-top: 4px; padding-left: 14px; font-weight: ${qFontWeight}; line-height: 1.25;">${t2EscapeHtml(stmt)}</div>`;
                            });
                        }

                        if (q.codeBlock) {
                            let codeStyles = `font-size: ${Math.round(pxFontSize * 0.8)}px; line-height: 1.4; `;
                            if (enableCodeBorder) {
                                codeStyles += `border: 1.5px solid #cbd5e1; `;
                                if (codeBorderShape === 'rounded') codeStyles += `border-radius: 6px; `;
                                else codeStyles += `border-radius: 0px; `;
                            } else {
                                codeStyles += `border: none; `;
                            }
                            if (enableCodeHighlight) {
                                const rgbaBg = t2HexToRgba(codeBlockBgColor, codeBlockOpacity);
                                codeStyles += `background: ${rgbaBg}; `;
                            } else {
                                codeStyles += `background: transparent; `;
                            }
                            
                            const codeDisplayContent = enableSyntaxHighlighter ? t2HighlightSyntax(q.codeBlock) : t2EscapeHtml(q.codeBlock);
                            html += `<div class="code-preview-box" style="${codeStyles}">${codeDisplayContent}</div>`;
                        }

                        if (!hideOpts && q.options) {
                            q.options.forEach(opt => {
                                html += `<div class="opt-item" style="font-size: ${Math.round(pxFontSize * 0.82)}px; color: ${optionsColor}; margin-top: 3px; font-weight: ${optFontWeight}; line-height: 1.25;">${opt.prefix ? opt.prefix + ' ' : ''}${t2EscapeHtml(opt.text)}</div>`;
                            });
                        }
                        if (showAns && q.answer) {
                            let cleanAnswerText = q.answer.trim();
                            if (!cleanAnswerText.startsWith('(')) {
                                cleanAnswerText = `(${cleanAnswerText})`;
                            }
                            html += `<div class="q-answer" style="font-size: ${Math.round(pxFontSize * 0.82)}px; color: ${answerKeyColor}; margin-top: 5px; font-weight: bold; line-height: 1.25;">Answer: ${t2EscapeHtml(cleanAnswerText)}</div>`;
                        }

                        html += `</div>`;

                        if (q.image) {
                            const dynSize = t2GetDynamicImageDimensions(q, scale);
                            html += `<div class="question-image-side"><img decoding="async" src="${q.image}" class="question-image-box" style="width: ${dynSize.width}px; height: ${dynSize.height}px;" alt="Question Graphic"/></div>`;
                        }

                        html += `</div>`;
                        html += `</div>`;
                    });
                    html += `</div>`;
                    stage.innerHTML = html;
                } else if (slide.type === 'answerkey') {
                    stage.innerHTML = t2BuildSingleAnswerKeyTableHTML(slide.questions, slide.setNumber);
                } else if (slide.type === 'normal-answerkey') {
                    stage.innerHTML = t2BuildSingleAnswerKeyTableHTML(slide.questions, null);
                }
            } else {
                stage.innerHTML = `<div style="text-align: center; padding-top: 100px; font-weight: bold; color: #555;">No preview available</div>`;
            }
        }

        function t2PrevSlide() {
            if (t2CurrentSlideIndex > 0) {
                t2CurrentSlideIndex--;
                t2RenderSlidePreview();
            }
        }

        function t2NextSlide() {
            if (t2CurrentSlideIndex < t2MasterSlides.length - 1) {
                t2CurrentSlideIndex++;
                t2RenderSlidePreview();
            }
        }

        function t2JumpToSlide() {
            const input = document.getElementById('t2JumpPageInput');
            if (!input) return;
            const target = parseInt(input.value) - 1;
            const totalSlides = t2MasterSlides.length || 1;
            if (!isNaN(target) && target >= 0 && target < totalSlides) {
                t2CurrentSlideIndex = target;
                t2RenderSlidePreview();
            } else {
                alert(`Please enter a valid slide number between 1 and ${totalSlides}.`);
            }
        }

        function t2DownloadPDF() {
            if (t2CurrentFilteredQuestions.length === 0) {
                alert("Please generate and view the preview first.");
                return;
            }
            t2MasterSlides = t2BuildMasterSlides(t2CurrentFilteredQuestions);

            const fontFamily = document.getElementById('t2FontFamily').value;
            const ptFontSize = parseInt(document.getElementById('t2BaseFontSize').value) || 45;
            const boldStyleMode = document.getElementById('t2BoldStyleMode').value;
            const hindiColor = document.getElementById('t2HindiColor').value;
            const englishColor = document.getElementById('t2EnglishColor').value;
            const optionsColor = document.getElementById('t2OptionsColor').value;
            const answerKeyColor = document.getElementById('t2AnswerKeyColor').value;
            const showAns = document.getElementById('t2ShowAnswerOnSlide').checked;
            const hideOpts = document.getElementById('t2HideOptions').checked;
            const columns = parseInt(document.getElementById('t2ColumnLayout').value) || 1;
            const orientation = document.getElementById('t2Orientation').value;
            const questionSpacing = parseInt(document.getElementById('t2QuestionSpacing').value) || 12;
            
            const enableCodeHighlight = document.getElementById('t2EnableCodeHighlight').checked;
            const enableSyntaxHighlighter = document.getElementById('t2EnableSyntaxHighlighter').checked;
            const enableCodeBorder = document.getElementById('t2EnableCodeBorder').checked;
            const codeBorderShape = document.getElementById('t2CodeBorderShape').value;
            const codeBlockBgColor = document.getElementById('t2CodeBlockBgColor').value;
            const codeBlockOpacity = parseFloat(document.getElementById('t2CodeBlockOpacity').value) || 1.0;

            const mTop = parseInt(document.getElementById('t2MarginTop').value) || 120;
            const mRight = parseInt(document.getElementById('t2MarginRight').value) || 30;
            const mBottom = parseInt(document.getElementById('t2MarginBottom').value) || 30;
            const mLeft = parseInt(document.getElementById('t2MarginLeft').value) || 120;
            
            const dims = t2GetActiveDimensions();
            const bgToDraw = t2ActiveBgJpegDataUrl || t2CreateDefaultBgCanvas(dims.width, dims.height);

            const printContainer = document.getElementById('t2PrintSection');
            if (!printContainer) return;

            let dynamicStyleTag = document.getElementById('t2DynamicPrintStyle');
            if (!dynamicStyleTag) {
                dynamicStyleTag = document.createElement('style');
                dynamicStyleTag.id = 't2DynamicPrintStyle';
                document.head.appendChild(dynamicStyleTag);
            }
            dynamicStyleTag.innerHTML = `@media print { @page { size: ${orientation}; margin: 0; } body { background-color: white !important; } }`;

            let printHTML = '';

            t2MasterSlides.forEach((slide) => {
                printHTML += `<div class="print-page" style="font-family: '${fontFamily}', 'Noto Sans Devanagari', sans-serif; padding: ${mTop}px ${mRight}px ${mBottom}px ${mLeft}px; background-image: url('${bgToDraw}');">`;
                
                if (slide.type === 'divider') {
                    printHTML += `<div style="font-size: 64px; font-weight: 900; text-align: center; margin: auto; color: ${hindiColor}; letter-spacing: 2px; text-transform: uppercase;">SET-${slide.setNumber}</div>`;
                } else if (slide.type === 'question' || slide.type === 'normal-question') {
                    printHTML += `<div style="column-count: ${columns}; column-gap: 15px; column-fill: auto; width: 100%; height: 100%; overflow: hidden; box-sizing: border-box;">`;
                    slide.questions.forEach((q, idx) => {
                        const activePt = t2GetActivePtForQuestion(q, ptFontSize);
                        const qNum = q.displayNum !== undefined ? q.displayNum : q.num;
                        const bottomMargin = (idx < slide.questions.length - 1) ? questionSpacing : 0;

                        const qFontWeight = (boldStyleMode === 'all' || boldStyleMode === 'questions_only' || boldStyleMode === 'questions_and_options') ? 'bold' : 'normal';
                        const optFontWeight = (boldStyleMode === 'all' || boldStyleMode === 'questions_and_options') ? 'bold' : 'normal';

                        printHTML += `<div class="q-item-block" style="margin-bottom: ${bottomMargin}px;">`;
                        printHTML += `<div style="display: flex; flex-direction: row; align-items: flex-start; justify-content: space-between; gap: 20px; width: 100%; box-sizing: border-box;">`;
                        printHTML += `<div style="flex: 1; display: flex; flex-direction: column; min-width: 0;">`;

                        if (q.hindiQ) {
                            printHTML += `<div class="q-hindi" style="font-size: ${activePt}px; color: ${hindiColor}; font-weight: ${qFontWeight}; line-height: 1.25; word-break: break-word; overflow-wrap: break-word; white-space: normal;">Q${qNum}. ${t2EscapeHtml(q.hindiQ)}</div>`;
                        }
                        if (q.englishQ) {
                            printHTML += `<div class="q-english" style="font-size: ${activePt}px; color: ${englishColor}; margin-top: 4px; font-weight: ${qFontWeight}; line-height: 1.25; word-break: break-word; overflow-wrap: break-word; white-space: normal;">${t2EscapeHtml(q.englishQ)}</div>`;
                        }

                        if (q.statements && q.statements.length > 0) {
                            q.statements.forEach(stmt => {
                                printHTML += `<div style="font-size: ${Math.round(activePt * 0.9)}px; color: ${englishColor}; margin-top: 4px; padding-left: 14px; font-weight: ${qFontWeight}; line-height: 1.25; word-break: break-word; overflow-wrap: break-word; white-space: normal;">${t2EscapeHtml(stmt)}</div>`;
                            });
                        }

                        if (q.codeBlock) {
                            let codeStyles = `font-family: 'Fira Code', monospace; font-size: ${Math.round(activePt * 0.8)}px; line-height: 1.4; padding: 6px 10px; margin: 6px 0; white-space: pre; display: inline-block; box-sizing: border-box; `;
                            if (enableCodeBorder) {
                                codeStyles += `border: 1.5px solid #cbd5e1; `;
                                if (codeBorderShape === 'rounded') codeStyles += `border-radius: 6px; `;
                                else codeStyles += `border-radius: 0px; `;
                            } else {
                                codeStyles += `border: none; `;
                            }
                            if (enableCodeHighlight) {
                                const rgbaBg = t2HexToRgba(codeBlockBgColor, codeBlockOpacity);
                                codeStyles += `background: ${rgbaBg}; `;
                            } else {
                                codeStyles += `background: transparent; `;
                            }
                            const codeDisplayContent = enableSyntaxHighlighter ? t2HighlightSyntax(q.codeBlock) : t2EscapeHtml(q.codeBlock);
                            printHTML += `<div style="${codeStyles}">${codeDisplayContent}</div>`;
                        }

                        if (!hideOpts && q.options) {
                            printHTML += q.options.map(opt => `<div class="opt-item" style="font-size: ${Math.round(activePt * 0.82)}px; color: ${optionsColor}; padding-left: 18px; text-indent: -18px; margin-top: 3px; font-weight: ${optFontWeight}; line-height: 1.25; word-break: break-word; overflow-wrap: break-word; white-space: normal;">${opt.prefix ? opt.prefix + ' ' : ''}${t2EscapeHtml(opt.text)}</div>`).join('');
                        }
                        if (showAns && q.answer) {
                            let cleanAnswerText = q.answer.trim();
                            if (!cleanAnswerText.startsWith('(')) {
                                cleanAnswerText = `(${cleanAnswerText})`;
                            }
                            printHTML += `<div class="q-answer" style="font-size: ${Math.round(activePt * 0.82)}px; color: ${answerKeyColor}; margin-top: 5px; font-weight: bold; line-height: 1.25; word-break: break-word; overflow-wrap: break-word; white-space: normal;">Answer: ${t2EscapeHtml(cleanAnswerText)}</div>`;
                        }

                        printHTML += `</div>`;

                        if (q.image) {
                            const dynPrintSize = t2GetDynamicImageDimensions(q, 1.0);
                            printHTML += `<div style="flex-shrink: 0; display: flex; align-items: flex-start; justify-content: flex-end;"><img decoding="async" src="${q.image}" style="width: ${dynPrintSize.width}px; height: ${dynPrintSize.height}px; object-fit: contain; border: none !important; background: transparent !important; display: block;" alt="Question Graphic"/></div>`;
                        }

                        printHTML += `</div>`;
                        printHTML += `</div>`;
                    });
                    printHTML += `</div>`;
                } else if (slide.type === 'answerkey') {
                    printHTML += t2BuildSingleAnswerKeyTableHTML(slide.questions, slide.setNumber);
                } else if (slide.type === 'normal-answerkey') {
                    printHTML += t2BuildSingleAnswerKeyTableHTML(slide.questions, null);
                }

                printHTML += `</div>`;
            });

            printContainer.innerHTML = printHTML;
            printContainer.style.display = 'block';
            
            setTimeout(() => {
                window.print();
                setTimeout(() => {
                    printContainer.style.display = 'none';
                }, 1000);
            }, 400);
        }

        async function t2DownloadDOCX(isCompatibilityMode) {
            if (t2CurrentFilteredQuestions.length === 0) return;

            try {
                const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, WidthType, PageOrientation, AlignmentType, Header, ImageRun, BorderStyle, ShadingType } = window.docx;
                const orientation = document.getElementById('t2Orientation').value;
                const pageSizeMode = document.getElementById('t2PageSize').value;
                const resolutionMode = document.getElementById('t2ResolutionQuality').value;
                const baseFontSize = parseInt(document.getElementById('t2BaseFontSize').value) || 45;
                const boldStyleMode = document.getElementById('t2BoldStyleMode').value;
                const selectedFont = document.getElementById('t2FontFamily').value;
                const showAns = document.getElementById('t2ShowAnswerOnSlide').checked;
                const hideOpts = document.getElementById('t2HideOptions').checked;
                const columns = parseInt(document.getElementById('t2ColumnLayout').value) || 1;
                const questionSpacing = parseInt(document.getElementById('t2QuestionSpacing').value) || 12;

                const enableCodeHighlight = document.getElementById('t2EnableCodeHighlight').checked;
                const enableSyntaxHighlighter = document.getElementById('t2EnableSyntaxHighlighter').checked;
                const enableCodeBorder = document.getElementById('t2EnableCodeBorder').checked;
                const codeBlockBgColor = document.getElementById('t2CodeBlockBgColor').value.replace('#', '');

                const mTop = (parseInt(document.getElementById('t2MarginTop').value) || 120) * 15;
                const mRight = (parseInt(document.getElementById('t2MarginRight').value) || 30) * 15;
                const mBottom = (parseInt(document.getElementById('t2MarginBottom').value) || 30) * 15;
                const mLeft = (parseInt(document.getElementById('t2MarginLeft').value) || 120) * 15;
                const docxSpacingAfter = questionSpacing * 20;

                const hindiColor = document.getElementById('t2HindiColor').value.replace('#', '');
                const englishColor = document.getElementById('t2EnglishColor').value.replace('#', '');
                const optionsColor = document.getElementById('t2OptionsColor').value.replace('#', '');
                const answerKeyColor = document.getElementById('t2AnswerKeyColor').value.replace('#', '');
                const isLandscape = (orientation === 'landscape');

                const isQBold = (boldStyleMode === 'all' || boldStyleMode === 'questions_only' || boldStyleMode === 'questions_and_options');
                const isOptBold = (boldStyleMode === 'all' || boldStyleMode === 'questions_and_options');

                let dxaWidth, dxaHeight;
                if (pageSizeMode === 'hd') {
                    if (resolutionMode === '720p') {
                        dxaWidth = 12825;
                        dxaHeight = 22860;
                    } else {
                        dxaWidth = 19305;
                        dxaHeight = 34290;
                    }
                } else if (pageSizeMode === 'a4') {
                    dxaWidth = 11900;
                    dxaHeight = 16838;
                } else if (pageSizeMode === 'a3') {
                    dxaWidth = 16838;
                    dxaHeight = 23811;
                } else {
                    dxaWidth = 12240;
                    dxaHeight = 15840;
                }

                const basePortraitRef = t2GetPortraitBaseDimensions();

                let headerObj = undefined;
                if (t2RawBgData) {
                    headerObj = {
                        default: new Header({
                            children: [
                                new Paragraph({
                                    children: [
                                        new ImageRun({
                                            data: Uint8Array.from(atob(t2RawBgData.base64), c => c.charCodeAt(0)),
                                            transformation: { 
                                                width: isLandscape ? basePortraitRef.height : basePortraitRef.width, 
                                                height: isLandscape ? basePortraitRef.width : basePortraitRef.height 
                                            },
                                            floating: {
                                                horizontalPosition: { relative: window.docx.HorizontalPositionRelativeFrom.PAGE, offset: 0 },
                                                verticalPosition: { relative: window.docx.VerticalPositionRelativeFrom.PAGE, offset: 0 },
                                                behindDocument: true
                                            }
                                        })
                                    ]
                                })
                            ]
                        })
                    };
                }

                const localMasterSlides = t2BuildMasterSlides(t2CurrentFilteredQuestions);
                const sections = [];

                localMasterSlides.forEach((slide) => {
                    const children = [];

                    if (slide.type === 'divider') {
                        children.push(new Paragraph({
                            children: [new TextRun({ text: `SET-${slide.setNumber}`, bold: true, size: 96, color: hindiColor, font: selectedFont })],
                            alignment: AlignmentType.CENTER,
                            spacing: { before: 2000, after: 1000 }
                        }));
                    } else if (slide.type === 'question' || slide.type === 'normal-question') {
                        slide.questions.forEach((q, qIdx) => {
                            const activePt = t2GetActivePtForQuestion(q, baseFontSize);
                            const qNum = q.displayNum !== undefined ? q.displayNum : q.num;
                            const isLastInSlide = (qIdx === slide.questions.length - 1);
                            const currentAfterSpace = isLastInSlide ? 50 : docxSpacingAfter;

                            let textParagraphs = [];

                            if (q.hindiQ) {
                                textParagraphs.push(new Paragraph({
                                    children: [new TextRun({ text: `Q${qNum}. ${q.hindiQ}`, bold: isQBold, size: Math.round(activePt * 2), color: hindiColor, font: selectedFont })],
                                    spacing: { before: 25, after: 10, line: 300, lineRule: "auto" }
                                }));
                            }
                            if (q.englishQ) {
                                textParagraphs.push(new Paragraph({
                                    children: [new TextRun({ text: q.englishQ, bold: isQBold, size: Math.round(activePt * 2), color: englishColor, font: selectedFont })],
                                    spacing: { after: 12, line: 300, lineRule: "auto" }
                                }));
                            }

                            if (q.statements && q.statements.length > 0) {
                                q.statements.forEach(stmt => {
                                    textParagraphs.push(new Paragraph({
                                        children: [new TextRun({ text: stmt, bold: isQBold, size: Math.round(activePt * 1.7), color: englishColor, font: selectedFont })],
                                        indent: { left: 280 },
                                        spacing: { after: 8, line: 300, lineRule: "auto" }
                                    }));
                                });
                            }

                            if (q.codeBlock) {
                                const codeLines = q.codeBlock.split('\n');
                                const codeParagraphs = codeLines.map((cLine) => {
                                    let leadingMatch = cLine.match(/^(\s*)/);
                                    let leadingSpaces = leadingMatch ? leadingMatch[1].length : 0;
                                    let NBSP = '\u00A0'.repeat(leadingSpaces);
                                    let lineText = NBSP + cLine.trimStart();

                                    let lineRuns = [];
                                    if (enableSyntaxHighlighter) {
                                        lineRuns = t2TokenizeCodeForDocxLine(lineText, Math.round(activePt * 1.6));
                                    } else {
                                        lineRuns = [new window.docx.TextRun({ text: lineText, font: "Fira Code", size: Math.round(activePt * 1.6), color: "0F172A" })];
                                    }

                                    return new Paragraph({
                                        children: lineRuns,
                                        spacing: { before: 0, after: 0, line: 240, lineRule: "auto" }
                                    });
                                });

                                const cellProps = {
                                    children: codeParagraphs,
                                    width: { size: 0, type: WidthType.AUTO },
                                    margins: { top: 60, bottom: 60, left: 100, right: 100 }
                                };

                                if (enableCodeHighlight) {
                                    cellProps.shading = { fill: codeBlockBgColor, type: ShadingType.CLEAR, color: "auto" };
                                }
                                if (enableCodeBorder) {
                                    const borderConfig = { style: BorderStyle.SINGLE, size: 12, color: "CBD5E1" };
                                    cellProps.borders = { top: borderConfig, bottom: borderConfig, left: borderConfig, right: borderConfig };
                                }

                                const codeTable = new Table({
                                    rows: [new TableRow({ children: [new TableCell(cellProps)] })],
                                    width: { size: 0, type: WidthType.AUTO }
                                });

                                textParagraphs.push(codeTable);
                                textParagraphs.push(new Paragraph({ spacing: { after: 12 } }));
                            }

                            if (!hideOpts && q.options) {
                                q.options.forEach((opt, optIdx) => {
                                    const isLastOpt = (optIdx === q.options.length - 1);
                                    const optAfterSpace = (isLastOpt && !showAns) ? currentAfterSpace : 12;
                                    textParagraphs.push(new Paragraph({
                                        children: [new TextRun({ text: `${opt.prefix ? opt.prefix + ' ' : ''}${opt.text}`, bold: isOptBold, size: Math.round(activePt * 1.7), color: optionsColor, font: selectedFont })],
                                        indent: { left: 420, hanging: 230 },
                                        spacing: { after: optAfterSpace, line: 300, lineRule: "auto" }
                                    }));
                                });
                            }
                            if (showAns && q.answer) {
                                let cleanAnswerText = q.answer.trim();
                                if (!cleanAnswerText.startsWith('(')) {
                                    cleanAnswerText = `(${cleanAnswerText})`;
                                }
                                textParagraphs.push(new Paragraph({
                                    children: [new TextRun({ text: `Answer: ${cleanAnswerText}`, bold: true, size: Math.round(activePt * 1.7), color: answerKeyColor, font: selectedFont })],
                                    spacing: { before: 12, after: currentAfterSpace, line: 300, lineRule: "auto" }
                                }));
                            }

                            if (q.image) {
                                try {
                                    const base64DataImg = q.image.split(',')[1];
                                    const uint8Arr = Uint8Array.from(atob(base64DataImg), c => c.charCodeAt(0));
                                    
                                    const imgPara = new Paragraph({
                                        children: [
                                            new ImageRun({
                                                data: uint8Arr,
                                                transformation: { width: 300, height: 210 }
                                            })
                                        ],
                                        alignment: AlignmentType.RIGHT
                                    });

                                    const availableWidth = dxaWidth - mLeft - mRight;
                                    const leftColWidth = Math.floor(availableWidth * 0.58);
                                    const rightColWidth = Math.floor(availableWidth * 0.42);

                                    const noBorderConfig = { style: BorderStyle.NONE, size: 0, color: "auto" };
                                    const borderlessConfig = { top: noBorderConfig, bottom: noBorderConfig, left: noBorderConfig, right: noBorderConfig };

                                    const layoutTable = new Table({
                                        rows: [
                                            new TableRow({
                                                children: [
                                                    new TableCell({
                                                        children: textParagraphs,
                                                        width: { size: leftColWidth, type: WidthType.DXA },
                                                        verticalAlign: window.docx.VerticalAlign.TOP,
                                                        borders: borderlessConfig
                                                    }),
                                                    new TableCell({
                                                        children: [imgPara],
                                                        width: { size: rightColWidth, type: WidthType.DXA },
                                                        verticalAlign: window.docx.VerticalAlign.TOP,
                                                        borders: borderlessConfig
                                                    })
                                                ]
                                            })
                                        ],
                                        width: { size: availableWidth, type: WidthType.DXA },
                                        alignment: AlignmentType.CENTER
                                    });

                                    children.push(layoutTable);
                                    children.push(new Paragraph({ spacing: { after: 20 } }));
                                } catch (e) {
                                    children.push(...textParagraphs);
                                }
                            } else {
                                children.push(...textParagraphs);
                            }
                        });
                    } else if (slide.type === 'answerkey' || slide.type === 'normal-answerkey') {
                        let akHeading = slide.setNumber ? `ANSWER KEY SET-${slide.setNumber}` : `ANSWER KEY`;
                        children.push(new Paragraph({
                            children: [new TextRun({ text: akHeading, bold: true, size: 36, color: "CC0000", font: selectedFont })],
                            alignment: AlignmentType.CENTER,
                            spacing: { before: 150, after: 200 }
                        }));

                        const chunkQ = slide.questions;
                        const totalQ = Math.min(100, chunkQ.length);
                        const colsCount = Math.ceil(totalQ / 10);
                        const rowsPerCol = 10;
                        
                        const tableRows = [];
                        const borderCfg = { style: BorderStyle.SINGLE, size: 8, color: "000000" };
                        const cellBorders = { top: borderCfg, bottom: borderCfg, left: borderCfg, right: borderCfg };

                        const availableTableWidth = dxaWidth - mLeft - mRight;
                        const totalCellsPerColumnPair = colsCount * 2;
                        const baseCellWidth = Math.floor(availableTableWidth / totalCellsPerColumnPair);
                        const numWidth = Math.max(360, Math.floor(baseCellWidth * 0.75));
                        const ansWidth = Math.max(480, Math.floor(baseCellWidth * 1.25));

                        for (let r = 0; r < rowsPerCol; r++) {
                            const rowCells = [];
                            const isEvenRow = (r % 2 !== 0);
                            const rowShading = isEvenRow ? { fill: "D1D5DB", type: ShadingType.CLEAR, color: "auto" } : undefined;

                            for (let c = 0; c < colsCount; c++) {
                                const localIndex = r + (c * rowsPerCol);
                                if (localIndex < totalQ) {
                                    const qNum = localIndex + 1;
                                    let ansRaw = chunkQ[localIndex].answer || '-';
                                    let cleanAns = ansRaw.replace(/[\(\)]/g, '').trim().charAt(0).toUpperCase();
                                    
                                    rowCells.push(new TableCell({ 
                                        children: [new Paragraph({ children: [new TextRun({ text: qNum.toString(), bold: true, size: 22, color: "000000", font: selectedFont })], alignment: AlignmentType.CENTER })], 
                                        borders: cellBorders,
                                        shading: rowShading,
                                        margins: { top: 60, bottom: 60, left: 30, right: 30 },
                                        width: { size: numWidth, type: WidthType.DXA } 
                                    }));
                                    rowCells.push(new TableCell({ 
                                        children: [new Paragraph({ children: [new TextRun({ text: cleanAns, bold: true, size: 22, color: "000000", font: selectedFont })], alignment: AlignmentType.CENTER })], 
                                        borders: cellBorders,
                                        shading: rowShading,
                                        margins: { top: 60, bottom: 60, left: 30, right: 30 },
                                        width: { size: ansWidth, type: WidthType.DXA } 
                                    }));
                                } else {
                                    rowCells.push(new TableCell({ children: [new Paragraph({ text: "" })], borders: cellBorders, shading: rowShading, margins: { top: 60, bottom: 60, left: 30, right: 30 }, width: { size: numWidth, type: WidthType.DXA } }));
                                    rowCells.push(new TableCell({ children: [new Paragraph({ text: "" })], borders: cellBorders, shading: rowShading, margins: { top: 60, bottom: 60, left: 30, right: 30 }, width: { size: ansWidth, type: WidthType.DXA } }));
                                }
                            }
                            tableRows.push(new TableRow({ children: rowCells }));
                        }

                        children.push(new Table({ 
                            rows: tableRows, 
                            width: { size: availableTableWidth, type: WidthType.DXA },
                            alignment: AlignmentType.CENTER 
                        }));
                    }

                    const secProps = {
                        page: {
                            margin: { top: mTop, right: mRight, bottom: mBottom, left: mLeft },
                            size: {
                                width: dxaWidth,
                                height: dxaHeight,
                                orientation: isLandscape ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT
                            }
                        }
                    };

                    if (columns > 1 && slide.type.includes('question')) {
                        secProps.column = {
                            space: 300,
                            count: columns
                        };
                    }

                    sections.push({
                        properties: secProps,
                        headers: headerObj,
                        children: children
                    });
                });

                const docConfig = {
                    sections: sections,
                    compatibility: isCompatibilityMode,
                    styles: {
                        default: {
                            document: {
                                run: { font: selectedFont }
                            }
                        }
                    }
                };

                const doc = new Document(docConfig);

                Packer.toBlob(doc).then(blob => {
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = `Generated_Presentation_AllSets_${isCompatibilityMode ? 'Compat' : 'Normal'}_${orientation}.docx`;
                    link.click();
                });
            } catch (err) {
                alert("Error exporting Word document: " + err.message);
            }
        }

        async function t2DownloadSpecificSetDOCX(targetSetNum, isCompatibilityMode) {
            if (t2CurrentFilteredQuestions.length === 0) return;

            const questionsPerSet = parseInt(document.getElementById('t2QuestionsPerSet').value) || 10;
            const sets = [];
            for (let i = 0; i < t2CurrentFilteredQuestions.length; i += questionsPerSet) {
                sets.push(t2CurrentFilteredQuestions.slice(i, i + questionsPerSet));
            }

            const targetSetQuestions = sets[targetSetNum - 1];
            if (!targetSetQuestions) return;

            try {
                const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, WidthType, PageOrientation, AlignmentType, Header, ImageRun, BorderStyle, ShadingType } = window.docx;
                const orientation = document.getElementById('t2Orientation').value;
                const pageSizeMode = document.getElementById('t2PageSize').value;
                const resolutionMode = document.getElementById('t2ResolutionQuality').value;
                const baseFontSize = parseInt(document.getElementById('t2BaseFontSize').value) || 45;
                const boldStyleMode = document.getElementById('t2BoldStyleMode').value;
                const selectedFont = document.getElementById('t2FontFamily').value;
                const showAns = document.getElementById('t2ShowAnswerOnSlide').checked;
                const hideOpts = document.getElementById('t2HideOptions').checked;
                const columns = parseInt(document.getElementById('t2ColumnLayout').value) || 1;
                const questionSpacing = parseInt(document.getElementById('t2QuestionSpacing').value) || 12;
                const includeAK = document.getElementById('t2IncludeAnswerKey').checked;

                const enableCodeHighlight = document.getElementById('t2EnableCodeHighlight').checked;
                const enableSyntaxHighlighter = document.getElementById('t2EnableSyntaxHighlighter').checked;
                const enableCodeBorder = document.getElementById('t2EnableCodeBorder').checked;
                const codeBlockBgColor = document.getElementById('t2CodeBlockBgColor').value.replace('#', '');

                const mTop = (parseInt(document.getElementById('t2MarginTop').value) || 120) * 15;
                const mRight = (parseInt(document.getElementById('t2MarginRight').value) || 30) * 15;
                const mBottom = (parseInt(document.getElementById('t2MarginBottom').value) || 120) * 15;
                const mLeft = (parseInt(document.getElementById('t2MarginLeft').value) || 120) * 15;
                const docxSpacingAfter = questionSpacing * 20;

                const hindiColor = document.getElementById('t2HindiColor').value.replace('#', '');
                const englishColor = document.getElementById('t2EnglishColor').value.replace('#', '');
                const optionsColor = document.getElementById('t2OptionsColor').value.replace('#', '');
                const answerKeyColor = document.getElementById('t2AnswerKeyColor').value.replace('#', '');
                const isLandscape = (orientation === 'landscape');

                const isQBold = (boldStyleMode === 'all' || boldStyleMode === 'questions_only' || boldStyleMode === 'questions_and_options');
                const isOptBold = (boldStyleMode === 'all' || boldStyleMode === 'questions_and_options');

                let dxaWidth, dxaHeight;
                if (pageSizeMode === 'hd') {
                    if (resolutionMode === '720p') {
                        dxaWidth = 12825;
                        dxaHeight = 22860;
                    } else {
                        dxaWidth = 19305;
                        dxaHeight = 34290;
                    }
                } else if (pageSizeMode === 'a4') {
                    dxaWidth = 11900;
                    dxaHeight = 16838;
                } else if (pageSizeMode === 'a3') {
                    dxaWidth = 16838;
                    dxaHeight = 23811;
                } else {
                    dxaWidth = 12240;
                    dxaHeight = 15840;
                }

                const basePortraitRef = t2GetPortraitBaseDimensions();

                let headerObj = undefined;
                if (t2RawBgData) {
                    headerObj = {
                        default: new Header({
                            children: [
                                new Paragraph({
                                    children: [
                                        new ImageRun({
                                            data: Uint8Array.from(atob(t2RawBgData.base64), c => c.charCodeAt(0)),
                                            transformation: { 
                                                width: isLandscape ? basePortraitRef.height : basePortraitRef.width, 
                                                height: isLandscape ? basePortraitRef.width : basePortraitRef.height 
                                            },
                                            floating: {
                                                horizontalPosition: { relative: window.docx.HorizontalPositionRelativeFrom.PAGE, offset: 0 },
                                                verticalPosition: { relative: window.docx.VerticalPositionRelativeFrom.PAGE, offset: 0 },
                                                behindDocument: true
                                            }
                                        })
                                    ]
                                })
                            ]
                        })
                    };
                }

                const tempSetQuestions = targetSetQuestions.map((q, qIndex) => ({
                    ...q,
                    displayNum: qIndex + 1
                }));

                const qPerSlide = t2GetSmartQuestionsPerSlide();
                const singleSetSlides = [];

                singleSetSlides.push({ type: 'divider', setNumber: targetSetNum });

                for (let i = 0; i < tempSetQuestions.length; i += qPerSlide) {
                    singleSetSlides.push({
                        type: 'question',
                        setNumber: targetSetNum,
                        questions: tempSetQuestions.slice(i, i + qPerSlide)
                    });
                }

                if (includeAK) {
                    for (let i = 0; i < tempSetQuestions.length; i += 100) {
                        singleSetSlides.push({
                            type: 'answerkey',
                            setNumber: targetSetNum,
                            questions: tempSetQuestions.slice(i, i + 100)
                        });
                    }
                }

                const sections = [];

                singleSetSlides.forEach((slide) => {
                    const children = [];

                    if (slide.type === 'divider') {
                        children.push(new Paragraph({
                            children: [new TextRun({ text: `SET-${slide.setNumber}`, bold: true, size: 96, color: hindiColor, font: selectedFont })],
                            alignment: AlignmentType.CENTER,
                            spacing: { before: 2000, after: 1000 }
                        }));
                    } else if (slide.type === 'question') {
                        slide.questions.forEach((q, qIdx) => {
                            const activePt = t2GetActivePtForQuestion(q, baseFontSize);
                            const qNum = q.displayNum;
                            const isLastInSlide = (qIdx === slide.questions.length - 1);
                            const currentAfterSpace = isLastInSlide ? 50 : docxSpacingAfter;

                            let textParagraphs = [];

                            if (q.hindiQ) {
                                textParagraphs.push(new Paragraph({
                                    children: [new TextRun({ text: `Q${qNum}. ${q.hindiQ}`, bold: isQBold, size: Math.round(activePt * 2), color: hindiColor, font: selectedFont })],
                                    spacing: { before: 25, after: 10, line: 300, lineRule: "auto" }
                                }));
                            }
                            if (q.englishQ) {
                                textParagraphs.push(new Paragraph({
                                    children: [new TextRun({ text: q.englishQ, bold: isQBold, size: Math.round(activePt * 2), color: englishColor, font: selectedFont })],
                                    spacing: { after: 12, line: 300, lineRule: "auto" }
                                }));
                            }

                            if (q.statements && q.statements.length > 0) {
                                q.statements.forEach(stmt => {
                                    textParagraphs.push(new Paragraph({
                                        children: [new TextRun({ text: stmt, bold: isQBold, size: Math.round(activePt * 1.7), color: englishColor, font: selectedFont })],
                                        indent: { left: 280 },
                                        spacing: { after: 8, line: 300, lineRule: "auto" }
                                    }));
                                });
                            }

                            if (q.codeBlock) {
                                const codeLines = q.codeBlock.split('\n');
                                const codeParagraphs = codeLines.map((cLine) => {
                                    let leadingMatch = cLine.match(/^(\s*)/);
                                    let leadingSpaces = leadingMatch ? leadingMatch[1].length : 0;
                                    let NBSP = '\u00A0'.repeat(leadingSpaces);
                                    let lineText = NBSP + cLine.trimStart();

                                    let lineRuns = [];
                                    if (enableSyntaxHighlighter) {
                                        lineRuns = t2TokenizeCodeForDocxLine(lineText, Math.round(activePt * 1.6));
                                    } else {
                                        lineRuns = [new window.docx.TextRun({ text: lineText, font: "Fira Code", size: Math.round(activePt * 1.6), color: "0F172A" })];
                                    }

                                    return new Paragraph({
                                        children: lineRuns,
                                        spacing: { before: 0, after: 0, line: 240, lineRule: "auto" }
                                    });
                                });

                                const cellProps = {
                                    children: codeParagraphs,
                                    width: { size: 0, type: WidthType.AUTO },
                                    margins: { top: 60, bottom: 60, left: 100, right: 100 }
                                };

                                if (enableCodeHighlight) {
                                    cellProps.shading = { fill: codeBlockBgColor, type: ShadingType.CLEAR, color: "auto" };
                                }
                                if (enableCodeBorder) {
                                    const borderConfig = { style: BorderStyle.SINGLE, size: 12, color: "CBD5E1" };
                                    cellProps.borders = { top: borderConfig, bottom: borderConfig, left: borderConfig, right: borderConfig };
                                }

                                const codeTable = new Table({
                                    rows: [new TableRow({ children: [new TableCell(cellProps)] })],
                                    width: { size: 0, type: WidthType.AUTO }
                                });

                                textParagraphs.push(codeTable);
                                textParagraphs.push(new Paragraph({ spacing: { after: 12 } }));
                            }

                            if (!hideOpts && q.options) {
                                q.options.forEach((opt, optIdx) => {
                                    const isLastOpt = (optIdx === q.options.length - 1);
                                    const optAfterSpace = (isLastOpt && !showAns) ? currentAfterSpace : 12;
                                    textParagraphs.push(new Paragraph({
                                        children: [new TextRun({ text: `${opt.prefix ? opt.prefix + ' ' : ''}${opt.text}`, bold: isOptBold, size: Math.round(activePt * 1.7), color: optionsColor, font: selectedFont })],
                                        indent: { left: 420, hanging: 230 },
                                        spacing: { after: optAfterSpace, line: 300, lineRule: "auto" }
                                    }));
                                });
                            }
                            if (showAns && q.answer) {
                                let cleanAnswerText = q.answer.trim();
                                if (!cleanAnswerText.startsWith('(')) {
                                    cleanAnswerText = `(${cleanAnswerText})`;
                                }
                                textParagraphs.push(new Paragraph({
                                    children: [new TextRun({ text: `Answer: ${cleanAnswerText}`, bold: true, size: Math.round(activePt * 1.7), color: answerKeyColor, font: selectedFont })],
                                    spacing: { before: 12, after: currentAfterSpace, line: 300, lineRule: "auto" }
                                }));
                            }

                            if (q.image) {
                                try {
                                    const base64DataImg = q.image.split(',')[1];
                                    const uint8Arr = Uint8Array.from(atob(base64DataImg), c => c.charCodeAt(0));
                                    
                                    const imgPara = new Paragraph({
                                        children: [
                                            new ImageRun({
                                                data: uint8Arr,
                                                transformation: { width: 300, height: 210 }
                                            })
                                        ],
                                        alignment: AlignmentType.RIGHT
                                    });

                                    const availableWidth = dxaWidth - mLeft - mRight;
                                    const leftColWidth = Math.floor(availableWidth * 0.58);
                                    const rightColWidth = Math.floor(availableWidth * 0.42);

                                    const noBorderConfig = { style: BorderStyle.NONE, size: 0, color: "auto" };
                                    const borderlessConfig = { top: noBorderConfig, bottom: noBorderConfig, left: noBorderConfig, right: noBorderConfig };

                                    const layoutTable = new Table({
                                        rows: [
                                            new TableRow({
                                                children: [
                                                    new TableCell({
                                                        children: textParagraphs,
                                                        width: { size: leftColWidth, type: WidthType.DXA },
                                                        verticalAlign: window.docx.VerticalAlign.TOP,
                                                        borders: borderlessConfig
                                                    }),
                                                    new TableCell({
                                                        children: [imgPara],
                                                        width: { size: rightColWidth, type: WidthType.DXA },
                                                        verticalAlign: window.docx.VerticalAlign.TOP,
                                                        borders: borderlessConfig
                                                    })
                                                ]
                                            })
                                        ],
                                        width: { size: availableWidth, type: WidthType.DXA },
                                        alignment: AlignmentType.CENTER
                                    });

                                    children.push(layoutTable);
                                    children.push(new Paragraph({ spacing: { after: 20 } }));
                                } catch (e) {
                                    children.push(...textParagraphs);
                                }
                            } else {
                                children.push(...textParagraphs);
                            }
                        });
                    } else if (slide.type === 'answerkey') {
                        let akHeading = `ANSWER KEY SET-${slide.setNumber}`;
                        children.push(new Paragraph({
                            children: [new TextRun({ text: akHeading, bold: true, size: 36, color: "CC0000", font: selectedFont })],
                            alignment: AlignmentType.CENTER,
                            spacing: { before: 150, after: 200 }
                        }));

                        const chunkQ = slide.questions;
                        const totalQ = Math.min(100, chunkQ.length);
                        const colsCount = Math.ceil(totalQ / 10);
                        const rowsPerCol = 10;
                        
                        const tableRows = [];
                        const borderCfg = { style: BorderStyle.SINGLE, size: 8, color: "000000" };
                        const cellBorders = { top: borderCfg, bottom: borderCfg, left: borderCfg, right: borderCfg };

                        const availableTableWidth = dxaWidth - mLeft - mRight;
                        const totalCellsPerColumnPair = colsCount * 2;
                        const baseCellWidth = Math.floor(availableTableWidth / totalCellsPerColumnPair);
                        const numWidth = Math.max(360, Math.floor(baseCellWidth * 0.75));
                        const ansWidth = Math.max(480, Math.floor(baseCellWidth * 1.25));

                        for (let r = 0; r < rowsPerCol; r++) {
                            const rowCells = [];
                            const isEvenRow = (r % 2 !== 0);
                            const rowShading = isEvenRow ? { fill: "D1D5DB", type: ShadingType.CLEAR, color: "auto" } : undefined;

                            for (let c = 0; c < colsCount; c++) {
                                const localIndex = r + (c * rowsPerCol);
                                if (localIndex < totalQ) {
                                    const qNum = localIndex + 1;
                                    let ansRaw = chunkQ[localIndex].answer || '-';
                                    let cleanAns = ansRaw.replace(/[\(\)]/g, '').trim().charAt(0).toUpperCase();
                                    
                                    rowCells.push(new TableCell({ 
                                        children: [new Paragraph({ children: [new TextRun({ text: qNum.toString(), bold: true, size: 22, color: "000000", font: selectedFont })], alignment: AlignmentType.CENTER })], 
                                        borders: cellBorders,
                                        shading: rowShading,
                                        margins: { top: 60, bottom: 60, left: 30, right: 30 },
                                        width: { size: numWidth, type: WidthType.DXA } 
                                    }));
                                    rowCells.push(new TableCell({ 
                                        children: [new Paragraph({ children: [new TextRun({ text: cleanAns, bold: true, size: 22, color: "000000", font: selectedFont })], alignment: AlignmentType.CENTER })], 
                                        borders: cellBorders,
                                        shading: rowShading,
                                        margins: { top: 60, bottom: 60, left: 30, right: 30 },
                                        width: { size: ansWidth, type: WidthType.DXA } 
                                    }));
                                } else {
                                    rowCells.push(new TableCell({ children: [new Paragraph({ text: "" })], borders: cellBorders, shading: rowShading, margins: { top: 60, bottom: 60, left: 30, right: 30 }, width: { size: numWidth, type: WidthType.DXA } }));
                                    rowCells.push(new TableCell({ children: [new Paragraph({ text: "" })], borders: cellBorders, shading: rowShading, margins: { top: 60, bottom: 60, left: 30, right: 30 }, width: { size: ansWidth, type: WidthType.DXA } }));
                                }
                            }
                            tableRows.push(new TableRow({ children: rowCells }));
                        }

                        children.push(new Table({ 
                            rows: tableRows, 
                            width: { size: availableTableWidth, type: WidthType.DXA },
                            alignment: AlignmentType.CENTER 
                        }));
                    }

                    const secProps = {
                        page: {
                            margin: { top: mTop, right: mRight, bottom: mBottom, left: mLeft },
                            size: {
                                width: dxaWidth,
                                height: dxaHeight,
                                orientation: isLandscape ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT
                            }
                        }
                    };

                    if (columns > 1 && slide.type.includes('question')) {
                        secProps.column = {
                            space: 300,
                            count: columns.toString()
                        };
                    }

                    sections.push({
                        properties: secProps,
                        headers: headerObj,
                        children: children
                    });
                });

                const docConfig = {
                    sections: sections,
                    compatibility: isCompatibilityMode,
                    styles: {
                        default: {
                            document: {
                                run: { font: selectedFont }
                            }
                        }
                    }
                };

                const doc = new Document(docConfig);

                Packer.toBlob(doc).then(blob => {
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = `GyanXp_Set_${targetSetNum}_${orientation}.docx`;
                    link.click();
                });
            } catch (err) {
                alert("Error exporting set document: " + err.message);
            }
        }
    </script>
    <!-- Include Docx.js Library for Tool 2 & Native Tool 1 Word Export -->
    <script src="https://cdn.jsdelivr.net/npm/docx@8.5.0/build/index.umd.js"></script>
</body>
</html>				</div>
				</div>
					</div>
		</div>
					</div>
		</section>
				</div>
		<p>The post <a href="https://gyanxp.com/tool/">tool</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/tool/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>iul</title>
		<link>https://gyanxp.com/iul/</link>
					<comments>https://gyanxp.com/iul/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Tue, 18 Aug 2026 14:50:24 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=6264</guid>

					<description><![CDATA[<p>University Exam Seating &#038; Attendance System Select Course Code(s) for Attendance Sheets ✕ Select one or more course codes below. 0 Selected Select All &#124; Deselect All No course codes detected. Generate reports first. Cancel Generate &#038; View Restricted Access University Exam Seating &#038; Attendance System Portal Invalid User ID or Password. Please try again. [&#8230;]</p>
<p>The post <a href="https://gyanxp.com/iul/">iul</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[		<div data-elementor-type="wp-post" data-elementor-id="6264" class="elementor elementor-6264">
						<section class="elementor-section elementor-top-section elementor-element elementor-element-4cd98a4 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="4cd98a4" data-element_type="section" data-e-type="section">
						<div class="elementor-container elementor-column-gap-default">
					<div class="elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-d387464" data-id="d387464" data-element_type="column" data-e-type="column">
			<div class="elementor-widget-wrap elementor-element-populated">
						<div class="elementor-element elementor-element-52f3c63 elementor-widget elementor-widget-html" data-id="52f3c63" data-element_type="widget" data-e-type="widget" data-widget_type="html.default">
				<div class="elementor-widget-container">
					<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>University Exam Seating & Attendance System</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js"></script>
  <style>
    /* Print Orientation & Formatting Rules */
    @media print {
      body * {
        visibility: hidden !important;
      }
      #print-area, #print-area * {
        visibility: visible !important;
      }
      #print-area {
        position: absolute !important;
        left: 0 !important;
        top: 0 !important;
        width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
      }
      .no-print {
        display: none !important;
      }

      .page-break {
        page-break-after: always !important;
        break-after: page !important;
        height: 100vh !important;
        max-height: 100vh !important;
        display: flex !important;
        flex-direction: column !important;
        justify-content: space-between !important;
        overflow: hidden !important;
      }

      .detained-row {
        background-color: #fee2e2 !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      .detained-cell {
        background-color: #fca5a5 !important;
        color: #991b1b !important;
        font-weight: bold !important;
        text-decoration: line-through !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      .custom-header-box {
        background: #fff !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      .cohort-a-cell {
        background-color: #ffffff !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      .cohort-b-cell {
        background-color: #f1f5f9 !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
    }

    /* Page Setup & Margins */
    @page portrait-page {
      size: A4 portrait;
      margin: 6mm 10mm 6mm 10mm;
    }
    @page landscape-page {
      size: A4 landscape;
      margin: 6mm 10mm 6mm 10mm;
    }

    .portrait-view {
      page: portrait-page;
    }
    .landscape-view {
      page: landscape-page;
    }

    /* Professional Double-Ribbon Header Box */
    .pro-header-container {
      border: 2px solid #0f172a;
      border-radius: 6px;
      padding: 6px 10px;
      margin-bottom: 6px;
      background: #ffffff;
      box-shadow: 0 1px 3px rgba(0,0,0,0.05);
      position: relative;
    }
    .pro-header-divider {
      height: 2px;
      background: linear-gradient(90deg, #0f172a 0%, #2563eb 50%, #0f172a 100%);
      margin: 4px 0;
    }

    /* 1. Exact Student List & Attendance Table CSS (Portrait) */
    .report-table {
      width: 100%;
      border-collapse: collapse;
      border: 2px solid #0f172a;
      font-family: Arial, Helvetica, sans-serif;
      margin-bottom: 4px;
    }
    .report-table th, .report-table td {
      border: 1px solid #334155;
      padding: 3px 5px;
      font-size: 11px;
      line-height: 1.15;
    }
    .header-cell {
      border: 1px solid #0f172a;
      text-align: center;
      font-weight: bold;
      padding: 4px;
    }
    .cohort-header {
      border: 1.5px solid #0f172a;
      text-align: center;
      font-weight: 800;
      font-size: 12px;
      padding: 3px;
      text-transform: uppercase;
      letter-spacing: 0.06em;
    }
    .col-sno { width: 45px; text-align: center; font-weight: 700; }
    .col-roll { width: 130px; text-align: left; font-size: 12px; font-weight: 700; }
    .col-enroll { width: 140px; text-align: left; font-size: 12px; font-weight: 700; }
    .col-name { text-align: left; text-transform: uppercase; font-weight: 700; font-size: 12px; }
    .col-group { width: 85px; text-align: center; font-weight: 700; }
    .col-sign { width: 130px; text-align: center; }
    .col-reason { width: 150px; text-align: center; font-weight: 800; color: #b91c1c; }

    /* Highlight classes */
    .detained-row {
      background-color: #fee2e2;
    }
    .detained-cell {
      background-color: #fca5a5;
      color: #991b1b;
      font-weight: bold;
      text-decoration: line-through;
    }

    /* Cohort Shadow Differentiation Classes for Seating Matrix */
    .cohort-a-cell {
      background-color: #ffffff;
    }
    .cohort-b-cell {
      background-color: #f1f5f9;
    }

    /* 2. Seating Matrix CSS (Landscape) */
    .matrix-table {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;
      border: 2px solid #0f172a;
      font-family: Arial, Helvetica, sans-serif;
    }
    .matrix-table td {
      border: 1px solid #334155;
      padding: 3px 2px;
      font-size: 11px;
      text-align: center;
      line-height: 1.2;
      height: 36px;
      vertical-align: middle;
      word-break: break-word;
    }
    .matrix-aisle {
      border-top: none !important;
      border-bottom: none !important;
      border-left: 2px solid #0f172a !important;
      border-right: 2px solid #0f172a !important;
      width: 32px !important;
      background: #f8fafc;
    }
  </style>
</head>
<body class="bg-slate-100 font-sans text-slate-900 min-h-screen">

  <!-- Course Code Selection Modal for Separate Course Code Wise Attendance Sheets -->
  <div id="courseCodeModal" class="hidden fixed inset-0 z-50 bg-slate-950/70 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full p-6 space-y-4 border border-slate-200">
      <div class="flex justify-between items-center border-b pb-3">
        <h3 class="text-sm font-black text-slate-900 uppercase">Select Course Code(s) for Attendance Sheets</h3>
        <button onclick="closeCourseCodeModal()" class="text-slate-400 hover:text-slate-700 font-bold text-lg">✕</button>
      </div>
      <div class="flex justify-between items-center text-xs">
        <p class="text-slate-500 font-medium">Select one or more course codes below.</p>
        <span id="selectedCourseCountBadge" class="bg-indigo-100 text-indigo-800 font-bold px-2.5 py-0.5 rounded-full text-[11px]">0 Selected</span>
      </div>
      
      <div class="flex items-center gap-2 py-1">
        <button onclick="toggleAllCourseCodes(true)" class="text-[11px] font-bold text-indigo-600 hover:underline">Select All</button>
        <span class="text-slate-300">|</span>
        <button onclick="toggleAllCourseCodes(false)" class="text-[11px] font-bold text-slate-600 hover:underline">Deselect All</button>
      </div>

      <div id="courseCodeCheckboxContainer" class="max-h-60 overflow-y-auto space-y-2 border p-3 rounded-lg bg-slate-50">
        <p class="text-xs text-slate-400 italic">No course codes detected. Generate reports first.</p>
      </div>

      <div class="flex justify-end gap-2 pt-3 border-t">
        <button onclick="closeCourseCodeModal()" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-800 text-xs font-bold rounded-lg transition">Cancel</button>
        <button onclick="confirmGenerateCourseCodeAttendance()" class="px-5 py-2 bg-indigo-700 hover:bg-indigo-800 text-white text-xs font-bold rounded-lg shadow transition">Generate & View</button>
      </div>
    </div>
  </div>

  <!-- Login Overlay Section -->
  <div id="loginOverlay" class="fixed inset-0 z-50 bg-slate-950 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-8 space-y-6 border border-slate-200">
      <div class="text-center space-y-2">
        <h2 class="text-2xl font-black text-slate-900 uppercase tracking-wide">Restricted Access</h2>
        <p class="text-xs text-slate-500 font-medium">University Exam Seating & Attendance System Portal</p>
      </div>
      
      <div id="loginError" class="hidden bg-red-50 border border-red-200 text-red-700 text-xs p-3 rounded-lg font-semibold text-center">
        Invalid User ID or Password. Please try again.
      </div>

      <div class="space-y-4">
        <div>
          <label class="block text-xs font-bold text-slate-700 mb-1">USER ID</label>
          <input id="loginUserId" type="text" placeholder="Enter User ID" class="w-full border rounded-lg p-3 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-600 focus:outline-none" />
        </div>
        <div>
          <label class="block text-xs font-bold text-slate-700 mb-1">PASSWORD</label>
          <input id="loginPassword" type="password" placeholder="Enter Password" class="w-full border rounded-lg p-3 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-600 focus:outline-none" />
        </div>
        <button onclick="handleLogin()" class="w-full bg-indigo-700 hover:bg-indigo-800 text-white py-3 rounded-lg text-xs font-extrabold shadow-lg transition tracking-wider uppercase">
          Login to System
        </button>
      </div>
      <div class="text-center">
        <p class="text-[10px] text-slate-400 font-medium">Department of Computer Science & Engineering, Integral University</p>
      </div>
    </div>
  </div>

  <!-- Main Application Wrapper (Hidden until authenticated) -->
  <div id="appContainer" class="hidden">
    <!-- Application Navbar -->
    <header class="bg-slate-900 text-white shadow sticky top-0 z-50 no-print">
      <div class="max-w-7xl mx-auto px-6 py-3 flex flex-wrap justify-between items-center gap-4">
        <div>
          <div class="flex items-center gap-2">
            <h1 class="text-lg font-bold">University Exam Seating Plan & Report Generator</h1>
            <span class="bg-indigo-700 text-indigo-100 text-[10px] font-bold px-2 py-0.5 rounded">v10.2 Pro</span>
          </div>
          <p class="text-xs text-indigo-300 font-medium tracking-wide mt-0.5">
            Develop by Balmukund Maurya, Integral University, Department of CSE
          </p>
        </div>
        <div class="flex items-center gap-3">
          <button onclick="exportToWordDoc()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold shadow flex items-center gap-2 transition">
            <span>📄 Export Word (.doc)</span>
          </button>
          <button onclick="safePrintReport()" class="bg-emerald-600 hover:bg-emerald-700 text-white px-5 py-2 rounded-lg text-xs font-bold shadow flex items-center gap-2 transition">
            <span>🖨️ Print / Save PDF</span>
          </button>
          <button onclick="handleLogout()" class="bg-red-600 hover:bg-red-700 text-white px-3 py-2 rounded-lg text-xs font-bold shadow transition" title="Logout">
            <span>Logout</span>
          </button>
        </div>
      </div>
    </header>

    <main class="max-w-7xl mx-auto p-6 space-y-6 no-print">

      <!-- TOP ANALYSIS DASHBOARD -->
      <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Total Rooms</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashRooms" class="text-lg font-extrabold text-slate-900">0</span>
            <span class="text-[9px] text-slate-400 font-medium">Configured</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Total Capacity</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashTotalCap" class="text-lg font-extrabold text-indigo-700">0</span>
            <span class="text-[9px] text-indigo-400 font-medium">Seats</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Total Students</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashTotalStudents" class="text-lg font-extrabold text-slate-900">0</span>
            <span class="text-[9px] text-slate-400 font-medium">Slot A + B</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Allotted Students</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashAllotted" class="text-lg font-extrabold text-emerald-700">0</span>
            <span class="text-[9px] text-emerald-500 font-medium">Seated</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Cohort A / B</span>
          <div class="flex items-baseline justify-between mt-1">
            <span class="text-xs font-bold text-indigo-900"><span id="dashA">0</span> / <span id="dashB">0</span></span>
            <span class="text-[9px] text-slate-400 font-medium">Enrolled</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-red-600 uppercase tracking-wider">Detained</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashDetained" class="text-lg font-extrabold text-red-600">0</span>
            <span class="text-[9px] text-red-400 font-medium">Marked</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-amber-600 uppercase tracking-wider">Unallotted</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashUnallotted" class="text-lg font-extrabold text-amber-600">0</span>
            <span class="text-[9px] text-amber-400 font-medium">Overflow</span>
          </div>
        </div>

        <div class="bg-white p-3 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
          <span class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Occupancy</span>
          <div class="flex items-baseline justify-between mt-1">
            <span id="dashOccupancy" class="text-lg font-extrabold text-emerald-600">0%</span>
            <span id="dashVacant" class="text-[9px] text-emerald-600 font-medium">0 Vacant</span>
          </div>
        </div>
      </div>

      <!-- Advanced Deep Analysis Breakdown Cards -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
        <div class="bg-white p-3.5 rounded-xl border border-slate-200 shadow-sm space-y-2">
          <div class="flex justify-between items-center text-xs">
            <span class="font-bold text-slate-700">Room Utilization Overview</span>
            <span id="utilizationRatio" class="font-bold text-indigo-700 text-[11px]">0 / 0 Seats</span>
          </div>
          <div class="w-full bg-slate-100 rounded-full h-2.5 overflow-hidden flex">
            <div id="utilizationBar" class="bg-indigo-600 h-2.5 transition-all duration-500" style="width: 0%"></div>
          </div>
          <div class="flex justify-between text-[10px] text-slate-500 font-medium pt-0.5">
            <span>Utilization Rate</span>
            <span id="utilizationPct" class="font-bold text-slate-700">0%</span>
          </div>
        </div>

        <div class="bg-white p-3.5 rounded-xl border border-slate-200 shadow-sm space-y-2">
          <div class="flex justify-between items-center text-xs">
            <span class="font-bold text-slate-700">Cohort Distribution Mix</span>
            <span class="text-[10px] text-slate-500 font-medium">Ratio A : B</span>
          </div>
          <div class="w-full bg-slate-100 rounded-full h-2.5 overflow-hidden flex">
            <div id="cohortABar" class="bg-indigo-500 h-2.5" style="width: 50%" title="Cohort A"></div>
            <div id="cohortBBar" class="bg-emerald-500 h-2.5" style="width: 50%" title="Cohort B"></div>
          </div>
          <div class="flex justify-between text-[10px] font-semibold pt-0.5">
            <span class="text-indigo-700 flex items-center gap-1"><span class="w-1.5 h-1.5 rounded-full bg-indigo-500 inline-block"></span> Cohort A: <span id="cohortAPct">0%</span></span>
            <span class="text-emerald-700 flex items-center gap-1"><span class="w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block"></span> Cohort B: <span id="cohortBPct">0%</span></span>
          </div>
        </div>

        <div class="bg-white p-3.5 rounded-xl border border-slate-200 shadow-sm space-y-1.5">
          <div class="flex justify-between items-center text-xs">
            <span class="font-bold text-slate-700">Branch & Section Breakdown</span>
            <div class="flex items-center gap-2">
              <span id="groupTotalBadge" class="text-[10px] bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded font-bold">0 Sections</span>
              <button onclick="printBranchSectionPdf()" class="bg-rose-600 hover:bg-rose-700 text-white text-[10px] px-2 py-0.5 rounded font-bold shadow transition" title="Download Branch & Section PDF">📥 PDF</button>
            </div>
          </div>
          <div id="groupStatsContainer" class="flex flex-wrap gap-1 max-h-12 overflow-y-auto pr-1">
            <span class="text-[11px] text-slate-400 italic">Generate report to view branch breakdown</span>
          </div>
        </div>
      </div>

      <!-- Used and Unused Rooms Detailed Status Card -->
      <div class="bg-white p-4 rounded-xl border border-slate-200 shadow-sm space-y-2">
        <div class="flex justify-between items-center text-xs border-b pb-1.5">
          <span class="font-bold text-slate-800">Rooms Allocation Status (Used vs Unused)</span>
          <span class="text-[10px] text-slate-500 font-semibold" id="roomStatusSummaryBadge">0 Used / 0 Unused</span>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 pt-1">
          <div class="bg-emerald-50/50 border border-emerald-200 p-2.5 rounded-lg">
            <div class="text-[11px] font-bold text-emerald-900 mb-1 flex items-center gap-1">
              <span>✅ Used Rooms:</span>
              <span id="usedRoomsCount" class="bg-emerald-200 text-emerald-950 px-1.5 py-0.5 rounded text-[10px]">0</span>
            </div>
            <div id="usedRoomsList" class="text-[11px] text-emerald-800 font-medium flex flex-wrap gap-1">
              <span class="italic text-slate-400">None</span>
            </div>
          </div>
          <div class="bg-slate-50 border border-slate-200 p-2.5 rounded-lg">
            <div class="text-[11px] font-bold text-slate-700 mb-1 flex items-center gap-1">
              <span>📌 Unused Rooms:</span>
              <span id="unusedRoomsCount" class="bg-slate-200 text-slate-800 px-1.5 py-0.5 rounded text-[10px]">0</span>
            </div>
            <div id="unusedRoomsList" class="text-[11px] text-slate-600 font-medium flex flex-wrap gap-1">
              <span class="italic text-slate-400">None</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Room-Wise Subject / Question Paper Count Summary -->
      <div class="bg-white p-5 rounded-xl border border-slate-200 shadow-sm space-y-3">
        <div class="flex justify-between items-center border-b pb-2 flex-wrap gap-3">
          <div>
            <h2 class="font-bold text-slate-800 text-sm">📊 Room-Wise Subject / Question Paper Count Summary (Cohort A & B)</h2>
            <p class="text-[11px] text-slate-500">Breakdown of question paper requirements per room for all uploaded student subjects.</p>
          </div>
          <div class="flex gap-2 flex-wrap">
            <button onclick="generateSubjectPaperSummary()" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs px-3 py-1.5 rounded font-bold shadow transition">
              🔄 Refresh Counts
            </button>
            <button onclick="downloadSubjectPaperSummaryExcel()" class="bg-emerald-600 hover:bg-emerald-700 text-white text-xs px-3 py-1.5 rounded font-bold shadow flex items-center gap-1.5 transition">
              <span>📥 Download Excel (.xlsx)</span>
            </button>
            <button onclick="printSubjectPaperSummaryPdf()" class="bg-rose-600 hover:bg-rose-700 text-white text-xs px-3 py-1.5 rounded font-bold shadow flex items-center gap-1.5 transition">
              <span>🖨️ Download PDF / Print</span>
            </button>
          </div>
        </div>
        <div id="subjectPaperSummaryContainer" class="overflow-x-auto max-h-96">
          <p class="text-xs text-slate-400 italic py-2">Generate reports to calculate subject-wise question paper distribution per room.</p>
        </div>
      </div>

      <!-- 0. Download Sample Excel Templates Bar -->
      <div class="bg-gradient-to-r from-slate-800 to-indigo-900 text-white p-4 rounded-xl shadow-sm flex flex-wrap items-center justify-between gap-4">
        <div>
          <h2 class="text-sm font-bold flex items-center gap-2">
            <span>📥 Download Sample Excel Templates</span>
          </h2>
          <p class="text-[11px] text-slate-300">Download ready-to-use template spreadsheets with proper column formatting.</p>
        </div>
        <div class="flex flex-wrap gap-2">
          <button onclick="downloadSampleRoomsExcel()" class="bg-white/10 hover:bg-white/20 border border-white/30 text-white px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition">
            <span>🏢 Rooms Template</span>
          </button>
          <button onclick="downloadSampleCourseExcel('A')" class="bg-white/10 hover:bg-white/20 border border-white/30 text-white px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition">
            <span>🎓 Course A Template</span>
          </button>
          <button onclick="downloadSampleCourseExcel('B')" class="bg-white/10 hover:bg-white/20 border border-white/30 text-white px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition">
            <span>🎓 Course B Template</span>
          </button>
          <button onclick="downloadSampleDetainedExcel()" class="bg-red-500/20 hover:bg-red-500/30 border border-red-400/40 text-red-200 px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition">
            <span>🚫 Detained Template</span>
          </button>
        </div>
      </div>

      <!-- 1. Header Information & Shift Branding -->
      <div class="bg-white p-5 rounded-xl border border-slate-200 shadow-sm space-y-4">
        <h2 class="font-bold text-slate-800 text-sm border-b pb-2">1. University, Examination & Session Details</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="block text-xs font-bold text-slate-700 mb-1">UNIVERSITY NAME</label>
            <input id="uniTitle" type="text" value="INTEGRAL UNIVERSITY" class="w-full border rounded p-2 text-xs font-bold text-slate-800" />
          </div>
          <div>
            <label class="block text-xs font-bold text-slate-700 mb-1">DEPARTMENT & SHIFT</label>
            <input id="deptShiftHeader" type="text" value="Department of CSE: Seating Plan 1st and 3rd Shift" class="w-full border rounded p-2 text-xs font-semibold text-slate-800" />
          </div>
          <div>
            <label class="block text-xs font-bold text-slate-700 mb-1">PROGRAM / DEGREE LINE</label>
            <input id="progHeader" type="text" value="Bachelor of Technology - Computer Science & Engineering" class="w-full border rounded p-2 text-xs font-semibold text-slate-800" />
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-1">
          <div>
            <label class="block text-xs font-bold text-indigo-900 mb-1">EXAMINATION NAME / TEST TITLE</label>
            <input id="examName" type="text" value="FIRST CONTINUOUS ASSESSMENT (ODD SEMESTER)" class="w-full border border-indigo-200 bg-indigo-50/30 rounded p-2 text-xs font-bold text-indigo-950" />
          </div>
          <div>
            <label class="block text-xs font-bold text-indigo-900 mb-1">ACADEMIC SESSION / YEAR</label>
            <input id="examSession" type="text" value="ACADEMIC SESSION 2026-2027" class="w-full border border-indigo-200 bg-indigo-50/30 rounded p-2 text-xs font-bold text-indigo-950" />
          </div>
        </div>
      </div>

      <!-- 2. Room & Grid Matrix Configuration -->
      <div class="bg-white p-5 rounded-xl border border-slate-200 shadow-sm space-y-3">
        <div class="flex justify-between items-center border-b pb-2">
          <div>
            <h2 class="font-bold text-slate-800 text-sm">2. Room Roster & Seating Grids</h2>
            <p class="text-[11px] text-slate-500">Configure rooms manually or upload room list via Excel/CSV (Columns: Room No, Block, Rows, Columns, Capacity).</p>
          </div>
          <div class="flex items-center gap-2">
            <span id="roomCountBadge" class="text-xs bg-indigo-100 text-indigo-800 px-2.5 py-0.5 rounded font-bold">0 Rooms</span>
            <span id="totalCapBadge" class="text-xs bg-emerald-100 text-emerald-800 px-2.5 py-0.5 rounded font-bold">Total Capacity: 0</span>
          </div>
        </div>

        <!-- Optional Room Excel Upload -->
        <div class="bg-indigo-50/60 border border-indigo-200 p-2.5 rounded-lg flex flex-wrap items-center justify-between gap-3">
          <div class="flex items-center gap-2">
            <span class="text-xs font-bold text-indigo-900">📂 Upload Room List Excel/CSV (Optional):</span>
            <input type="file" id="fileRooms" accept=".csv, .xlsx, .xls" class="text-xs text-slate-500 file:mr-2 file:py-1 file:px-2.5 file:rounded file:border-0 file:text-xs file:bg-indigo-600 file:text-white" />
          </div>
          <button onclick="clearAllRooms()" class="text-xs text-red-600 font-bold hover:underline">Clear All Rooms</button>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-6 gap-2 bg-slate-50 p-3 rounded-lg border">
          <div>
            <label class="text-[10px] font-bold text-slate-600">ROOM NO.</label>
            <input id="rName" placeholder="e.g. E319" value="E319" class="w-full border rounded p-1.5 text-xs font-bold" />
          </div>
          <div>
            <label class="text-[10px] font-bold text-slate-600">BLOCK</label>
            <input id="rBlock" placeholder="e.g. BNLT" value="BNLT" class="w-full border rounded p-1.5 text-xs" />
          </div>
          <div>
            <label class="text-[10px] font-bold text-slate-600">ROWS</label>
            <input id="rRows" type="number" value="12" min="1" class="w-full border rounded p-1.5 text-xs font-semibold" />
          </div>
          <div>
            <label class="text-[10px] font-bold text-slate-600">COLUMNS</label>
            <input id="rCols" type="number" value="8" min="2" class="w-full border rounded p-1.5 text-xs font-semibold" />
          </div>
          <div>
            <label class="text-[10px] font-bold text-slate-600">CAPACITY</label>
            <input id="rCap" type="number" value="96" readonly class="w-full border bg-slate-200 rounded p-1.5 text-xs font-bold text-indigo-900" />
          </div>
          <div class="flex items-end">
            <button onclick="addCustomRoom()" class="w-full bg-slate-800 hover:bg-black text-white text-xs py-2 rounded font-bold">+ Add Room</button>
          </div>
        </div>

        <div class="flex flex-wrap gap-2 pt-1">
          <span class="text-slate-500 font-semibold text-[11px] self-center">Presets:</span>
          <button onclick="applyPreset('E319', 'BNLT', 12, 8)" class="px-2.5 py-1 bg-slate-200 hover:bg-slate-300 rounded text-slate-700 text-xs font-medium">E319/BNLT (12R × 8C = 96)</button>
          <button onclick="applyPreset('E410', 'BNLT', 8, 6)" class="px-2.5 py-1 bg-slate-200 hover:bg-slate-300 rounded text-slate-700 text-xs font-medium">E410/BNLT (8R × 6C = 48)</button>
          <button onclick="applyPreset('E107', 'BNLT BLOCK', 8, 6)" class="px-2.5 py-1 bg-slate-200 hover:bg-slate-300 rounded text-slate-700 text-xs font-medium">E107 (8R × 6C = 48)</button>
        </div>

        <!-- Room Order Arrangement List -->
        <div class="border-t pt-2 space-y-1">
          <div class="text-[11px] font-bold text-slate-700 mb-1">ROOM ALLOCATION ORDER (Use ⬆ / ⬇ to reorder):</div>
          <div id="roomPillsContainer" class="flex flex-col gap-1.5 max-h-48 overflow-y-auto pr-1"></div>
        </div>
      </div>

      <!-- 3. Multi-File Student Uploads & Detained List Section -->
      <div class="bg-white p-5 rounded-xl border border-slate-200 shadow-sm space-y-4">
        <h2 class="font-bold text-slate-800 text-sm border-b pb-2">3. Upload Course Files, Optional Mapping & Detained List</h2>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <!-- Slot A -->
          <div class="border border-indigo-200 bg-indigo-50/40 p-3 rounded-xl space-y-2">
            <div class="flex justify-between items-center">
              <span class="text-xs font-bold text-indigo-900 uppercase">📁 Cohort A (1st Sem)</span>
              <span id="badgeCountA" class="text-xs bg-indigo-200 text-indigo-900 px-2 py-0.5 rounded font-bold">0</span>
            </div>
            <div>
              <label class="block text-[10px] font-semibold text-slate-600 mb-0.5">SECTION HEADER</label>
              <input id="titleA" value="FIRST YEAR/ FIRST SEMESTER" class="w-full border bg-white rounded p-1 text-[11px] font-semibold" />
            </div>
            <div>
              <label class="block text-[10px] font-semibold text-slate-600 mb-0.5">UPLOAD EXCEL/CSV</label>
              <input type="file" id="fileA" accept=".csv, .xlsx, .xls" class="w-full text-[11px] text-slate-500 file:mr-1 file:py-1 file:px-2 file:rounded file:border-0 file:text-[11px] file:bg-indigo-600 file:text-white" />
            </div>
          </div>

          <!-- Slot B -->
          <div class="border border-emerald-200 bg-emerald-50/40 p-3 rounded-xl space-y-2">
            <div class="flex justify-between items-center">
              <span class="text-xs font-bold text-emerald-900 uppercase">📁 Cohort B (3rd Sem)</span>
              <span id="badgeCountB" class="text-xs bg-emerald-200 text-emerald-900 px-2 py-0.5 rounded font-bold">0</span>
            </div>
            <div>
              <label class="block text-[10px] font-semibold text-slate-600 mb-0.5">SECTION HEADER</label>
              <input id="titleB" value="THIRD YEAR/ FIFTH SEMESTER" class="w-full border bg-white rounded p-1 text-[11px] font-semibold" />
            </div>
            <div>
              <label class="block text-[10px] font-semibold text-slate-600 mb-0.5">UPLOAD EXCEL/CSV</label>
              <input type="file" id="fileB" accept=".csv, .xlsx, .xls" class="w-full text-[11px] text-slate-500 file:mr-1 file:py-1 file:px-2 file:rounded file:border-0 file:text-[11px] file:bg-emerald-600 file:text-white" />
            </div>
          </div>

          <!-- Course Name Mapping (Optional) -->
          <div class="border border-blue-200 bg-blue-50/40 p-3 rounded-xl space-y-2">
            <div class="flex justify-between items-center">
              <span class="text-xs font-bold text-blue-900 uppercase">📚 Course Mapping</span>
              <span id="badgeCountMapping" class="text-xs bg-blue-200 text-blue-900 px-2 py-0.5 rounded font-bold">0 Mapped</span>
            </div>
            <div>
              <p class="text-[10px] text-slate-500 leading-tight">Optional Excel/CSV with columns: <strong>Course Code</strong>, <strong>Course Name</strong>.</p>
            </div>
            <div>
              <label class="block text-[10px] font-semibold text-slate-600 mb-0.5">UPLOAD MAPPING FILE</label>
              <input type="file" id="fileMapping" accept=".csv, .xlsx, .xls" class="w-full text-[11px] text-slate-500 file:mr-1 file:py-1 file:px-2 file:rounded file:border-0 file:text-[11px] file:bg-blue-600 file:text-white" />
            </div>
          </div>

          <!-- Detained Students Slot -->
          <div class="border border-red-200 bg-red-50/40 p-3 rounded-xl space-y-2">
            <div class="flex justify-between items-center">
              <span class="text-xs font-bold text-red-900 uppercase">🚫 Detained File</span>
              <span id="badgeCountDetained" class="text-xs bg-red-200 text-red-900 px-2 py-0.5 rounded font-bold">0</span>
            </div>
            <div>
              <p class="text-[10px] text-slate-500 leading-tight">Matched by <strong>Enrollment No</strong>.</p>
            </div>
            <div>
              <label class="block text-[10px] font-semibold text-slate-600 mb-0.5">UPLOAD DETAINED LIST</label>
              <input type="file" id="fileDetained" accept=".csv, .xlsx, .xls" class="w-full text-[11px] text-slate-500 file:mr-1 file:py-1 file:px-2 file:rounded file:border-0 file:text-[11px] file:bg-red-600 file:text-white" />
            </div>
          </div>
        </div>

        <!-- Additional Options & Toggles -->
        <div class="bg-slate-50 p-3 rounded-lg border border-slate-200 flex flex-wrap items-center justify-between gap-4">
          <label class="flex items-center gap-2 text-xs font-bold text-slate-800 cursor-pointer">
            <input type="checkbox" id="chkFillRemaining" checked class="w-4 h-4 text-indigo-600 rounded border-slate-300 focus:ring-indigo-500" />
            <span>Fill remaining seats with single cohort when student counts are unequal (Fill Same Cohort in Room)</span>
          </label>
        </div>

        <div class="flex flex-wrap justify-between items-center pt-2 gap-3">
          <div class="flex gap-2">
            <button onclick="loadSampleDataExact()" class="bg-slate-200 hover:bg-slate-300 text-slate-800 text-xs px-4 py-2 rounded font-semibold">
              Load Sample Data
            </button>
            <button onclick="generateAllReports()" class="bg-indigo-700 hover:bg-indigo-800 text-white text-xs px-6 py-2 rounded font-bold shadow">
              Generate Reports
            </button>
          </div>

          <div class="flex flex-wrap items-center gap-1 border border-slate-300 p-1 rounded-lg bg-slate-100">
            <button id="btnViewList" onclick="switchReportFormat('roomWise')" class="px-3 py-1.5 rounded text-xs font-bold bg-slate-900 text-white transition">
              📄 Student List (Portrait)
            </button>
            <button id="btnViewMatrix" onclick="switchReportFormat('matrix')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-slate-700 hover:bg-slate-200 transition">
              📐 Seating Matrix (Landscape)
            </button>
            <button id="btnViewAttendance" onclick="switchReportFormat('attendance')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-slate-700 hover:bg-slate-200 transition">
              ✍️ Room/Group Attendance
            </button>
            <button id="btnViewCourseCodeAttendance" onclick="openCourseCodeModal()" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-indigo-700 hover:bg-indigo-100 transition" title="Generate Course Code Wise Room Wise Attendance Sheet">
              🎓 Course Code Attendance
            </button>
            <button id="btnViewUnallotted" onclick="switchReportFormat('unallotted')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-slate-700 hover:bg-slate-200 transition">
              ⚠️ Unallotted Students
            </button>
            <button id="btnViewDetained" onclick="switchReportFormat('detainedReport')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-slate-700 hover:bg-slate-200 transition">
              🚫 Room-Wise Detained
            </button>
            <button id="btnViewDetainedContinuous" onclick="switchReportFormat('detainedContinuous')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-slate-700 hover:bg-slate-200 transition" title="Continuous Detained List with Header at Top">
              📋 Detained (Continuous Print)
            </button>
            <button id="btnViewBlankAttendance" onclick="switchReportFormat('blankAttendance')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-emerald-800 hover:bg-emerald-100 transition" title="Print Blank Attendance Sheet (30 Rows)">
              🖨️ Print Blank Attendance (30 Rows)
            </button>
            <button id="btnViewCopyCollection" onclick="switchReportFormat('copyCollection')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-blue-800 hover:bg-blue-100 transition" title="Room-Wise Exam Copy Collection Sheet">
              📦 Copy Collection Sheet
            </button>
            <button id="btnViewBlankCopyCollection" onclick="switchReportFormat('blankCopyCollection')" class="px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-blue-800 hover:bg-blue-100 transition" title="Print Blank Copy Collection Sheet">
              📦 Print Blank Copy Collection
            </button>
          </div>
        </div>
      </div>

      <!-- ON-PAGE ACTION TOOLBAR ABOVE REPORT SECTION -->
      <div class="bg-slate-900 text-white p-4 rounded-xl shadow-md flex flex-wrap justify-between items-center gap-4">
        <div class="flex items-center gap-2">
          <span class="w-3 h-3 rounded-full bg-emerald-500 animate-pulse"></span>
          <span class="text-sm font-bold tracking-wide">Generated Report Preview & Actions:</span>
        </div>
        <div class="flex items-center gap-3">
          <button onclick="printDetainedStudentsPdf()" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-xs font-bold shadow flex items-center gap-1.5 transition">
            <span>📥 Detained Students PDF</span>
          </button>
          <button onclick="exportToWordDoc()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold shadow flex items-center gap-1.5 transition">
            <span>📄 Download Word (.doc)</span>
          </button>
          <button onclick="safePrintReport()" class="bg-emerald-600 hover:bg-emerald-700 text-white px-5 py-2 rounded-lg text-xs font-extrabold shadow-lg flex items-center gap-2 transition ring-2 ring-emerald-400/50">
            <span>🖨️ Print Report (PDF)</span>
          </button>
        </div>
      </div>

    </main>

    <div id="print-area" class="mx-auto min-h-screen bg-white">
      <div id="reportContainer" class="p-6">
        <div class="text-center py-20 text-slate-400 no-print">
          <p class="text-base font-bold">No Report Generated Yet.</p>
          <p class="text-xs mt-1">Upload both Course Excel files or click "Load Sample Data", then click "Generate Reports".</p>
        </div>
      </div>
    </div>
  </div>

  <script>
    // Authentication System Logic
    const AUTH_USER = "F01270";
    const AUTH_PASS = "Myexam@2026";

    function handleLogin() {
      const uInput = document.getElementById("loginUserId").value.trim();
      const pInput = document.getElementById("loginPassword").value.trim();
      const errBox = document.getElementById("loginError");

      if (uInput === AUTH_USER && pInput === AUTH_PASS) {
        document.getElementById("loginOverlay").classList.add("hidden");
        document.getElementById("appContainer").classList.remove("hidden");
        sessionStorage.setItem("isExamAuthenticated", "true");
      } else {
        errBox.classList.remove("hidden");
      }
    }

    function handleLogout() {
      sessionStorage.removeItem("isExamAuthenticated");
      document.getElementById("appContainer").classList.add("hidden");
      document.getElementById("loginOverlay").classList.remove("hidden");
      document.getElementById("loginUserId").value = "";
      document.getElementById("loginPassword").value = "";
      document.getElementById("loginError").classList.add("hidden");
    }

    window.addEventListener("DOMContentLoaded", () => {
      if (sessionStorage.getItem("isExamAuthenticated") === "true") {
        document.getElementById("loginOverlay").classList.add("hidden");
        document.getElementById("appContainer").classList.remove("hidden");
      }
    });

    document.getElementById('rRows').addEventListener('input', refreshCapacity);
    document.getElementById('rCols').addEventListener('input', refreshCapacity);
    function refreshCapacity() {
      const r = parseInt(document.getElementById('rRows').value) || 0;
      const c = parseInt(document.getElementById('rCols').value) || 0;
      document.getElementById('rCap').value = r * c;
    }

    let roomRoster = [
      { name: "E319", block: "BNLT", rows: 12, cols: 8, capacity: 96, subCap: 48 },
      { name: "E410", block: "BNLT", rows: 8, cols: 6, capacity: 48, subCap: 24 },
      { name: "E107", block: "BNLT BLOCK", rows: 8, cols: 6, capacity: 48, subCap: 24 },
      { name: "E108", block: "BNLT BLOCK", rows: 8, cols: 6, capacity: 48, subCap: 24 },
      { name: "E109", block: "BNLT BLOCK", rows: 8, cols: 6, capacity: 48, subCap: 24 }
    ];

    let datasetA = [];
    let datasetB = [];
    let detainedSet = new Set();
    let courseNameMapping = new Map();
    let allocatedRooms = [];
    let unallottedStudents = [];
    let activeFormat = 'roomWise';
    let selectedCourseCodesForAttendance = new Set();

    // GLOBAL HELPER FUNCTIONS DECLARED FIRST TO AVOID REFERENCE ERRORS
    function getField(obj, possibleKeys, defaultVal = "") {
      for (const k of Object.keys(obj)) {
        const cleaned = k.toLowerCase().replace(/[^a-z0-9]/g, '');
        for (const pk of possibleKeys) {
          if (cleaned === pk.toLowerCase().replace(/[^a-z0-9]/g, '')) {
            return obj[k];
          }
        }
      }
      return defaultVal;
    }

    function normalizeEnroll(val) {
      if (val === undefined || val === null) return "";
      return String(val).replace(/\.0+$/, '').trim().toUpperCase();
    }

    function isStudentDetained(st) {
      if (!st) return false;
      const eNorm = normalizeEnroll(st.enrollmentNo);
      const rNorm = normalizeEnroll(st.rollNo);
      return (eNorm !== "" && detainedSet.has(eNorm)) || (rNorm !== "" && detainedSet.has(rNorm));
    }

    function renderRoomBadges() {
      const container = document.getElementById('roomPillsContainer');
      const totalCapacity = roomRoster.reduce((sum, r) => sum + (parseInt(r.capacity) || 0), 0);
      
      document.getElementById('roomCountBadge').innerText = `${roomRoster.length} Rooms`;
      document.getElementById('totalCapBadge').innerText = `Total Capacity: ${totalCapacity}`;
      updateTopDashboard();
      
      container.innerHTML = "";
      roomRoster.forEach((r, idx) => {
        const item = document.createElement("div");
        item.className = "flex justify-between items-center bg-slate-50 border border-slate-300 text-slate-800 text-xs px-3 py-1.5 rounded shadow-sm";
        item.innerHTML = `
          <div class="flex items-center gap-2">
            <span class="font-bold text-slate-500 w-5">${idx + 1}.</span>
            <strong class="text-slate-900">${r.name}/${r.block}</strong>
            <span class="text-slate-500 text-[11px]">(${r.rows}R × ${r.cols}C = ${r.capacity} seats)</span>
          </div>
          <div class="flex items-center gap-1">
            <button onclick="moveRoomOrder(${idx}, -1)" ${idx === 0 ? 'disabled' : ''} class="px-1.5 py-0.5 bg-slate-200 hover:bg-slate-300 disabled:opacity-30 rounded font-bold text-xs" title="Move Up">⬆</button>
            <button onclick="moveRoomOrder(${idx}, 1)" ${idx === roomRoster.length - 1 ? 'disabled' : ''} class="px-1.5 py-0.5 bg-slate-200 hover:bg-slate-300 disabled:opacity-30 rounded font-bold text-xs" title="Move Down">⬇</button>
            <button onclick="removeRoom(${idx})" class="text-red-500 font-bold hover:text-red-700 ml-2 px-1 text-sm" title="Delete Room">✕</button>
          </div>
        `;
        container.appendChild(item);
      });
    }

    function updateTopDashboard() {
      const totalRooms = roomRoster.length;
      const totalCap = roomRoster.reduce((sum, r) => sum + (parseInt(r.capacity) || 0), 0);
      const countA = datasetA.length;
      const countB = datasetB.length;
      const totalStudents = countA + countB;
      const detainedCount = detainedSet.size;
      const unallottedCount = unallottedStudents.length;
      const allottedCount = totalStudents - unallottedCount;

      document.getElementById('dashRooms').innerText = totalRooms;
      document.getElementById('dashTotalCap').innerText = totalCap;
      document.getElementById('dashTotalStudents').innerText = totalStudents;
      document.getElementById('dashAllotted').innerText = allottedCount;
      document.getElementById('dashA').innerText = countA;
      document.getElementById('dashB').innerText = countB;
      document.getElementById('dashDetained').innerText = detainedCount;
      document.getElementById('dashUnallotted').innerText = unallottedCount;

      document.getElementById('utilizationRatio').innerText = `${allottedCount} / ${totalCap} Seats`;
      if (totalCap > 0) {
        const occupancy = Math.min(100, Math.round((allottedCount / totalCap) * 100));
        const vacant = Math.max(0, totalCap - allottedCount);
        document.getElementById('dashOccupancy').innerText = `${occupancy}%`;
        document.getElementById('dashVacant').innerText = `${vacant} Vacant`;
        document.getElementById('utilizationBar').style.width = `${occupancy}%`;
        document.getElementById('utilizationPct').innerText = `${occupancy}%`;
      } else {
        document.getElementById('dashOccupancy').innerText = "0%";
        document.getElementById('dashVacant').innerText = "0 Vacant";
        document.getElementById('utilizationBar').style.width = "0%";
        document.getElementById('utilizationPct').innerText = "0%";
      }

      if (totalStudents > 0) {
        const pctA = Math.round((countA / totalStudents) * 100);
        const pctB = 100 - pctA;
        document.getElementById('cohortABar').style.width = `${pctA}%`;
        document.getElementById('cohortBBar').style.width = `${pctB}%`;
        document.getElementById('cohortAPct').innerText = `${pctA}% (${countA})`;
        document.getElementById('cohortBPct').innerText = `${pctB}% (${countB})`;
      } else {
        document.getElementById('cohortABar').style.width = "50%";
        document.getElementById('cohortBBar').style.width = "50%";
        document.getElementById('cohortAPct').innerText = "0%";
        document.getElementById('cohortBPct').innerText = "0%";
      }

      const groupCounts = {};
      [...datasetA, ...datasetB].forEach(s => {
        if (s.group) groupCounts[s.group] = (groupCounts[s.group] || 0) + 1;
      });

      const groupContainer = document.getElementById('groupStatsContainer');
      const groupEntries = Object.entries(groupCounts);
      document.getElementById('groupTotalBadge').innerText = `${groupEntries.length} Sections`;

      if (groupEntries.length > 0) {
        groupContainer.innerHTML = groupEntries.map(([grp, count] ) => `
          <span class="inline-flex items-center gap-1 bg-slate-100 border border-slate-300 text-slate-800 text-[10px] px-2 py-0.5 rounded font-semibold">
            <span>${grp}:</span>
            <strong class="text-indigo-700">${count}</strong>
          </span>
        `).join('');
      } else {
        groupContainer.innerHTML = `<span class="text-[11px] text-slate-400 italic">No section data imported</span>`;
      }

      const usedRoomsNames = new Set(allocatedRooms.map(item => item.room.name));
      const usedList = [];
      const unusedList = [];

      roomRoster.forEach(r => {
        const roomIdentifier = `${r.name}(${r.capacity})`;
        if (usedRoomsNames.has(r.name)) {
          usedList.push(roomIdentifier);
        } else {
          unusedList.push(roomIdentifier);
        }
      });

      document.getElementById('usedRoomsCount').innerText = usedList.length;
      document.getElementById('unusedRoomsCount').innerText = unusedList.length;
      document.getElementById('roomStatusSummaryBadge').innerText = `${usedList.length} Used / ${unusedList.length} Unused`;

      document.getElementById('usedRoomsList').innerHTML = usedList.length > 0 ? 
        usedList.map(item => `<span class="bg-emerald-100 text-emerald-900 px-1.5 py-0.5 rounded text-[10px] font-bold">${item}</span>`).join(' ') : 
        `<span class="italic text-slate-400">None</span>`;

      document.getElementById('unusedRoomsList').innerHTML = unusedList.length > 0 ? 
        unusedList.map(item => `<span class="bg-slate-200 text-slate-700 px-1.5 py-0.5 rounded text-[10px] font-bold">${item}</span>`).join(' ') : 
        `<span class="italic text-slate-400">None</span>`;
      
      if (allocatedRooms.length > 0) {
        generateSubjectPaperSummary();
      }
    }

    // COURSE CODE ATTENDANCE MODAL LOGIC
    function openCourseCodeModal() {
      if (!allocatedRooms || allocatedRooms.length === 0) {
        return alert("⚠️ Please generate reports first before selecting course code attendance.");
      }

      const allSubjectsSet = new Set();
      allocatedRooms.forEach(plan => {
        const checkSubs = (st) => {
          if (st.subjects && Array.isArray(st.subjects)) {
            st.subjects.forEach(sub => allSubjectsSet.add(sub));
          }
        };
        plan.studentsA.forEach(checkSubs);
        plan.studentsB.forEach(checkSubs);
      });

      const subjects = Array.from(allSubjectsSet).sort();
      const container = document.getElementById('courseCodeCheckboxContainer');

      if (subjects.length === 0) {
        container.innerHTML = `<p class="text-xs text-red-600 font-semibold">⚠️ No course/subject codes detected in uploaded datasets.</p>`;
        document.getElementById('courseCodeModal').classList.remove('hidden');
        return;
      }

      container.innerHTML = subjects.map(sub => `
        <label class="flex items-center gap-2 text-xs font-bold text-slate-800 cursor-pointer p-1 hover:bg-slate-100 rounded">
          <input type="checkbox" value="${sub}" onchange="updateSelectedCourseCount()" class="course-code-chk w-4 h-4 text-indigo-600 rounded border-slate-300 focus:ring-indigo-500" checked />
          <span>${sub}</span>
        </label>
      `).join('');

      updateSelectedCourseCount();
      document.getElementById('courseCodeModal').classList.remove('hidden');
    }

    function closeCourseCodeModal() {
      document.getElementById('courseCodeModal').classList.add('hidden');
    }

    function toggleAllCourseCodes(selectState) {
      document.querySelectorAll('.course-code-chk').forEach(chk => chk.checked = selectState);
      updateSelectedCourseCount();
    }

    function updateSelectedCourseCount() {
      const checkedCount = document.querySelectorAll('.course-code-chk:checked').length;
      const badge = document.getElementById('selectedCourseCountBadge');
      if (badge) badge.innerText = `${checkedCount} Selected`;
    }

    function confirmGenerateCourseCodeAttendance() {
      selectedCourseCodesForAttendance.clear();
      document.querySelectorAll('.course-code-chk:checked').forEach(chk => {
        selectedCourseCodesForAttendance.add(chk.value);
      });

      if (selectedCourseCodesForAttendance.size === 0) {
        return alert("⚠️ Please select at least one course code.");
      }

      closeCourseCodeModal();
      switchReportFormat('courseCodeAttendance');
    }

    // DOWNLOAD TEMPLATE FUNCTIONS
    function downloadSampleRoomsExcel() {
      const rooms = [
        { "Room No": "E107", "Block": "BNLT", "Rows": 8, "Columns": 6, "Capacity": 48 },
        { "Room No": "E108", "Block": "BNLT", "Rows": 8, "Columns": 6, "Capacity": 48 },
        { "Room No": "E119", "Block": "BNLT", "Rows": 12, "Columns": 8, "Capacity": 96 },
        { "Room No": "E319", "Block": "BNLT", "Rows": 12, "Columns": 8, "Capacity": 96 }
      ];
      const ws = XLSX.utils.json_to_sheet(rooms);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Rooms");
      XLSX.writeFile(wb, "Sample_Rooms_List.xlsx");
    }

    function downloadSampleCourseExcel(cohort) {
      let filename = cohort === 'A' ? "Sample_Course_A_Students.xlsx" : "Sample_Course_B_Students.xlsx";
      let students = [
        { rollno: "2501012001", enrollmentno: "2500100039", studentname: "ADIL KAMAL", GroupName: "CSE-A", SUB1: "CS204", SUB2: "CS270", SUB3: "CS203" },
        { rollno: "2501012002", enrollmentno: "2500100075", studentname: "ABDUL QADIR", GroupName: "CSE-A", SUB1: "CS204", SUB2: "CS270", SUB3: "CS203" },
        { rollno: "2501012003", enrollmentno: "2500100196", studentname: "ABDUL GHALIB", GroupName: "CSE-B", SUB1: "CS204", SUB2: "CS270", SUB3: "CS203" },
        { rollno: "2501012004", enrollmentno: "2500100171", studentname: "AATIF ALI", GroupName: "CSE-B", SUB1: "CS204", SUB2: "CS270", SUB3: "CS203" }
      ];
      const ws = XLSX.utils.json_to_sheet(students);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, `Course_${cohort}`);
      XLSX.writeFile(wb, filename);
    }

    function downloadSampleDetainedExcel() {
      const detained = [
        { rollno: "2501012004", enrollmentno: "2500100171", studentname: "AATIF ALI", GroupName: "CSE-B", Reason: "Short Attendance (<75%)" }
      ];
      const ws = XLSX.utils.json_to_sheet(detained);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Detained");
      XLSX.writeFile(wb, "Sample_Detained_Students_List.xlsx");
    }

    // GENERATE ALL REPORTS ALLOCATION ENGINE
    function generateAllReports() {
      if (datasetA.length === 0 && datasetB.length === 0) {
        return alert("Please upload files or load sample data first.");
      }

      const qA = [...datasetA];
      const qB = [...datasetB];
      const titleA = document.getElementById("titleA").value.trim() || "FIRST YEAR/ FIRST SEMESTER";
      const titleB = document.getElementById("titleB").value.trim() || "THIRD YEAR/ FIFTH SEMESTER";
      const fillRemainingSameCohort = document.getElementById("chkFillRemaining").checked;

      allocatedRooms = [];
      unallottedStudents = [];

      let workingRooms = JSON.parse(JSON.stringify(roomRoster));
      let roomIdx = 0;
      let extraCount = 1;

      while (qA.length > 0 || qB.length > 0) {
        let room;
        if (roomIdx < workingRooms.length) {
          room = workingRooms[roomIdx];
        } else {
          room = {
            name: `EXTRA ROOM ${extraCount}`,
            block: "MAIN BLOCK",
            rows: 8,
            cols: 6,
            capacity: 48,
            subCap: 24
          };
          workingRooms.push(room);
          extraCount++;
        }

        let subCapA = room.subCap || Math.floor(room.capacity / 2);
        let subCapB = room.subCap || Math.floor(room.capacity / 2);

        let batchA = qA.splice(0, subCapA);
        let batchB = qB.splice(0, subCapB);

        if (fillRemainingSameCohort) {
          const roomTotalCap = room.capacity || (room.rows * room.cols);
          let currentRoomAllotted = batchA.length + batchB.length;
          let remainingSeats = roomTotalCap - currentRoomAllotted;

          if (remainingSeats > 0) {
            if (qA.length > 0 && batchB.length < subCapB) {
              const extraA = qA.splice(0, remainingSeats);
              batchA = batchA.concat(extraA);
            } else if (qB.length > 0 && batchA.length < subCapA) {
              const extraB = qB.splice(0, remainingSeats);
              batchB = batchB.concat(extraB);
            }
          }
        }

        batchA.forEach(s => {
          s.allottedRoom = `${room.name} (${room.block})`;
          s.cohortTag = titleA;
        });
        batchB.forEach(s => {
          s.allottedRoom = `${room.name} (${room.block})`;
          s.cohortTag = titleB;
        });

        const grid = Array.from({ length: room.rows }, () => Array(room.cols).fill(null));
        const poolA = [...batchA];
        const poolB = [...batchB];
        const stats = {};

        for (let c = 0; c < room.cols; c++) {
          for (let r = 0; r < room.rows; r++) {
            const isSlotA = (r + c) % 2 === 0;
            let student = null;
            if (isSlotA) {
              if (poolA.length > 0) student = poolA.shift();
              else if (fillRemainingSameCohort && poolB.length > 0) student = poolB.shift();
            } else {
              if (poolB.length > 0) student = poolB.shift();
              else if (fillRemainingSameCohort && poolA.length > 0) student = poolA.shift();
            }

            if (student) {
              student.isCohortB = (student.cohortTag === titleB);
              grid[r][c] = student;
              stats[student.group] = (stats[student.group] || 0) + 1;
            }
          }
        }

        allocatedRooms.push({
          room,
          titleA,
          titleB,
          studentsA: batchA,
          studentsB: batchB,
          grid,
          stats
        });

        roomIdx++;
      }

      if (qA.length > 0) {
        qA.forEach(s => unallottedStudents.push({ ...s, cohort: titleA, reason: "Capacity Exhausted" }));
      }
      if (qB.length > 0) {
        qB.forEach(s => unallottedStudents.push({ ...s, cohort: titleB, reason: "Capacity Exhausted" }));
      }

      updateTopDashboard();
      renderDocument();
    }

    // Room-Wise Subject / Question Paper Count Summary Calculation & Rendering
    function generateSubjectPaperSummary() {
      const container = document.getElementById('subjectPaperSummaryContainer');
      if (!allocatedRooms || allocatedRooms.length === 0) {
        container.innerHTML = `<p class="text-xs text-slate-400 italic py-2">No room allocations found. Generate reports first.</p>`;
        return;
      }

      const allSubjectsSet = new Set();
      allocatedRooms.forEach(plan => {
        const checkSubjects = (st) => {
          if (st.subjects && Array.isArray(st.subjects)) {
            st.subjects.forEach(sub => allSubjectsSet.add(sub));
          }
        };
        plan.studentsA.forEach(checkSubjects);
        plan.studentsB.forEach(checkSubjects);
      });

      const subjects = Array.from(allSubjectsSet).sort();
      if (subjects.length === 0) {
        container.innerHTML = `<p class="text-xs text-amber-600 font-semibold py-2">⚠️ No subject codes detected in uploaded student datasets. Make sure columns like 'SUB1', 'SUB2', etc. are present.</p>`;
        return;
      }

      let tableHtml = `
        <table id="paperSummaryTable" class="w-full border-collapse border border-slate-300 text-xs text-left">
          <thead>
            <tr class="bg-slate-900 text-white">
              <th class="border border-slate-700 p-2 text-center sticky top-0 bg-slate-900">Room No.</th>
              <th class="border border-slate-700 p-2 text-center sticky top-0 bg-slate-900">Block</th>
              <th class="border border-slate-700 p-2 text-center sticky top-0 bg-slate-900">Total Seated</th>
              ${subjects.map(sub => `<th class="border border-slate-700 p-2 text-center sticky top-0 bg-slate-900">${sub}</th>`).join('')}
              <th class="border border-slate-700 p-2 text-center bg-indigo-950 sticky top-0">Total Papers</th>
            </tr>
          </thead>
          <tbody>
      `;

      let grandTotals = {};
      subjects.forEach(sub => grandTotals[sub] = 0);
      let grandTotalPapers = 0;

      allocatedRooms.forEach(plan => {
        const roomSubCounts = {};
        subjects.forEach(sub => roomSubCounts[sub] = 0);

        const countStudentSubjects = (st) => {
          if (st.subjects && Array.isArray(st.subjects)) {
            st.subjects.forEach(sub => {
              if (roomSubCounts[sub] !== undefined) roomSubCounts[sub]++;
            });
          }
        };

        plan.studentsA.forEach(countStudentSubjects);
        plan.studentsB.forEach(countStudentSubjects);

        let roomTotalPapers = 0;
        subjects.forEach(sub => {
          roomTotalPapers += roomSubCounts[sub];
          grandTotals[sub] += roomSubCounts[sub];
        });
        grandTotalPapers += roomTotalPapers;

        const seatedCount = plan.studentsA.length + plan.studentsB.length;

        tableHtml += `
          <tr class="hover:bg-slate-50">
            <td class="border border-slate-300 p-2 font-bold text-center">${plan.room.name}</td>
            <td class="border border-slate-300 p-2 text-center text-slate-600">${plan.room.block}</td>
            <td class="border border-slate-300 p-2 font-bold text-center text-indigo-700">${seatedCount}</td>
            ${subjects.map(sub => `<td class="border border-slate-300 p-2 text-center ${roomSubCounts[sub] > 0 ? 'font-bold text-slate-900 bg-indigo-50/40' : 'text-slate-300'}">${roomSubCounts[sub] > 0 ? roomSubCounts[sub] : '-'}</td>`).join('')}
            <td class="border border-slate-300 p-2 font-extrabold text-center bg-indigo-50 text-indigo-950">${roomTotalPapers}</td>
          </tr>
        `;
      });

      tableHtml += `
          <tr class="bg-slate-100 font-extrabold text-slate-900 border-t-2 border-slate-900">
            <td colspan="2" class="border border-slate-300 p-2 text-right">GRAND TOTAL PAPERS:</td>
            <td class="border border-slate-300 p-2 text-center text-indigo-900">${allocatedRooms.reduce((sum, p) => sum + p.studentsA.length + p.studentsB.length, 0)}</td>
            ${subjects.map(sub => `<td class="border border-slate-300 p-2 text-center text-indigo-900">${grandTotals[sub]}</td>`).join('')}
            <td class="border border-slate-300 p-2 text-center bg-indigo-900 text-white">${grandTotalPapers}</td>
          </tr>
        </tbody>
      </table>
      `;

      container.innerHTML = tableHtml;
    }

    function downloadSubjectPaperSummaryExcel() {
      if (!allocatedRooms || allocatedRooms.length === 0) {
        return alert("⚠️ Please generate reports first before downloading paper summary.");
      }

      const allSubjectsSet = new Set();
      allocatedRooms.forEach(plan => {
        const checkSubjects = (st) => {
          if (st.subjects && Array.isArray(st.subjects)) {
            st.subjects.forEach(sub => allSubjectsSet.add(sub));
          }
        };
        plan.studentsA.forEach(checkSubjects);
        plan.studentsB.forEach(checkSubjects);
      });

      const subjects = Array.from(allSubjectsSet).sort();
      if (subjects.length === 0) {
        return alert("⚠️ No subject codes detected in student datasets.");
      }

      let summaryData = [];
      let grandTotals = {};
      subjects.forEach(sub => grandTotals[sub] = 0);
      let grandTotalPapers = 0;

      allocatedRooms.forEach(plan => {
        const roomSubCounts = {};
        subjects.forEach(sub => roomSubCounts[sub] = 0);

        const countStudentSubjects = (st) => {
          if (st.subjects && Array.isArray(st.subjects)) {
            st.subjects.forEach(sub => {
              if (roomSubCounts[sub] !== undefined) roomSubCounts[sub]++;
            });
          }
        };

        plan.studentsA.forEach(countStudentSubjects);
        plan.studentsB.forEach(countStudentSubjects);

        let roomTotalPapers = 0;
        subjects.forEach(sub => {
          roomTotalPapers += roomSubCounts[sub];
          grandTotals[sub] += roomSubCounts[sub];
        });
        grandTotalPapers += roomTotalPapers;

        let rowObj = {
          "Room No": plan.room.name,
          "Block": plan.room.block,
          "Total Seated": plan.studentsA.length + plan.studentsB.length
        };

        subjects.forEach(sub => {
          rowObj[sub] = roomSubCounts[sub];
        });
        rowObj["Total Papers"] = roomTotalPapers;

        summaryData.push(rowObj);
      });

      let totalRowObj = {
        "Room No": "GRAND TOTAL",
        "Block": "",
        "Total Seated": allocatedRooms.reduce((sum, p) => sum + p.studentsA.length + p.studentsB.length, 0)
      };
      subjects.forEach(sub => {
        totalRowObj[sub] = grandTotals[sub];
      });
      totalRowObj["Total Papers"] = grandTotalPapers;
      summaryData.push(totalRowObj);

      const ws = XLSX.utils.json_to_sheet(summaryData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Paper_Summary");
      XLSX.writeFile(wb, "Room_Wise_Subject_Paper_Summary.xlsx");
    }

    function printSubjectPaperSummaryPdf() {
      const summaryElem = document.getElementById('subjectPaperSummaryContainer');
      if (!summaryElem || !summaryElem.querySelector('table')) {
        return alert("⚠️ Please generate or refresh the paper summary table first.");
      }

      const tableHtml = summaryElem.innerHTML;
      const uni = document.getElementById("uniTitle").value;
      const deptShift = document.getElementById("deptShiftHeader").value;
      const exam = document.getElementById("examName").value;
      const session = document.getElementById("examSession").value;

      const printWindow = window.open('', '_blank', 'width=1100,height=800');
      if (!printWindow) return alert("Pop-up blocked. Please allow pop-ups for printing.");

      printWindow.document.open();
      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>Room-Wise Subject Paper Count Summary</title>
          <script src="https://cdn.tailwindcss.com"><\/script>
          <style>
            @page { size: A4 landscape; margin: 10mm; }
            body { font-family: Arial, sans-serif; padding: 20px; color: #000; background: #fff; }
            table { width: 100%; border-collapse: collapse; margin-top: 15px; }
            th, td { border: 1px solid #334155; padding: 6px 8px; font-size: 11px; text-align: center; }
            th { background-color: #0f172a !important; color: white !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
          </style>
        </head>
        <body onload="setTimeout(function(){ window.print(); window.close(); }, 400);">
          <div class="border-b-2 border-slate-900 pb-3 mb-4">
            <h1 class="text-2xl font-black uppercase">${uni}</h1>
            <p class="text-xs font-bold text-slate-700">${deptShift}</p>
            <p class="text-sm font-black text-indigo-900 mt-1">${exam} • ${session}</p>
            <h2 class="text-md font-bold uppercase mt-2 text-slate-900">Room-Wise Subject / Question Paper Count Summary (Cohort A & B)</h2>
          </div>
          ${tableHtml}
        </body>
        </html>
      `);
      printWindow.document.close();
    }

    function printBranchSectionPdf() {
      const groupCounts = {};
      [...datasetA, ...datasetB].forEach(s => {
        if (s.group) groupCounts[s.group] = (groupCounts[s.group] || 0) + 1;
      });

      const entries = Object.entries(groupCounts);
      if (entries.length === 0) {
        return alert("⚠️ No branch/section breakdown data available. Upload files or load sample data first.");
      }

      const uni = document.getElementById("uniTitle").value;
      const deptShift = document.getElementById("deptShiftHeader").value;
      const exam = document.getElementById("examName").value;
      const session = document.getElementById("examSession").value;

      let rowsHtml = entries.map(([grp, count], idx) => `
        <tr>
          <td style="border: 1px solid #334155; padding: 6px; text-align: center; font-weight: bold;">${idx + 1}</td>
          <td style="border: 1px solid #334155; padding: 6px; font-weight: bold; text-transform: uppercase;">${grp}</td>
          <td style="border: 1px solid #334155; padding: 6px; text-align: center; font-weight: bold; color: #3730a3;">${count} Students</td>
        </tr>
      `).join('');

      const printWindow = window.open('', '_blank', 'width=900,height=700');
      if (!printWindow) return alert("Pop-up blocked. Please allow pop-ups.");

      printWindow.document.open();
      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>Branch & Section Breakdown Report</title>
          <style>
            @page { size: A4 portrait; margin: 12mm; }
            body { font-family: Arial, sans-serif; padding: 20px; color: #000; background: #fff; }
            table { width: 100%; border-collapse: collapse; margin-top: 15px; }
            th, td { border: 1px solid #334155; padding: 8px; font-size: 12px; }
            th { background-color: #0f172a; color: white; text-align: center; }
          </style>
        </head>
        <body onload="setTimeout(function(){ window.print(); window.close(); }, 400);">
          <div style="border-bottom: 2px solid #0f172a; padding-bottom: 10px; margin-bottom: 15px;">
            <h1 style="font-size: 20px; font-weight: 900; text-transform: uppercase; margin: 0;">${uni}</h1>
            <p style="font-size: 11px; font-weight: bold; text-transform: uppercase; margin: 2px 0;">${deptShift}</p>
            <p style="font-size: 12px; font-weight: 900; color: #3730a3; margin: 4px 0;">${exam} • ${session}</p>
            <h2 style="font-size: 14px; font-weight: bold; text-transform: uppercase; margin-top: 10px;">Branch & Section Enrollment Breakdown Report</h2>
          </div>
          <table>
            <thead>
              <tr>
                <th style="width: 60px;">S.No.</th>
                <th>Branch / Section Name</th>
                <th style="width: 150px;">Enrolled Count</th>
              </tr>
            </thead>
            <tbody>
              ${rowsHtml}
            </tbody>
          </table>
          <div style="margin-top: 30px; display: flex; justify-content: space-between; font-size: 11px; font-weight: bold;">
            <div>Total Sections: ${entries.length}</div>
            <div>Total Students: ${Object.values(groupCounts).reduce((a, b) => a + b, 0)}</div>
          </div>
        </body>
        </html>
      `);
      printWindow.document.close();
    }

    function printDetainedStudentsPdf() {
      if (!allocatedRooms || allocatedRooms.length === 0) {
        return alert("⚠️ Please generate reports first before printing detained list.");
      }

      const uni = document.getElementById("uniTitle").value;
      const deptShift = document.getElementById("deptShiftHeader").value;
      const exam = document.getElementById("examName").value;
      const session = document.getElementById("examSession").value;

      let detainedRoomsHtml = "";
      let totalDetainedCount = 0;

      const instructionsBlock = `
        <div style="margin-top: 25px; padding: 10px 12px; border: 1.5px solid #991b1b; background: #fef2f2; font-size: 10.5px; color: #7f1d1d; border-radius: 4px;">
          <strong>Instructions for Invigilators:</strong><br>
          • Verify each student’s name against the provided Detained Students List before entry.<br>
          • Do not allow any Detained Student to enter or appear for the examination.<br>
          • Report any discrepancy immediately to the Examination Control Room.
        </div>
      `;

      allocatedRooms.forEach(plan => {
        const roomDetained = [];
        const checkDetained = (st) => {
          if (isStudentDetained(st)) roomDetained.push(st);
        };
        plan.studentsA.forEach(checkDetained);
        plan.studentsB.forEach(checkDetained);

        if (roomDetained.length > 0) {
          totalDetainedCount += roomDetained.length;
          const rows = roomDetained.map((st, idx) => `
            <tr>
              <td style="border: 1px solid #334155; padding: 5px; text-align: center; font-weight: bold;">${idx + 1}</td>
              <td style="border: 1px solid #334155; padding: 5px; font-weight: bold;">${st.rollNo || ''}</td>
              <td style="border: 1px solid #334155; padding: 5px; font-family: monospace; font-weight: bold; color: #991b1b;">${st.enrollmentNo || ''}</td>
              <td style="border: 1px solid #334155; padding: 5px; font-weight: bold; text-transform: uppercase;">${st.name}</td>
              <td style="border: 1px solid #334155; padding: 5px; text-align: center; font-weight: bold;">${st.group}</td>
              <td style="border: 1px solid #334155; padding: 5px; text-align: center; font-weight: bold; color: #b91c1c;">DETAINED</td>
            </tr>
          `).join('');

          detainedRoomsHtml += `
            <div style="margin-bottom: 25px; page-break-after: always; break-after: page;">
              <div style="border-bottom: 2px solid #0f172a; padding-bottom: 8px; margin-bottom: 12px;">
                <h1 style="font-size: 18px; font-weight: 900; text-transform: uppercase; margin: 0;">${uni}</h1>
                <p style="font-size: 11px; font-weight: bold; text-transform: uppercase; margin: 2px 0;">${deptShift}</p>
                <p style="font-size: 12px; font-weight: 900; color: #991b1b; margin: 3px 0;">${exam} • ${session}</p>
              </div>
              <h3 style="background: #fee2e2; color: #991b1b; padding: 6px 10px; font-size: 12.5px; font-weight: 900; border: 1px solid #f87171; text-transform: uppercase; margin-bottom: 8px;">
                Room: ${plan.room.name} — Detained Candidates: ${roomDetained.length}
              </h3>
              <table style="width: 100%; border-collapse: collapse; font-size: 11px;">
                <thead>
                  <tr style="background: #f1f5f9;">
                    <th style="border: 1px solid #334155; padding: 5px; width: 45px;">S.No.</th>
                    <th style="border: 1px solid #334155; padding: 5px; width: 120px;">Roll No</th>
                    <th style="border: 1px solid #334155; padding: 5px; width: 130px;">Enrollment No</th>
                    <th style="border: 1px solid #334155; padding: 5px;">Student Name</th>
                    <th style="border: 1px solid #334155; padding: 5px; width: 80px;">Group</th>
                    <th style="border: 1px solid #334155; padding: 5px; width: 100px;">Status</th>
                  </tr>
                </thead>
                <tbody>
                  ${rows}
                </tbody>
              </table>
              ${instructionsBlock}
              <div style="margin-top: 25px; display: flex; justify-content: space-between; font-size: 11px; font-weight: bold;">
                <div>Total Detained in Room ${plan.room.name}: <strong>${roomDetained.length}</strong></div>
                <div style="text-align: center;">Head Dept. of CSE</div>
              </div>
            </div>
          `;
        }
      });

      if (totalDetainedCount === 0) {
        return alert("ℹ️ No detained students are currently seated in any room.");
      }

      const printWindow = window.open('', '_blank', 'width=900,height=800');
      if (!printWindow) return alert("Pop-up blocked. Please allow pop-ups.");

      printWindow.document.open();
      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>Room-Wise Detained Students List</title>
          <style>
            @page { size: A4 portrait; margin: 10mm; }
            body { font-family: Arial, sans-serif; padding: 15px; color: #000; background: #fff; }
          </style>
        </head>
        <body onload="setTimeout(function(){ window.print(); window.close(); }, 400);">
          ${detainedRoomsHtml}
        </body>
        </html>
      `);
      printWindow.document.close();
    }

    function renderDocument() {
      const container = document.getElementById("reportContainer");
      container.innerHTML = "";

      const uni = document.getElementById("uniTitle").value;
      const deptShift = document.getElementById("deptShiftHeader").value;
      const prog = document.getElementById("progHeader").value;
      const exam = document.getElementById("examName").value;
      const session = document.getElementById("examSession").value;
      const printArea = document.getElementById("print-area");

      if (activeFormat === 'roomWise') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        allocatedRooms.forEach(plan => {
          const maxRowsPerChunk = 40;
          
          let allRoomEntries = [];
          plan.studentsA.forEach(st => allRoomEntries.push({ cohortTitle: plan.titleA, student: st }));
          plan.studentsB.forEach(st => allRoomEntries.push({ cohortTitle: plan.titleB, student: st }));

          let chunks = [];
          for (let i = 0; i < allRoomEntries.length; i += maxRowsPerChunk) {
            chunks.push(allRoomEntries.slice(i, i + maxRowsPerChunk));
          }

          chunks.forEach(chunk => {
            const page = document.createElement("div");
            page.className = "page-break mb-8";

            const chunkSectionsMap = {};
            chunk.forEach(item => {
              if (!chunkSectionsMap[item.cohortTitle]) chunkSectionsMap[item.cohortTitle] = [];
              chunkSectionsMap[item.cohortTitle].push(item.student);
            });

            let tablesSectionsHtml = "";
            Object.keys(chunkSectionsMap).forEach(cohortTitle => {
              const list = chunkSectionsMap[cohortTitle];
              const globalStartIndex = allRoomEntries.findIndex(e => e.student === list[0]);

              const rows = list.map((st, idx) => {
                const isDetained = isStudentDetained(st);
                return `
                  <tr class="${isDetained ? 'detained-row' : ''}">
                    <td class="col-sno">${globalStartIndex + idx + 1}.</td>
                    <td class="col-roll">${st.rollNo || ''}</td>
                    <td class="col-enroll font-mono ${isDetained ? 'font-bold text-red-700' : ''}">${st.enrollmentNo || ''}</td>
                    <td class="col-name">${st.name} ${isDetained ? '<span class="text-red-600 font-bold ml-1">(DETAINED)</span>' : ''}</td>
                    <td class="col-group">${st.group}</td>
                  </tr>
                `;
              }).join('');

              tablesSectionsHtml += `
                <thead>
                  <tr>
                    <th colspan="5" class="cohort-header bg-slate-100 text-slate-950 font-black border-b-2 border-slate-900">${cohortTitle}</th>
                  </tr>
                  <tr class="font-bold text-center bg-slate-50 text-slate-900 border-b border-slate-900">
                    <th class="col-sno">S.No.</th>
                    <th class="col-roll">Roll No</th>
                    <th class="col-enroll">Enrollment No</th>
                    <th class="col-name">Student Name</th>
                    <th class="col-group">Group</th>
                  </tr>
                </thead>
                <tbody>
                  ${rows}
                </tbody>
              `;
            });

            page.innerHTML = `
              <div class="pro-header-container">
                <div class="flex justify-between items-start">
                  <div class="space-y-0.5">
                    <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                    <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'}</div>
                    <div class="text-xs font-semibold text-slate-700">${prog}</div>
                  </div>
                  <div class="text-right">
                    <div class="inline-block bg-slate-900 text-white text-xs font-black px-3.5 py-1 rounded shadow uppercase tracking-widest">
                      ROOM: ${plan.room.name} <span class="text-slate-300 font-normal">(${plan.room.block})</span>
                    </div>
                    <div class="text-[11px] font-black text-indigo-900 mt-1 uppercase tracking-tight">${session}</div>
                  </div>
                </div>
                <div class="pro-header-divider"></div>
                <div class="flex justify-between items-center text-[11px] text-slate-800 font-bold uppercase">
                  <span class="text-indigo-900 font-extrabold tracking-wide"> ${exam}</span>
                  <span>Allotted / Cap: <strong class="text-slate-950 font-black">${plan.studentsA.length + plan.studentsB.length} / ${plan.room.capacity}</strong></span>
                </div>
              </div>

              <table class="report-table">
                ${tablesSectionsHtml}
              </table>
            `;
            container.appendChild(page);
          });
        });

      } else if (activeFormat === 'attendance') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        allocatedRooms.forEach(plan => {
          // GROUP-WISE BREAKDOWN WITHIN EACH ROOM
          const groupMap = {};
          const categorize = (st) => {
            const g = st.group || "GENERAL";
            if (!groupMap[g]) groupMap[g] = [];
            groupMap[g].push(st);
          };
          plan.studentsA.forEach(categorize);
          plan.studentsB.forEach(categorize);

          Object.keys(groupMap).forEach(groupName => {
            const groupStudents = groupMap[groupName];
            if (!groupStudents || groupStudents.length === 0) return;

            const page = document.createElement("div");
            page.className = "page-break mb-8";

            const rowsHtml = groupStudents.map((st, idx) => {
              const isDetained = isStudentDetained(st);
              return `
                <tr class="${isDetained ? 'detained-row' : ''}">
                  <td class="col-sno">${idx + 1}.</td>
                  <td class="col-roll">${st.rollNo || ''}</td>
                  <td class="col-enroll font-mono ${isDetained ? 'font-bold text-red-700' : ''}">${st.enrollmentNo || ''}</td>
                  <td class="col-name">${st.name} ${isDetained ? '<span class="text-red-600 font-bold ml-1">(DETAINED)</span>' : ''}</td>
                  <td class="col-group font-bold text-indigo-900">${st.group}</td>
                  <td class="col-sign">${isDetained ? '<span class="text-red-700 font-bold text-[10px]">DETAINED</span>' : ''}</td>
                </tr>
              `;
            }).join('');

            page.innerHTML = `
              <div class="pro-header-container">
                <div class="flex justify-between items-start">
                  <div class="space-y-0.5">
                    <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                    <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                    <div class="text-[11px] font-bold text-indigo-900 uppercase tracking-tight">${exam} • ${session}</div>
                  </div>
                  <div class="text-right">
                    <div class="inline-block border-2 border-slate-950 bg-slate-950 text-white text-xs font-black px-3 py-0.5 rounded uppercase tracking-wider shadow">
                      EXAM ATTENDANCE SHEET
                    </div>
                    <div class="text-xs font-black text-slate-900 mt-1 uppercase">Room: ${plan.room.name} (${plan.room.block})</div>
                  </div>
                </div>
                <div class="pro-header-divider"></div>
                
                <!-- ATTENDANCE HEADER ROW: Course Name on left, Course Code with dotted line on right -->
                <div class="flex justify-between items-center text-xs text-slate-900 font-bold uppercase mb-1.5 bg-slate-50 p-2 rounded border border-slate-200">
                  <div>Course Name: <span class="border-b border-dashed border-slate-400 inline-block w-48 font-semibold text-indigo-900"></span></div>
                  <div>Course Code: <span class="border-b border-dashed border-slate-400 inline-block w-32"></span></div>
                </div>

                <!-- NEXT ROW: Group Name (increased font), Group Seated Count, Date -->
                <div class="flex justify-between items-center text-xs text-slate-900 font-bold uppercase mb-1 bg-slate-50 p-2 rounded border border-slate-200">
                  <div>Group Name: <span class="text-indigo-900 font-black text-sm tracking-wide ml-1">${groupName}</span></div>
                  <div>Group Seated Count: <span class="text-slate-950 font-black">${groupStudents.length}</span></div>
                  <div>Shift: <span class="border-b border-dashed border-slate-400 inline-block w-32"></span></div>
                  <div>Exam Date: <span class="border-b border-dashed border-slate-400 inline-block w-24"></span></div>
                </div>
              </div>

              <table class="report-table">
                <thead>
                  <tr class="font-bold text-center bg-slate-100 text-slate-900 border-b-2 border-slate-900">
                    <th class="col-sno">S.No.</th>
                    <th class="col-roll">Roll No</th>
                    <th class="col-enroll">Enrollment No</th>
                    <th class="col-name">Student Name</th>
                    <th class="col-group">Group</th>
                    <th class="col-sign">Student Sign</th>
                  </tr>
                </thead>
                <tbody>
                  ${rowsHtml}
                </tbody>
              </table>

              <!-- 4 Invigilators Name & Sign in vertical manner -->
              <div class="mt-4 pt-2 text-[11px] font-bold text-slate-900 space-y-2">
                <div class="flex justify-between items-end pb-1 border-b border-slate-300">
                  <div>Total Candidates Present: ________ / ${groupStudents.length}</div>
                  <div class="text-slate-700">Invigilation Duty Verification & Signatures</div>
                </div>
                <div class="space-y-1.5 pt-1 font-semibold text-slate-900">
                  <div>1. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                  <div>2. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                  <div>3. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                  <div>4. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                </div>
              </div>
            `;
            container.appendChild(page);
          });
        });

      } else if (activeFormat === 'courseCodeAttendance') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        allocatedRooms.forEach(plan => {
          selectedCourseCodesForAttendance.forEach(selectedCode => {
            const matchingStudents = [];
            const checkMatch = (st) => {
              if (st.subjects && st.subjects.includes(selectedCode)) {
                matchingStudents.push(st);
              }
            };
            plan.studentsA.forEach(checkMatch);
            plan.studentsB.forEach(checkMatch);

            if (matchingStudents.length === 0) return;

            const courseNameFromMap = courseNameMapping.get(selectedCode) || "";

            const page = document.createElement("div");
            page.className = "page-break mb-8";

            const rowsHtml = matchingStudents.map((st, idx) => {
              const isDetained = isStudentDetained(st);
              return `
                <tr class="${isDetained ? 'detained-row' : ''}">
                  <td class="col-sno">${idx + 1}.</td>
                  <td class="col-roll">${st.rollNo || ''}</td>
                  <td class="col-enroll font-mono ${isDetained ? 'font-bold text-red-700' : ''}">${st.enrollmentNo || ''}</td>
                  <td class="col-name">${st.name} ${isDetained ? '<span class="text-red-600 font-bold ml-1">(DETAINED)</span>' : ''}</td>
                  <td class="col-group font-bold text-indigo-900">${st.group}</td>
                  <td class="col-sign">${isDetained ? '<span class="text-red-700 font-bold text-[10px]">DETAINED</span>' : ''}</td>
                </tr>
              `;
            }).join('');

            page.innerHTML = `
              <div class="pro-header-container">
                <div class="flex justify-between items-start">
                  <div class="space-y-0.5">
                    <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                    <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                    <div class="text-[11px] font-bold text-indigo-900 uppercase tracking-tight">${exam} • ${session}</div>
                  </div>
                  <div class="text-right">
                    <div class="inline-block border-2 border-slate-950 bg-slate-950 text-white text-xs font-black px-3 py-0.5 rounded uppercase tracking-wider shadow">
                      ATTENDANCE SHEET
                    </div>
                    <div class="text-xs font-black text-slate-900 mt-1 uppercase">Room: ${plan.room.name} (${plan.room.block})</div>
                  </div>
                </div>
                <div class="pro-header-divider"></div>
                
                <!-- HEADER ROW: Course Name first (auto-filled if mapping uploaded, else blank line), then Course Code -->
                <div class="flex justify-between items-center text-xs text-slate-900 font-bold uppercase mb-1.5 bg-slate-50 p-2 rounded border border-slate-200">
                  <div>Course Name: <span class="font-semibold text-slate-900 ml-1">${courseNameFromMap !== "" ? courseNameFromMap : '<span class="border-b border-dashed border-slate-400 inline-block w-56">&nbsp;</span>'}</span></div>
                  <div>Course Code: <span class="text-indigo-900 font-black text-sm tracking-wide ml-1">${selectedCode}</span></div>
                </div>

                <!-- NEXT ROW: Enrolled Candidates and Exam Date -->
                <div class="flex justify-between items-center text-xs text-slate-900 font-bold uppercase mb-1 bg-slate-50 p-2 rounded border border-slate-200">
                  <div>Enrolled Candidates: <span class="text-slate-950 font-black">${matchingStudents.length}</span></div>
                  <div>Shift: <span class="border-b border-dashed border-slate-400 inline-block w-32"></span></div>
                  <div>Exam Date: <span class="border-b border-dashed border-slate-400 inline-block w-32"></span></div>
                </div>
              </div>

              <table class="report-table">
                <thead>
                  <tr class="font-bold text-center bg-slate-100 text-slate-900 border-b-2 border-slate-900">
                    <th class="col-sno">S.No.</th>
                    <th class="col-roll">Roll No</th>
                    <th class="col-enroll">Enrollment No</th>
                    <th class="col-name">Student Name</th>
                    <th class="col-group">Group</th>
                    <th class="col-sign">Student Sign</th>
                  </tr>
                </thead>
                <tbody>
                  ${rowsHtml}
                </tbody>
              </table>

              <div class="mt-4 pt-2 text-[11px] font-bold text-slate-900 space-y-2">
                <div class="flex justify-between items-end pb-1 border-b border-slate-300">
                  <div>Total Candidates Present: ________ / ${matchingStudents.length}</div>
                  <div class="text-slate-700">Invigilation Duty Verification & Signatures</div>
                </div>
                <div class="space-y-1.5 pt-1 font-semibold text-slate-900">
                  <div>1. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                  <div>2. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                  <div>3. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                  <div>4. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
                </div>
              </div>
            `;
            container.appendChild(page);
          });
        });

      } else if (activeFormat === 'unallotted') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        const page = document.createElement("div");
        page.className = "page-break mb-8";

        const rowsHtml = unallottedStudents.map((st, idx) => `
          <tr>
            <td class="col-sno">${idx + 1}.</td>
            <td class="col-roll">${st.rollNo || ''}</td>
            <td class="col-enroll font-mono font-bold">${st.enrollmentNo || ''}</td>
            <td class="col-name">${st.name}</td>
            <td class="col-group">${st.group}</td>
            <td class="text-center font-bold text-slate-800">${st.cohort || ''}</td>
            <td class="col-reason">${st.reason || 'Unallotted'}</td>
          </tr>
        `).join('');

        page.innerHTML = `
          <div class="pro-header-container border-amber-800 bg-amber-50/40">
            <div class="flex justify-between items-start">
              <div class="space-y-0.5">
                <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                <div class="text-[11px] font-bold text-amber-950 uppercase tracking-tight">${exam} • ${session}</div>
              </div>
              <div class="text-right">
                <div class="inline-block bg-amber-800 text-white text-xs font-black px-3.5 py-1 rounded uppercase tracking-wider shadow">
                  UNALLOTTED CANDIDATES
                </div>
              </div>
            </div>
            <div class="pro-header-divider bg-amber-800"></div>
            <div class="text-[11px] text-amber-950 font-bold uppercase">
              Notice: The following candidates could not be accommodated within the configured room roster.
            </div>
          </div>

          <table class="report-table">
            <thead>
              <tr class="font-bold text-center bg-amber-100/80 text-slate-900 border-b-2 border-slate-900">
                <th class="col-sno">S.No.</th>
                <th class="col-roll">Roll No</th>
                <th class="col-enroll">Enrollment No</th>
                <th class="col-name">Student Name</th>
                <th class="col-group">Group</th>
                <th class="text-center">Cohort / Semester</th>
                <th class="col-reason">Status</th>
              </tr>
            </thead>
            <tbody>
              ${rowsHtml || '<tr><td colspan="7" class="text-center italic py-4 text-emerald-700 font-black text-xs">All students successfully allotted to rooms! (No unallotted candidates)</td></tr>'}
            </tbody>
          </table>
          <div class="mt-8 pt-4 flex justify-between items-end text-[11px] font-semibold text-slate-800">
            <div>Total Unallotted Candidates: <strong>${unallottedStudents.length}</strong></div>
            <div class="text-center font-bold">Head Dept. of CSE</div>
          </div>
        `;
        container.appendChild(page);

      } else if (activeFormat === 'detainedReport') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        allocatedRooms.forEach(plan => {
          const roomDetained = [];
          const checkDetained = (st) => {
            if (isStudentDetained(st)) roomDetained.push(st);
          };
          plan.studentsA.forEach(checkDetained);
          plan.studentsB.forEach(checkDetained);

          if (roomDetained.length > 0) {
            const page = document.createElement("div");
            page.className = "page-break mb-8";

            const rowsHtml = roomDetained.map((st, idx) => `
              <tr class="detained-row">
                <td class="col-sno">${idx + 1}.</td>
                <td class="col-roll">${st.rollNo || ''}</td>
                <td class="col-enroll font-mono font-bold text-red-700">${st.enrollmentNo || ''}</td>
                <td class="col-name">${st.name}</td>
                <td class="col-group">${st.group}</td>
                <td class="col-reason">DETAINED</td>
              </tr>
            `).join('');

            page.innerHTML = `
              <div class="pro-header-container border-red-800 bg-red-50/40">
                <div class="flex justify-between items-start">
                  <div class="space-y-0.5">
                    <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                    <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                    <div class="text-[11px] font-bold text-red-900 uppercase tracking-tight">${exam} • ${session}</div>
                  </div>
                  <div class="text-right">
                    <div class="inline-block bg-red-800 text-white text-xs font-black px-3.5 py-1 rounded uppercase tracking-wider shadow">
                      ROOM-WISE DETAINED LIST
                    </div>
                    <div class="text-xs font-black text-slate-900 mt-1 uppercase">Room: ${plan.room.name}</div>
                  </div>
                </div>
                <div class="pro-header-divider bg-red-800"></div>
                <div class="flex justify-between items-center text-[11px] text-red-950 font-bold uppercase">
                  <span>Room Detained Candidates: <strong class="text-red-700 font-black">${roomDetained.length}</strong></span>
                </div>
              </div>

              <table class="report-table">
                <thead>
                  <tr class="font-bold text-center bg-red-100 text-slate-900 border-b-2 border-slate-900">
                    <th class="col-sno">S.No.</th>
                    <th class="col-roll">Roll No</th>
                    <th class="col-enroll">Enrollment No</th>
                    <th class="col-name">Student Name</th>
                    <th class="col-group">Group</th>
                    <th class="col-reason">Status</th>
                  </tr>
                </thead>
                <tbody>
                  ${rowsHtml}
                </tbody>
              </table>

              <div style="margin-top: 15px; padding: 8px 10px; border: 1.5px solid #991b1b; background: #fef2f2; font-size: 10px; color: #7f1d1d; border-radius: 4px;">
                <strong>Instructions for Invigilators:</strong><br>
                • Verify each student’s name against the provided Detained Students List before entry.<br>
                • Do not allow any Detained Student to enter or appear for the examination.<br>
                • Report any discrepancy immediately to the Examination Control Room.
              </div>

              <div class="mt-4 pt-2 flex justify-between items-end text-[11px] font-semibold text-slate-800">
                <div>Total Detained in Room ${plan.room.name}: <strong>${roomDetained.length}</strong></div>
                <div class="text-center font-bold">Head Dept. of CSE</div>
              </div>
            `;
            container.appendChild(page);
          }
        });

      } else if (activeFormat === 'detainedContinuous') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        let allDetainedEntries = [];
        allocatedRooms.forEach(plan => {
          const checkDetained = (st) => {
            if (isStudentDetained(st)) {
              allDetainedEntries.push({ roomName: plan.room.name, student: st });
            }
          };
          plan.studentsA.forEach(checkDetained);
          plan.studentsB.forEach(checkDetained);
        });

        const page = document.createElement("div");
        page.className = "mb-8";

        const rowsHtml = allDetainedEntries.map((item, idx) => `
          <tr class="detained-row">
            <td class="col-sno">${idx + 1}.</td>
            <td class="text-center font-bold text-indigo-900">${item.roomName}</td>
            <td class="col-roll">${item.student.rollNo || ''}</td>
            <td class="col-enroll font-mono font-bold text-red-700">${item.student.enrollmentNo || ''}</td>
            <td class="col-name">${item.student.name}</td>
            <td class="col-group">${item.student.group}</td>
          </tr>
        `).join('');

        page.innerHTML = `
          <div class="pro-header-container border-red-800 bg-red-50/40">
            <div class="flex justify-between items-start">
              <div class="space-y-0.5">
                <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                <div class="text-[11px] font-bold text-red-900 uppercase tracking-tight">${exam} • ${session}</div>
              </div>
              <div class="text-right">
                <div class="inline-block bg-red-800 text-white text-xs font-black px-3.5 py-1 rounded uppercase tracking-wider shadow">
                  DETAINED STUDENT LIST 
                </div>
              </div>
            </div>
            <div class="pro-header-divider bg-red-800"></div>
            <div class="flex justify-between items-center text-[11px] text-red-950 font-bold uppercase">
              <span>Total Detained Candidates: <strong class="text-red-700 font-black">${allDetainedEntries.length}</strong></span>
            </div>
          </div>

          <table class="report-table">
            <thead>
              <tr class="font-bold text-center bg-red-100 text-slate-900 border-b-2 border-slate-900">
                <th class="col-sno">S.No.</th>
                <th class="text-center w-24">Room</th>
                <th class="col-roll">Roll No</th>
                <th class="col-enroll">Enrollment No</th>
                <th class="col-name">Student Name</th>
                <th class="col-group">Group</th>
              </tr>
            </thead>
            <tbody>
              ${rowsHtml || '<tr><td colspan="6" class="text-center italic py-4 text-emerald-700 font-black text-xs">No detained students found across rooms!</td></tr>'}
            </tbody>
          </table>

          <div style="margin-top: 20px; padding: 10px 12px; border: 1.5px solid #991b1b; background: #fef2f2; font-size: 10.5px; color: #7f1d1d; border-radius: 4px;">
            <strong>Instructions for Invigilators:</strong><br>
            • Verify each student’s name against the provided Detained Students List before entry.<br>
            • Do not allow any Detained Student to enter or appear for the examination.<br>
            • Report any discrepancy immediately to the Examination Control Room.
          </div>

          <div class="mt-8 pt-4 flex justify-between items-end text-[11px] font-semibold text-slate-800">
            <div>Total Detained Candidates: <strong>${allDetainedEntries.length}</strong></div>
            <div class="text-center font-bold">Head Dept. of CSE</div>
          </div>
        `;
        container.appendChild(page);

      } else if (activeFormat === 'blankAttendance') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        const page = document.createElement("div");
        page.className = "page-break mb-8";

        let blankRows = "";
        for (let i = 1; i <= 30; i++) {
          blankRows += `
            <tr>
              <td class="col-sno" style="height: 18px;">${i}.</td>
              <td class="col-roll"></td>
              <td class="col-enroll"></td>
              <td class="col-name"></td>
              <td class="col-group"></td>
              <td class="col-sign"></td>
            </tr>
          `;
        }

        page.innerHTML = `
          <div class="pro-header-container">
            <div class="flex justify-between items-start">
              <div class="space-y-0.5">
                <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                <div class="text-[11px] font-bold text-indigo-900 uppercase tracking-tight">${exam} • ${session}</div>
              </div>
              <div class="text-right">
                <div class="inline-block border-2 border-slate-950 bg-slate-950 text-white text-xs font-black px-3 py-0.5 rounded uppercase tracking-wider shadow">
                  BLANK EXAMINATION ATTENDANCE SHEET
                </div>
                <div class="text-xs font-black text-slate-900 mt-1 uppercase">Room: ___________________</div>
              </div>
            </div>
            <div class="pro-header-divider"></div>
            
            <div class="flex justify-between items-center text-xs text-slate-900 font-bold uppercase mb-1.5 bg-slate-50 p-2 rounded border border-slate-200">
              <div>Course Name: <span class="border-b border-dashed border-slate-400 inline-block w-48 font-semibold text-indigo-900"></span></div>
              <div>Course Code: <span class="border-b border-dashed border-slate-400 inline-block w-32"></span></div>
            </div>

            <div class="flex justify-between items-center text-xs text-slate-900 font-bold uppercase mb-1 bg-slate-50 p-2 rounded border border-slate-200">
              <div>Group Name: <span class="text-indigo-900 font-black text-sm tracking-wide ml-1">___________________</span></div>
              <div>Group Seated Count: <span class="text-slate-950 font-black">________</span></div>
              <div>Shift: <span class="border-b border-dashed border-slate-400 inline-block w-32"></span></div>
              <div>Exam Date: <span class="border-b border-dashed border-slate-400 inline-block w-24"></span></div>
            </div>
          </div>

          <table class="report-table">
            <thead>
              <tr class="font-bold text-center bg-slate-100 text-slate-900 border-b-2 border-slate-900">
                <th class="col-sno">S.No.</th>
                <th class="col-roll">Roll No</th>
                <th class="col-enroll">Enrollment No</th>
                <th class="col-name">Student Name</th>
                <th class="col-group">Group</th>
                <th class="col-sign">Student Sign</th>
              </tr>
            </thead>
            <tbody>
              ${blankRows}
            </tbody>
          </table>

          <div class="mt-3 pt-1 text-[11px] font-bold text-slate-900 space-y-1.5">
            <div class="flex justify-between items-end pb-1 border-b border-slate-300">
              <div>Total Candidates Present: ________ / 30</div>
              <div class="text-slate-700">Invigilation Duty Verification & Signatures</div>
            </div>
            <div class="space-y-1 pt-0.5 font-semibold text-slate-900">
              <div>1. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
              <div>2. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
              <div>3. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
              <div>4. Invigilator Name: ___________________________________________ &nbsp;&nbsp;&nbsp; Sign: ____________</div>
            </div>
          </div>
        `;
        container.appendChild(page);

      } else if (activeFormat === 'copyCollection') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        allocatedRooms.forEach((plan, idx) => {
          const page = document.createElement("div");
          page.className = "page-break mb-8";

          const roomGroupsSet = new Set();
          const checkGrp = (st) => { if (st.group) roomGroupsSet.add(st.group); };
          plan.studentsA.forEach(checkGrp);
          plan.studentsB.forEach(checkGrp);
          const roomGroupsList = Array.from(roomGroupsSet).sort();

          let tableRowsHtml = "";
          let ufmRowsHtml = "";

          if (roomGroupsList.length > 0) {
            roomGroupsList.forEach((grp, gIdx) => {
              tableRowsHtml += `
                <tr>
                  <td class="text-center font-bold" style="padding: 5px; border: 1px solid #000;">${gIdx + 1}</td>
                  <td class="font-bold text-indigo-900 uppercase" style="padding: 5px; border: 1px solid #000;">${grp}</td>
                  <td class="text-center" style="padding: 5px; border: 1px solid #000;"></td>
                  <td class="text-center" style="padding: 5px; border: 1px solid #000;"></td>
                  <td class="text-center" style="padding: 5px; border: 1px solid #000;"></td>
                </tr>
              `;
            });
          } else {
            tableRowsHtml = `
              <tr>
                <td class="text-center font-bold" style="padding: 5px; border: 1px solid #000;">1</td>
                <td class="font-bold text-indigo-900 uppercase" style="padding: 5px; border: 1px solid #000;">GENERAL</td>
                <td class="text-center" style="padding: 5px; border: 1px solid #000;"></td>
                <td class="text-center" style="padding: 5px; border: 1px solid #000;"></td>
                <td class="text-center" style="padding: 5px; border: 1px solid #000;"></td>
              </tr>
            `;
          }

          let currentCount = roomGroupsList.length > 0 ? roomGroupsList.length : 1;
          for (let i = currentCount + 1; i <= 12; i++) {
            tableRowsHtml += `
              <tr>
                <td class="text-center font-bold" style="padding: 5px; border: 1px solid #000;">${i}</td>
                <td style="padding: 5px; border: 1px solid #000;"></td>
                <td style="padding: 5px; border: 1px solid #000;"></td>
                <td style="padding: 5px; border: 1px solid #000;"></td>
                <td style="padding: 5px; border: 1px solid #000;"></td>
              </tr>
            `;
          }

          for (let u = 1; u <= 5; u++) {
            ufmRowsHtml += `
              <tr>
                <td class="text-center font-bold" style="padding: 4px; border: 1px solid #000;">${u}</td>
                <td style="padding: 4px; border: 1px solid #000;"></td>
                <td style="padding: 4px; border: 1px solid #000;"></td>
                <td style="padding: 4px; border: 1px solid #000;"></td>
                <td style="padding: 4px; border: 1px solid #000;"></td>
              </tr>
            `;
          }

          page.innerHTML = `
            <div class="pro-header-container border-blue-900 bg-blue-50/35">
              <div class="flex justify-between items-start">
                <div class="space-y-0.5">
                  <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                  <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                  <div class="text-[11px] font-bold text-blue-950 uppercase tracking-tight">${exam} • ${session}</div>
                </div>
                <div class="text-right">
                  <div class="inline-block bg-blue-900 text-white text-xs font-black px-3.5 py-1 rounded uppercase tracking-wider shadow">
                    EXAM COPY COLLECTION SHEET
                  </div>
                  <div class="text-xs font-black text-slate-900 mt-1 uppercase">Room: ${plan.room.name} (${plan.room.block})</div>
                </div>
              </div>
              <div class="pro-header-divider bg-blue-900"></div>
              
              <div class="grid grid-cols-2 gap-2 text-xs text-slate-900 font-bold uppercase bg-white p-2 rounded border border-slate-200">
                <div>Shift: <span class="border-b border-dashed border-slate-400 inline-block w-48 font-semibold text-indigo-900"></span></div>
                <div>Date: <span class="border-b border-dashed border-slate-400 inline-block w-40"></span></div>
              </div>
            </div>

            <table style="width: 100%; border-collapse: collapse; border: 2px solid #000; font-family: Arial, sans-serif; margin-top: 4px;">
              <thead>
                <tr style="background-color: #1e3a8a; color: #fff; font-weight: bold; text-align: center; font-size: 11.5px;">
                  <th style="padding: 6px; width: 45px; border: 1px solid #000;">S. No.</th>
                  <th style="padding: 6px; text-align: left; border: 1px solid #000;">Group Name</th>
                  <th style="padding: 6px; width: 100px; border: 1px solid #000;">Year/Sem</th>
                  <th style="padding: 6px; width: 120px; border: 1px solid #000;">Course Code</th>
                  <th style="padding: 6px; width: 90px; border: 1px solid #000;">No of Copy</th>
                </tr>
              </thead>
              <tbody>
                ${tableRowsHtml}
              </tbody>
            </table>

            <div style="margin-top: 6px; font-size: 10.5px; font-weight: 900; text-transform: uppercase; color: #991b1b;">UFM Cases Record (If Any)</div>
            <table style="width: 100%; border-collapse: collapse; border: 2px solid #7f1d1d; font-family: Arial, sans-serif; margin-top: 2px;">
              <thead>
                <tr style="background-color: #7f1d1d; color: #fff; font-weight: bold; text-align: center; font-size: 11px;">
                  <th style="padding: 5px; width: 40px; border: 1px solid #000;">S.No</th>
                  <th style="padding: 5px; width: 110px; border: 1px solid #000;">Roll No</th>
                  <th style="padding: 5px; width: 120px; border: 1px solid #000;">Enrollment No.</th>
                  <th style="padding: 5px; text-align: left; border: 1px solid #000;">Student Name</th>
                  <th style="padding: 5px; width: 140px; border: 1px solid #000;">Course Name/Code</th>
                </tr>
              </thead>
              <tbody>
                ${ufmRowsHtml}
              </tbody>
            </table>

            <div class="mt-2 p-2 border border-slate-300 rounded-lg bg-slate-50 text-[10px] font-semibold text-slate-800">
              <div><strong>Collection Note:</strong> Group Name(s) are auto-filled from system records. Invigilators must fill Year/Sem, Course Code, No of Copies, and UFM records if applicable.</div>
            </div>

            <div class="mt-3 pt-1 flex justify-between items-end text-[11px] font-bold text-slate-900">
              <div>
                <div>Invigilator 1 Signature: ______________________</div>
                <div class="mt-1">Invigilator 2 Signature: ______________________</div>
              </div>
              <div class="text-center font-bold">
                Head Dept. of CSE<br>
                __________________________________<br>
                Received By (Examination Control Room)
              </div>
            </div>
          `;
          container.appendChild(page);
        });

      } else if (activeFormat === 'blankCopyCollection') {
        printArea.className = "max-w-4xl mx-auto min-h-screen bg-white portrait-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        const page = document.createElement("div");
        page.className = "page-break mb-8";

        let blankCollectionRows = "";
        for (let i = 1; i <= 12; i++) {
          blankCollectionRows += `
            <tr>
              <td class="text-center font-bold" style="padding: 6px; border: 1px solid #000;">${i}</td>
              <td style="padding: 6px; border: 1px solid #000;"></td>
              <td style="padding: 6px; border: 1px solid #000;"></td>
              <td style="padding: 6px; border: 1px solid #000;"></td>
              <td style="padding: 6px; border: 1px solid #000;"></td>
            </tr>
          `;
        }

        let blankUfmRows = "";
        for (let u = 1; u <= 5; u++) {
          blankUfmRows += `
            <tr>
              <td class="text-center font-bold" style="padding: 5px; border: 1px solid #000;">${u}</td>
              <td style="padding: 5px; border: 1px solid #000;"></td>
              <td style="padding: 5px; border: 1px solid #000;"></td>
              <td style="padding: 5px; border: 1px solid #000;"></td>
              <td style="padding: 5px; border: 1px solid #000;"></td>
            </tr>
          `;
        }

        page.innerHTML = `
          <div class="pro-header-container border-blue-900 bg-blue-50/35">
            <div class="flex justify-between items-start">
              <div class="space-y-0.5">
                <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                <div class="text-xs font-extrabold uppercase text-slate-800 tracking-wider">${deptShift.split(':')[0] || 'Department of CSE'} - ${prog}</div>
                <div class="text-[11px] font-bold text-blue-950 uppercase tracking-tight">${exam} • ${session}</div>
              </div>
              <div class="text-right">
                <div class="inline-block bg-blue-900 text-white text-xs font-black px-3.5 py-1 rounded uppercase tracking-wider shadow">
                  BLANK EXAM COPY COLLECTION SHEET
                </div>
                <div class="text-xs font-black text-slate-900 mt-1 uppercase">Room: ___________________</div>
              </div>
            </div>
            <div class="pro-header-divider bg-blue-900"></div>
            
            <div class="grid grid-cols-2 gap-2 text-xs text-slate-900 font-bold uppercase bg-white p-2 rounded border border-slate-200">
              <div>Shift: <span class="border-b border-dashed border-slate-400 inline-block w-48 font-semibold text-indigo-900"></span></div>
              <div>Date: <span class="border-b border-dashed border-slate-400 inline-block w-40"></span></div>
            </div>
          </div>

          <table style="width: 100%; border-collapse: collapse; border: 2px solid #000; font-family: Arial, sans-serif; margin-top: 4px;">
            <thead>
              <tr style="background-color: #1e3a8a; color: #fff; font-weight: bold; text-align: center; font-size: 11.5px;">
                <th style="padding: 8px; width: 50px; border: 1px solid #000;">S. No.</th>
                <th style="padding: 8px; text-align: left; border: 1px solid #000;">Group Name</th>
                <th style="padding: 8px; width: 110px; border: 1px solid #000;">Year/Sem</th>
                <th style="padding: 8px; width: 130px; border: 1px solid #000;">Course Code</th>
                <th style="padding: 8px; width: 100px; border: 1px solid #000;">No of Copy</th>
              </tr>
            </thead>
            <tbody>
              ${blankCollectionRows}
            </tbody>
          </table>

          <div style="margin-top: 8px; font-size: 11px; font-weight: 900; text-transform: uppercase; color: #991b1b;">UFM Cases Record (If Any)</div>
          <table style="width: 100%; border-collapse: collapse; border: 2px solid #7f1d1d; font-family: Arial, sans-serif; margin-top: 2px;">
            <thead>
              <tr style="background-color: #7f1d1d; color: #fff; font-weight: bold; text-align: center; font-size: 11px;">
                <th style="padding: 6px; width: 45px; border: 1px solid #000;">S.No</th>
                <th style="padding: 6px; width: 120px; border: 1px solid #000;">Roll No</th>
                <th style="padding: 6px; width: 130px; border: 1px solid #000;">Enrollment No.</th>
                <th style="padding: 6px; text-align: left; border: 1px solid #000;">Student Name</th>
                <th style="padding: 6px; width: 150px; border: 1px solid #000;">Course Name/Course Code</th>
              </tr>
            </thead>
            <tbody>
              ${blankUfmRows}
            </tbody>
          </table>

          <div class="mt-3 p-2 border border-slate-300 rounded-lg bg-slate-50 text-[10px] font-semibold text-slate-800">
            <div><strong>Collection Note:</strong> Invigilators must fill Room No, Shift, Date, Group Name, Year/Sem, Course Code, No of Copies, and UFM records manually, and submit this signed sheet along with answer booklets to the Examination Control Room.</div>
          </div>

          <div class="mt-6 pt-1 flex justify-between items-end text-[11px] font-bold text-slate-900">
            <div>
              <div>Invigilator 1 Signature: ______________________</div>
              <div class="mt-1.5">Invigilator 2 Signature: ______________________</div>
            </div>
            <div class="text-center font-bold">
              Head Dept. of CSE<br>
              __________________________________<br>
              Received By (Examination Control Room)
            </div>
          </div>
        `;
        container.appendChild(page);

      } else {
        printArea.className = "max-w-6xl mx-auto min-h-screen bg-white landscape-view";
        document.body.className = "bg-slate-100 text-slate-900 min-h-screen";

        allocatedRooms.forEach(item => {
          const room = item.room;
          const page = document.createElement("div");
          page.className = "page-break mb-8";

          const halfCol = Math.floor(room.cols / 2);

          let tableRowsHtml = "";
          for (let r = 0; r < room.rows; r++) {
            tableRowsHtml += "<tr>";
            
            for (let c = 0; c < halfCol; c++) {
              const st = item.grid[r][c];
              const isDetained = isStudentDetained(st);
              let cohortShadowClass = '';
              if (st) {
                cohortShadowClass = st.isCohortB ? 'cohort-b-cell' : 'cohort-a-cell';
              }

              if (st) {
                tableRowsHtml += `
                  <td class="${cohortShadowClass} ${isDetained ? 'detained-cell' : ''}">
                    <div class="text-[9.5px] uppercase leading-tight truncate font-bold">${st.name}</div>
                    <div class="font-mono text-[10.5px] font-extrabold tracking-tight leading-tight">${st.enrollmentNo || st.rollNo}</div>
                  </td>
                `;
              } else {
                tableRowsHtml += `<td></td>`;
              }
            }

            tableRowsHtml += `<td class="matrix-aisle"></td>`;

            for (let c = halfCol; c < room.cols; c++) {
              const st = item.grid[r][c];
              const isDetained = isStudentDetained(st);
              let cohortShadowClass = '';
              if (st) {
                cohortShadowClass = st.isCohortB ? 'cohort-b-cell' : 'cohort-a-cell';
              }

              if (st) {
                tableRowsHtml += `
                  <td class="${cohortShadowClass} ${isDetained ? 'detained-cell' : ''}">
                    <div class="text-[9.5px] uppercase leading-tight truncate font-bold">${st.name}</div>
                    <div class="font-mono text-[10.5px] font-extrabold tracking-tight leading-tight">${st.enrollmentNo || st.rollNo}</div>
                  </td>
                `;
              } else {
                tableRowsHtml += `<td></td>`;
              }
            }

            tableRowsHtml += "</tr>";
          }

          const statsArray = Object.entries(item.stats);
          const midPoint = Math.ceil(statsArray.length / 2);
          const col1Stats = statsArray.slice(0, midPoint);
          const col2Stats = statsArray.slice(midPoint);

          page.innerHTML = `
            <div class="pro-header-container p-3 mb-2">
              <div class="flex justify-between items-center">
                <div class="space-y-0.5">
                  <div class="text-2xl font-black tracking-wide text-slate-950 uppercase font-serif leading-none">${uni}</div>
                  <div class="text-xs font-black text-slate-800 uppercase tracking-wide mt-1">${deptShift}</div>
                  <div class="text-[11px] font-bold text-indigo-900 uppercase tracking-tight">${exam} • ${session}</div>
                </div>
                <div class="flex items-center gap-3">
                  <div class="border-2 border-red-700 bg-red-50/70 px-3.5 py-1 rounded text-right shadow-sm">
                    <div class="text-[9.5px] font-bold text-red-700 leading-tight">INTEGRAL UNIVERSITY</div>
                    <div class="text-xs font-black text-red-800 uppercase tracking-tight">ACCREDITED BY NAAC A+</div>
                  </div>
                  <div class="bg-slate-900 text-white px-4 py-1.5 rounded text-center shadow-md">
                    <div class="text-sm font-black tracking-wide">${room.name} / ${room.block}</div>
                    <div class="text-[10px] font-bold text-slate-300">Capacity: ${room.capacity} Seats</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="w-full text-center my-1.5">
              <div class="inline-block text-xs font-black uppercase text-slate-950 tracking-widest px-8 pb-0.5 border-b-2 border-slate-900">
                Board / Stage (Front)
              </div>
            </div>

            <table class="matrix-table my-1">
              <tbody>${tableRowsHtml}</tbody>
            </table>

            <div class="mt-3 flex justify-end gap-16 text-xs font-bold text-slate-900 pr-4">
              <div class="space-y-0.5">
                ${col1Stats.map(([grp, cnt]) => `<div>${grp} (${cnt})</div>`).join('')}
              </div>
              <div class="space-y-0.5">
                ${col2Stats.map(([grp, cnt]) => `<div>${grp} (${cnt})</div>`).join('')}
              </div>
            </div>
          `;
          container.appendChild(page);
        });
      }
    }

    function switchReportFormat(format) {
      activeFormat = format;
      const btnList = document.getElementById("btnViewList");
      const btnMatrix = document.getElementById("btnViewMatrix");
      const btnAttendance = document.getElementById("btnViewAttendance");
      const btnCourseCodeAtt = document.getElementById("btnViewCourseCodeAttendance");
      const btnUnallotted = document.getElementById("btnViewUnallotted");
      const btnDetained = document.getElementById("btnViewDetained");
      const btnDetainedCont = document.getElementById("btnViewDetainedContinuous");
      const btnBlankAtt = document.getElementById("btnViewBlankAttendance");
      const btnCopyCol = document.getElementById("btnViewCopyCollection");
      const btnBlankCopyCol = document.getElementById("btnViewBlankCopyCollection");

      [btnList, btnMatrix, btnAttendance, btnCourseCodeAtt, btnUnallotted, btnDetained, btnDetainedCont, btnBlankAtt, btnCopyCol, btnBlankCopyCol].forEach(btn => {
        if(btn) btn.className = "px-3 py-1.5 rounded text-xs font-semibold bg-transparent text-slate-700 hover:bg-slate-200 transition";
      });

      if (format === 'roomWise') {
        btnList.className = "px-3 py-1.5 rounded text-xs font-bold bg-slate-900 text-white transition";
      } else if (format === 'matrix') {
        btnMatrix.className = "px-3 py-1.5 rounded text-xs font-bold bg-slate-900 text-white transition";
      } else if (format === 'attendance') {
        btnAttendance.className = "px-3 py-1.5 rounded text-xs font-bold bg-slate-900 text-white transition";
      } else if (format === 'courseCodeAttendance') {
        btnCourseCodeAtt.className = "px-3 py-1.5 rounded text-xs font-bold bg-indigo-800 text-white transition";
      } else if (format === 'unallotted') {
        btnUnallotted.className = "px-3 py-1.5 rounded text-xs font-bold bg-slate-900 text-white transition";
      } else if (format === 'detainedReport') {
        btnDetained.className = "px-3 py-1.5 rounded text-xs font-bold bg-red-900 text-white transition";
      } else if (format === 'detainedContinuous') {
        btnDetainedCont.className = "px-3 py-1.5 rounded text-xs font-bold bg-red-800 text-white transition";
      } else if (format === 'blankAttendance') {
        btnBlankAtt.className = "px-3 py-1.5 rounded text-xs font-bold bg-emerald-800 text-white transition";
      } else if (format === 'copyCollection') {
        btnCopyCol.className = "px-3 py-1.5 rounded text-xs font-bold bg-blue-900 text-white transition";
      } else if (format === 'blankCopyCollection') {
        btnBlankCopyCol.className = "px-3 py-1.5 rounded text-xs font-bold bg-blue-800 text-white transition";
      }

      if (activeFormat === 'blankAttendance' || activeFormat === 'copyCollection' || activeFormat === 'blankCopyCollection' || activeFormat === 'courseCodeAttendance' || allocatedRooms.length > 0 || unallottedStudents.length > 0) renderDocument();
    }

    function exportToWordDoc() {
      if (activeFormat !== 'blankAttendance' && activeFormat !== 'copyCollection' && activeFormat !== 'blankCopyCollection' && activeFormat !== 'courseCodeAttendance' && allocatedRooms.length === 0 && unallottedStudents.length === 0) {
        return alert("Please generate reports first before exporting to Word.");
      }

      const reportContent = document.getElementById("reportContainer").innerHTML;
      const isLandscape = (activeFormat === 'matrix');
      const pageOrientation = isLandscape ? 'landscape' : 'portrait';
      const pageSize = isLandscape ? '29.7cm 21.0cm' : '21.0cm 29.7cm';

      const wordHtml = `
        <html xmlns:o='urn:schemas-microsoft-com:office:office' 
              xmlns:w='urn:schemas-microsoft-com:office:word' 
              xmlns='http://www.w3.org/TR/REC-html40'>
        <head>
          <meta charset='utf-8'>
          <title>Examination Report</title>
          <!--[if gte mso 9]>
          <xml>
            <w:WordDocument>
              <w:View>Print</w:View>
              <w:Zoom>100</w:Zoom>
              <w:DoNotOptimizeForBrowser/>
            </w:WordDocument>
          </xml>
          <![endif]-->
          <style>
            @page Section1 {
              size: ${pageSize};
              mso-page-orientation: ${pageOrientation};
              margin: 1.0cm 1.0cm 1.0cm 1.0cm;
              mso-header-margin: 0.8cm;
              mso-footer-margin: 0.8cm;
            }
            div.Section1 {
              page: Section1;
            }
            body {
              font-family: Arial, sans-serif;
              font-size: 10pt;
            }
            .pro-header-container {
              border: 1.5pt solid #0f172a;
              padding: 6pt 10pt;
              margin-bottom: 8pt;
              background: #ffffff;
            }
            .pro-header-divider {
              height: 1.5pt;
              background: #0f172a;
              margin: 4pt 0;
            }
            table {
              width: 100%;
              border-collapse: collapse;
              margin-bottom: 12pt;
            }
            table, th, td {
              border: 1px solid black;
            }
            th, td {
              padding: 4px 6px;
              font-size: 9pt;
            }
            .header-cell {
              text-align: center;
              font-weight: bold;
            }
            .cohort-header {
              text-align: center;
              font-weight: bold;
              text-transform: uppercase;
              background-color: #f2f2f2;
            }
            .detained-row {
              background-color: #fee2e2 !important;
            }
            .detained-cell {
              background-color: #fca5a5 !important;
              color: #991b1b !important;
              font-weight: bold !important;
              text-decoration: line-through !important;
            }
            .cohort-a-cell {
              background-color: #ffffff !important;
            }
            .cohort-b-cell {
              background-color: #f1f5f9 !important;
            }
            .matrix-table td {
              text-align: center;
              font-size: 8.5pt;
              padding: 3px 2px;
            }
            .matrix-aisle {
              border-top: none !important;
              border-bottom: none !important;
              border-left: 1px solid black !important;
              border-right: 1px solid black !important;
              width: 25px;
            }
            .page-break {
              page-break-after: always;
              mso-special-character: line-break;
            }
          </style>
        </head>
        <body>
          <div class="Section1">
            ${reportContent}
          </div>
        </body>
        </html>
      `;

      const blob = new Blob(['\ufeff' + wordHtml], {
        type: 'application/msword;charset=utf-8'
      });

      const url = URL.createObjectURL(blob);
      const downloadLink = document.createElement("a");
      document.body.appendChild(downloadLink);

      let filename = "Exam_Report";
      if (activeFormat === 'roomWise') filename = "Room_Wise_Student_List.doc";
      else if (activeFormat === 'attendance') filename = "Room_Wise_Attendance_List.doc";
      else if (activeFormat === 'courseCodeAttendance') filename = "Course_Code_Attendance_List.doc";
      else if (activeFormat === 'matrix') filename = "Room_Wise_Seating_Matrix.doc";
      else if (activeFormat === 'unallotted') filename = "Unallotted_Students_List.doc";
      else if (activeFormat === 'detainedReport') filename = "Room_Wise_Detained_List.doc";
      else if (activeFormat === 'detainedContinuous') filename = "Continuous_Detained_List.doc";
      else if (activeFormat === 'blankAttendance') filename = "Blank_Attendance_Sheet.doc";
      else if (activeFormat === 'copyCollection') filename = "Exam_Copy_Collection_Sheet.doc";
      else if (activeFormat === 'blankCopyCollection') filename = "Blank_Copy_Collection_Sheet.doc";

      downloadLink.href = url;
      downloadLink.download = filename;
      downloadLink.click();
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(url);
    }

    // WordPress-Safe Isolation Printing Engine
    function safePrintReport() {
      if (activeFormat !== 'blankAttendance' && activeFormat !== 'copyCollection' && activeFormat !== 'blankCopyCollection' && activeFormat !== 'courseCodeAttendance' && allocatedRooms.length === 0 && unallottedStudents.length === 0) {
        return alert("⚠️ Please generate reports first before printing.");
      }

      const content = document.getElementById("reportContainer").innerHTML;
      const isLandscape = (activeFormat === 'matrix');
      const orientationCss = isLandscape ? 
        `@page { size: A4 landscape; margin: 6mm 10mm 6mm 10mm; }` : 
        `@page { size: A4 portrait; margin: 8mm 10mm 8mm 10mm; }`;

      const printWindow = window.open('', '_blank', 'width=1150,height=850');
      if (!printWindow) {
        window.print();
        return;
      }

      printWindow.document.open();
      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>Print Examination Reports</title>
          <script src="https://cdn.tailwindcss.com"><\/script>
          <style>
            ${orientationCss}
            * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
            body { font-family: Arial, Helvetica, sans-serif; background: #fff; color: #000; margin: 0; padding: 0; }
            .page-break { page-break-after: always; break-after: page; display: block; clear: both; margin-bottom: 20px; }
            .pro-header-container { border: 2px solid #0f172a; border-radius: 4px; padding: 8px 12px; margin-bottom: 8px; background: #fff; }
            .pro-header-divider { height: 2px; background: #0f172a; margin: 6px 0; }
            .report-table { width: 100%; border-collapse: collapse; border: 2px solid #0f172a; }
            .report-table th, .report-table td { border: 1px solid #334155; padding: 3px 5px; font-size: 11px; line-height: 1.2; }
            .cohort-header { border: 1.5px solid #0f172a; text-align: center; font-weight: bold; font-size: 12px; padding: 4px; text-transform: uppercase; background: #f1f5f9; }
            .matrix-table { width: 100%; table-layout: fixed; border-collapse: collapse; border: 2px solid #0f172a; }
            .matrix-table td { border: 1px solid #334155; padding: 2px; font-size: 10.5px; text-align: center; height: 34px; vertical-align: middle; }
            .matrix-aisle { border-top: none !important; border-bottom: none !important; border-left: 2px solid #0f172a !important; border-right: 2px solid #0f172a !important; width: 30px !important; background: #f8fafc; }
            .detained-row { background-color: #fee2e2 !important; }
            .detained-cell { background-color: #fca5a5 !important; color: #991b1b !important; font-weight: bold !important; text-decoration: line-through !important; }
            .cohort-a-cell { background-color: #ffffff !important; }
            .cohort-b-cell { background-color: #f1f5f9 !important; }
          </style>
        </head>
        <body onload="setTimeout(function(){ window.print(); window.close(); }, 400);">
          <div style="padding: 10px;">
            ${content}
          </div>
        </body>
        </html>
      `);
      printWindow.document.close();
    }

    function parseUploadedFile(file, callback) {
      const reader = new FileReader();
      if (file.name.endsWith('.csv')) {
        reader.onload = e => {
          const res = Papa.parse(e.target.result, { header: true, skipEmptyLines: true });
          callback(mapData(res.data));
        };
        reader.readAsText(file);
      } else {
        reader.onload = e => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
          const json = XLSX.utils.sheet_to_json(firstSheet);
          callback(mapData(json));
        };
        reader.readAsArrayBuffer(file);
      }
    }

    function parseCourseMappingFile(file) {
      const reader = new FileReader();
      const processMapping = (data) => {
        courseNameMapping.clear();
        data.forEach(item => {
          const code = getField(item, ["coursecode", "subjectcode", "code", "subcode"]);
          const name = getField(item, ["coursename", "subjectname", "name", "subname", "title"]);
          const normCode = String(code || "").trim().toUpperCase();
          const normName = String(name || "").trim().toUpperCase();
          if (normCode !== "") {
            courseNameMapping.set(normCode, normName);
          }
        });
        document.getElementById("badgeCountMapping").innerText = `${courseNameMapping.size} Mapped`;
      };

      if (file.name.endsWith('.csv')) {
        reader.onload = e => {
          const res = Papa.parse(e.target.result, { header: true, skipEmptyLines: true });
          processMapping(res.data);
        };
        reader.readAsText(file);
      } else {
        reader.onload = e => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
          const json = XLSX.utils.sheet_to_json(firstSheet);
          processMapping(json);
        };
        reader.readAsArrayBuffer(file);
      }
    }

    function parseUploadedRoomFile(file) {
      const reader = new FileReader();
      const processRooms = (data) => {
        const parsed = data.map(item => {
          const name = getField(item, ["roomno", "room", "roomnumber", "room_no", "roomname"]);
          const block = getField(item, ["block", "blockname", "building"], "BNLT BLOCK");
          let rows = parseInt(getField(item, ["rows", "row", "depth", "totalrows"])) || 0;
          let cols = parseInt(getField(item, ["columns", "cols", "col", "width", "totalcols"])) || 0;
          let cap = parseInt(getField(item, ["capacity", "cap", "totalseats", "totalcapacity"])) || 0;

          if (rows > 0 && cols > 0 && cap === 0) {
            cap = rows * cols;
          } else if (cap > 0 && rows === 0 && cols === 0) {
            cols = 6;
            rows = Math.ceil(cap / cols);
            cap = rows * cols;
          } else if (rows === 0 && cols === 0 && cap === 0) {
            rows = 8;
            cols = 6;
            cap = 48;
          }

          const subCap = parseInt(getField(item, ["subcap", "persectioncap", "perslotcap"])) || Math.floor(cap / 2);

          return {
            name: String(name || "").trim(),
            block: String(block || "").trim(),
            rows: rows,
            cols: cols,
            capacity: cap,
            subCap: subCap
          };
        }).filter(r => r.name !== "");

        if (parsed.length > 0) {
          roomRoster = parsed;
          renderRoomBadges();
          alert(`Successfully loaded ${parsed.length} rooms from Excel.`);
        } else {
          alert("No valid room rows found in the uploaded file.");
        }
      };

      if (file.name.endsWith('.csv')) {
        reader.onload = e => {
          const res = Papa.parse(e.target.result, { header: true, skipEmptyLines: true });
          processRooms(res.data);
        };
        reader.readAsText(file);
      } else {
        reader.onload = e => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
          const json = XLSX.utils.sheet_to_json(firstSheet);
          processRooms(json);
        };
        reader.readAsArrayBuffer(file);
      }
    }

    function mapData(arr) {
      return arr.map((item, idx) => {
        const roll = getField(item, ["rollno", "roll", "rollnumber", "roll_no", "roll no"]);
        const enroll = getField(item, ["enrollmentno", "enrollment", "enrollno", "enroll", "enroll_no", "enrolment no", "enrolmentno"], `250010${1000 + idx}`);
        const name = getField(item, ["studentname", "name", "student_name", "student name"], `STUDENT ${idx+1}`);
        const group = getField(item, ["group", "section", "branch", "groupname"], "CSE-A");

        const subjects = [];
        Object.keys(item).forEach(colKey => {
          const colClean = colKey.toLowerCase().replace(/[^a-z0-9]/g, '');
          if (colClean.startsWith('sub') || colClean.startsWith('subject') || colClean.startsWith('course')) {
            const val = String(item[colKey] || '').trim();
            if (val && val.toLowerCase() !== 'nan') {
              val.split(',').forEach(s => {
                const cleanSub = s.trim();
                if (cleanSub) subjects.push(cleanSub);
              });
            }
          }
        });

        return {
          rollNo: String(roll || "").trim(),
          enrollmentNo: normalizeEnroll(enroll),
          name: String(name || "").trim().toUpperCase(),
          group: String(group || "").trim(),
          subjects: subjects
        };
      });
    }

    document.getElementById("fileRooms").addEventListener("change", function(e) {
      if (e.target.files[0]) {
        parseUploadedRoomFile(e.target.files[0]);
      }
    });

    document.getElementById("fileA").addEventListener("change", function(e) {
      if (e.target.files[0]) {
        parseUploadedFile(e.target.files[0], res => {
          datasetA = res;
          document.getElementById("badgeCountA").innerText = datasetA.length;
          updateTopDashboard();
        });
      }
    });

    document.getElementById("fileB").addEventListener("change", function(e) {
      if (e.target.files[0]) {
        parseUploadedFile(e.target.files[0], res => {
          datasetB = res;
          document.getElementById("badgeCountB").innerText = datasetB.length;
          updateTopDashboard();
        });
      }
    });

    document.getElementById("fileMapping").addEventListener("change", function(e) {
      if (e.target.files[0]) {
        parseCourseMappingFile(e.target.files[0]);
      }
    });

    // STRICT UNIQUE COUNT FILTER FOR DETAINED LIST
    document.getElementById("fileDetained").addEventListener("change", function(e) {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      
      const processDetainedData = (data) => {
        detainedSet.clear();
        data.forEach(item => {
          const enroll = getField(item, ["enrollmentno", "enrollment", "enrollno", "enroll", "enroll_no", "enrolment no", "enrolmentno"]);
          const roll = getField(item, ["rollno", "roll", "rollnumber", "roll_no", "roll no"]);
          
          const normE = normalizeEnroll(enroll);
          const normR = normalizeEnroll(roll);

          if (normE !== "" && normE !== "UNDEFINED" && normE !== "NULL" && normE !== "NAN") {
            detainedSet.add(normE);
          } else if (normR !== "" && normR !== "UNDEFINED" && normR !== "NULL" && normR !== "NAN") {
            detainedSet.add(normR);
          }
        });
        document.getElementById("badgeCountDetained").innerText = `${detainedSet.size}`;
        updateTopDashboard();
        if (allocatedRooms.length > 0) renderDocument();
      };

      if (file.name.endsWith('.csv')) {
        reader.onload = ev => {
          const res = Papa.parse(ev.target.result, { header: true, skipEmptyLines: true });
          processDetainedData(res.data);
        };
        reader.readAsText(file);
      } else {
        reader.onload = ev => {
          const data = new Uint8Array(ev.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
          const json = XLSX.utils.sheet_to_json(firstSheet);
          processDetainedData(json);
        };
        reader.readAsArrayBuffer(file);
      }
    });

    // FINAL INITIALIZATION CALL
    renderRoomBadges();
  </script>
</body>
</html>				</div>
				</div>
					</div>
		</div>
					</div>
		</section>
				</div>
		<p>The post <a href="https://gyanxp.com/iul/">iul</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/iul/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Online Python Practical Solution (PR3)</title>
		<link>https://gyanxp.com/online-python-practical-solution/</link>
					<comments>https://gyanxp.com/online-python-practical-solution/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Wed, 12 Aug 2026 07:46:41 +0000</pubDate>
				<category><![CDATA[Online Practical]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=5917</guid>

					<description><![CDATA[<p>O Level Python Practical Solutions (M3-R5) Practice 50+ NIELIT practical exam questions with dynamic code runners, timer tracking, and instant solutions! 📚 Practical Completion Progress 0 / 51 Practiced (0%) 📑 Practical Index ◀ ▶</p>
<p>The post <a href="https://gyanxp.com/online-python-practical-solution/">Online Python Practical Solution (PR3)</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[		<div data-elementor-type="wp-post" data-elementor-id="5917" class="elementor elementor-5917">
						<section class="elementor-section elementor-top-section elementor-element elementor-element-22ce531 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="22ce531" data-element_type="section" data-e-type="section">
						<div class="elementor-container elementor-column-gap-default">
					<div class="elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-eb0ad13" data-id="eb0ad13" data-element_type="column" data-e-type="column">
			<div class="elementor-widget-wrap elementor-element-populated">
						<div class="elementor-element elementor-element-135feea elementor-widget__width-initial elementor-widget elementor-widget-html" data-id="135feea" data-element_type="widget" data-e-type="widget" data-widget_type="html.default">
				<div class="elementor-widget-container">
					<!-- Google Fonts & Prism.js Syntax Highlighting -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />

<style>
  :root {
    --gyanxp-orange: #ff6600;
    --gyanxp-orange-hover: #e65c00;
    --gyanxp-dark: #1f2421;
    --gyanxp-accent-blue: #007bff;
    --gyanxp-bg: #f8f9fa;
    --gyanxp-card-bg: #ffffff;
    --gyanxp-danger: #dc3545;
    --gyanxp-success: #28a745;
  }

  /* Universal Box-Sizing & Reset */
  .gyanxp-full-page,
  .gyanxp-full-page * {
    box-sizing: border-box !important;
    font-family: 'Poppins', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }

  /* Full Width Outer Container */
  .gyanxp-full-page {
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 !important;
    padding: clamp(10px, 2vw, 24px) !important;
    background-color: var(--gyanxp-bg);
  }

  /* =========================================================
     TOP BOX 1: FULL WIDTH HEADER BANNER
     ========================================================= */
  .gyanxp-page-header {
    width: 100% !important;
    margin: 0 0 16px 0 !important;
    background: linear-gradient(135deg, var(--gyanxp-dark) 0%, #2c302e 100%) !important;
    color: #ffffff !important;
    padding: clamp(16px, 2.5vw, 24px) clamp(18px, 3vw, 30px) !important;
    border-radius: 12px !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
    border: 1px solid #2c302e !important;
    border-left: 6px solid var(--gyanxp-orange) !important;
    display: flex !important;
    flex-direction: column !important;
    gap: 6px !important;
  }

  .gyanxp-page-header h1 {
    margin: 0 !important;
    padding: 0 !important;
    font-size: clamp(20px, 2.8vw, 28px) !important;
    font-weight: 700 !important;
    line-height: 1.35 !important;
    color: #ffffff !important;
  }

  .gyanxp-page-header p {
    margin: 0 !important;
    padding: 0 !important;
    font-size: clamp(13px, 1.8vw, 15px) !important;
    color: #d1d5db !important;
    line-height: 1.5 !important;
  }

  /* =========================================================
     TOP BOX 2: FULL WIDTH PROGRESS WIDGET
     ========================================================= */
  .progress-widget {
    width: 100% !important;
    margin: 0 0 20px 0 !important;
    background: var(--gyanxp-card-bg) !important;
    padding: clamp(16px, 2vw, 20px) clamp(18px, 3vw, 30px) !important;
    border-radius: 12px !important;
    border: 1px solid #e9ecef !important;
    border-left: 6px solid var(--gyanxp-orange) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04) !important;
  }

  .progress-info {
    display: flex !important;
    justify-content: space-between !important;
    align-items: center !important;
    flex-wrap: wrap !important;
    gap: 8px 12px !important;
    margin-bottom: 12px !important;
  }

  .progress-title {
    font-size: clamp(13.5px, 2vw, 15px) !important;
    font-weight: 600 !important;
    color: var(--gyanxp-dark) !important;
    display: inline-flex !important;
    align-items: center !important;
    gap: 6px !important;
  }

  .progress-counter-badge {
    font-size: clamp(12px, 1.8vw, 13.5px) !important;
    font-weight: 600 !important;
    color: var(--gyanxp-orange) !important;
    background: #fff0e6 !important;
    padding: 4px 14px !important;
    border-radius: 20px !important;
    border: 1px solid rgba(255, 102, 0, 0.2) !important;
    white-space: nowrap !important;
  }

  .progress-bar-bg {
    width: 100% !important;
    height: 10px !important;
    background: #e9ecef !important;
    border-radius: 10px !important;
    overflow: hidden !important;
  }

  .progress-bar-fill {
    height: 100% !important;
    width: 0% !important;
    background: linear-gradient(90deg, var(--gyanxp-orange), #ff9933) !important;
    transition: width 0.4s ease-in-out !important;
  }

  /* =========================================================
     FULL WIDTH PRACTICAL GRID LAYOUT
     ========================================================= */
  .practical-layout {
    width: 100% !important;
    display: grid !important;
    grid-template-columns: 320px 1fr !important;
    gap: 20px !important;
    align-items: start !important;
    margin: 0 !important;
  }

  /* Sidebar (Practical Index) */
  .program-sidebar {
    width: 100% !important;
    background: var(--gyanxp-card-bg);
    border-radius: 12px;
    padding: 18px 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
    position: sticky;
    top: 15px;
    border: 1px solid #e9ecef;
  }

  .sidebar-title {
    font-size: 15px;
    font-weight: 700;
    color: var(--gyanxp-dark);
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 2px solid var(--gyanxp-orange);
  }

  .sidebar-scroll-wrapper {
    position: relative;
    width: 100%;
  }

  .program-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: calc(100vh - 220px);
    overflow-y: auto;
    padding-right: 4px;
    scroll-behavior: smooth;
  }

  /* Floating Scroll Arrows for Small Screens */
  .sidebar-nav-arrow {
    display: none;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 10;
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(4px);
    color: var(--gyanxp-dark);
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    cursor: pointer;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    transition: all 0.2s ease;
  }

  .sidebar-nav-arrow:hover {
    background: #ffffff;
    color: var(--gyanxp-orange);
  }

  .sidebar-nav-prev { left: -8px; }
  .sidebar-nav-next { right: -8px; }

  .nav-btn {
    width: 100%;
    text-align: left;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    padding: 12px 14px;
    border-radius: 8px;
    font-size: 13.5px;
    font-weight: 600;
    color: var(--gyanxp-dark);
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 44px;
  }

  .nav-btn:hover { background: #fff0e6; color: var(--gyanxp-orange); border-color: var(--gyanxp-orange); }
  .nav-btn.active { background: var(--gyanxp-orange); color: #ffffff; border-color: var(--gyanxp-orange); box-shadow: 0 3px 8px rgba(255, 102, 0, 0.25); }

  /* Workspace Card */
  .program-workspace {
    width: 100% !important;
    background: var(--gyanxp-card-bg);
    border-radius: 12px;
    padding: clamp(18px, 2.5vw, 30px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
    border: 1px solid #e9ecef;
    min-width: 0;
  }

  .program-content { display: none; }
  .program-content.active { display: block; }

  .meta-tags { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
  .badge { font-size: 11px; font-weight: 700; padding: 4px 10px; border-radius: 20px; text-transform: uppercase; }
  .badge-tag { background: #fff0e6; color: var(--gyanxp-orange); }
  .badge-easy { background: #e6f4ea; color: #137333; }
  .badge-medium { background: #fef7e0; color: #b06000; }
  .badge-hard { background: #fce8e6; color: #c5221f; }
  .badge-marks { background: #e8f0fe; color: #1a73e8; }

  .question-title { font-size: clamp(18px, 2.2vw, 22px); font-weight: 700; color: var(--gyanxp-dark); margin: 0 0 12px 0; line-height: 1.4; }
  .question-desc { font-size: clamp(13px, 1.8vw, 14px); color: #555; line-height: 1.6; margin-bottom: 18px; background: #fffcf9; padding: 14px 16px; border-radius: 8px; border-left: 4px solid var(--gyanxp-orange); }

  /* Timer Box */
  .timer-box { 
    display: flex; 
    align-items: center; 
    justify-content: space-between; 
    background: #f1f3f5; 
    padding: 10px 16px; 
    border-radius: 8px; 
    margin-bottom: 18px; 
    font-size: 13.5px; 
    font-weight: 600; 
    flex-wrap: wrap; 
    gap: 10px; 
  }
  .timer-controls { display: inline-flex; align-items: center; gap: 8px; }
  .timer-display { font-family: monospace; font-size: 15px; color: var(--gyanxp-orange); background: #ffffff; padding: 4px 10px; border-radius: 4px; border: 1px solid #ced4da; line-height: 1; }
  .timer-btn { background: var(--gyanxp-dark); color: #fff; border: none; padding: 6px 14px; border-radius: 4px; cursor: pointer; font-size: 12.5px; font-weight: 500; }
  .timer-btn:hover { background: #000; }

  /* Code Section */
  .code-header { margin-bottom: 6px; }
  .code-section-title { font-size: 14px; font-weight: 600; color: var(--gyanxp-dark); }
  .program-workspace pre { border-radius: 8px; margin: 0 0 18px 0; font-size: 13.5px; max-height: 500px; overflow: auto; }

  /* Action Buttons */
  .btn-group { display: flex; gap: 10px; margin-bottom: 18px; flex-wrap: wrap; }
  .btn-action { 
    border: none; 
    height: 40px;
    padding: 0 18px; 
    font-size: 13px; 
    font-weight: 600; 
    border-radius: 6px; 
    cursor: pointer; 
    transition: all 0.2s ease; 
    display: inline-flex; 
    align-items: center; 
    justify-content: center;
    gap: 6px; 
    user-select: none;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  }
  .try-code-btn { background-color: var(--gyanxp-orange); color: #ffffff; }
  .try-code-btn:hover { background-color: var(--gyanxp-orange-hover); }
  
  .show-result-btn { background-color: var(--gyanxp-accent-blue); color: #ffffff; }
  .show-result-btn:hover { background-color: #0069d9; }
  .show-result-btn.active-btn { background-color: var(--gyanxp-danger); }
  .show-result-btn.active-btn:hover { background-color: #bd2130; }

  .complete-btn { background-color: #e9ecef; color: var(--gyanxp-dark); }
  .complete-btn:hover { background-color: #dde2e6; }
  .complete-btn.done { background-color: var(--gyanxp-success); color: #ffffff; }
  .complete-btn.done:hover { background-color: #218838; }

  /* Accordions */
  .accordion-box { margin-bottom: 18px; border: 1px solid #e9ecef; border-radius: 8px; overflow: hidden; }
  .accordion-header { background: #f8f9fa; padding: 12px 16px; font-size: 13.5px; font-weight: 600; color: var(--gyanxp-dark); cursor: pointer; display: flex; justify-content: space-between; align-items: center; user-select: none; }
  .accordion-body { display: none; padding: 14px 16px; font-size: 13.5px; color: #444; line-height: 1.6; background: #ffffff; border-top: 1px solid #e9ecef; }

  /* Output Frame */
  .result-container { display: none; margin-top: 14px; margin-bottom: 18px; background: #000000; border-radius: 8px; overflow: hidden; border: 1px solid #333333; }
  .result-header { background: #1e1e1e; color: #a0aec0; font-size: 11px; padding: 8px 14px; text-transform: uppercase; font-weight: 700; border-bottom: 1px solid #333333; }
  .result-container iframe { width: 100%; height: 400px; border: none; display: block; }

  /* Pagination */
  .pagination-group { display: flex; justify-content: space-between; margin-top: 24px; padding-top: 18px; border-top: 1px dashed #e9ecef; gap: 10px; }
  .btn-page { 
    height: 40px;
    padding: 0 20px; 
    background-color: #f1f3f5; 
    color: var(--gyanxp-dark); 
    border: 1px solid #ced4da; 
    font-size: 13px; 
    font-weight: 600; 
    border-radius: 6px; 
    cursor: pointer; 
    display: inline-flex; 
    align-items: center; 
    justify-content: center;
    transition: all 0.2s ease;
  }
  .btn-page:hover:not(:disabled) { background-color: var(--gyanxp-orange); color: #ffffff; border-color: var(--gyanxp-orange); }
  .btn-page:disabled { opacity: 0.4; cursor: not-allowed; }

  /* =========================================================
     RESPONSIVE (MOBILE & TABLET): FLUID INDEX BAR
     ========================================================= */
  @media (max-width: 992px) {
    .practical-layout { 
      grid-template-columns: 100% !important; 
      gap: 15px !important; 
    }
    
    .program-sidebar { 
      position: static; 
      width: 100% !important;
      padding: 12px 14px; 
      border-radius: 12px;
    }
    
    .sidebar-title { 
      font-size: 14px; 
      margin-bottom: 8px; 
    }

    .sidebar-nav-arrow {
      display: inline-flex;
    }

    .program-list {
      flex-direction: row;
      overflow-x: auto;
      max-height: none;
      padding: 4px 20px 8px 20px;
      gap: 8px;
      scroll-snap-type: x mandatory;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
    }
    .program-list::-webkit-scrollbar {
      display: none;
    }

    .nav-btn {
      white-space: nowrap;
      width: auto;
      flex-shrink: 0;
      padding: 6px 16px;
      font-size: 12.5px;
      min-height: 38px;
      border-radius: 20px;
      gap: 8px;
      scroll-snap-align: center;
    }

    .program-workspace { 
      padding: 18px 14px; 
      border-radius: 12px;
    }

    .btn-group { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
    .btn-action { width: 100%; height: 40px; font-size: 12.5px; padding: 0 10px; }
    .btn-action.complete-btn { grid-column: span 2; }
    .pagination-group .btn-page { flex: 1; height: 40px; }
    .result-container iframe { height: 280px; }
  }

  @media (max-width: 480px) {
    .btn-group { grid-template-columns: 1fr; }
    .btn-action.complete-btn { grid-column: auto; }
    .timer-box { flex-direction: column; align-items: flex-start; }
    .timer-controls { width: 100%; justify-content: space-between; }
  }
</style>

<div class="gyanxp-full-page">
  
  <!-- Uniform Full Width Header Banner -->
  <div class="gyanxp-page-header">
    <h1>O Level Python Practical Solutions (M3-R5)</h1>
    <p>Practice 50+ NIELIT practical exam questions with dynamic code runners, timer tracking, and instant solutions!</p>
  </div>

  <!-- Uniform Full Width Progress Widget -->
  <div class="progress-widget">
    <div class="progress-info">
      <span class="progress-title">📚 Practical Completion Progress</span>
      <span class="progress-counter-badge" id="progress-text">0 / 51 Practiced (0%)</span>
    </div>
    <div class="progress-bar-bg">
      <div class="progress-bar-fill" id="progress-fill"></div>
    </div>
  </div>

  <!-- Full Width Practical Grid Layout -->
  <div class="practical-layout">
    
    <!-- Practical Index Sidebar with Live Dynamic Count -->
    <div class="program-sidebar">
      <div class="sidebar-title" id="sidebar-main-title">📑 Practical Index</div>
      <div class="sidebar-scroll-wrapper">
        <button class="sidebar-nav-arrow sidebar-nav-prev" onclick="scrollIndexSidebar(-140)" title="Previous Programs">◀</button>
        <div class="program-list" id="sidebar-list"></div>
        <button class="sidebar-nav-arrow sidebar-nav-next" onclick="scrollIndexSidebar(140)" title="Next Programs">▶</button>
      </div>
    </div>

    <!-- Main Workspace -->
    <div class="program-workspace" id="workspace-container"></div>
  </div>

</div>

<!-- Prism.js Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>

<script>
  /* =========================================================================
     50+ NIELIT O-LEVEL PYTHON (M3-R5) PRACTICAL QUESTIONS
     ========================================================================= */
  var programsData = [
    {
      id: 1,
      title: "Q1. Calculator Program using Python Functions",
      problem: "By using Python functions design a small calculator program having four operations: addition, subtraction, multiplication, and division.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 8,
      explanation: "Define separate functions for <code>add()</code>, <code>subtract()</code>, <code>multiply()</code>, and <code>divide()</code> with zero-division handling.",
      code: `def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): return a / b if b != 0 else "Error: Div by 0"

num1, num2 = 20, 5
print(f"{num1} + {num2} = {add(num1, num2)}")
print(f"{num1} - {num2} = {subtract(num1, num2)}")
print(f"{num1} * {num2} = {multiply(num1, num2)}")
print(f"{num1} / {num2} = {divide(num1, num2)}")`
    },
    {
      id: 2,
      title: "Q2. Sum of Digits of an Integer using While Loop",
      problem: "Write a python program to find the sum of digits of an integer number using while loop.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Extract the last digit using modulus <code>% 10</code> and trim the number using integer floor division <code>// 10</code> until it becomes 0.",
      code: `num = 12345
total = 0
temp = num
while temp > 0:
    total += temp % 10
    temp //= 10

print(f"Sum of digits of {num} is: {total}")`
    },
    {
      id: 3,
      title: "Q3. Find Odd Numbers in an Array / List",
      problem: "Write a python program to find the odd numbers in an array.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Iterate through elements and check if element modulo 2 is not equal to 0 (<code>x % 2 != 0</code>).",
      code: `arr = [12, 17, 24, 39, 40, 55, 60, 71]
odds = [x for x in arr if x % 2 != 0]
print("Original Array:", arr)
print("Odd Numbers:", odds)`
    },
    {
      id: 4,
      title: "Q4. Swap First Two Characters of Two Strings",
      problem: "Write a Python program for: Input = 'abc', 'xyz' -> Output = 'xyc abz'",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Use string slicing to swap the first 2 characters: <code>s2[:2] + s1[2:]</code> and <code>s1[:2] + s2[2:]</code>.",
      code: `str1 = "abc"
str2 = "xyz"

new_str1 = str2[:2] + str1[2:]
new_str2 = str1[:2] + str2[2:]

print(f"Input:  '{str1}', '{str2}'")
print(f"Output: '{new_str1} {new_str2}'")`
    },
    {
      id: 5,
      title: "Q5. Print Full Pyramid using *",
      problem: "Program to print full pyramid using * pattern.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "On row <code>i</code>, print <code>(n - i)</code> leading spaces and repeat <code>'* '</code> <code>i</code> times.",
      code: `rows = 5
for i in range(1, rows + 1):
    print(" " * (rows - i) + "* " * i)`
    },
    {
      id: 6,
      title: "Q6. Number of Days Between Two Given Dates",
      problem: "Python Program to Find Number of Days Between Two Given Dates.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Import <code>datetime.date</code> and compute difference directly using timedelta subtraction.",
      code: `from datetime import date

d1 = date(2026, 1, 1)
d2 = date(2026, 8, 15)
delta = d2 - d1
print(f"Days between {d1} and {d2}: {delta.days} days")`
    },
    {
      id: 7,
      title: "Q7. Sum of Numbers Between 100 and 500 Divisible by 2",
      problem: "Write a python function to find the sum of all numbers between 100 and 500 which are divisible by 2.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Use <code>range(100, 501, 2)</code> to step only through even integers in that interval.",
      code: `def sum_even_range():
    return sum(x for x in range(100, 501) if x % 2 == 0)

print("Sum of even numbers (100 to 500):", sum_even_range())`
    },
    {
      id: 8,
      title: "Q8. Reverse a String",
      problem: "Write a python program to reverse a string.",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Use extended slice step <code>[::-1]</code> to reverse string sequence in linear time.",
      code: `text = "GyanXp Python"
reversed_text = text[::-1]
print(f"Original: '{text}'")
print(f"Reversed: '{reversed_text}'")`
    },
    {
      id: 9,
      title: "Q9. Count Repeated Characters in a String",
      problem: "Write a Python program to show character repetition count in 'thequickbrownfoxjumpsovorthelazydog'.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Use a dictionary to track letter occurrences and filter characters with frequency > 1.",
      code: `s = 'thequickbrownfoxjumpsovorthelazydog'
counts = {}
for ch in s:
    counts[ch] = counts.get(ch, 0) + 1

print("Repeated Characters:")
for ch, count in counts.items():
    if count > 1:
        print(f"'{ch}': {count}")`
    },
    {
      id: 10,
      title: "Q10. Sum of Series 1^3 + 2^3 + ... + n^3",
      problem: "Write a Python program to print the sum of series 1^3 + 2^3 + ... + n^3 till n-th term.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Iterate from 1 to n computing <code>i**3</code> or apply formula <code>((n*(n+1))//2)**2</code>.",
      code: `n = 5
series_sum = sum(i**3 for i in range(1, n + 1))
print(f"Sum of cubes up to {n} terms: {series_sum}")`
    },
    {
      id: 11,
      title: "Q11. Count Even and Odd Numbers in a List",
      problem: "Write a program to count even and odd numbers in list: [4, 7, 5, 64, 13, 18, 22, 29, 37].",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Iterate through elements: increment even counter if <code>x % 2 == 0</code>, otherwise increment odd counter.",
      code: `list1 = [4, 7, 5, 64, 13, 18, 22, 29, 37]
evens = sum(1 for x in list1 if x % 2 == 0)
odds = len(list1) - evens
print(f"Input: {list1}")
print(f"Count of even numbers: {evens}")
print(f"Count of odd numbers: {odds}")`
    },
    {
      id: 12,
      title: "Q12. Multiply Two Numbers by Repeated Addition",
      problem: "Write a Python program to multiply two numbers by repeated addition. Example: 6*3 = 6+6+6.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Initialize product accumulator to 0 and add first number inside a loop running second number times.",
      code: `a, b = 6, 3
prod = 0
for _ in range(abs(b)):
    prod += a

if b < 0: prod = -prod
print(f"{a} * {b} (by repeated addition) = {prod}")`
    },
    {
      id: 13,
      title: "Q13. Count Words, Capital, Small Letters, and Symbols",
      problem: "Take a sentence as input and display number of words, capital letters, small letters, and special symbols.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 10,
      explanation: "Use <code>.split()</code> for words; iterate through characters with <code>isupper()</code>, <code>islower()</code>, and symbols.",
      code: `text = "GyanXp O-Level 2026 Batch: #1 Exam Platform!"
words = len(text.split())
caps = sum(1 for c in text if c.isupper())
smalls = sum(1 for c in text if c.islower())
specials = sum(1 for c in text if not c.isalnum() and not c.isspace())

print(f"Sentence: '{text}'")
print(f"Words: {words}, Capital: {caps}, Small: {smalls}, Special Symbols: {specials}")`
    },
    {
      id: 14,
      title: "Q14. Sum of All Odd Numbers till 100",
      problem: "Write a Python program to find the sum of all odd numbers till 100.",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Sum sequence generated by <code>range(1, 101, 2)</code>.",
      code: `total = sum(range(1, 101, 2))
print("Sum of all odd numbers till 100 is:", total)`
    },
    {
      id: 15,
      title: "Q15. Check Leap Year",
      problem: "Write a program to Check Leap Year.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "A year is leap if <code>(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)</code>.",
      code: `year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year} is Leap Year: {is_leap}")`
    },
    {
      id: 16,
      title: "Q16. Print Elements of Upper Triangular Matrix",
      problem: "Write a program to print elements of upper triangular matrix.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "In an upper triangular matrix, row index <code>i <= column index j</code>.",
      code: `mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print("Upper Triangular Elements:")
for i in range(len(mat)):
    for j in range(len(mat[0])):
        if i <= j:
            print(mat[i][j], end=" ")
        else:
            print(" ", end=" ")
    print()`
    },
    {
      id: 17,
      title: "Q17. Count Number of Digits in an Integer",
      problem: "Count digits in an integer (e.g. 12345 -> 5, 153 -> 3, '00003452' -> 4).",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Convert number to string, strip leading zeroes (or parse as int) and find length.",
      code: `val = "00003452"
clean_digits = str(int(val))
print(f"Input: {val} -> Digit Count: {len(clean_digits)}")`
    },
    {
      id: 18,
      title: "Q18. Check Prime Number (Quick Check)",
      problem: "Write a Python program to verify whether a given integer is prime.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Test divisibility up to square root of n.",
      code: `def is_prime(n):
    return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))

n = 37
print(f"{n} is Prime: {is_prime(n)}")`
    },
    {
      id: 19,
      title: "Q19. Fibonacci Series of N Numbers",
      problem: "Write a Python program to find the Fibonacci series of n numbers. (Input: 7 -> 0 1 1 2 3 5 8).",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Maintain two pointers initialized to 0 and 1; generate next value via <code>a, b = b, a + b</code>.",
      code: `n = 7
a, b = 0, 1
fib = []
for _ in range(n):
    fib.append(a)
    a, b = b, a + b

print(f"Fibonacci series of {n} numbers:", *fib)`
    },
    {
      id: 20,
      title: "Q20. Slicing, Splitting, and Joining Strings",
      problem: "Input string: (a) Slice first 5 & last 5 chars, (b) split into words, (c) join back into single string.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Use slices <code>[:5]</code> and <code>[-5:]</code>, <code>str.split()</code>, and <code>' '.join()</code>.",
      code: `text = "Python is an amazing programming language"

# (a) Slicing
first_5 = text[:5]
last_5 = text[-5:]
print(f"First 5: '{first_5}', Last 5: '{last_5}'")

# (b) Splitting
words = text.split()
print("Words List:", words)

# (c) Joining
joined = " ".join(words)
print("Joined back:", joined)`
    },
    {
      id: 21,
      title: "Q21. Biggest Number Among 3 Numbers",
      problem: "Write a program for finding biggest number among 3 numbers.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Use conditional <code>if-elif-else</code> or max() function.",
      code: `a, b, c = 45, 89, 23
if a >= b and a >= c: biggest = a
elif b >= a and b >= c: biggest = b
else: biggest = c

print(f"Numbers: {a}, {b}, {c}")
print("Biggest number is:", biggest)`
    },
    {
      id: 22,
      title: "Q22. Iterate Through Tuple Using For Loop",
      problem: "Write a Python program to iterate through a tuple: ('apple', 'banana', 'orange').",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Use a standard <code>for item in my_tuple</code> loop to print each element.",
      code: `fruits = ('apple', 'banana', 'orange')
print("Iterating through tuple:")
for fruit in fruits:
    print("-", fruit)`
    },
    {
      id: 23,
      title: "Q23. Volume of Cylinder Given Radius & Height",
      problem: "Calculate the volume (V) of a cylinder given radius (r) and height (h). Formula: V = π × r² × h.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Import <code>math.pi</code> and calculate <code>math.pi * (r**2) * h</code>.",
      code: `import math

r = 5.0
h = 12.0
volume = math.pi * (r ** 2) * h
print(f"Radius: {r}, Height: {h}")
print(f"Volume of Cylinder: {volume:.2f}")`
    },
    {
      id: 24,
      title: "Q24. Simple Calculator using If-Elif-Else",
      problem: "Design a Simple Calculator using 'if-elif-else' statements.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Check operator symbol with conditional blocks.",
      code: `a, b = 15, 3
operator = '*'

if operator == '+': res = a + b
elif operator == '-': res = a - b
elif operator == '*': res = a * b
elif operator == '/': res = a / b if b != 0 else "Cannot divide by 0"
else: res = "Invalid operator"

print(f"{a} {operator} {b} = {res}")`
    },
    {
      id: 25,
      title: "Q25. Sentence Slicing and Concatenation",
      problem: "(a) Accept sentence, (b) display first 5 chars using slicing, (c) concatenate with predefined string.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Extract <code>sentence[:5]</code> and concatenate with <code>+</code> operator.",
      code: `sentence = "GyanXp Academy provides best education."
first_5 = sentence[:5]
extra = " [Verified O-Level Portal]"
combined = sentence + extra

print("First 5 chars:", first_5)
print("Concatenated: ", combined)`
    },
    {
      id: 26,
      title: "Q26. Length of a Dictionary",
      problem: "Write a Python program to find the length of a dictionary (dic = {'10': 'ten', '20': 'twenty'}).",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "<code>len(dictionary)</code> returns total number of key-value pairs.",
      code: `dic = {"10": "ten", "20": "twenty"}
print("Dictionary:", dic)
print("Length of Dictionary:", len(dic))`
    },
    {
      id: 27,
      title: "Q27. Reverse Elements of a List",
      problem: "Write a Python program to reverse the elements of a list.",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Use <code>list.reverse()</code> in-place or slicing <code>list[::-1]</code>.",
      code: `nums = [10, 20, 30, 40, 50]
reversed_list = nums[::-1]
print("Original List:", nums)
print("Reversed List:", reversed_list)`
    },
    {
      id: 28,
      title: "Q28. Factorial of a Number",
      problem: "Given an integer number n, write a Python program to print the factorial of this number.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Iterate from 1 to n multiplying into result accumulator.",
      code: `n = 5
fact = 1
for i in range(1, n + 1):
    fact *= i

print(f"Factorial of {n} is: {fact}")`
    },
    {
      id: 29,
      title: "Q29. Generate Prime Number Series up to N",
      problem: "Implement Python script to generate prime number series up to n.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Check each number up to n for prime divisibility and collect in a list.",
      code: `n = 50
primes = [x for x in range(2, n + 1) if all(x % i != 0 for i in range(2, int(x**0.5) + 1))]
print(f"Primes up to {n}:", primes)`
    },
    {
      id: 30,
      title: "Q30. Sum of Even Numbers Between M & N using Pass Statement",
      problem: "Compute sum of all even numbers between m & n (inclusive) using pass statement for odd numbers.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Use <code>if x % 2 == 0: total += x else: pass</code> to explicitly demonstrate the pass statement.",
      code: `m, n = 10, 25
total = 0
for num in range(m, n + 1):
    if num % 2 == 0:
        total += num
    else:
        pass  # pass statement for non-even numbers

print(f"Sum of even numbers between {m} and {n}: {total}")`
    },
    {
      id: 31,
      title: "Q31. Remove Duplicate Even Positive Integers from List",
      problem: "Remove duplicate even positive integers (including zero) keeping first occurrence intact.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Track seen even numbers in a set while maintaining original order.",
      code: `def filter_even_duplicates(text_input):
    seen_evens = set()
    result = []
    for ch in str(text_input):
        digit = int(ch)
        if digit % 2 == 0:
            if digit not in seen_evens:
                seen_evens.add(digit)
                result.append(ch)
        else:
            result.append(ch)
    return "".join(result)

print("4321 ->", filter_even_duplicates("4321"))
print("0001 ->", filter_even_duplicates("0001"))
print("1133 ->", filter_even_duplicates("1133"))`
    },
    {
      id: 32,
      title: "Q32. Calculate Area of Triangle (0.5 * b * h)",
      problem: "Write a python program to calculate area of triangle. Area = 0.5 * b * h.",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Multiply base by height and scale by 0.5.",
      code: `base = 10
height = 5
area = 0.5 * base * height
print(f"Base: {base}, Height: {height} -> Triangle Area: {area}")`
    },
    {
      id: 33,
      title: "Q33. Check Given Number is Armstrong or Not",
      problem: "Implement python script program to check if given number is Armstrong or not.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Sum each digit raised to total digit count power.",
      code: `num = 371
order = len(str(num))
total = sum(int(d)**order for d in str(num))
print(f"{num} is Armstrong: {total == num}")`
    },
    {
      id: 34,
      title: "Q34. Sum of Series: X + X^4/4! + X^6/6! + X^8/8! + ...",
      problem: "Write a Function to Compute the Sum of n Terms of: X + X^4/4! + X^6/6! + X^8/8! + ...",
      difficulty: "Medium",
      marks: 15,
      timerMins: 10,
      explanation: "First term is X, subsequent terms k from 2 to n have power and factorial of <code>2 * k</code>.",
      code: `import math

def compute_series(x, n):
    if n <= 0: return 0
    total = x
    for k in range(2, n + 1):
        power = 2 * k
        total += (x ** power) / math.factorial(power)
    return total

x_val, terms = 2, 4
print(f"Sum of series for X={x_val}, N={terms}: {compute_series(x_val, terms):.4f}")`
    },
    {
      id: 35,
      title: "Q35. Count Characters, Vowels, and Spaces in Text",
      problem: "Accept a line of text and find total characters, number of vowels, and number of blank spaces.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Iterate across the string checking <code>char in 'aeiouAEIOU'</code> and <code>char == ' '</code>.",
      code: `text = "GyanXp provides live interactive online batches"
total_chars = len(text)
vowels = sum(1 for c in text if c.lower() in "aeiou")
spaces = sum(1 for c in text if c == " ")

print(f"Characters: {total_chars}")
print(f"Vowels: {vowels}")
print(f"Spaces: {spaces}")`
    },
    {
      id: 36,
      title: "Q36. Linear Search on List of 10 Positive Numbers",
      problem: "Take a list of 10 numbers and a key value; apply Linear Search to check if key is present.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Iterate sequentially through list indices.",
      code: `numbers = [12, 45, 23, 67, 89, 90, 34, 56, 78, 11]
key = 90
found_idx = -1

for i in range(len(numbers)):
    if numbers[i] == key:
        found_idx = i
        break

if found_idx != -1:
    print(f"Key {key} found at index {found_idx}")
else:
    print(f"Key {key} not found")`
    },
    {
      id: 37,
      title: "Q37. Check Number is Palindrome or Not",
      problem: "Write a Python program to check whether a given number is a palindrome or not.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Convert number to string and compare with reversed string.",
      code: `num = 12321
s = str(num)
is_pal = (s == s[::-1])
print(f"Number {num} is Palindrome: {is_pal}")`
    },
    {
      id: 38,
      title: "Q38. Sum of Squares of N Natural Numbers",
      problem: "Find sum of squares of N natural numbers (e.g. 5 -> 55, 10 -> 385, 50 -> 42925, 100 -> 338350).",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Apply direct mathematical formula <code>(n * (n + 1) * (2*n + 1)) // 6</code> or sum iteration.",
      code: `def sum_of_squares(n):
    return (n * (n + 1) * (2 * n + 1)) // 6

for val in [5, 10, 50, 100]:
    print(f"N={val} -> Sum of Squares: {sum_of_squares(val)}")`
    },
    {
      id: 39,
      title: "Q39. NumPy 3x3 Array Slicing (Row, Col, Sub-array)",
      problem: "Create 3x3 array (1 to 9). Extract 2nd row, 2nd column, and 2x2 bottom-right sub-array.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Index 2D arrays with <code>arr[1, :]</code> for row 2, <code>arr[:, 1]</code> for col 2, and <code>arr[1:, 1:]</code> for corner.",
      code: `import numpy as np

arr = np.arange(1, 10).reshape(3, 3)
print("3x3 Matrix:\\n", arr)
print("Second Row:", arr[1, :])
print("Second Column:", arr[:, 1])
print("2x2 Bottom-Right Sub-array:\\n", arr[1:, 1:])`
    },
    {
      id: 40,
      title: "Q40. Store Lengths of Sub-Tuples into New Tuple",
      problem: "Given T1 = ((1,2,3), (3,4), (2,3,4,5), (5,6,7)), output T2 = (3, 2, 4, 3).",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Use a tuple comprehension or generator <code>tuple(len(sub) for sub in T1)</code>.",
      code: `T1 = ((1, 2, 3), (3, 4), (2, 3, 4, 5), (5, 6, 7))
T2 = tuple(len(sub) for sub in T1)
print("T1 =", T1)
print("T2 =", T2)`
    },
    {
      id: 41,
      title: "Q41. Array Copy and Modify Second Element",
      problem: "Create original array [5,10,15,20]. Copy and modify copy[1] = 50. Verify original remains unchanged.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "Use <code>.copy()</code> to create an independent copy without shared reference pointer.",
      code: `import numpy as np

original = np.array([5, 10, 15, 20])
modified_copy = original.copy()
modified_copy[1] = 50

print("Original Array:     ", original)
print("Modified Copy Array:", modified_copy)`
    },
    {
      id: 42,
      title: "Q42. Perform Bitwise Operations (AND, OR, XOR, Shifts)",
      problem: "Perform bitwise operations: (A) AND, (B) OR, (C) XOR, (D) Left Shift (by 2), (E) Right Shift (by 2).",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Python operators: <code>&</code> (AND), <code>|</code> (OR), <code>^</code> (XOR), <code><<</code> (Left shift), <code>>></code> (Right shift).",
      code: `a, b = 12, 5  # 12 = 1100, 5 = 0101 in binary

print(f"a = {a}, b = {b}")
print("(A) a & b (AND):       ", a & b)
print("(B) a | b (OR):        ", a | b)
print("(C) a ^ b (XOR):       ", a ^ b)
print("(D) a << 2 (Left Shift):", a << 2)
print("(E) a >> 2 (Right Shift):", a >> 2)`
    },
    {
      id: 43,
      title: "Q43. Modular Student Grade Calculator",
      problem: "Calculate student final grade modularly with separate functions for average and grade assignment.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 10,
      explanation: "Separate business logic into <code>calc_avg()</code> and <code>assign_grade()</code> functions.",
      code: `def calc_avg(scores):
    return sum(scores) / len(scores)

def assign_grade(avg):
    if avg >= 85: return 'S (Outstanding)'
    elif avg >= 75: return 'A (Excellent)'
    elif avg >= 65: return 'B (Good)'
    elif avg >= 50: return 'C (Satisfactory)'
    else: return 'F (Failed)'

student_marks = [78, 85, 90]
avg = calc_avg(student_marks)
grade = assign_grade(avg)
print(f"Marks: {student_marks} -> Average: {avg:.2f} -> Grade: {grade}")`
    },
    {
      id: 44,
      title: "Q44. Reverse of a String",
      problem: "Write a program to print reverse of a string.",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Reverse sequence using Python string slice step -1.",
      code: `msg = "NIELIT O Level M3-R5"
print("Original:", msg)
print("Reversed:", msg[::-1])`
    },
    {
      id: 45,
      title: "Q45. NumPy 5x5 Random Array & Replace Min with 0",
      problem: "Create a 5x5 array with random values and replace the minimum value with 0.",
      difficulty: "Medium",
      marks: 15,
      timerMins: 8,
      explanation: "Use <code>np.random.rand(5,5)</code> and assign <code>arr[arr == arr.min()] = 0</code>.",
      code: `import numpy as np

arr = np.random.randint(10, 100, (5, 5))
print("Original 5x5 Matrix:\\n", arr)
min_val = arr.min()
arr[arr == min_val] = 0
print(f"\\nAfter Replacing Min Value ({min_val}) with 0:\\n", arr)`
    },
    {
      id: 46,
      title: "Q46. Generate Fibonacci Series",
      problem: "Write a python program to generate Fibonacci series.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Produce terms iteratively.",
      code: `terms = 8
a, b = 0, 1
print("Fibonacci:", end=" ")
for _ in range(terms):
    print(a, end=" ")
    a, b = b, a + b
print()`
    },
    {
      id: 47,
      title: "Q47. Divisible by Both 3 and 5 in Range [a, b]",
      problem: "Print numbers between a and b divisible by both 3 and 5. If none, display 'No numbers found'.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Divisible by both 3 and 5 means divisible by 15 (<code>x % 15 == 0</code>).",
      code: `a, b = 10, 50
matches = [x for x in range(a, b + 1) if x % 3 == 0 and x % 5 == 0]

if matches:
    print(f"Numbers between {a} and {b} divisible by 3 & 5:", matches)
else:
    print("No numbers found")`
    },
    {
      id: 48,
      title: "Q48. Find Palindromes in Range 200 to 400",
      problem: "Write a python program to find all palindrome numbers in given range 200 to 400.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 6,
      explanation: "Iterate across range and select numbers whose string form equals reversed string.",
      code: `palindromes = [x for x in range(200, 401) if str(x) == str(x)[::-1]]
print("Palindromes between 200 and 400:")
print(palindromes)`
    },
    {
      id: 49,
      title: "Q49. Display Numbers 0 to 6 Except 3 and 6",
      problem: "Write a program to display numbers from 0 to 6 except 3 and 6 using continue statement.",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Use <code>continue</code> inside loop when iteration reaches 3 or 6.",
      code: `print("Numbers (0 to 6 except 3 and 6):")
for x in range(7):
    if x == 3 or x == 6:
        continue
    print(x, end=" ")
print()`
    },
    {
      id: 50,
      title: "Q50. Check Positive Number using Assert Statement",
      problem: "Check if a number is positive using the Python assert statement.",
      difficulty: "Easy",
      marks: 10,
      timerMins: 5,
      explanation: "<code>assert condition, 'error message'</code> raises AssertionError if condition is false.",
      code: `def verify_positive(num):
    assert num > 0, f"Assertion Failed: {num} is not positive!"
    return f"{num} is valid positive number."

print(verify_positive(15))
try:
    print(verify_positive(-5))
except AssertionError as err:
    print(err)`
    },
    {
      id: 51,
      title: "Q51. Formatted Current Date & Time (YYYY-MM-DD HH:MM)",
      problem: "Print the current date and time in formatted form (Year-Month-Day Hour:Minute).",
      difficulty: "Easy",
      marks: 5,
      timerMins: 4,
      explanation: "Use <code>datetime.datetime.now().strftime('%Y-%m-%d %H:%M')</code>.",
      code: `from datetime import datetime

now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M")
print("Current Formatted Date & Time:", formatted)`
    }
  ];

  /* =========================================================================
     CORE SCRIPT & DYNAMIC LOGIC
     ========================================================================= */
  var TOTAL_PROGRAMS = programsData.length;
  var completedPrograms = JSON.parse(localStorage.getItem('gyanxp_completed')) || [];
  var activeTimers = {};

  function escapeHtml(text) {
    return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }

  function scrollIndexSidebar(offset) {
    var sidebarList = document.getElementById('sidebar-list');
    if (sidebarList) {
      sidebarList.scrollBy({ left: offset, behavior: 'smooth' });
    }
  }

  function renderAllPrograms() {
    var sidebarHtml = '';
    var workspaceHtml = '';

    // Set Dynamic Sidebar Header Title
    var mainTitleEl = document.getElementById('sidebar-main-title');
    if (mainTitleEl) {
      mainTitleEl.innerText = '📑 Practical Index (' + TOTAL_PROGRAMS + ' Problems)';
    }

    programsData.forEach(function (item, index) {
      var isFirst = index === 0;
      var progNum = index + 1;
      var diffClass = 'badge-' + item.difficulty.toLowerCase();

      // Updated Button Label to "Practical X"
      sidebarHtml += `
        <button class="nav-btn ${isFirst ? 'active' : ''}" id="side-btn-${item.id}" onclick="switchProgram(${item.id})">
          <span>Practical ${progNum}</span>
          <span class="status-dot" id="dot-${item.id}">⚪</span>
        </button>
      `;

      workspaceHtml += `
        <div id="prog-${item.id}" class="program-content ${isFirst ? 'active' : ''}">
          <div class="meta-tags">
            <span class="badge badge-tag">Practical #${progNum}</span>
            <span class="badge ${diffClass}">${item.difficulty}</span>
            <span class="badge badge-marks">Weightage: ${item.marks} Marks</span>
          </div>

          <h2 class="question-title">${item.title}</h2>
          <div class="question-desc"><strong>Problem Statement:</strong> ${item.problem}</div>

          <div class="timer-box">
            <span>⏱ Recommended Time: ${item.timerMins} mins</span>
            <div class="timer-controls">
              <span class="timer-display" id="timer-${item.id}">00:00</span>
              <button class="timer-btn" onclick="toggleTimer(${item.id})">Start Timer</button>
            </div>
          </div>

          <div class="code-header"><span class="code-section-title">Solution Code:</span></div>
          <pre><code class="language-python" id="code-snippet-${item.id}">${escapeHtml(item.code)}</code></pre>

          <div class="btn-group">
            <button class="btn-action try-code-btn" onclick="openCompilerTab(${item.id}, 'python')">▶ Try Full Editor</button>
            <button class="btn-action show-result-btn" id="toggle-btn-${item.id}" onclick="toggleResult(${item.id}, 'python')">⚡ Show Result</button>
            <button class="btn-action complete-btn" id="mark-btn-${item.id}" onclick="toggleCompletion(${item.id})">✔ Mark Done</button>
          </div>

          <div class="accordion-box">
            <div class="accordion-header" onclick="toggleAccordion(${item.id})">
              <span>💡 Logic Explanation</span><span id="acc-icon-${item.id}">➕</span>
            </div>
            <div class="accordion-body" id="acc-body-${item.id}">${item.explanation}</div>
          </div>

          <div id="result-box-${item.id}" class="result-container">
            <div class="result-header">Live Output Console</div>
            <div id="iframe-holder-${item.id}"></div>
          </div>

          <div class="pagination-group">
            <button class="btn-page" ${index === 0 ? 'disabled' : `onclick="switchProgram(${programsData[index - 1].id})"`}>◀ Previous</button>
            <button class="btn-page" ${index === programsData.length - 1 ? 'disabled' : `onclick="switchProgram(${programsData[index + 1].id})"`}>Next ▶</button>
          </div>
        </div>
      `;
    });

    document.getElementById('sidebar-list').innerHTML = sidebarHtml;
    document.getElementById('workspace-container').innerHTML = workspaceHtml;

    if (window.Prism) {
      Prism.highlightAll();
    }
  }

  function switchProgram(progId) {
    document.querySelectorAll('.program-content').forEach(function(el) { el.classList.remove('active'); });
    document.querySelectorAll('.nav-btn').forEach(function(btn) { btn.classList.remove('active'); });

    var targetProg = document.getElementById('prog-' + progId);
    var targetBtn = document.getElementById('side-btn-' + progId);

    if (targetProg) targetProg.classList.add('active');
    if (targetBtn) {
      targetBtn.classList.add('active');
      targetBtn.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
  }

  function openCompilerTab(progId, language) {
    var codeText = document.getElementById('code-snippet-' + progId).innerText;
    localStorage.setItem('pendingCode', codeText);
    localStorage.setItem('pendingLang', language);
    window.open('/test-online-python-compiler/', '_blank');
  }

  function toggleResult(progId, language) {
    var resultBox = document.getElementById('result-box-' + progId);
    var iframeHolder = document.getElementById('iframe-holder-' + progId);
    var toggleBtn = document.getElementById('toggle-btn-' + progId);
    var codeText = document.getElementById('code-snippet-' + progId).innerText;

    if (resultBox.style.display === 'block') {
      resultBox.style.display = 'none';
      iframeHolder.innerHTML = '';
      toggleBtn.innerText = '⚡ Show Result';
      toggleBtn.classList.remove('active-btn');
    } else {
      resultBox.style.display = 'block';
      toggleBtn.innerText = '✕ Hide Result';
      toggleBtn.classList.add('active-btn');

      var embedUrl = 'https://onecompiler.com/embed/' + language + '?listenToEvents=true&hideLanguageSelection=true&hideTitle=true&hideNew=true&theme=dark';
      iframeHolder.innerHTML = '<iframe id="runner-iframe-' + progId + '" src="' + embedUrl + '"></iframe>';

      var iframe = document.getElementById('runner-iframe-' + progId);
      iframe.onload = function () {
        setTimeout(function () {
          iframe.contentWindow.postMessage({
            eventType: 'populateCode',
            language: language,
            files: [{ name: 'main.py', content: codeText }]
          }, "*");

          setTimeout(function () {
            iframe.contentWindow.postMessage({ eventType: 'triggerRun' }, "*");
          }, 300);
        }, 500);
      };
    }
  }

  function toggleAccordion(progId) {
    var body = document.getElementById('acc-body-' + progId);
    var icon = document.getElementById('acc-icon-' + progId);
    var isOpen = body.style.display === 'block';
    body.style.display = isOpen ? 'none' : 'block';
    icon.innerText = isOpen ? '➕' : '➖';
  }

  function toggleTimer(progId) {
    var timerDisplay = document.getElementById('timer-' + progId);
    var timerBtn = timerDisplay.nextElementSibling;

    if (activeTimers[progId]) {
      clearInterval(activeTimers[progId].interval);
      delete activeTimers[progId];
      timerBtn.innerText = 'Start Timer';
    } else {
      var seconds = 0;
      timerBtn.innerText = 'Stop Timer';
      activeTimers[progId] = {
        interval: setInterval(function () {
          seconds++;
          var mins = Math.floor(seconds / 60);
          var secs = seconds % 60;
          timerDisplay.innerText = (mins < 10 ? '0' : '') + mins + ':' + (secs < 10 ? '0' : '') + secs;
        }, 1000)
      };
    }
  }

  function toggleCompletion(progId) {
    var index = completedPrograms.indexOf(progId);
    if (index > -1) {
      completedPrograms.splice(index, 1);
    } else {
      completedPrograms.push(progId);
    }
    localStorage.setItem('gyanxp_completed', JSON.stringify(completedPrograms));
    updateProgressUI();
  }

  function updateProgressUI() {
    programsData.forEach(function (item) {
      var markBtn = document.getElementById('mark-btn-' + item.id);
      var dot = document.getElementById('dot-' + item.id);

      if (completedPrograms.includes(item.id)) {
        if (markBtn) { markBtn.innerText = '✔ Practiced'; markBtn.classList.add('done'); }
        if (dot) dot.innerText = '🟢';
      } else {
        if (markBtn) { markBtn.innerText = '✔ Mark Done'; markBtn.classList.remove('done'); }
        if (dot) dot.innerText = '⚪';
      }
    });

    var validCompleted = completedPrograms.filter(function(id) {
      return programsData.some(p => p.id === id);
    }).length;

    var percentage = TOTAL_PROGRAMS > 0 ? Math.round((validCompleted / TOTAL_PROGRAMS) * 100) : 0;
    document.getElementById('progress-fill').style.width = percentage + '%';
    document.getElementById('progress-text').innerText = validCompleted + ' / ' + TOTAL_PROGRAMS + ' Practiced (' + percentage + '%)';
  }

  document.addEventListener("DOMContentLoaded", function () {
    renderAllPrograms();
    updateProgressUI();
  });
</script>				</div>
				</div>
					</div>
		</div>
					</div>
		</section>
				</div>
		<p>The post <a href="https://gyanxp.com/online-python-practical-solution/">Online Python Practical Solution (PR3)</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/online-python-practical-solution/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Online Python Compiler</title>
		<link>https://gyanxp.com/test-online-python-compiler/</link>
					<comments>https://gyanxp.com/test-online-python-compiler/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Wed, 12 Aug 2026 07:44:43 +0000</pubDate>
				<category><![CDATA[Online Practical]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=5912</guid>

					<description><![CDATA[<p>Run Fullscreen</p>
<p>The post <a href="https://gyanxp.com/test-online-python-compiler/">Online Python Compiler</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[		<div data-elementor-type="wp-post" data-elementor-id="5912" class="elementor elementor-5912">
						<section class="elementor-section elementor-top-section elementor-element elementor-element-63aa4f6 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="63aa4f6" data-element_type="section" data-e-type="section">
						<div class="elementor-container elementor-column-gap-default">
					<div class="elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-66390a6" data-id="66390a6" data-element_type="column" data-e-type="column">
			<div class="elementor-widget-wrap elementor-element-populated">
						<div class="elementor-element elementor-element-eb0d555 elementor-widget__width-initial elementor-widget elementor-widget-html" data-id="eb0d555" data-element_type="widget" data-e-type="widget" data-widget_type="html.default">
				<div class="elementor-widget-container">
					<style>
  /* Outer Container */
  .compiler-container {
    width: 100%;
    margin: 0;
    padding: 0;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  }

  /* Top Actions Bar (Above the Editor) */
  .compiler-toolbar {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
  }

  /* Run Button - Exact OneCompiler Default Material Design */
  .custom-run-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    height: 32px;
    padding: 0 16px;
    background-color: #e91e63;
    color: #ffffff;
    font-size: 13px;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.12), 0 1px 5px 0 rgba(0, 0, 0, 0.2);
    transition: background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    user-select: none;
    outline: none;
  }

  .custom-run-btn:hover {
    background-color: #d81b60;
    box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
  }

  .custom-run-btn:active {
    background-color: #c2185b;
  }

  /* Fullscreen Toggle Button */
  .fullscreen-toggle-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    height: 32px;
    padding: 0 14px;
    background-color: #333333;
    color: #ffffff;
    font-size: 13px;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14);
    transition: background-color 0.2s ease;
  }

  .fullscreen-toggle-btn:hover {
    background-color: #444444;
  }

  /* Compiler Window Wrapper */
  .compiler-wrapper {
    width: 100%;
    height: 450px;
    margin: 0;
    padding: 0;
    background-color: #1e1e1e;
    border-radius: 8px;
    overflow: hidden;
  }

  .compiler-wrapper iframe {
    width: 100%;
    height: 100%;
    border: none;
    display: block;
  }

  /* =======================================================
     Mobile Fullscreen Mode (Portrait & Landscape)
     ======================================================= */
  .compiler-container.is-fullscreen {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    height: 100dvh !important;
    z-index: 999999 !important;
    background-color: #1e1e1e !important;
    padding: 8px 10px 10px 10px !important;
    box-sizing: border-box !important;
    display: flex !important;
    flex-direction: column !important;
    overflow: hidden !important;
  }

  .compiler-container.is-fullscreen .compiler-toolbar {
    flex-shrink: 0;
    margin-bottom: 6px;
    z-index: 1000000;
  }

  .compiler-container.is-fullscreen .compiler-wrapper {
    flex: 1 !important;
    width: 100% !important;
    height: auto !important;
    border-radius: 4px !important;
  }

  /* Responsive Adjustments for Mobile Viewports */
  @media (max-width: 768px) {
    .custom-run-btn, 
    .fullscreen-toggle-btn {
      height: 30px;
      padding: 0 12px;
      font-size: 12px;
    }
  }

  /* Landscape Optimizations on Mobile */
  @media (max-width: 900px) and (orientation: landscape) {
    .compiler-container.is-fullscreen {
      padding: 4px 8px 6px 8px !important;
    }

    .compiler-container.is-fullscreen .compiler-toolbar {
      margin-bottom: 4px;
    }

    .custom-run-btn, 
    .fullscreen-toggle-btn {
      height: 26px;
      padding: 0 10px;
      font-size: 11px;
    }
  }
</style>

<div id="compiler-container" class="compiler-container">
  <!-- Outside Top-Left Toolbar -->
  <div class="compiler-toolbar">
    <!-- Run Button -->
    <button id="custom-run-btn" class="custom-run-btn" title="Run Code">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
        <path d="M8 5v14l11-7z"/>
      </svg>
      Run
    </button>

    <!-- Fullscreen Toggle Button -->
    <button id="fullscreen-btn" class="fullscreen-toggle-btn" title="Toggle Fullscreen">
      <svg id="fullscreen-icon" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
        <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>
      </svg>
      <span id="fullscreen-text">Fullscreen</span>
    </button>
  </div>

  <!-- OneCompiler Embedded Frame -->
  <div class="compiler-wrapper">
    <iframe 
      id="oc-editor"
      src="https://onecompiler.com/embed/python?listenToEvents=true&theme=dark" 
      width="100%" 
      height="100%">
    </iframe>
  </div>
</div>

<script>
  document.addEventListener("DOMContentLoaded", function () {
    var iframe = document.getElementById('oc-editor');
    var runButton = document.getElementById('custom-run-btn');
    var fullscreenBtn = document.getElementById('fullscreen-btn');
    var container = document.getElementById('compiler-container');
    var fullscreenText = document.getElementById('fullscreen-text');
    var fullscreenIcon = document.getElementById('fullscreen-icon');

    // Trigger code execution inside OneCompiler
    function runCode() {
      if (iframe && iframe.contentWindow) {
        iframe.contentWindow.postMessage({
          eventType: 'triggerRun'
        }, "*");
      }
    }

    // Toggle Fullscreen View
    fullscreenBtn.addEventListener('click', function () {
      container.classList.toggle('is-fullscreen');
      var isFull = container.classList.contains('is-fullscreen');

      if (isFull) {
        fullscreenText.textContent = "Exit Fullscreen";
        // Exit Fullscreen Icon
        fullscreenIcon.innerHTML = '<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>';
        document.body.style.overflow = 'hidden'; // Lock background scrolling
      } else {
        fullscreenText.textContent = "Fullscreen";
        // Enter Fullscreen Icon
        fullscreenIcon.innerHTML = '<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>';
        document.body.style.overflow = '';
      }
    });

    // Attach click event to Run button
    runButton.addEventListener('click', runCode);

    // Initial load handling for pending code from localStorage
    iframe.onload = function () {
      var codeText = localStorage.getItem('pendingCode');
      var lang = localStorage.getItem('pendingLang') || 'python';

      if (codeText) {
        setTimeout(function () {
          // 1. Populate code into editor
          iframe.contentWindow.postMessage({
            eventType: 'populateCode',
            language: lang,
            files: [
              {
                name: 'main.py',
                content: codeText
              }
            ]
          }, "*");

          // 2. Trigger automatic code execution on first load
          setTimeout(function () {
            runCode();

            // Clean up temporary storage
            localStorage.removeItem('pendingCode');
            localStorage.removeItem('pendingLang');
          }, 300);

        }, 500);
      }
    };
  });
</script>				</div>
				</div>
					</div>
		</div>
					</div>
		</section>
				</div>
		<p>The post <a href="https://gyanxp.com/test-online-python-compiler/">Online Python Compiler</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/test-online-python-compiler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Web PR2 Interface</title>
		<link>https://gyanxp.com/web-pr2-demo/</link>
					<comments>https://gyanxp.com/web-pr2-demo/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Tue, 13 May 2025 16:48:09 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=4433</guid>

					<description><![CDATA[<p>Coming Soon&#8230;&#8230;&#8230;&#8230;.</p>
<p>The post <a href="https://gyanxp.com/web-pr2-demo/">Web PR2 Interface</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Coming Soon&#8230;&#8230;&#8230;&#8230;.</h2>
<p>The post <a href="https://gyanxp.com/web-pr2-demo/">Web PR2 Interface</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/web-pr2-demo/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>WDP Practical 1</title>
		<link>https://gyanxp.com/wdp-practical-1/</link>
					<comments>https://gyanxp.com/wdp-practical-1/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Mon, 12 May 2025 18:07:56 +0000</pubDate>
				<category><![CDATA[Web Design Practical]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=4422</guid>

					<description><![CDATA[<p>Object: Write a HTML program to design a form which should allow to enter your personal data (Hint: make use of text field, password field, e-mail, lists, radio buttons, checkboxes, submit button) Practical 1 Enter Full Name :- Enter Your Email :- Enter Your Password :- Choose Your Course :- CCC O Level A Level Your Gender [&#8230;]</p>
<p>The post <a href="https://gyanxp.com/wdp-practical-1/">WDP Practical 1</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><strong>Object: Write a HTML program to design a form which should allow to enter your personal data (Hint: make use of text field, password field, e-mail, lists, radio buttons, checkboxes, submit button)</strong></p>



<!DOCTYPE html>
<html>
           <head>
	             <title> Practical 1 </title>
	  </head>
	  <body>
	         <form>			        
			 Enter Full Name :- <input type="text" >  <br><br>
	                     Enter Your Email :- <input type="email" >  <br><br>
		           Enter Your Password :- <input type="password" ><br><br>
		           Choose Your Course :- <select>
                                                                                     <option> CCC </option>
					                                   <option> O Level </option>							               <option> A Level </option>
						           </select>  <br><br>
			 Your Gender :- <input type="radio" name="gen"> Male
					       <input type="radio" name="gen"> Female						       <input type="radio" ="gen">Others<br><br>
			 Certificate Available :- <input type= "checkbox" > 10th 
						          <input type= "checkbox" > 12th
					  <input type= "checkbox" >Graduation<br><br>
                               <input type="submit" value="SUBMIT">
	          </form>
	  </body>
</html>



    <a href="https://gyanxp.com/code-compiler" class="btn btn-success mt-2 text-white fw-bold"
       onclick="gxpSendCode()" target="_blank">
        Try it Yourself »
    </a>
    <script>
        function gxpSendCode() {
            const encoded = "CjwhRE9DVFlQRSBodG1sPgo8aHRtbD4KICAgICAgICAgICA8aGVhZD4KCSAgICAgICAgICAgICA8dGl0bGU+IFByYWN0aWNhbCAxIDwvdGl0bGU+CgkgIDwvaGVhZD4KCSAgPGJvZHk+CgkgICAgICAgICA8Zm9ybT4JCQkgICAgICAgIAoJCQkgRW50ZXIgRnVsbCBOYW1lIDotIDxpbnB1dCB0eXBlPSJ0ZXh0IiA+ICA8YnI+PGJyPgoJICAgICAgICAgICAgICAgICAgICAgRW50ZXIgWW91ciBFbWFpbCA6LSA8aW5wdXQgdHlwZT0iZW1haWwiID4gIDxicj48YnI+CgkJICAgICAgICAgICBFbnRlciBZb3VyIFBhc3N3b3JkIDotIDxpbnB1dCB0eXBlPSJwYXNzd29yZCIgPjxicj48YnI+CgkJICAgICAgICAgICBDaG9vc2UgWW91ciBDb3Vyc2UgOi0gPHNlbGVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxvcHRpb24+IENDQyA8L29wdGlvbj4KCQkJCQkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxvcHRpb24+IE8gTGV2ZWwgPC9vcHRpb24+CQkJCQkJCSAgICAgICAgICAgICAgIDxvcHRpb24+IEEgTGV2ZWwgPC9vcHRpb24+CgkJCQkJCSAgICAgICAgICAgPC9zZWxlY3Q+ICA8YnI+PGJyPgoJCQkgWW91ciBHZW5kZXIgOi0gPGlucHV0IHR5cGU9InJhZGlvIiBuYW1lPSJnZW4iPiBNYWxlCgkJCQkJICAgICAgIDxpbnB1dCB0eXBlPSJyYWRpbyIgbmFtZT0iZ2VuIj4gRmVtYWxlCQkJCQkJICAgICAgIDxpbnB1dCB0eXBlPSJyYWRpbyIgPSJnZW4iPk90aGVyczxicj48YnI+CgkJCSBDZXJ0aWZpY2F0ZSBBdmFpbGFibGUgOi0gPGlucHV0IHR5cGU9ICJjaGVja2JveCIgPiAxMHRoIAoJCQkJCQkgICAgICAgICAgPGlucHV0IHR5cGU9ICJjaGVja2JveCIgPiAxMnRoCgkJCQkJICA8aW5wdXQgdHlwZT0gImNoZWNrYm94IiA+R3JhZHVhdGlvbjxicj48YnI+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA8aW5wdXQgdHlwZT0ic3VibWl0IiB2YWx1ZT0iU1VCTUlUIj4KCSAgICAgICAgICA8L2Zvcm0+CgkgIDwvYm9keT4KPC9odG1sPgoK";
            const decoded = atob(encoded);
            localStorage.setItem("shared-html-code", decoded);
        }
    </script>
    
<p>The post <a href="https://gyanxp.com/wdp-practical-1/">WDP Practical 1</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/wdp-practical-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python Language</title>
		<link>https://gyanxp.com/python-language/</link>
					<comments>https://gyanxp.com/python-language/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Mon, 12 May 2025 17:51:01 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=4420</guid>

					<description><![CDATA[<p>The post <a href="https://gyanxp.com/python-language/">Python Language</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[[gxp_code_python]
[/gxp_code_python]
<p>The post <a href="https://gyanxp.com/python-language/">Python Language</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/python-language/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>MariaDB</title>
		<link>https://gyanxp.com/mariadb/</link>
					<comments>https://gyanxp.com/mariadb/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Mon, 12 May 2025 17:47:31 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=4416</guid>

					<description><![CDATA[<p>The post <a href="https://gyanxp.com/mariadb/">MariaDB</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[[gxp_code_mariadb][/gxp_code_mariadb]
<p>The post <a href="https://gyanxp.com/mariadb/">MariaDB</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/mariadb/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>C Language</title>
		<link>https://gyanxp.com/c-language/</link>
					<comments>https://gyanxp.com/c-language/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Mon, 12 May 2025 17:42:52 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=4412</guid>

					<description><![CDATA[<p>[gxp_code_c] #include // Create a function void myFunction() { printf(&#8220;I just got executed!&#8221;); } int main() { myFunction(); // call the function return 0; } [/gxp_code_c]</p>
<p>The post <a href="https://gyanxp.com/c-language/">C Language</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[
[gxp_code_c]
#include <stdio.h>

// Create a function
void myFunction() {
  printf(&#8220;I just got executed!&#8221;);
}

int main() {
  myFunction(); // call the function
  return 0;
}
[/gxp_code_c]
<p>The post <a href="https://gyanxp.com/c-language/">C Language</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/c-language/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>HTML Tables</title>
		<link>https://gyanxp.com/html-tables/</link>
					<comments>https://gyanxp.com/html-tables/#respond</comments>
		
		<dc:creator><![CDATA[Balmukund Maurya]]></dc:creator>
		<pubDate>Mon, 12 May 2025 17:36:05 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://gyanxp.com/?p=4406</guid>

					<description><![CDATA[<p>HTML Table Company Contact Country Alfreds Futterkiste Maria Anders Germany Centro comercial Moctezuma Francisco Chang Mexico Ernst Handel Roland Mendel Austria Island Trading Helen Bennett UK Laughing Bacchus Winecellars Yoshi Tannamuri Canada Magazzini Alimentari Riuniti Giovanni Rovelli Italy</p>
<p>The post <a href="https://gyanxp.com/html-tables/">HTML Tables</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

</body>
</html>



    <a href="https://gyanxp.com/code-compiler" class="btn btn-success mt-2 text-white fw-bold"
       onclick="gxpSendCode()" target="_blank">
        Try it Yourself »
    </a>
    <script>
        function gxpSendCode() {
            const encoded = "DQo8IURPQ1RZUEUgaHRtbD4NCjxodG1sPg0KPGhlYWQ+DQo8c3R5bGU+DQp0YWJsZSB7DQogIGZvbnQtZmFtaWx5OiBhcmlhbCwgc2Fucy1zZXJpZjsNCiAgYm9yZGVyLWNvbGxhcHNlOiBjb2xsYXBzZTsNCiAgd2lkdGg6IDEwMCU7DQp9DQoNCnRkLCB0aCB7DQogIGJvcmRlcjogMXB4IHNvbGlkICNkZGRkZGQ7DQogIHRleHQtYWxpZ246IGxlZnQ7DQogIHBhZGRpbmc6IDhweDsNCn0NCg0KdHI6bnRoLWNoaWxkKGV2ZW4pIHsNCiAgYmFja2dyb3VuZC1jb2xvcjogI2RkZGRkZDsNCn0NCjwvc3R5bGU+DQo8L2hlYWQ+DQo8Ym9keT4NCg0KPGgyPkhUTUwgVGFibGU8L2gyPg0KDQo8dGFibGU+DQogIDx0cj4NCiAgICA8dGg+Q29tcGFueTwvdGg+DQogICAgPHRoPkNvbnRhY3Q8L3RoPg0KICAgIDx0aD5Db3VudHJ5PC90aD4NCiAgPC90cj4NCiAgPHRyPg0KICAgIDx0ZD5BbGZyZWRzIEZ1dHRlcmtpc3RlPC90ZD4NCiAgICA8dGQ+TWFyaWEgQW5kZXJzPC90ZD4NCiAgICA8dGQ+R2VybWFueTwvdGQ+DQogIDwvdHI+DQogIDx0cj4NCiAgICA8dGQ+Q2VudHJvIGNvbWVyY2lhbCBNb2N0ZXp1bWE8L3RkPg0KICAgIDx0ZD5GcmFuY2lzY28gQ2hhbmc8L3RkPg0KICAgIDx0ZD5NZXhpY288L3RkPg0KICA8L3RyPg0KICA8dHI+DQogICAgPHRkPkVybnN0IEhhbmRlbDwvdGQ+DQogICAgPHRkPlJvbGFuZCBNZW5kZWw8L3RkPg0KICAgIDx0ZD5BdXN0cmlhPC90ZD4NCiAgPC90cj4NCiAgPHRyPg0KICAgIDx0ZD5Jc2xhbmQgVHJhZGluZzwvdGQ+DQogICAgPHRkPkhlbGVuIEJlbm5ldHQ8L3RkPg0KICAgIDx0ZD5VSzwvdGQ+DQogIDwvdHI+DQogIDx0cj4NCiAgICA8dGQ+TGF1Z2hpbmcgQmFjY2h1cyBXaW5lY2VsbGFyczwvdGQ+DQogICAgPHRkPllvc2hpIFRhbm5hbXVyaTwvdGQ+DQogICAgPHRkPkNhbmFkYTwvdGQ+DQogIDwvdHI+DQogIDx0cj4NCiAgICA8dGQ+TWFnYXp6aW5pIEFsaW1lbnRhcmkgUml1bml0aTwvdGQ+DQogICAgPHRkPkdpb3Zhbm5pIFJvdmVsbGk8L3RkPg0KICAgIDx0ZD5JdGFseTwvdGQ+DQogIDwvdHI+DQo8L3RhYmxlPg0KDQo8L2JvZHk+DQo8L2h0bWw+DQo=";
            const decoded = atob(encoded);
            localStorage.setItem("shared-html-code", decoded);
        }
    </script>
    



<pre class="wp-block-code"><code></code></pre>



<pre class="wp-block-code"><code><strong>&lt;h1>Heading 1<mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">&lt;/h1></mark>
&lt;h2>Heading 2&lt;/h2>
&lt;h3>Heading 3&lt;/h3>
&lt;h4>Heading 4&lt;/h4>
&lt;h5>Heading 5&lt;/h5>
&lt;h6>Heading 6&lt;/h6></strong></code></pre>



<p class="wp-block-paragraph"></p>
<p>The post <a href="https://gyanxp.com/html-tables/">HTML Tables</a> appeared first on <a href="https://gyanxp.com">GyanXp</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://gyanxp.com/html-tables/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
