<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Barabonajansen on Medium]]></title>
        <description><![CDATA[Stories by Barabonajansen on Medium]]></description>
        <link>https://medium.com/@barabonajansen?source=rss-7bc118dd1dc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2cGEuykhbeahb755</url>
            <title>Stories by Barabonajansen on Medium</title>
            <link>https://medium.com/@barabonajansen?source=rss-7bc118dd1dc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:48:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barabonajansen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Smart_eis_qa_validation_studio_v12 Developed By: Jansen B.]]></title>
            <link>https://medium.com/@barabonajansen/smart-eis-qa-validation-studio-v12-developed-by-jansen-b-0ea3ecb73153?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ea3ecb73153</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 10:20:05 GMT</pubDate>
            <atom:updated>2026-11-20T10:20:05.488Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot; class=&quot;dark&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>  &lt;title&gt;SMART EIS &amp; QA Validation Studio&lt;/title&gt;<br><br>  &lt;!-- Google Fonts: Inter &amp; JetBrains Mono --&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt;<br>  &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&amp;family=JetBrains+Mono:wght@400;500;600&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br><br>  &lt;!-- Tailwind CSS --&gt;<br>  &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    tailwind.config = {<br>      darkMode: &#39;class&#39;,<br>      theme: {<br>        extend: {<br>          fontFamily: {<br>            sans: [&#39;Inter&#39;, &#39;system-ui&#39;, &#39;sans-serif&#39;],<br>            mono: [&#39;JetBrains Mono&#39;, &#39;monospace&#39;]<br>          },<br>          colors: {<br>            brand: {<br>              50: &#39;#eef2ff&#39;,<br>              100: &#39;#e0e7ff&#39;,<br>              400: &#39;#818cf8&#39;,<br>              500: &#39;#6366f1&#39;,<br>              600: &#39;#4f46e5&#39;,<br>              700: &#39;#4338ca&#39;,<br>              900: &#39;#312e81&#39;,<br>              950: &#39;#1e1b4b&#39;<br>            }<br>          }<br>        }<br>      }<br>    };<br>  &lt;/script&gt;<br><br>  &lt;!-- Lucide Icons --&gt;<br>  &lt;script src=&quot;https://unpkg.com/lucide@latest&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Chart.js for Dashboard Analytics --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- PDF.js for Multi-Page PDF Receipt Rendering &amp; Text Extraction --&gt;<br>  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Tesseract.js for Client-Side Local-First OCR --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;style&gt;<br>    * { box-sizing: border-box; }<br>    body { font-family: &#39;Inter&#39;, system-ui, sans-serif; overflow-x: hidden; }<br>    ::-webkit-scrollbar { width: 6px; height: 6px; }<br>    ::-webkit-scrollbar-track { background: transparent; }<br>    ::-webkit-scrollbar-thumb { background: rgba(100, 116, 139, 0.35); border-radius: 9999px; }<br>    ::-webkit-scrollbar-thumb:hover { background: rgba(100, 116, 139, 0.6); }<br><br>    @media print {<br>      body * { visibility: hidden; }<br>      #printable-report-area, #printable-report-area * { visibility: visible; }<br>      #printable-report-area {<br>        position: absolute;<br>        left: 0;<br>        top: 0;<br>        width: 100%;<br>        background: #ffffff !important;<br>        color: #0f172a !important;<br>        padding: 20px;<br>      }<br>      .no-print { display: none !important; }<br>      .page-break { page-break-before: always; }<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100 antialiased selection:bg-brand-500 selection:text-white&quot;&gt;<br><br>  &lt;!-- Main Application Shell --&gt;<br>  &lt;div id=&quot;app-shell&quot; class=&quot;min-h-screen flex flex-col lg:flex-row&quot;&gt;<br><br>    &lt;!-- Mobile Top Header --&gt;<br>    &lt;header class=&quot;lg:hidden flex items-center justify-between px-4 py-3 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 sticky top-0 z-40&quot;&gt;<br>      &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>        &lt;button id=&quot;mobile-menu-btn&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; aria-label=&quot;Toggle Menu&quot;&gt;<br>          &lt;i data-lucide=&quot;menu&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>          &lt;div class=&quot;w-8 h-8 rounded-xl bg-gradient-to-br from-brand-500 to-indigo-600 flex items-center justify-center text-white font-bold shadow-md&quot;&gt;N&lt;/div&gt;<br>          &lt;span class=&quot;font-bold tracking-tight text-sm&quot;&gt;SMART EIS &amp; QA&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>        &lt;span id=&quot;mobile-save-badge&quot; class=&quot;text-xs px-2 py-1 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium&quot;&gt;Saved&lt;/span&gt;<br>        &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Toggle Theme&quot;&gt;<br>          &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/header&gt;<br><br>    &lt;!-- Collapsible Navigation Sidebar --&gt;<br>    &lt;aside id=&quot;sidebar&quot; class=&quot;fixed inset-y-0 left-0 z-50 w-72 lg:w-64 transform -translate-x-full lg:translate-x-0 lg:static transition-all duration-200 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col shrink-0&quot;&gt;<br>      &lt;!-- Brand Header --&gt;<br>      &lt;div class=&quot;p-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 overflow-hidden&quot;&gt;<br>          &lt;div class=&quot;w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500 via-indigo-600 to-violet-600 flex items-center justify-center text-white font-extrabold shadow-lg shrink-0&quot;&gt;<br>            N<br>          &lt;/div&gt;<br>          &lt;div class=&quot;sidebar-label truncate&quot;&gt;<br>            &lt;div class=&quot;font-bold text-sm tracking-tight&quot;&gt;SMART Studio&lt;/div&gt;<br>            &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;EIS Receipt &amp; QA Engine&lt;/div&gt;<br>   &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;Developed By: Jansen B.&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;button onclick=&quot;toggleSidebarCollapse()&quot; class=&quot;hidden lg:flex p-1.5 rounded-lg text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Collapse Sidebar&quot;&gt;<br>          &lt;i data-lucide=&quot;panel-left-close&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;button onclick=&quot;toggleMobileSidebar()&quot; class=&quot;lg:hidden p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- Active Project Quick Switcher --&gt;<br>      &lt;div class=&quot;p-3 border-b border-slate-200 dark:border-slate-800 sidebar-label&quot;&gt;<br>        &lt;label class=&quot;block text-[10px] font-semibold uppercase tracking-wider text-slate-400 mb-1&quot;&gt;Active Project&lt;/label&gt;<br>        &lt;select id=&quot;sidebar-project-select&quot; onchange=&quot;switchActiveProject(this.value)&quot; class=&quot;w-full text-xs font-medium bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-2.5 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- 11 Core Modules Navigation --&gt;<br>      &lt;nav id=&quot;sidebar-nav&quot; class=&quot;flex-1 overflow-y-auto p-2.5 space-y-1&quot;&gt;<br>        &lt;!-- Populated dynamically --&gt;<br>      &lt;/nav&gt;<br><br>      &lt;!-- Footer Status &amp; Privacy Badge --&gt;<br>      &lt;div class=&quot;p-3 border-t border-slate-200 dark:border-slate-800 sidebar-label space-y-2&quot;&gt;<br>        &lt;div class=&quot;flex items-center justify-between text-xs&quot;&gt;<br>          &lt;span class=&quot;text-slate-500 dark:text-slate-400 flex items-center gap-1.5&quot;&gt;<br>            &lt;span class=&quot;w-2 h-2 rounded-full bg-emerald-500 animate-pulse&quot;&gt;&lt;/span&gt;<br>            IndexedDB Local<br>          &lt;/span&gt;<br>          &lt;span id=&quot;sidebar-version-tag&quot; class=&quot;font-mono text-[11px] text-slate-400&quot;&gt;v2.4.0&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-800/70 rounded-xl p-2 flex items-center gap-2&quot;&gt;<br>          &lt;i data-lucide=&quot;shield-check&quot; class=&quot;w-4 h-4 text-emerald-500 shrink-0&quot;&gt;&lt;/i&gt;<br>          &lt;span&gt;Local-first storage. Zero external receipt uploads.&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/aside&gt;<br><br>    &lt;!-- Backdrop for mobile drawer --&gt;<br>    &lt;div id=&quot;mobile-backdrop&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;fixed inset-0 bg-slate-950/60 backdrop-blur-xs z-40 hidden lg:hidden&quot;&gt;&lt;/div&gt;<br><br>    &lt;!-- Main Content Workspace --&gt;<br>    &lt;div class=&quot;flex-1 flex flex-col min-w-0&quot;&gt;<br><br>      &lt;!-- Desktop Top Workspace Bar --&gt;<br>      &lt;header class=&quot;hidden lg:flex items-center justify-between px-6 py-3.5 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 sticky top-0 z-30&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 min-w-0&quot;&gt;<br>          &lt;h1 id=&quot;topbar-title&quot; class=&quot;text-base font-bold tracking-tight truncate&quot;&gt;Dashboard&lt;/h1&gt;<br>          &lt;span id=&quot;topbar-subtitle&quot; class=&quot;text-xs text-slate-500 dark:text-slate-400 hidden xl:inline truncate&quot;&gt;Enterprise EIS Receipt &amp; QA Evidence Overview&lt;/span&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>          &lt;!-- Autosave Status Pill --&gt;<br>          &lt;div id=&quot;save-status-pill&quot; class=&quot;flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20&quot;&gt;<br>            &lt;i data-lucide=&quot;check-circle-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span id=&quot;save-status-text&quot;&gt;All changes saved&lt;/span&gt;<br>          &lt;/div&gt;<br><br>          &lt;!-- Manual Save Button --&gt;<br>          &lt;button onclick=&quot;manualSaveProject()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Save Project Now (Ctrl+S)&quot;&gt;<br>            &lt;i data-lucide=&quot;save&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Save&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Run Validation CTA --&gt;<br>          &lt;button onclick=&quot;runActivePageValidation(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm transition&quot;&gt;<br>            &lt;i data-lucide=&quot;play&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Validate Active Page&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Theme Switcher --&gt;<br>          &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Toggle Dark/Light Theme&quot;&gt;<br>            &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br><br>      &lt;!-- Dynamic Module Viewport --&gt;<br>      &lt;main id=&quot;main-viewport&quot; class=&quot;flex-1 p-4 sm:p-6 max-w-[1600px] w-full mx-auto space-y-6&quot;&gt;<br>        &lt;!-- Active module renders here --&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Toast Notification Container --&gt;<br>  &lt;div id=&quot;toast-container&quot; class=&quot;fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-sm w-full pointer-events-none px-4 sm:px-0&quot;&gt;&lt;/div&gt;<br><br>  &lt;!-- Reusable Modal Container --&gt;<br>  &lt;div id=&quot;modal-overlay&quot; class=&quot;fixed inset-0 z-50 bg-slate-950/70 backdrop-blur-xs hidden items-center justify-center p-4&quot;&gt;<br>    &lt;div id=&quot;modal-box&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] flex flex-col overflow-hidden&quot;&gt;<br>      &lt;div class=&quot;px-5 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;h3 id=&quot;modal-title&quot; class=&quot;font-bold text-base&quot;&gt;Modal Title&lt;/h3&gt;<br>        &lt;button onclick=&quot;closeModal()&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;modal-body&quot; class=&quot;p-5 overflow-y-auto space-y-4 text-sm&quot;&gt;&lt;/div&gt;<br>      &lt;div id=&quot;modal-footer&quot; class=&quot;px-5 py-3.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-end gap-2 bg-slate-50 dark:bg-slate-900/50&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;script&gt;<br>    /****************************************************************************<br>     * SMART EIS &amp; QA VALIDATION STUDIO — MODULAR ARCHITECTURE<br>     * 1. Persistence &amp; Backup Engine (IndexedDB + Versioned Migration)<br>     * 2. Financial Calculator &amp; EIS Fee Validation Engine (Deterministic)<br>     * 3. Intelligent OCR &amp; Smart Field Mapping Engine (PDF.js + Tesseract.js)<br>     * 4. QA Screenshot &amp; Vector Annotation Engine<br>     * 5. Test Case, Defect &amp; Unified Reporting Engine<br>     * 6. Automated 12-Point Acceptance Test Suite<br>     ****************************************************************************/<br><br>    // Configure PDF.js worker with safe error guard<br>    try {<br>      if (window.pdfjsLib) {<br>        pdfjsLib.GlobalWorkerOptions.workerSrc = &#39;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js&#39;;<br>      }<br>    } catch (pdfInitErr) {<br>      console.warn(&#39;PDF.js worker initialization warning:&#39;, pdfInitErr);<br>    }<br><br>    const APP_SCHEMA_VERSION = 3;<br>    const DB_NAME = &#39;SMARTEisQaStudioDB&#39;;<br>    const DB_VERSION = 1;<br>    const STORE_NAME = &#39;workspaceState&#39;;<br><br>    const MODULES = [<br>      { id: &#39;dashboard&#39;, label: &#39;Dashboard&#39;, icon: &#39;layout-dashboard&#39;, subtitle: &#39;Real-time EIS validation metrics &amp; QA progress&#39; },<br>      { id: &#39;projects&#39;, label: &#39;Projects&#39;, icon: &#39;folder-kanban&#39;, subtitle: &#39;Manage isolated audit workspaces, backups &amp; imports&#39; },<br>      { id: &#39;main-pages&#39;, label: &#39;Main Pages&#39;, icon: &#39;file-spreadsheet&#39;, subtitle: &#39;Configure numbered fields (1–50+), per-page dynamic rows &amp; fees&#39; },<br>      { id: &#39;validation&#39;, label: &#39;Receipt Validation&#39;, icon: &#39;split-square-horizontal&#39;, subtitle: &#39;Side-by-side receipt comparison, OCR boxes &amp; mismatch review&#39; },<br>      { id: &#39;ocr-intel&#39;, label: &#39;OCR &amp; Doc Intel&#39;, icon: &#39;scan-text&#39;, subtitle: &#39;Preprocessing pipeline, confidence inspection &amp; block mapping&#39; },<br>      { id: &#39;screenshots&#39;, label: &#39;QA Screenshot Studio&#39;, icon: &#39;camera&#39;, subtitle: &#39;Screen capture, image merging &amp; dynamic QA evidence labels (1–200+)&#39; },<br>      { id: &#39;evidence&#39;, label: &#39;Evidence Screenshots&#39;, icon: &#39;images&#39;, hidden: true, subtitle: &#39;Per-Main-Page evidence screenshots: QA-n box value fills Expected Value or Found on Receipt of field Cn (main toggle)&#39; },<br>      { id: &#39;test-cases&#39;, label: &#39;Test Cases&#39;, icon: &#39;check-square&#39;, subtitle: &#39;QA test execution, preconditions &amp; linked receipt evidence&#39; },<br>      { id: &#39;defects&#39;, label: &#39;Defect Management&#39;, icon: &#39;bug&#39;, subtitle: &#39;Issue tracking, severity triage &amp; copy-ready Jira markup&#39; },<br>      { id: &#39;templates&#39;, label: &#39;Templates&#39;, icon: &#39;copy-plus&#39;, subtitle: &#39;Reusable EIS fee schemas, column mappings &amp; project templates&#39; },<br>      { id: &#39;settings&#39;, label: &#39;Settings &amp; Diagnostics&#39;, icon: &#39;settings&#39;, subtitle: &#39;Validation tolerances, OCR rules &amp; 12-point self-test suite&#39; },<br>      { id: &#39;reports&#39;, label: &#39;Reports&#39;, icon: &#39;file-bar-chart-2&#39;, subtitle: &#39;All results, projects &amp; QA reports (CSV, HTML, PDF, Word/DOC, JSON, TXT)&#39; }<br>    ];<br><br>    // Global Application State<br>    let appState = {<br>      schemaVersion: APP_SCHEMA_VERSION,<br>      theme: &#39;dark&#39;,<br>      sidebarCollapsed: false,<br>      activeModule: &#39;dashboard&#39;,<br>      activeProjectId: null,<br>      activeMainPageId: null,<br>      lastSavedAt: null,<br>      settings: {<br>        numericTolerance: 0.01,<br>        caseSensitiveNames: false,<br>        normalizeWhitespace: true,<br>        autoAcceptConfidenceThreshold: 88,<br>        cwtDeductionMode: &#39;absolute&#39;,<br>        qaLabelMax: 200,<br>        qaAutoIncrement: true<br>      },<br>      templates: [],<br>      projects: [],<br>      ui: {<br>        viewerZoom: 1,<br>        viewerRotation: 0,<br>        showOcrBoxes: true,<br>        selectedComparisonRowId: null,<br>        selectedScreenshotsForMerge: [],<br>        annotationTool: &#39;rect&#39;,<br>        annotationColor: &#39;#ef4444&#39;,<br>        selectedAnnotationId: null,<br>        selectedQaLabel: 1,<br>        mainPageQuickListOpen: false,<br>        selectedMainPageIds: []<br>      }<br>    };<br><br>    let chartInstances = {};<br>    let autosaveTimer = null;<br><br>    /**<br>     * Escapes HTML special characters safely for UI templates and exported HTML/DOC files.<br>     */<br>    function escapeHtml(str) {<br>      if (str === null || str === undefined) return &#39;&#39;;<br>      return String(str)<br>        .replace(/&amp;/g, &#39;&amp;amp;&#39;)<br>        .replace(/&lt;/g, &#39;&amp;lt;&#39;)<br>        .replace(/&gt;/g, &#39;&amp;gt;&#39;)<br>        .replace(/&quot;/g, &#39;&amp;quot;&#39;)<br>        .replace(/&#39;/g, &#39;&amp;#039;&#39;);<br>    }<br><br>    /**<br>     * Sanitizes image URLs or data URIs for safe embedding in HTML and Word (.doc) reports.<br>     */<br>    function sanitizeImageSrc(src) {<br>      if (!src || typeof src !== &#39;string&#39;) return &#39;&#39;;<br>      const trimmed = src.trim();<br>      if (/^data:image\/(png|jpeg|jpg|webp|gif|svg\+xml);/i.test(trimmed)) return trimmed;<br>      if (/^https?:\/\//i.test(trimmed)) return trimmed;<br>      return &#39;&#39;;<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1: PERSISTENCE &amp; BACKUP ENGINE (IndexedDB)<br>     ****************************************************************************/<br>    const PersistenceEngine = {<br>      openDB() {<br>        return new Promise((resolve, reject) =&gt; {<br>          if (!window.indexedDB) {<br>            reject(new Error(&#39;IndexedDB is unavailable in this browser environment.&#39;));<br>            return;<br>          }<br>          const req = indexedDB.open(DB_NAME, DB_VERSION);<br>          req.onupgradeneeded = (e) =&gt; {<br>            const db = e.target.result;<br>            if (!db.objectStoreNames.contains(STORE_NAME)) {<br>              db.createObjectStore(STORE_NAME, { keyPath: &#39;id&#39; });<br>            }<br>          };<br>          req.onsuccess = () =&gt; resolve(req.result);<br>          req.onerror = () =&gt; reject(req.error);<br>        });<br>      },<br><br>      async saveState(stateObj) {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readwrite&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const payload = {<br>            id: &#39;primary_workspace&#39;,<br>            updatedAt: new Date().toISOString(),<br>            data: JSON.parse(JSON.stringify(stateObj))<br>          };<br>          store.put(payload);<br>          return new Promise((resolve, reject) =&gt; {<br>            tx.oncomplete = () =&gt; {<br>              appState.lastSavedAt = payload.updatedAt;<br>              updateSaveIndicator(&#39;saved&#39;);<br>              resolve(true);<br>            };<br>            tx.onerror = () =&gt; reject(tx.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Save Error:&#39;, err);<br>          updateSaveIndicator(&#39;error&#39;);<br>          return false;<br>        }<br>      },<br><br>      async loadState() {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readonly&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const req = store.get(&#39;primary_workspace&#39;);<br>          return new Promise((resolve, reject) =&gt; {<br>            req.onsuccess = () =&gt; resolve(req.result ? req.result.data : null);<br>            req.onerror = () =&gt; reject(req.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Load Error:&#39;, err);<br>          return null;<br>        }<br>      },<br><br>      migrateState(raw) {<br>        if (!raw) return null;<br>        if (!raw.schemaVersion || raw.schemaVersion &lt; APP_SCHEMA_VERSION) {<br>          raw.schemaVersion = APP_SCHEMA_VERSION;<br>          raw.settings = Object.assign({<br>            numericTolerance: 0.01,<br>            caseSensitiveNames: false,<br>            normalizeWhitespace: true,<br>            autoAcceptConfidenceThreshold: 88,<br>            cwtDeductionMode: &#39;absolute&#39;,<br>            qaLabelMax: 200,<br>            qaAutoIncrement: true<br>          }, raw.settings || {});<br>        }<br>        (raw.projects || []).forEach(proj =&gt; {<br>          const migPages = proj.mainPages || [];<br>          if (Array.isArray(proj.evidenceShots) &amp;&amp; proj.evidenceShots.length) {<br>            proj.evidenceShots.forEach(sh =&gt; {<br>              const owner = migPages.find(mp =&gt; (mp.evidenceAnnotations || []).some(a =&gt; a.screenshotId === sh.id)) || migPages[0];<br>              if (owner) { owner.evidenceShots = owner.evidenceShots || []; owner.evidenceShots.push(sh); }<br>            });<br>          }<br>          delete proj.evidenceShots;<br>          if (proj.evidenceMergeHistory) {<br>            if (migPages[0] &amp;&amp; !migPages[0].evidenceMergeHistory) migPages[0].evidenceMergeHistory = proj.evidenceMergeHistory;<br>            delete proj.evidenceMergeHistory;<br>          }<br>          migPages.forEach(mp =&gt; {<br>            const evIds = new Set((mp.evidenceAnnotations || []).map(a =&gt; a.id));<br>            (mp.fields || []).forEach(f =&gt; {<br>              if (f.actualSource &amp;&amp; evIds.has(f.actualSource)) {<br>                f.expectedValue = f.actualValue || f.expectedValue || &#39;&#39;;<br>                f.actualValue = &#39;&#39;;<br>                f.expectedSource = f.actualSource;<br>                delete f.actualSource;<br>              }<br>            });<br>          });<br>          (proj.mainPages || []).forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>          });<br>        });<br>        return raw;<br>      }<br>    };<br><br>    function scheduleAutosave(reason = &#39;&#39;) {<br>      updateSaveIndicator(&#39;saving&#39;);<br>      if (autosaveTimer) clearTimeout(autosaveTimer);<br>      autosaveTimer = setTimeout(async () =&gt; {<br>        try {<br>          const proj = getActiveProject();<br>          if (proj) proj.lastModified = new Date().toISOString();<br>          await PersistenceEngine.saveState(appState);<br>        } catch (err) {<br>          console.error(&#39;Autosave error:&#39;, err);<br>        }<br>      }, 450);<br>    }<br><br>    async function manualSaveProject() {<br>      try {<br>        const proj = getActiveProject();<br>        if (proj) proj.lastModified = new Date().toISOString();<br>        const saved = await PersistenceEngine.saveState(appState);<br>        if (saved) {<br>          showToast(&#39;Project state persisted to IndexedDB.&#39;, &#39;success&#39;);<br>        } else {<br>          showToast(&#39;Unable to persist project state to IndexedDB.&#39;, &#39;error&#39;);<br>        }<br>      } catch (err) {<br>        showToast(&#39;Save failed: &#39; + err.message, &#39;error&#39;);<br>      }<br>    }<br><br>    function updateSaveIndicator(status) {<br>      const textEl = document.getElementById(&#39;save-status-text&#39;);<br>      const mobileBadge = document.getElementById(&#39;mobile-save-badge&#39;);<br>      if (status === &#39;saving&#39;) {<br>        if (textEl) textEl.textContent = &#39;Saving...&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saving...&#39;;<br>      } else if (status === &#39;saved&#39;) {<br>        const t = new Date().toLocaleTimeString([], { hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39;, second: &#39;2-digit&#39; });<br>        if (textEl) textEl.textContent = `Saved ${t}`;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saved&#39;;<br>      } else {<br>        if (textEl) textEl.textContent = &#39;Save error&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Error&#39;;<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2: FINANCIAL CALCULATOR &amp; EIS FEE VALIDATION ENGINE<br>     ****************************************************************************/<br>    const FinancialCalculator = {<br>      parseAmount(raw) {<br>        if (raw === null || raw === undefined || raw === &#39;&#39;) return null;<br>        if (typeof raw === &#39;number&#39;) return Number.isFinite(raw) ? raw : null;<br>        let str = String(raw).trim();<br>        if (!str) return null;<br><br>        let isNegative = false;<br>        if (/^\(.*\)$/.test(str)) {<br>          isNegative = true;<br>          str = str.replace(/^\(|\)$/g, &#39;&#39;).trim();<br>        }<br>        if (str.startsWith(&#39;-&#39;)) {<br>          isNegative = true;<br>          str = str.slice(1).trim();<br>        }<br>        str = str.replace(/[^0-9.\-]/g, &#39;&#39;);<br>        if (!str || str === &#39;.&#39; || str === &#39;-&#39;) return null;<br>        const val = parseFloat(str);<br>        if (!Number.isFinite(val)) return null;<br>        return isNegative ? -Math.abs(val) : val;<br>      },<br><br>      isCwtEntry(fee) {<br>        if (!fee) return false;<br>        if (fee.isCwt === true) return true;<br>        const code = String(fee.code || fee.actualCode || &#39;&#39;).trim().toUpperCase();<br>        const name = String(fee.name || fee.actualName || &#39;&#39;).trim().toUpperCase();<br>        return code === &#39;CWT&#39; || /\bCWT\b|WITHHOLDING/.test(name);<br>      },<br><br>      calculateTotals(fees = []) {<br>        let expectedGross = 0;<br>        let expectedCwt = 0;<br>        let actualGross = 0;<br>        let actualCwt = 0;<br>        let hasMissingActual = false;<br><br>        fees.forEach(fee =&gt; {<br>          const isCwt = this.isCwtEntry(fee);<br>          const expAmt = this.parseAmount(fee.expectedAmount);<br>          const actAmt = this.parseAmount(fee.actualAmount);<br><br>          if (expAmt !== null) {<br>            if (isCwt) {<br>              expectedCwt += Math.abs(expAmt);<br>            } else {<br>              expectedGross += expAmt;<br>            }<br>          }<br><br>          if (actAmt !== null) {<br>            if (isCwt) {<br>              actualCwt += Math.abs(actAmt);<br>            } else {<br>              actualGross += actAmt;<br>            }<br>          } else {<br>            hasMissingActual = true;<br>          }<br>        });<br><br>        expectedGross = Number(expectedGross.toFixed(2));<br>        expectedCwt = Number(expectedCwt.toFixed(2));<br>        actualGross = Number(actualGross.toFixed(2));<br>        actualCwt = Number(actualCwt.toFixed(2));<br><br>        const expectedNet = Number((expectedGross - expectedCwt).toFixed(2));<br>        const actualNet = Number((actualGross - actualCwt).toFixed(2));<br>        const netDifference = Number((actualNet - expectedNet).toFixed(2));<br>        const grossDifference = Number((actualGross - expectedGross).toFixed(2));<br>        const cwtDifference = Number((actualCwt - expectedCwt).toFixed(2));<br><br>        return {<br>          expectedGross,<br>          expectedCwt,<br>          expectedNet,<br>          actualGross,<br>          actualCwt,<br>          actualNet,<br>          grossDifference,<br>          cwtDifference,<br>          netDifference,<br>          hasMissingActual,<br>          formulaExplanation: `Gross Fees (non-CWT sum) - |CWT Deductions| = Net Total (${actualGross.toFixed(2)} - ${actualCwt.toFixed(2)} = ${actualNet.toFixed(2)})`<br>        };<br>      }<br>    };<br><br>    const ValidationEngine = {<br>      normalizeText(str, settings = appState.settings) {<br>        if (str === null || str === undefined) return &#39;&#39;;<br>        let s = String(str);<br>        if (settings.normalizeWhitespace) s = s.replace(/\s+/g, &#39; &#39;).trim();<br>        if (!settings.caseSensitiveNames) s = s.toLowerCase();<br>        return s;<br>      },<br><br>      validateFeeRow(fee, settings = appState.settings) {<br>        const tolerance = Number(settings.numericTolerance ?? 0.01);<br>        const timestamp = new Date().toISOString();<br>        const isCwt = FinancialCalculator.isCwtEntry(fee);<br><br>        const expName = String(fee.expectedName || &#39;&#39;).trim();<br>        const actName = String(fee.actualName || &#39;&#39;).trim();<br>        const expCode = String(fee.expectedCode || &#39;&#39;).trim();<br>        const actCode = String(fee.actualCode || &#39;&#39;).trim();<br>        const expAmt = FinancialCalculator.parseAmount(fee.expectedAmount);<br>        const actAmt = FinancialCalculator.parseAmount(fee.actualAmount);<br><br>        const nameResult = this.compareTextAttribute(&#39;Fee Name&#39;, expName, actName, true, fee.ocrConfidence, settings);<br><br>        let amtStatus = &#39;PENDING&#39;;<br>        let amtDiff = null;<br>        let amtExplanation = &#39;&#39;;<br>        if (expAmt === null &amp;&amp; actAmt === null) {<br>          amtStatus = &#39;NOT APPLICABLE&#39;;<br>          amtExplanation = &#39;No expected or receipt amount configured.&#39;;<br>        } else if (expAmt === null) {<br>          amtStatus = &#39;REVIEW&#39;;<br>          amtExplanation = `Receipt has ${actAmt.toFixed(2)} but Expected Amount is blank.`;<br>        } else if (actAmt === null) {<br>          amtStatus = &#39;PENDING&#39;;<br>          amtExplanation = `Missing receipt amount for expected ${expAmt.toFixed(2)}.`;<br>        } else {<br>          const cmpExp = isCwt ? Math.abs(expAmt) : expAmt;<br>          const cmpAct = isCwt ? Math.abs(actAmt) : actAmt;<br>          amtDiff = Number((cmpAct - cmpExp).toFixed(2));<br>          if (Math.abs(amtDiff) &lt;= tolerance) {<br>            amtStatus = (fee.ocrConfidence !== null &amp;&amp; fee.ocrConfidence !== undefined &amp;&amp; fee.ocrConfidence &lt; settings.autoAcceptConfidenceThreshold &amp;&amp; !fee.manuallyVerified)<br>              ? &#39;REVIEW&#39;<br>              : &#39;PASS&#39;;<br>            amtExplanation = isCwt<br>              ? `CWT deduction magnitude matches (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`<br>              : `Amount matches within ±${tolerance} tolerance (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`;<br>          } else {<br>            amtStatus = &#39;FAIL&#39;;<br>            amtExplanation = `Amount mismatch: Expected ${cmpExp.toFixed(2)}, Receipt ${cmpAct.toFixed(2)}, Difference ${amtDiff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${amtDiff.toFixed(2)}.`;<br>          }<br>        }<br><br>        const codeResult = this.compareTextAttribute(&#39;Fee Code&#39;, expCode, actCode, true, fee.ocrConfidence, settings, true);<br><br>        const statuses = [nameResult.status, amtStatus, codeResult.status];<br>        let overallStatus = &#39;PASS&#39;;<br>        if (statuses.includes(&#39;FAIL&#39;)) overallStatus = &#39;FAIL&#39;;<br>        else if (statuses.includes(&#39;PENDING&#39;)) overallStatus = &#39;PENDING&#39;;<br>        else if (statuses.includes(&#39;REVIEW&#39;)) overallStatus = &#39;REVIEW&#39;;<br>        else if (statuses.every(s =&gt; s === &#39;NOT APPLICABLE&#39;)) overallStatus = &#39;NOT APPLICABLE&#39;;<br><br>        const explanations = [nameResult.explanation, amtExplanation, codeResult.explanation].filter(Boolean);<br><br>        return {<br>          feeId: fee.id,<br>          isCwt,<br>          nameComparison: nameResult,<br>          amountComparison: {<br>            rule: isCwt ? &#39;CWT Absolute Value Match&#39; : `Numeric Tolerance (±${tolerance})`,<br>            expected: expAmt !== null ? expAmt.toFixed(2) : &#39;&#39;,<br>            actual: actAmt !== null ? actAmt.toFixed(2) : &#39;&#39;,<br>            difference: amtDiff !== null ? amtDiff.toFixed(2) : &#39;N/A&#39;,<br>            status: amtStatus,<br>            explanation: amtExplanation<br>          },<br>          codeComparison: codeResult,<br>          status: overallStatus,<br>          explanation: explanations.join(&#39; | &#39;),<br>          ocrConfidence: fee.ocrConfidence ?? null,<br>          sourceLocation: fee.sourceLocation || &#39;Manual / Unmapped&#39;,<br>          evaluatedAt: timestamp<br>        };<br>      },<br><br>      compareTextAttribute(label, expected, actual, required, confidence, settings, exactCode = false) {<br>        if (!expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual: &#39;&#39;,<br>            difference: &#39;0&#39;,<br>            status: required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            explanation: required ? `${label} is missing on both Expected and Receipt.` : `${label} not configured.`<br>          };<br>        }<br>        if (!expected &amp;&amp; actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual,<br>            difference: &#39;Unconfigured expected&#39;,<br>            status: &#39;REVIEW&#39;,<br>            explanation: `${label} &quot;${actual}&quot; found on receipt, but expected value is empty.`<br>          };<br>        }<br>        if (expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual: &#39;&#39;,<br>            difference: &#39;Missing on receipt&#39;,<br>            status: &#39;PENDING&#39;,<br>            explanation: `Required ${label} &quot;${expected}&quot; is missing from receipt extraction.`<br>          };<br>        }<br><br>        const normExp = exactCode ? expected.trim().toUpperCase() : this.normalizeText(expected, settings);<br>        const normAct = exactCode ? actual.trim().toUpperCase() : this.normalizeText(actual, settings);<br><br>        if (normExp === normAct) {<br>          const lowConf = confidence !== null &amp;&amp; confidence !== undefined &amp;&amp; confidence &lt; settings.autoAcceptConfidenceThreshold;<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual,<br>            difference: &#39;0&#39;,<br>            status: lowConf ? &#39;REVIEW&#39; : &#39;PASS&#39;,<br>            explanation: lowConf ? `${label} matched (&quot;${actual}&quot;), flagged REVIEW due to ${confidence}% OCR confidence.` : `${label} matched (&quot;${actual}&quot;).`<br>          };<br>        }<br><br>        return {<br>          rule: `${label} Match`,<br>          expected,<br>          actual,<br>          difference: `&quot;${expected}&quot; ≠ &quot;${actual}&quot;`,<br>          status: &#39;FAIL&#39;,<br>          explanation: `${label} mismatch: Expected &quot;${expected}&quot;, Receipt &quot;${actual}&quot;.`<br>        };<br>      },<br><br>      validateField(field, settings = appState.settings) {<br>        if (!field.enabled &amp;&amp; !field.expectedValue &amp;&amp; !field.actualValue) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: &#39;Field disabled / unused.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        const exp = String(field.expectedValue ?? &#39;&#39;).trim();<br>        const act = String(field.actualValue ?? &#39;&#39;).trim();<br><br>        if (!exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: field.required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: field.required ? &#39;Required field has no expected or actual value.&#39; : &#39;Optional field blank.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;PENDING&#39;,<br>            difference: &#39;Missing actual&#39;,<br>            explanation: `Expected &quot;${exp}&quot;, awaiting receipt/system value.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (!exp &amp;&amp; act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;REVIEW&#39;,<br>            difference: &#39;Missing expected&#39;,<br>            explanation: `Actual &quot;${act}&quot; present, but Expected value is blank.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        if (field.dataType === &#39;Currency&#39; || field.dataType === &#39;Number&#39; || field.dataType === &#39;Percentage&#39;) {<br>          const nExp = FinancialCalculator.parseAmount(exp);<br>          const nAct = FinancialCalculator.parseAmount(act);<br>          const tol = Number(field.tolerance ?? settings.numericTolerance ?? 0.01);<br>          if (nExp !== null &amp;&amp; nAct !== null) {<br>            const diff = Number((nAct - nExp).toFixed(4));<br>            const pass = Math.abs(diff) &lt;= tol;<br>            return {<br>              fieldId: field.id,<br>              status: pass ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>              difference: diff === 0 ? &#39;0.00&#39; : `${diff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${diff.toFixed(2)}`,<br>              explanation: pass ? `Numeric match within ±${tol}.` : `Expected ${nExp}, found ${nAct} (Diff: ${diff}).`,<br>              evaluatedAt: new Date().toISOString()<br>            };<br>          }<br>        }<br><br>        const normExp = this.normalizeText(exp, settings);<br>        const normAct = this.normalizeText(act, settings);<br>        const match = normExp === normAct;<br>        return {<br>          fieldId: field.id,<br>          status: match ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>          difference: match ? &#39;0&#39; : `&quot;${exp}&quot; ≠ &quot;${act}&quot;`,<br>          explanation: match ? &#39;Value matched.&#39; : `Expected &quot;${exp}&quot;, got &quot;${act}&quot;.`,<br>          evaluatedAt: new Date().toISOString()<br>        };<br>      },<br><br>      validateMainPage(mainPage, recordHistory = false) {<br>        if (!mainPage) return null;<br>        const feeResults = (mainPage.fees || []).map(f =&gt; {<br>          const res = this.validateFeeRow(f);<br>          f.lastValidation = res;<br>          return res;<br>        });<br><br>        const fieldResults = (mainPage.fields || []).map(fld =&gt; {<br>          const res = this.validateField(fld);<br>          fld.lastValidation = res;<br>          return res;<br>        });<br><br>        const financials = FinancialCalculator.calculateTotals(mainPage.fees || []);<br><br>        const activeStatuses = [<br>          ...feeResults.map(r =&gt; r.status),<br>          ...fieldResults.filter(r =&gt; r.status !== &#39;NOT APPLICABLE&#39;).map(r =&gt; r.status)<br>        ];<br><br>        let overallStatus = &#39;PENDING&#39;;<br>        if (activeStatuses.length === 0) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;FAIL&#39;)) {<br>          overallStatus = &#39;FAIL&#39;;<br>        } else if (activeStatuses.includes(&#39;PENDING&#39;)) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;REVIEW&#39;)) {<br>          overallStatus = &#39;REVIEW&#39;;<br>        } else {<br>          overallStatus = &#39;PASS&#39;;<br>        }<br><br>        const summary = {<br>          overallStatus,<br>          feeResults,<br>          fieldResults,<br>          financials,<br>          counts: {<br>            pass: activeStatuses.filter(s =&gt; s === &#39;PASS&#39;).length,<br>            fail: activeStatuses.filter(s =&gt; s === &#39;FAIL&#39;).length,<br>            review: activeStatuses.filter(s =&gt; s === &#39;REVIEW&#39;).length,<br>            pending: activeStatuses.filter(s =&gt; s === &#39;PENDING&#39;).length<br>          },<br>          validatedAt: new Date().toISOString()<br>        };<br><br>        mainPage.validationSummary = summary;<br><br>        if (recordHistory) {<br>          mainPage.validationHistory = mainPage.validationHistory || [];<br>          mainPage.validationHistory.unshift({<br>            id: &#39;vh_&#39; + Date.now(),<br>            timestamp: summary.validatedAt,<br>            overallStatus: summary.overallStatus,<br>            counts: { ...summary.counts },<br>            netTotal: financials.actualNet<br>          });<br>          if (mainPage.validationHistory.length &gt; 25) mainPage.validationHistory.pop();<br>        }<br><br>        return summary;<br>      }<br>    };<br><br>    /****************************************************************************<br>     * MODULE 3: INTELLIGENT OCR, ROW PARSER &amp; SMART FIELD MAPPING ENGINE<br>     ****************************************************************************/<br>    const RowToFieldsEngine = {<br>      parseSpreadsheetRow(rawText, hasHeaderRow = false) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br>        if (!lines.length) return { headers: [], values: [], delimiter: &#39;None&#39; };<br><br>        const detectDelimiter = (line) =&gt; {<br>          if (line.includes(&#39;\t&#39;)) return &#39;\t&#39;;<br>          if (line.includes(&#39;|&#39;)) return &#39;|&#39;;<br>          if (line.includes(&#39;,&#39;)) return &#39;,&#39;;<br>          return &#39;\t&#39;;<br>        };<br><br>        const splitLine = (line, delim) =&gt; {<br>          if (delim === &#39;,&#39;) {<br>            const matches = line.match(/(&quot;.*?&quot;|[^&quot;,]+)(?=\s*,|\s*$)/g);<br>            return matches ? matches.map(c =&gt; c.replace(/^&quot;|&quot;$/g, &#39;&#39;).trim()) : line.split(&#39;,&#39;).map(c =&gt; c.trim());<br>          }<br>          return line.split(delim).map(c =&gt; c.trim());<br>        };<br><br>        const delim = detectDelimiter(lines[0]);<br>        const delimLabel = delim === &#39;\t&#39; ? &#39;Tab (Excel/Sheets)&#39; : delim === &#39;|&#39; ? &#39;Pipe (|)&#39; : &#39;CSV (,)&#39;;<br><br>        if (hasHeaderRow &amp;&amp; lines.length &gt;= 2) {<br>          return {<br>            headers: splitLine(lines[0], delim),<br>            values: splitLine(lines[1], delim),<br>            delimiter: delimLabel<br>          };<br>        }<br><br>        return {<br>          headers: [],<br>          values: splitLine(lines[0], delim),<br>          delimiter: delimLabel<br>        };<br>      },<br><br>      inferDataType(val) {<br>        const s = String(val || &#39;&#39;).trim();<br>        if (!s) return &#39;Dynamic&#39;;<br>        if (/^\d{4}-\d{2}-\d{2}$/.test(s) || /^\d{1,2}\/\d{1,2}\/\d{2,4}$/.test(s)) return &#39;Date&#39;;<br>        if (/^[$₱€£]?\s*\(?-?\d{1,3}(,\d{3})*(\.\d+)?\)?$/.test(s)) return &#39;Currency&#39;;<br>        if (/^[A-Z]{2,5}$/.test(s)) return &#39;Code&#39;;<br>        return &#39;Dynamic&#39;;<br>      },<br><br>      autoMatchReceiptAgainstExpectedFields(mainPage) {<br>        if (!mainPage || !mainPage.receipt || !mainPage.receipt.ocrRawText) {<br>          return { matched: 0, total: 0 };<br>        }<br>        const rawText = mainPage.receipt.ocrRawText;<br>        const normReceipt = rawText.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>        const compactReceipt = rawText.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br>        const lines = rawText.split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br><br>        let matched = 0;<br>        let total = 0;<br><br>        (mainPage.fields || []).forEach(f =&gt; {<br>          const exp = String(f.expectedValue || &#39;&#39;).trim();<br>          if (!exp) return;<br>          total++;<br><br>          const normExp = exp.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>          const compactExp = exp.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br><br>          if (normReceipt.includes(normExp) || (compactExp.length &gt;= 2 &amp;&amp; compactReceipt.includes(compactExp))) {<br>            f.actualValue = exp;<br>            f.enabled = true;<br>            matched++;<br>            return;<br>          }<br><br>          const labelNorm = f.name.toLowerCase();<br>          const labelLine = lines.find(l =&gt; l.toLowerCase().includes(labelNorm));<br>          if (labelLine) {<br>            const afterColon = labelLine.split(/[:\-]/).slice(1).join(&#39;:&#39;).trim();<br>            if (afterColon) {<br>              f.actualValue = afterColon;<br>              f.enabled = true;<br>            }<br>          }<br>        });<br><br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { matched, total };<br>      }<br>    };<br><br>    const OcrMappingEngine = {<br>      parseQuickPasteFees(rawText) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br><br>        const parsed = [];<br>        let i = 0;<br><br>        while (i &lt; lines.length) {<br>          const line = lines[i];<br><br>          if (line.includes(&#39;|&#39;) || line.includes(&#39;\t&#39;)) {<br>            const parts = line.split(/\||\t/).map(p =&gt; p.trim()).filter(Boolean);<br>            const name = parts[0] || `Fee ${parsed.length + 1}`;<br>            const amount = parts[1] || &#39;0&#39;;<br>            const isCwt = /\bcwt\b|withholding/i.test(name) || (parts[2] &amp;&amp; parts[2].toUpperCase() === &#39;CWT&#39;);<br>            const code = parts[2] || (isCwt ? &#39;CWT&#39; : &#39;&#39;);<br>            parsed.push({ name, amount, code, isCwt });<br>            i += 1;<br>            continue;<br>          }<br><br>          const name = line;<br>          const amount = lines[i + 1] !== undefined ? lines[i + 1] : &#39;&#39;;<br>          const isCwtName = /\bcwt\b|withholding/i.test(name);<br>          const possibleCode = lines[i + 2];<br><br>          const looksLikeCode = possibleCode !== undefined &amp;&amp;<br>            /^[A-Za-z0-9_-]{1,12}$/.test(possibleCode) &amp;&amp;<br>            !/^\d+(\.\d+)?$/.test(possibleCode);<br><br>          if (looksLikeCode) {<br>            const isCwt = isCwtName || possibleCode.toUpperCase() === &#39;CWT&#39;;<br>            parsed.push({ name, amount, code: possibleCode.toUpperCase(), isCwt });<br>            i += 3;<br>          } else {<br>            parsed.push({<br>              name,<br>              amount,<br>              code: isCwtName ? &#39;CWT&#39; : &#39;&#39;,<br>              isCwt: isCwtName<br>            });<br>            i += 2;<br>          }<br>        }<br><br>        return parsed;<br>      },<br><br>      parseReceiptTextToBlocks(rawText, pageNum = 1, baseConfidence = 92) {<br>        const lines = String(rawText || &#39;&#39;).split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br>        const blocks = [];<br><br>        lines.forEach((line, idx) =&gt; {<br>          const yPct = Math.min(92, 8 + idx * 7);<br>          const pipeOrCol = line.split(/\||\t|\s{2,}/).map(s =&gt; s.trim()).filter(Boolean);<br>          if (pipeOrCol.length &gt;= 2) {<br>            const name = pipeOrCol[0];<br>            const amtMatch = pipeOrCol.find(p =&gt; /^\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?$/.test(p)) || pipeOrCol[1];<br>            const codeMatch = pipeOrCol.find(p =&gt; /^[A-Z0-9]{2,8}$/.test(p) &amp;&amp; p !== amtMatch) || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;);<br>            blocks.push({<br>              id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>              page: pageNum,<br>              rawLine: line,<br>              detectedName: name,<br>              detectedAmount: amtMatch,<br>              detectedCode: codeMatch,<br>              confidence: baseConfidence,<br>              bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>              mappedToFeeId: null,<br>              status: &#39;UNMAPPED&#39;<br>            });<br>          } else {<br>            const regex = /^(.+?)\s+(\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?)(?:\s+([A-Za-z0-9_-]{2,10}))?$/;<br>            const m = line.match(regex);<br>            if (m) {<br>              const name = m[1].trim();<br>              const amt = m[2].trim();<br>              const code = (m[4] || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;)).toUpperCase();<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: name,<br>                detectedAmount: amt,<br>                detectedCode: code,<br>                confidence: baseConfidence,<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;UNMAPPED&#39;<br>              });<br>            } else {<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: line,<br>                detectedAmount: &#39;&#39;,<br>                detectedCode: &#39;&#39;,<br>                confidence: Math.max(65, baseConfidence - 10),<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;TEXT_ONLY&#39;<br>              });<br>            }<br>          }<br>        });<br><br>        return blocks;<br>      },<br><br>      autoMapBlocksToMainPage(mainPage) {<br>        if (!mainPage || !mainPage.receipt) return { autoAccepted: 0, reviewNeeded: 0 };<br>        const blocks = (mainPage.receipt.ocrBlocks || []).filter(b =&gt; b.detectedAmount !== &#39;&#39;);<br>        const fees = mainPage.fees || [];<br>        let autoAccepted = 0;<br>        let reviewNeeded = 0;<br><br>        const usedBlockIds = new Set();<br><br>        fees.forEach((fee, feeIdx) =&gt; {<br>          const expNameNorm = ValidationEngine.normalizeText(fee.expectedName);<br>          const expCodeNorm = String(fee.expectedCode || &#39;&#39;).trim().toUpperCase();<br><br>          let bestBlock = null;<br>          let bestScore = 0;<br><br>          blocks.forEach(blk =&gt; {<br>            if (usedBlockIds.has(blk.id)) return;<br>            let score = 0;<br>            const blkNameNorm = ValidationEngine.normalizeText(blk.detectedName);<br>            const blkCodeNorm = String(blk.detectedCode || &#39;&#39;).trim().toUpperCase();<br><br>            if (expNameNorm &amp;&amp; blkNameNorm === expNameNorm) score += 50;<br>            else if (expNameNorm &amp;&amp; (blkNameNorm.includes(expNameNorm) || expNameNorm.includes(blkNameNorm))) score += 30;<br><br>            if (expCodeNorm &amp;&amp; blkCodeNorm === expCodeNorm) score += 40;<br>            if (blocks.indexOf(blk) === feeIdx) score += 15;<br><br>            if (score &gt; bestScore) {<br>              bestScore = score;<br>              bestBlock = blk;<br>            }<br>          });<br><br>          if (bestBlock &amp;&amp; bestScore &gt;= 30) {<br>            usedBlockIds.add(bestBlock.id);<br>            fee.actualName = bestBlock.detectedName;<br>            fee.actualAmount = bestBlock.detectedAmount;<br>            fee.actualCode = bestBlock.detectedCode || fee.actualCode;<br>            fee.ocrConfidence = bestBlock.confidence;<br>            fee.sourceLocation = `Page ${bestBlock.page} (Y:${Math.round(bestBlock.bbox.y)}%)`;<br>            bestBlock.mappedToFeeId = fee.id;<br><br>            if (bestScore &gt;= 65 &amp;&amp; bestBlock.confidence &gt;= appState.settings.autoAcceptConfidenceThreshold) {<br>              bestBlock.status = &#39;AUTO_ACCEPTED&#39;;<br>              autoAccepted++;<br>            } else {<br>              bestBlock.status = &#39;REVIEW&#39;;<br>              reviewNeeded++;<br>            }<br>          }<br>        });<br><br>        RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(mainPage);<br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { autoAccepted, reviewNeeded };<br>      },<br><br>      async preprocessImageCanvas(imageDataUrl, opts = {}) {<br>        return new Promise((resolve) =&gt; {<br>          const img = new Image();<br>          img.onload = () =&gt; {<br>            try {<br>              const scale = opts.scale || 1.5;<br>              const canvas = document.createElement(&#39;canvas&#39;);<br>              canvas.width = Math.max(1, Math.round((img.naturalWidth || img.width || 400) * scale));<br>              canvas.height = Math.max(1, Math.round((img.naturalHeight || img.height || 400) * scale));<br>              const ctx = canvas.getContext(&#39;2d&#39;);<br>              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>              if (opts.grayscale || opts.contrast || opts.sharpen) {<br>                const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);<br>                const d = imgData.data;<br>                const contrastFactor = opts.contrast ? 1.35 : 1.0;<br>                for (let i = 0; i &lt; d.length; i += 4) {<br>                  let r = d[i], g = d[i + 1], b = d[i + 2];<br>                  if (opts.grayscale) {<br>                    const gray = 0.299 * r + 0.587 * g + 0.114 * b;<br>                    r = g = b = gray;<br>                  }<br>                  if (opts.contrast) {<br>                    r = Math.min(255, Math.max(0, (r - 128) * contrastFactor + 128));<br>                    g = Math.min(255, Math.max(0, (g - 128) * contrastFactor + 128));<br>                    b = Math.min(255, Math.max(0, (b - 128) * contrastFactor + 128));<br>                  }<br>                  d[i] = r; d[i + 1] = g; d[i + 2] = b;<br>                }<br>                ctx.putImageData(imgData, 0, 0);<br>              }<br>              resolve(canvas.toDataURL(&#39;image/png&#39;));<br>            } catch (canvasErr) {<br>              console.warn(&#39;Preprocessing canvas fallback:&#39;, canvasErr);<br>              resolve(imageDataUrl);<br>            }<br>          };<br>          img.onerror = () =&gt; resolve(imageDataUrl);<br>          img.src = imageDataUrl;<br>        });<br>      },<br><br>      async runRealTesseractOCR(imageDataUrl, onProgress) {<br>        if (!window.Tesseract) {<br>          throw new Error(&#39;Tesseract.js library is unavailable offline.&#39;);<br>        }<br>        const worker = await Tesseract.createWorker(&#39;eng&#39;, 1, {<br>          logger: m =&gt; {<br>            if (onProgress &amp;&amp; m.status === &#39;recognizing text&#39;) {<br>              onProgress(Math.round((m.progress || 0) * 100));<br>            }<br>          }<br>        });<br>        try {<br>          const ret = await worker.recognize(imageDataUrl);<br>          return {<br>            text: ret.data.text || &#39;&#39;,<br>            confidence: Math.round(ret.data.confidence || 85)<br>          };<br>        } finally {<br>          await worker.terminate();<br>        }<br>      }<br>    };<br><br>    /****************************************************************************<br>     * SAMPLE DATA &amp; SVG RECEIPT GENERATOR (100% SELF-CONTAINED)<br>     ****************************************************************************/<br>    function generateSyntheticReceiptSvgDataUrl({ title, invoiceNo, date, lines, footer }) {<br>      const lineRows = lines.map((l, idx) =&gt; {<br>        const y = 135 + idx * 32;<br>        return `<br>          &lt;text x=&quot;28&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; fill=&quot;#1e293b&quot;&gt;${escapeHtml(l.label)}&lt;/text&gt;<br>          &lt;text x=&quot;315&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(l.amount)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;13&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#4f46e5&quot;&gt;${escapeHtml(l.code)}&lt;/text&gt;<br>        `;<br>      }).join(&#39;&#39;);<br><br>      const svg = `<br>        &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;400&quot; height=&quot;420&quot; viewBox=&quot;0 0 400 420&quot;&gt;<br>          &lt;rect width=&quot;400&quot; height=&quot;420&quot; fill=&quot;#ffffff&quot; rx=&quot;8&quot;/&gt;<br>          &lt;rect x=&quot;12&quot; y=&quot;12&quot; width=&quot;376&quot; height=&quot;396&quot; fill=&quot;none&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1.5&quot; stroke-dasharray=&quot;4 3&quot; rx=&quot;6&quot;/&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;45&quot; font-family=&quot;sans-serif&quot; font-size=&quot;16&quot; font-weight=&quot;800&quot; text-anchor=&quot;middle&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(title)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;66&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;middle&quot; fill=&quot;#64748b&quot;&gt;OFFICIAL EIS ELECTRONIC RECEIPT&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;80&quot; x2=&quot;376&quot; y2=&quot;80&quot; stroke=&quot;#94a3b8&quot; stroke-width=&quot;1&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; fill=&quot;#334155&quot;&gt;REF: ${escapeHtml(invoiceNo)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;end&quot; fill=&quot;#334155&quot;&gt;${escapeHtml(date)}&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;112&quot; x2=&quot;376&quot; y2=&quot;112&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1&quot;/&gt;<br>          ${lineRows}<br>          &lt;line x1=&quot;24&quot; y1=&quot;315&quot; x2=&quot;376&quot; y2=&quot;315&quot; stroke=&quot;#0f172a&quot; stroke-width=&quot;1.5&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(footer.label)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;15&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#059669&quot;&gt;${escapeHtml(footer.value)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;385&quot; font-family=&quot;monospace&quot; font-size=&quot;10&quot; text-anchor=&quot;middle&quot; fill=&quot;#94a3b8&quot;&gt;EIS-AUTH-HASH: 9F82-77C1-SMART-QA&lt;/text&gt;<br>        &lt;/svg&gt;<br>      `;<br>      return &#39;data:image/svg+xml;charset=utf-8,&#39; + encodeURIComponent(svg);<br>    }<br><br><br>    /****************************************************************************<br>     * SHARED HEADERS: one set of Configurable Field / Column Names for all Main Pages<br>     * proj.sharedHeaders (toggle) + proj.sharedSchema [{number,name,dataType,required}]<br>     * Values (Expected / Found on Receipt) always stay per page.<br>     ****************************************************************************/<br>    function buildFieldStub(num, entry) {<br>      return {<br>        id: `fld_${num}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,<br>        number: num,<br>        name: entry ? entry.name : `Custom Field ${num}`,<br>        expectedValue: &#39;&#39;, actualValue: &#39;&#39;,<br>        dataType: entry ? entry.dataType : &#39;Dynamic&#39;,<br>        validationRule: &#39;Exact / Tolerance Match&#39;,<br>        ocrEnabled: true,<br>        required: entry ? Boolean(entry.required) : false,<br>        tolerance: 0.01,<br>        description: `Dynamic Column #${num}`,<br>        pageOverride: false,<br>        enabled: false<br>      };<br>    }<br><br>    // Copy the shared headers onto one page (rename/type/required only, never values)<br>    function applySharedSchemaToPage(proj, page) {<br>      if (!proj || !page || !proj.sharedHeaders || !Array.isArray(proj.sharedSchema)) return;<br>      page.fields = page.fields || [];<br>      proj.sharedSchema.forEach((entry, i) =&gt; {<br>        const num = i + 1;<br>        let f = page.fields[i];<br>        if (!f) { f = buildFieldStub(num, entry); page.fields.push(f); }<br>        f.name = entry.name;<br>        f.dataType = entry.dataType;<br>        f.required = Boolean(entry.required);<br>      });<br>    }<br><br>    // Make `sourcePage` the master: merge its headers into the schema, then push to all pages<br>    function pushSharedHeadersFrom(sourcePage) {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.sharedHeaders || !sourcePage) return;<br>      const old = Array.isArray(proj.sharedSchema) ? proj.sharedSchema : [];<br>      const len = Math.max(old.length, (sourcePage.fields || []).length);<br>      const next = [];<br>      for (let i = 0; i &lt; len; i++) {<br>        const f = (sourcePage.fields || [])[i];<br>        next.push(f<br>          ? { number: i + 1, name: f.name, dataType: f.dataType, required: Boolean(f.required) }<br>          : old[i]);<br>      }<br>      proj.sharedSchema = next;<br>      (proj.mainPages || []).forEach(p =&gt; {<br>        if (p.id === sourcePage.id) return;<br>        applySharedSchemaToPage(proj, p);<br>        ValidationEngine.validateMainPage(p);<br>      });<br>    }<br><br>    function toggleSharedHeaders(checked) {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      if (!checked) {<br>        proj.sharedHeaders = false;<br>        scheduleAutosave(&#39;Turned off shared headers&#39;);<br>        showToast(&#39;Shared headers OFF. Each Main Page now keeps its own copy of the headers.&#39;, &#39;info&#39;);<br>        return renderApp();<br>      }<br>      if (proj.mainPages.length &lt;= 1) {<br>        proj.sharedHeaders = true;<br>        proj.sharedSchema = [];<br>        pushSharedHeadersFrom(page);<br>        scheduleAutosave(&#39;Turned on shared headers&#39;);<br>        showToast(&#39;Shared headers ON. Every new Main Page will use these headers.&#39;, &#39;success&#39;);<br>        return renderApp();<br>      }<br>      openModal({<br>        title: &#39;Use the same headers on every Main Page?&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;p&gt;The Configurable Field / Column Names, Type and Req of &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; become the default for &lt;strong&gt;all ${proj.mainPages.length} Main Pages&lt;/strong&gt; and for every new Main Page you add.&lt;/p&gt;<br>            &lt;ul class=&quot;list-disc pl-5 space-y-1 text-slate-500 dark:text-slate-400&quot;&gt;<br>              &lt;li&gt;Headers on the other pages are overwritten with this page&#39;s headers.&lt;/li&gt;<br>              &lt;li&gt;Expected Values, Found on Receipt values, fees, receipts and evidence are &lt;strong&gt;not touched&lt;/strong&gt;.&lt;/li&gt;<br>              &lt;li&gt;From now on, renaming a header on any page updates all pages.&lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/div&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmSharedHeadersOn()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Apply to all pages&lt;/button&gt;`<br>      });<br>    }<br><br>    function confirmSharedHeadersOn() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      proj.sharedHeaders = true;<br>      proj.sharedSchema = [];<br>      pushSharedHeadersFrom(page);<br>      closeModal();<br>      logActivity(&#39;Shared Headers&#39;, `Applied headers of ${page.name} to ${proj.mainPages.length} Main Pages`);<br>      scheduleAutosave(&#39;Turned on shared headers&#39;);<br>      showToast(`Headers of ${page.name} applied to all ${proj.mainPages.length} Main Pages.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function reapplySharedHeaders() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      pushSharedHeadersFrom(page);<br>      scheduleAutosave(&#39;Re-applied shared headers&#39;);<br>      showToast(`Headers of ${page.name} re-applied to all Main Pages.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function createDefaultFields(count = 50) {<br>      const presets = [<br>        { name: &#39;Invoice / Receipt Number&#39;, type: &#39;Reference&#39;, req: true },<br>        { name: &#39;Transaction Date&#39;, type: &#39;Date&#39;, req: true },<br>        { name: &#39;Merchant / Taxpayer TIN&#39;, type: &#39;Reference&#39;, req: false },<br>        { name: &#39;Currency Code&#39;, type: &#39;Code&#39;, req: true },<br>        { name: &#39;Gross Settlement Total&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;CWT Withholding Amount&#39;, type: &#39;Currency&#39;, req: false },<br>        { name: &#39;Net Payable Amount&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;EIS Acknowledgement ID&#39;, type: &#39;Reference&#39;, req: false }<br>      ];<br>      const list = [];<br>      for (let i = 1; i &lt;= count; i++) {<br>        const p = presets[i - 1];<br>        list.push({<br>          id: `fld_${i}_${Math.random().toString(36).slice(2, 6)}`,<br>          number: i,<br>          name: p ? p.name : `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: p ? p.type : &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: p ? p.req : false,<br>          tolerance: 0.01,<br>          description: p ? `Standard EIS ${p.name}` : `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: i &lt;= 8<br>        });<br>      }<br>      return list;<br>    }<br><br>    function createSampleSeedState() {<br>      const now = new Date().toISOString();<br><br>      // Page 1: PASS (Fee 1 = 1000/NC, Fee 2 = 250/IC, CWT = -50 -&gt; Gross 1250, CWT 50, Net 1200)<br>      const p1ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;MANILA LOGISTICS &amp; FREIGHT CORP.&#39;,<br>        invoiceNo: &#39;EIS-2026-1001&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Fee 1 Charge&#39;, amount: &#39;1,000.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Fee 2 Charge&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;-50.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,200.00&#39; }<br>      });<br><br>      const p1RawText = `Fee 1 Charge | 1000.00 | NC\nFee 2 Charge | 250.00 | IC\nCWT | -50.00 | CWT`;<br>      const page1 = {<br>        id: &#39;mp_manila_01&#39;,<br>        name: &#39;MP-01: Manila HQ Settlement&#39;,<br>        description: &#39;Standard two-fee transaction with negative CWT notation (-50).&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;EIS-2026-1001\t2026-11-19\t004-892-110-000\tPHP\t1250.00\t50.00\t1200.00&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_01&#39;,<br>          fileName: &#39;manila_eis_receipt_1001.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p1ReceiptImg],<br>          ocrRawText: p1RawText,<br>          ocrConfidence: 96,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p1RawText, 1, 96),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_1a&#39;, expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1 Charge&#39;, actualAmount: &#39;1000.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 97, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_1b&#39;, expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 2 Charge&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 95, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_1c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;-50&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;-50.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 96, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_1&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#10b981&#39;, label: &#39;QA-1: Fee 1 Verified&#39;, comment: &#39;Matches 1000.00 NC&#39;, fieldRef: &#39;Fee 1 Charge&#39;, testCaseId: &#39;TC-001&#39;, defectId: &#39;&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page1.fields[0].expectedValue = &#39;EIS-2026-1001&#39;; page1.fields[0].actualValue = &#39;EIS-2026-1001&#39;;<br>      page1.fields[1].expectedValue = &#39;2026-11-19&#39;; page1.fields[1].actualValue = &#39;2026-11-19&#39;;<br>      page1.fields[2].expectedValue = &#39;004-892-110-000&#39;; page1.fields[2].actualValue = &#39;004-892-110-000&#39;;<br>      page1.fields[3].expectedValue = &#39;PHP&#39;; page1.fields[3].actualValue = &#39;PHP&#39;;<br>      page1.fields[4].expectedValue = &#39;1250.00&#39;; page1.fields[4].actualValue = &#39;1250.00&#39;;<br>      page1.fields[5].expectedValue = &#39;50.00&#39;; page1.fields[5].actualValue = &#39;50.00&#39;;<br>      page1.fields[6].expectedValue = &#39;1200.00&#39;; page1.fields[6].actualValue = &#39;1200.00&#39;;<br><br>      // Page 2: FAIL (Fee 1 Expected 1000 vs Receipt 1200 -&gt; Diff +200, CWT = (50))<br>      const p2ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;CEBU PORT TERMINAL SERVICES&#39;,<br>        invoiceNo: &#39;EIS-2026-2044&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Terminal Handling&#39;, amount: &#39;1,200.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Documentation Fee&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;(50.00)&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,400.00&#39; }<br>      });<br>      const p2RawText = `Terminal Handling | 1200.00 | NC\nDocumentation Fee | 250.00 | IC\nCWT | (50.00) | CWT`;<br>      const page2 = {<br>        id: &#39;mp_cebu_02&#39;,<br>        name: &#39;MP-02: Cebu Hub Clearance&#39;,<br>        description: &#39;Demonstrates Fee 1 amount mismatch (Expected 1000 vs Receipt 1200) &amp; parenthetical CWT (50).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_02&#39;,<br>          fileName: &#39;cebu_eis_receipt_2044.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p2ReceiptImg],<br>          ocrRawText: p2RawText,<br>          ocrConfidence: 93,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p2RawText, 1, 93),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_2a&#39;, expectedName: &#39;Terminal Handling&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Terminal Handling&#39;, actualAmount: &#39;1200.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 94, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_2b&#39;, expectedName: &#39;Documentation Fee&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Documentation Fee&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 93, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_2c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;(50)&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;(50.00)&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 92, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_2&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#ef4444&#39;, label: &#39;QA-1: Overcharge +200&#39;, comment: &#39;Expected 1000.00, Receipt shows 1200.00&#39;, fieldRef: &#39;Terminal Handling&#39;, testCaseId: &#39;TC-002&#39;, defectId: &#39;DEF-101&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page2.fields[0].expectedValue = &#39;EIS-2026-2044&#39;; page2.fields[0].actualValue = &#39;EIS-2026-2044&#39;;<br>      page2.fields[3].expectedValue = &#39;PHP&#39;; page2.fields[3].actualValue = &#39;PHP&#39;;<br><br>      // Page 3: PENDING (Missing Fee Code on Inspection Fee -&gt; verifies missing info never auto-passes)<br>      const p3ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;DAVAO AGRI-EXPORT GATEWAY&#39;,<br>        invoiceNo: &#39;EIS-2026-3099&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Export Inspection&#39;, amount: &#39;800.00&#39;, code: &#39;&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;40.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 760.00&#39; }<br>      });<br>      const p3RawText = `Export Inspection | 800.00\nCWT | 40.00 | CWT`;<br>      const page3 = {<br>        id: &#39;mp_davao_03&#39;,<br>        name: &#39;MP-03: Davao Branch Export&#39;,<br>        description: &#39;Demonstrates missing required fee code evaluation (PENDING rather than false PASS).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_03&#39;,<br>          fileName: &#39;davao_eis_receipt_3099.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p3ReceiptImg],<br>          ocrRawText: p3RawText,<br>          ocrConfidence: 89,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p3RawText, 1, 89),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_3a&#39;, expectedName: &#39;Export Inspection&#39;, expectedAmount: &#39;800&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Export Inspection&#39;, actualAmount: &#39;800.00&#39;, actualCode: &#39;&#39;, isCwt: false, ocrConfidence: 89, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_3b&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;40&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;40.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 91, sourceLocation: &#39;Page 1 Row 2&#39; }<br>        ],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      page3.fields[0].expectedValue = &#39;EIS-2026-3099&#39;; page3.fields[0].actualValue = &#39;EIS-2026-3099&#39;;<br><br>      [page1, page2, page3].forEach(p =&gt; ValidationEngine.validateMainPage(p, true));<br><br>      const sampleProject = {<br>        id: &#39;proj_eis_2026_q4&#39;,<br>        name: &#39;EIS Q4 Release — Core Settlement &amp; CWT Audit&#39;,<br>        reference: &#39;PRJ-EIS-2026-04&#39;,<br>        description: &#39;End-to-end EIS electronic receipt validation, CWT deduction accuracy, and QA screenshot evidence suite.&#39;,<br>        owner: &#39;Jansen B. (Lead QA Analyst)&#39;,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [page1, page2, page3],<br>        screenshots: [<br>          {<br>            id: &#39;scr_01&#39;,<br>            name: &#39;EIS_Portal_Manila_Settlement.svg&#39;,<br>            dataUrl: p1ReceiptImg,<br>            capturedAt: now,<br>            source: &#39;Sample Evidence&#39;,<br>            isMerged: false<br>          }<br>        ],<br>        mergeHistory: [],<br>        testCases: [<br>          {<br>            id: &#39;TC-001&#39;,<br>            title: &#39;Verify Standard 2-Fee Gross &amp; Negative CWT (-50) Net Settlement&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Manila HQ Settlement Main Page configured with Fee 1 (1000/NC), Fee 2 (250/IC), CWT (-50).&#39;,<br>            steps: &#39;1. Upload official EIS receipt.\n2. Run OCR extraction &amp; auto-mapping.\n3. Verify Gross = 1250.00, CWT = 50.00, Net = 1200.00.&#39;,<br>            expectedResult: &#39;All fee names, amounts, and codes PASS; Net Total equals 1200.00.&#39;,<br>            actualResult: &#39;Gross 1250.00 - CWT 50.00 = Net 1200.00. Status: PASS.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_manila_01&#39;,<br>            linkedDefectId: &#39;&#39;<br>          },<br>          {<br>            id: &#39;TC-002&#39;,<br>            title: &#39;Detect Fee 1 Overcharge Mismatch &amp; Parenthetical CWT (50)&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Cebu Hub Main Page expects Terminal Handling = 1000.00 NC.&#39;,<br>            steps: &#39;1. Attach Cebu receipt showing 1200.00 NC.\n2. Execute validation engine.&#39;,<br>            expectedResult: &#39;System flags FAIL with +200.00 difference while deducting 50.00 for (50) CWT.&#39;,<br>            actualResult: &#39;Flagged FAIL (+200.00 variance). Defect DEF-101 logged.&#39;,<br>            status: &#39;FAIL&#39;,<br>            priority: &#39;Critical&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            linkedDefectId: &#39;DEF-101&#39;<br>          },<br>          {<br>            id: &#39;TC-003&#39;,<br>            title: &#39;Verify Missing Fee Code Triggers PENDING Instead of False PASS&#39;,<br>            module: &#39;Validation Rules&#39;,<br>            preconditions: &#39;Davao Branch receipt omits IC fee code on Export Inspection.&#39;,<br>            steps: &#39;1. Validate Davao Branch Main Page.&#39;,<br>            expectedResult: &#39;Status evaluates to PENDING until code is verified.&#39;,<br>            actualResult: &#39;Evaluated as PENDING as expected.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_davao_03&#39;,<br>            linkedDefectId: &#39;&#39;<br>          }<br>        ],<br>        defects: [<br>          {<br>            id: &#39;DEF-101&#39;,<br>            title: &#39;Terminal Handling Fee billed at 1,200.00 instead of contracted 1,000.00 (+200.00 variance)&#39;,<br>            description: &#39;EIS receipt #EIS-2026-2044 reflects 1,200.00 NC for Terminal Handling, exceeding Main Page expected tariff by 200.00.&#39;,<br>            stepsToReproduce: &#39;1. Open MP-02: Cebu Hub Clearance.\n2. Compare Fee 1 expected (1000.00 NC) against uploaded receipt.\n3. Observe +200.00 variance.&#39;,<br>            expectedResult: &#39;Terminal Handling = 1,000.00 NC; Net Payable = 1,200.00&#39;,<br>            actualResult: &#39;Terminal Handling = 1,200.00 NC; Net Payable = 1,400.00&#39;,<br>            severity: &#39;High&#39;,<br>            priority: &#39;P1&#39;,<br>            status: &#39;Open&#39;,<br>            environment: &#39;EIS Staging v4.12&#39;,<br>            linkedTestCaseId: &#39;TC-002&#39;,<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            annotationRef: &#39;QA-1: Overcharge +200&#39;,<br>            dateReported: now.slice(0, 10),<br>            assignee: &#39;M. Santos (Billing Dev)&#39;<br>          }<br>        ],<br>        activityLog: [<br>          { timestamp: now, action: &#39;Initialized Workspace&#39;, detail: &#39;Loaded sample project PRJ-EIS-2026-04 with 3 isolated Main Pages.&#39; }<br>        ]<br>      };<br><br>      const defaultTemplates = [<br>        {<br>          id: &#39;tpl_standard_cwt&#39;,<br>          name: &#39;Standard 2-Fee + CWT Settlement&#39;,<br>          description: &#39;Includes Fee 1 (NC), Fee 2 (IC), and CWT deduction rule.&#39;,<br>          fees: [<br>            { expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, isCwt: false },<br>            { expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;50&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        },<br>        {<br>          id: &#39;tpl_brokerage_3fee&#39;,<br>          name: &#39;Customs Brokerage 3-Fee + 2% CWT&#39;,<br>          description: &#39;Brokerage, Arrastre, Wharfage, and Withholding Tax.&#39;,<br>          fees: [<br>            { expectedName: &#39;Brokerage Fee&#39;, expectedAmount: &#39;2500&#39;, expectedCode: &#39;BRK&#39;, isCwt: false },<br>            { expectedName: &#39;Arrastre Charge&#39;, expectedAmount: &#39;850&#39;, expectedCode: &#39;ARR&#39;, isCwt: false },<br>            { expectedName: &#39;Wharfage Fee&#39;, expectedAmount: &#39;400&#39;, expectedCode: &#39;WHF&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;75&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        }<br>      ];<br><br>      return {<br>        schemaVersion: APP_SCHEMA_VERSION,<br>        theme: &#39;dark&#39;,<br>        sidebarCollapsed: false,<br>        activeModule: &#39;dashboard&#39;,<br>        activeProjectId: sampleProject.id,<br>        activeMainPageId: page1.id,<br>        lastSavedAt: now,<br>        settings: {<br>          numericTolerance: 0.01,<br>          caseSensitiveNames: false,<br>          normalizeWhitespace: true,<br>          autoAcceptConfidenceThreshold: 88,<br>          cwtDeductionMode: &#39;absolute&#39;,<br>          qaLabelMax: 200,<br>          qaAutoIncrement: true<br>        },<br>        templates: defaultTemplates,<br>        projects: [sampleProject],<br>        ui: {<br>          viewerZoom: 1,<br>          viewerRotation: 0,<br>          showOcrBoxes: true,<br>          selectedComparisonRowId: null,<br>          selectedScreenshotsForMerge: [],<br>          annotationTool: &#39;rect&#39;,<br>          annotationColor: &#39;#ef4444&#39;,<br>          selectedAnnotationId: null,<br>          selectedQaLabel: 1,<br>          mainPageQuickListOpen: false,<br>          selectedMainPageIds: []<br>        }<br>      };<br>    }<br><br>    /****************************************************************************<br>     * STATE HELPERS &amp; NAVIGATION<br>     ****************************************************************************/<br>    function getActiveProject() {<br>      return appState.projects.find(p =&gt; p.id === appState.activeProjectId) || appState.projects[0] || null;<br>    }<br><br>    function getActiveMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.mainPages || proj.mainPages.length === 0) return null;<br>      return proj.mainPages.find(mp =&gt; mp.id === appState.activeMainPageId) || proj.mainPages[0];<br>    }<br><br>    function logActivity(action, detail) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.activityLog = proj.activityLog || [];<br>      proj.activityLog.unshift({ timestamp: new Date().toISOString(), action, detail });<br>      if (proj.activityLog.length &gt; 40) proj.activityLog.pop();<br>    }<br><br>    function navigateTo(moduleId) {<br>      appState.activeModule = moduleId;<br>      closeMobileSidebar();<br>      renderApp();<br>    }<br><br>    function switchActiveProject(projectId) {<br>      appState.activeProjectId = projectId;<br>      const proj = getActiveProject();<br>      appState.activeMainPageId = proj &amp;&amp; proj.mainPages[0] ? proj.mainPages[0].id : null;<br>      scheduleAutosave(&#39;Switched active project&#39;);<br>      renderApp();<br>    }<br><br>    function switchActiveMainPage(pageId) {<br>      appState.activeMainPageId = pageId;<br>      appState.ui.evPendingLabel = null;<br>      appState.ui.evSelectedAnnId = null;<br>      appState.ui.selectedComparisonRowId = null;<br>      appState.ui.selectedAnnotationId = null;<br>      scheduleAutosave(&#39;Switched Main Page&#39;);<br>      renderApp();<br>    }<br><br>    function toggleTheme() {<br>      appState.theme = appState.theme === &#39;dark&#39; ? &#39;light&#39; : &#39;dark&#39;;<br>      applyTheme();<br>      scheduleAutosave(&#39;Theme changed&#39;);<br>    }<br><br>    function applyTheme() {<br>      const html = document.documentElement;<br>      if (appState.theme === &#39;dark&#39;) html.classList.add(&#39;dark&#39;);<br>      else html.classList.remove(&#39;dark&#39;);<br>    }<br><br>    function toggleSidebarCollapse() {<br>      appState.sidebarCollapsed = !appState.sidebarCollapsed;<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const labels = document.querySelectorAll(&#39;.sidebar-label&#39;);<br>      if (appState.sidebarCollapsed) {<br>        sidebar.classList.remove(&#39;lg:w-64&#39;);<br>        sidebar.classList.add(&#39;lg:w-20&#39;);<br>        labels.forEach(el =&gt; el.classList.add(&#39;lg:hidden&#39;));<br>      } else {<br>        sidebar.classList.remove(&#39;lg:w-20&#39;);<br>        sidebar.classList.add(&#39;lg:w-64&#39;);<br>        labels.forEach(el =&gt; el.classList.remove(&#39;lg:hidden&#39;));<br>      }<br>    }<br><br>    function toggleMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      const isOpen = !sidebar.classList.contains(&#39;-translate-x-full&#39;);<br>      if (isOpen) {<br>        closeMobileSidebar();<br>      } else {<br>        sidebar.classList.remove(&#39;-translate-x-full&#39;);<br>        backdrop.classList.remove(&#39;hidden&#39;);<br>      }<br>    }<br><br>    function closeMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      if (sidebar) sidebar.classList.add(&#39;-translate-x-full&#39;);<br>      if (backdrop) backdrop.classList.add(&#39;hidden&#39;);<br>    }<br><br>    function showToast(message, type = &#39;info&#39;) {<br>      const container = document.getElementById(&#39;toast-container&#39;);<br>      if (!container) return;<br>      const colors = {<br>        success: &#39;bg-emerald-600 text-white border-emerald-500&#39;,<br>        error: &#39;bg-rose-600 text-white border-rose-500&#39;,<br>        warning: &#39;bg-amber-500 text-slate-950 border-amber-400&#39;,<br>        info: &#39;bg-slate-800 text-white border-slate-700&#39;<br>      };<br>      const el = document.createElement(&#39;div&#39;);<br>      el.className = `pointer-events-auto px-4 py-3 rounded-xl shadow-xl border text-xs font-medium flex items-center justify-between gap-3 transition-all ${colors[type] || colors.info}`;<br>      el.innerHTML = `&lt;span&gt;${escapeHtml(message)}&lt;/span&gt;&lt;button onclick=&quot;this.parentElement.remove()&quot; class=&quot;opacity-75 hover:opacity-100&quot;&gt;&amp;times;&lt;/button&gt;`;<br>      container.appendChild(el);<br>      setTimeout(() =&gt; { if (el.parentElement) el.remove(); }, 4200);<br>    }<br><br>    function openModal({ title, bodyHtml, footerHtml = &#39;&#39; }) {<br>      document.getElementById(&#39;modal-title&#39;).textContent = title;<br>      document.getElementById(&#39;modal-body&#39;).innerHTML = bodyHtml;<br>      document.getElementById(&#39;modal-footer&#39;).innerHTML = footerHtml;<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.remove(&#39;hidden&#39;);<br>      overlay.classList.add(&#39;flex&#39;);<br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    function closeModal() {<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.add(&#39;hidden&#39;);<br>      overlay.classList.remove(&#39;flex&#39;);<br>    }<br><br>    function statusBadge(status) {<br>      const s = String(status || &#39;PENDING&#39;).toUpperCase();<br>      const styles = {<br>        PASS: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;,<br>        FAIL: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        REVIEW: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        PENDING: &#39;bg-sky-500/15 text-sky-600 dark:text-sky-400 border-sky-500/30&#39;,<br>        &#39;NOT APPLICABLE&#39;: &#39;bg-slate-500/15 text-slate-500 dark:text-slate-400 border-slate-500/30&#39;,<br>        OPEN: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        &#39;IN PROGRESS&#39;: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        FIXED: &#39;bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border-indigo-500/30&#39;,<br>        RETEST: &#39;bg-purple-500/15 text-purple-600 dark:text-purple-400 border-purple-500/30&#39;,<br>        CLOSED: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;<br>      };<br>      return `&lt;span class=&quot;inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide border ${styles[s] || styles.PENDING}&quot;&gt;${escapeHtml(s)}&lt;/span&gt;`;<br>    }<br><br>    function runActivePageValidation(notify = false) {<br>      const mp = getActiveMainPage();<br>      if (!mp) return showToast(&#39;No active Main Page selected.&#39;, &#39;warning&#39;);<br>      const res = ValidationEngine.validateMainPage(mp, true);<br>      logActivity(&#39;Validated Main Page&#39;, `${mp.name} → ${res.overallStatus}`);<br>      scheduleAutosave(&#39;Validated Main Page&#39;);<br>      if (notify) showToast(`${mp.name}: ${res.overallStatus} (${res.counts.pass} Pass, ${res.counts.fail} Fail, ${res.counts.review} Review, ${res.counts.pending} Pending)`, res.overallStatus === &#39;PASS&#39; ? &#39;success&#39; : res.overallStatus === &#39;FAIL&#39; ? &#39;error&#39; : &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * SHELL &amp; NAVIGATION RENDERER<br>     ****************************************************************************/<br>    function renderShellChrome() {<br>      const projSelect = document.getElementById(&#39;sidebar-project-select&#39;);<br>      if (projSelect) {<br>        projSelect.innerHTML = appState.projects.map(p =&gt;<br>          `&lt;option value=&quot;${escapeHtml(p.id)}&quot; ${p.id === appState.activeProjectId ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(p.name)} ${p.archived ? &#39;(Archived)&#39; : &#39;&#39;}&lt;/option&gt;`<br>        ).join(&#39;&#39;);<br>      }<br><br>      const nav = document.getElementById(&#39;sidebar-nav&#39;);<br>      if (nav) {<br>        nav.innerHTML = MODULES.filter(m =&gt; !m.hidden).map(m =&gt; {<br>          const active = appState.activeModule === m.id || (m.id === &#39;validation&#39; &amp;&amp; appState.activeModule === &#39;evidence&#39;);<br>          return `<br>            &lt;button onclick=&quot;navigateTo(&#39;${m.id}&#39;)&quot; class=&quot;w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-xs font-semibold transition ${<br>              active<br>                ? &#39;bg-brand-600 text-white shadow-sm&#39;<br>                : &#39;text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800/80&#39;<br>            }&quot;&gt;<br>              &lt;i data-lucide=&quot;${m.icon}&quot; class=&quot;w-4 h-4 shrink-0&quot;&gt;&lt;/i&gt;<br>              &lt;span class=&quot;sidebar-label truncate&quot;&gt;${escapeHtml(m.label)}&lt;/span&gt;<br>            &lt;/button&gt;<br>          `;<br>        }).join(&#39;&#39;);<br>      }<br><br>      const activeMod = MODULES.find(m =&gt; m.id === appState.activeModule) || MODULES[0];<br>      const topTitle = document.getElementById(&#39;topbar-title&#39;);<br>      const topSub = document.getElementById(&#39;topbar-subtitle&#39;);<br>      if (topTitle) topTitle.textContent = activeMod.label;<br>      if (topSub) topSub.textContent = activeMod.subtitle;<br>    }<br><br>    function renderApp() {<br>      applyTheme();<br>      renderShellChrome();<br>      const viewport = document.getElementById(&#39;main-viewport&#39;);<br>      if (!viewport) return;<br><br>      Object.values(chartInstances).forEach(c =&gt; { try { c.destroy(); } catch (e) {} });<br>      chartInstances = {};<br><br>      switch (appState.activeModule) {<br>        case &#39;dashboard&#39;: viewport.innerHTML = renderDashboardModule(); initDashboardCharts(); break;<br>        case &#39;projects&#39;: viewport.innerHTML = renderProjectsModule(); break;<br>        case &#39;main-pages&#39;: viewport.innerHTML = renderMainPagesModule(); break;<br>        case &#39;validation&#39;: viewport.innerHTML = renderValidationWorkspaceModule(); break;<br>        case &#39;ocr-intel&#39;: viewport.innerHTML = renderOcrIntelligenceModule(); break;<br>        case &#39;screenshots&#39;: viewport.innerHTML = renderScreenshotStudioModule(); initAnnotationCanvasEvents(); break;<br>        case &#39;evidence&#39;: viewport.innerHTML = renderEvidenceModule(); initEvidenceCanvasEvents(); break;<br>        case &#39;test-cases&#39;: viewport.innerHTML = renderTestCasesModule(); break;<br>        case &#39;defects&#39;: viewport.innerHTML = renderDefectsModule(); break;<br>        case &#39;reports&#39;: viewport.innerHTML = renderReportsModule(); break;<br>        case &#39;templates&#39;: viewport.innerHTML = renderTemplatesModule(); break;<br>        case &#39;settings&#39;: viewport.innerHTML = renderSettingsModule(); break;<br>        default: viewport.innerHTML = renderDashboardModule();<br>      }<br><br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1 VIEW: DASHBOARD<br>     ****************************************************************************/<br>    function renderDashboardModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return `&lt;div class=&quot;p-8 text-center&quot;&gt;No project found. Create one in Projects.&lt;/div&gt;`;<br><br>      const totalProjects = appState.projects.length;<br>      const totalMainPages = proj.mainPages.length;<br>      const totalReceipts = proj.mainPages.filter(mp =&gt; mp.receipt).length;<br>      const totalScreenshots = (proj.screenshots || []).length;<br><br>      let passCount = 0, failCount = 0, reviewCount = 0, pendingCount = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        const c = mp.validationSummary.counts;<br>        passCount += c.pass;<br>        failCount += c.fail;<br>        reviewCount += c.review;<br>        pendingCount += c.pending;<br>      });<br>      const totalChecks = passCount + failCount + reviewCount + pendingCount;<br><br>      const totalTC = (proj.testCases || []).length;<br>      const passedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>      const failedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>      const openDefects = (proj.defects || []).filter(d =&gt; d.status !== &#39;Closed&#39; &amp;&amp; d.status !== &#39;Rejected&#39;).length;<br><br>      return `<br>        &lt;div class=&quot;bg-gradient-to-r from-brand-600 via-indigo-600 to-violet-700 rounded-2xl p-6 text-white shadow-lg flex flex-col lg:flex-row lg:items-center justify-between gap-4&quot;&gt;<br>          &lt;div class=&quot;space-y-1&quot;&gt;<br>            &lt;div class=&quot;inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-white/15 text-xs font-semibold&quot;&gt;<br>              &lt;span&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>              &lt;span&gt;•&lt;/span&gt;<br>              &lt;span&gt;${escapeHtml(proj.status)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;h2 class=&quot;text-xl sm:text-2xl font-extrabold tracking-tight&quot;&gt;${escapeHtml(proj.name)}&lt;/h2&gt;<br>            &lt;p class=&quot;text-xs sm:text-sm text-indigo-100 max-w-2xl&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap gap-2.5 shrink-0&quot;&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;validation&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white text-brand-700 font-bold text-xs shadow hover:bg-indigo-50 transition&quot;&gt;<br>              Open Side-by-Side Validator<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white/15 hover:bg-white/25 text-white font-semibold text-xs border border-white/20 transition&quot;&gt;<br>              Configure Main Pages (${totalMainPages})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3.5&quot;&gt;<br>          ${renderKpiCard(&#39;Projects&#39;, totalProjects, &#39;folder-kanban&#39;, &#39;text-brand-500&#39;)}<br>          ${renderKpiCard(&#39;Main Pages&#39;, totalMainPages, &#39;file-spreadsheet&#39;, &#39;text-indigo-500&#39;)}<br>          ${renderKpiCard(&#39;Receipts Attached&#39;, totalReceipts, &#39;receipt&#39;, &#39;text-emerald-500&#39;)}<br>          ${renderKpiCard(&#39;QA Screenshots&#39;, totalScreenshots, &#39;camera&#39;, &#39;text-violet-500&#39;)}<br>          ${renderKpiCard(&#39;Test Cases Passed&#39;, `${passedTC}/${totalTC}`, &#39;check-square&#39;, &#39;text-sky-500&#39;)}<br>          ${renderKpiCard(&#39;Open Defects&#39;, openDefects, &#39;bug&#39;, &#39;text-rose-500&#39;)}<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 lg:grid-cols-5 gap-3.5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;Total Checks&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold mt-1&quot;&gt;${totalChecks}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-emerald-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-emerald-600 dark:text-emerald-400 font-semibold&quot;&gt;PASS&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-emerald-600 dark:text-emerald-400 mt-1&quot;&gt;${passCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-rose-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-rose-600 dark:text-rose-400 font-semibold&quot;&gt;FAIL&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-rose-600 dark:text-rose-400 mt-1&quot;&gt;${failCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-amber-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-amber-600 dark:text-amber-400 font-semibold&quot;&gt;REVIEW&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-amber-600 dark:text-amber-400 mt-1&quot;&gt;${reviewCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-sky-500/30 rounded-2xl p-4 col-span-2 lg:col-span-1&quot;&gt;<br>            &lt;div class=&quot;text-xs text-sky-600 dark:text-sky-400 font-semibold&quot;&gt;PENDING&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-sky-600 dark:text-sky-400 mt-1&quot;&gt;${pendingCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Validation Status Distribution&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-validation-dist&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Main Page Net Totals (Expected vs Actual)&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-page-financials&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;QA Execution &amp; Defects&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-qa-health&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 overflow-x-auto&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between mb-4&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Main Pages Validation Matrix&lt;/h3&gt;<br>              &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;text-xs font-semibold text-brand-500 hover:underline&quot;&gt;+ Add Main Page&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Gross&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;CWT&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Net Actual&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; {<br>                  const fin = mp.validationSummary.financials;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-semibold&quot;&gt;${escapeHtml(mp.name)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;&lt;span class=&quot;text-amber-500&quot;&gt;None&lt;/span&gt;&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono font-bold&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(mp.validationSummary.overallStatus)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right&quot;&gt;<br>                        &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;); navigateTo(&#39;validation&#39;);&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 hover:bg-brand-500/20 font-semibold&quot;&gt;Inspect&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-4&quot;&gt;Recent Audit Activity&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-3 max-h-72 overflow-y-auto pr-1&quot;&gt;<br>              ${(proj.activityLog || []).slice(0, 12).map(item =&gt; `<br>                &lt;div class=&quot;flex items-start gap-2.5 text-xs border-b border-slate-100 dark:border-slate-800/60 pb-2.5&quot;&gt;<br>                  &lt;span class=&quot;w-2 h-2 rounded-full bg-brand-500 mt-1.5 shrink-0&quot;&gt;&lt;/span&gt;<br>                  &lt;div class=&quot;min-w-0 flex-1&quot;&gt;<br>                    &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(item.action)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 truncate&quot;&gt;${escapeHtml(item.detail)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-[10px] text-slate-400 mt-0.5&quot;&gt;${new Date(item.timestamp).toLocaleString()}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderKpiCard(label, value, icon, colorClass) {<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex items-center justify-between&quot;&gt;<br>          &lt;div&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;${escapeHtml(label)}&lt;/div&gt;<br>            &lt;div class=&quot;text-xl font-extrabold mt-1&quot;&gt;${escapeHtml(value)}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;w-10 h-10 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center ${colorClass}&quot;&gt;<br>            &lt;i data-lucide=&quot;${icon}&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initDashboardCharts() {<br>      const proj = getActiveProject();<br>      if (!proj || !window.Chart) return;<br><br>      let pass = 0, fail = 0, review = 0, pending = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        pass += mp.validationSummary.counts.pass;<br>        fail += mp.validationSummary.counts.fail;<br>        review += mp.validationSummary.counts.review;<br>        pending += mp.validationSummary.counts.pending;<br>      });<br><br>      const ctx1 = document.getElementById(&#39;chart-validation-dist&#39;);<br>      if (ctx1) {<br>        chartInstances.dist = new Chart(ctx1, {<br>          type: &#39;doughnut&#39;,<br>          data: {<br>            labels: [&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;],<br>            datasets: [{<br>              data: [pass, fail, review, pending],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f59e0b&#39;, &#39;#0ea5e9&#39;],<br>              borderWidth: 0<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: &#39;bottom&#39;, labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx2 = document.getElementById(&#39;chart-page-financials&#39;);<br>      if (ctx2) {<br>        chartInstances.fin = new Chart(ctx2, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: proj.mainPages.map(p =&gt; p.name.split(&#39;:&#39;)[0]),<br>            datasets: [<br>              { label: &#39;Expected Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.expectedNet), backgroundColor: &#39;#6366f1&#39;, borderRadius: 6 },<br>              { label: &#39;Actual Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.actualNet), backgroundColor: &#39;#10b981&#39;, borderRadius: 6 }<br>            ]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39; } } }, plugins: { legend: { labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx3 = document.getElementById(&#39;chart-qa-health&#39;);<br>      if (ctx3) {<br>        const tcPass = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>        const tcFail = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>        const defOpen = (proj.defects || []).filter(d =&gt; d.status === &#39;Open&#39;).length;<br>        const defClosed = (proj.defects || []).filter(d =&gt; d.status === &#39;Closed&#39;).length;<br>        chartInstances.qa = new Chart(ctx3, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: [&#39;TC Pass&#39;, &#39;TC Fail&#39;, &#39;Open Defects&#39;, &#39;Closed Defects&#39;],<br>            datasets: [{<br>              label: &#39;Count&#39;,<br>              data: [tcPass, tcFail, defOpen, defClosed],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f97316&#39;, &#39;#64748b&#39;],<br>              borderRadius: 6<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39;, stepSize: 1 } } } }<br>        });<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2 VIEW: PROJECT MANAGEMENT<br>     ****************************************************************************/<br>    let projectSearchQuery = &#39;&#39;;<br><br>    function renderProjectsModule() {<br>      const filtered = appState.projects.filter(p =&gt;<br>        p.name.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.reference.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.owner.toLowerCase().includes(projectSearchQuery.toLowerCase())<br>      );<br><br>      return `<br>        &lt;div class=&quot;flex flex-col sm:flex-row sm:items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;relative flex-1 max-w-md&quot;&gt;<br>            &lt;i data-lucide=&quot;search&quot; class=&quot;w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(projectSearchQuery)}&quot; oninput=&quot;projectSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search projects by name, reference, or owner...&quot; class=&quot;w-full pl-10 pr-4 py-2.5 rounded-xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-xl text-xs font-semibold bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Import Project JSON&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.json&quot; onchange=&quot;importProjectJson(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;openCreateProjectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Project&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5&quot;&gt;<br>          ${filtered.map(proj =&gt; {<br>            const isActive = proj.id === appState.activeProjectId;<br>            return `<br>              &lt;div class=&quot;bg-white dark:bg-slate-900 border ${isActive ? &#39;border-brand-500 ring-2 ring-brand-500/20&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 flex flex-col justify-between gap-4&quot;&gt;<br>                &lt;div class=&quot;space-y-2.5&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] px-2.5 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>                    &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                      ${isActive ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-brand-500/15 text-brand-500&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      ${proj.archived ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/15 text-amber-500&quot;&gt;ARCHIVED&lt;/span&gt;&#39; : &#39;&#39;}<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;h3 class=&quot;font-bold text-base leading-snug&quot;&gt;${escapeHtml(proj.name)}&lt;/h3&gt;<br>                  &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400 line-clamp-2&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>                  &lt;div class=&quot;grid grid-cols-3 gap-2 pt-2 text-center&quot;&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${proj.mainPages.length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Main Pages&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.testCases || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Test Cases&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.defects || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Defects&lt;/div&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;text-[11px] text-slate-400 pt-1&quot;&gt;<br>                    Owner: &lt;span class=&quot;text-slate-600 dark:text-slate-300 font-medium&quot;&gt;${escapeHtml(proj.owner)}&lt;/span&gt; • Updated ${new Date(proj.lastModified).toLocaleDateString()}<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;pt-3 border-t border-slate-100 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;button onclick=&quot;switchActiveProject(&#39;${proj.id}&#39;); navigateTo(&#39;dashboard&#39;);&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                    Open Workspace<br>                  &lt;/button&gt;<br>                  &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                    &lt;button onclick=&quot;openRenameProjectModal(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Rename Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;pencil&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;duplicateProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Duplicate Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;exportProjectJson(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Export Project JSON&quot;&gt;<br>                      &lt;i data-lucide=&quot;download&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;toggleArchiveProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Archive / Unarchive&quot;&gt;<br>                      &lt;i data-lucide=&quot;archive&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;confirmDeleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-rose-500/10 text-rose-500&quot; title=&quot;Delete Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openCreateProjectModal() {<br>      openModal({<br>        title: &#39;Create New EIS &amp; QA Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name *&lt;/label&gt;<br>              &lt;input id=&quot;new-proj-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Phase 2 — Regional Port Audit&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Reference&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-ref&quot; type=&quot;text&quot; value=&quot;PRJ-EIS-${Math.floor(1000 + Math.random() * 9000)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Owner / QA Lead&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-owner&quot; type=&quot;text&quot; value=&quot;QA Analyst&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Fee Template (Optional)&lt;/label&gt;<br>              &lt;select id=&quot;new-proj-template&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;&quot;&gt;Blank Main Page (No pre-configured fees)&lt;/option&gt;<br>                ${appState.templates.map(t =&gt; `&lt;option value=&quot;${t.id}&quot;&gt;${escapeHtml(t.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;new-proj-desc&quot; rows=&quot;2&quot; placeholder=&quot;Scope of receipt validation and QA evidence...&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;createNewProjectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;Create Project&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function createNewProjectFromModal() {<br>      const name = document.getElementById(&#39;new-proj-name&#39;).value.trim();<br>      if (!name) return showToast(&#39;Project name is required.&#39;, &#39;warning&#39;);<br>      const ref = document.getElementById(&#39;new-proj-ref&#39;).value.trim() || `PRJ-${Date.now()}`;<br>      const owner = document.getElementById(&#39;new-proj-owner&#39;).value.trim() || &#39;QA Tester&#39;;<br>      const desc = document.getElementById(&#39;new-proj-desc&#39;).value.trim();<br>      const tplId = document.getElementById(&#39;new-proj-template&#39;).value;<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br><br>      const now = new Date().toISOString();<br>      const firstPage = {<br>        id: &#39;mp_&#39; + Date.now(),<br>        name: &#39;MP-01: Primary Receipt Page&#39;,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: tpl ? tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;&#39;<br>        })) : [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(firstPage);<br><br>      const proj = {<br>        id: &#39;proj_&#39; + Date.now(),<br>        name,<br>        reference: ref,<br>        description: desc || &#39;EIS Receipt Validation &amp; QA Evidence Workspace&#39;,<br>        owner,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [firstPage],<br>        screenshots: [],<br>        mergeHistory: [],<br>        testCases: [],<br>        defects: [],<br>        activityLog: [{ timestamp: now, action: &#39;Project Created&#39;, detail: `Created ${name}` }]<br>      };<br><br>      appState.projects.unshift(proj);<br>      appState.activeProjectId = proj.id;<br>      appState.activeMainPageId = firstPage.id;<br>      closeModal();<br>      scheduleAutosave(&#39;Created project&#39;);<br>      showToast(`Created project &quot;${name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function openRenameProjectModal(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      openModal({<br>        title: &#39;Rename Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name&lt;/label&gt;<br>              &lt;input id=&quot;rename-proj-input&quot; type=&quot;text&quot; value=&quot;${escapeHtml(proj.name)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;rename-proj-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;${escapeHtml(proj.description)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveProjectRename(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Changes&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveProjectRename(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      const val = document.getElementById(&#39;rename-proj-input&#39;).value.trim();<br>      if (!val) return showToast(&#39;Project name cannot be empty.&#39;, &#39;warning&#39;);<br>      proj.name = val;<br>      proj.description = document.getElementById(&#39;rename-proj-desc&#39;).value.trim();<br>      closeModal();<br>      scheduleAutosave(&#39;Renamed project&#39;);<br>      showToast(&#39;Project updated.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateProject(projId) {<br>      const orig = appState.projects.find(p =&gt; p.id === projId);<br>      if (!orig) return;<br>      const copy = JSON.parse(JSON.stringify(orig));<br>      copy.id = &#39;proj_&#39; + Date.now();<br>      copy.name = orig.name + &#39; (Copy)&#39;;<br>      copy.reference = orig.reference + &#39;-COPY&#39;;<br>      copy.createdAt = new Date().toISOString();<br>      copy.lastModified = copy.createdAt;<br>      appState.projects.unshift(copy);<br>      scheduleAutosave(&#39;Duplicated project&#39;);<br>      showToast(`Duplicated &quot;${orig.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function toggleArchiveProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      proj.archived = !proj.archived;<br>      proj.status = proj.archived ? &#39;Archived&#39; : &#39;Active&#39;;<br>      scheduleAutosave(&#39;Toggled archive&#39;);<br>      showToast(proj.archived ? &#39;Project archived.&#39; : &#39;Project restored.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function confirmDeleteProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      if (appState.projects.length &lt;= 1) {<br>        return showToast(&#39;Cannot delete the only remaining project.&#39;, &#39;warning&#39;);<br>      }<br>      openModal({<br>        title: &#39;Confirm Project Deletion&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to permanently delete &lt;strong&gt;${escapeHtml(proj.name)}&lt;/strong&gt; (${proj.mainPages.length} Main Pages, receipts, and QA evidence)? This action cannot be undone unless you have exported a JSON backup.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;deleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete Permanently&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function deleteProject(projId) {<br>      appState.projects = appState.projects.filter(p =&gt; p.id !== projId);<br>      if (appState.activeProjectId === projId) {<br>        appState.activeProjectId = appState.projects[0].id;<br>        appState.activeMainPageId = appState.projects[0].mainPages[0]?.id || null;<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted project&#39;);<br>      showToast(&#39;Project deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportProjectJson(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId) || getActiveProject();<br>      if (!proj) return;<br>      const exportObj = {<br>        SMARTExportVersion: APP_SCHEMA_VERSION,<br>        exportedAt: new Date().toISOString(),<br>        project: proj<br>      };<br>      const blob = new Blob([JSON.stringify(exportObj, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `${proj.reference || &#39;SMART_project&#39;}_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full project JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function importProjectJson(event) {<br>      const file = event.target.files[0];<br>      if (!file) return;<br>      const reader = new FileReader();<br>      reader.onload = (e) =&gt; {<br>        try {<br>          const parsed = JSON.parse(e.target.result);<br>          const importedProj = parsed.project || parsed;<br>          if (!importedProj || !importedProj.name || !Array.isArray(importedProj.mainPages)) {<br>            throw new Error(&#39;Invalid SMART project JSON schema.&#39;);<br>          }<br>          importedProj.id = &#39;proj_&#39; + Date.now();<br>          importedProj.lastModified = new Date().toISOString();<br>          importedProj.mainPages.forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>            ValidationEngine.validateMainPage(mp);<br>          });<br>          appState.projects.unshift(importedProj);<br>          appState.activeProjectId = importedProj.id;<br>          appState.activeMainPageId = importedProj.mainPages[0]?.id || null;<br>          scheduleAutosave(&#39;Imported project JSON&#39;);<br>          showToast(`Imported &quot;${importedProj.name}&quot; successfully!`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;Import failed: &#39; + err.message, &#39;error&#39;);<br>        }<br>      };<br>      reader.readAsText(file);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 3 VIEW: MAIN PAGE MANAGEMENT (1-50+ Fields, Per-Page Dynamic Row &amp; Fees)<br>     ****************************************************************************/<br>    let fieldSearchQuery = &#39;&#39;;<br>    let showAll50Fields = false;<br>    let mainPageQuickListSearch = &#39;&#39;;<br><br>    function renderMainPagesModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page found.&lt;/div&gt;`;<br><br>      const fin = page.validationSummary ? page.validationSummary.financials : FinancialCalculator.calculateTotals(page.fees);<br>      const visibleFields = page.fields.filter(f =&gt; {<br>        if (!showAll50Fields &amp;&amp; !f.enabled &amp;&amp; f.number &gt; 10) return false;<br>        if (!fieldSearchQuery) return true;<br>        const q = fieldSearchQuery.toLowerCase();<br>        return String(f.number).includes(q) || f.name.toLowerCase().includes(q) || String(f.expectedValue).toLowerCase().includes(q) || String(f.actualValue).toLowerCase().includes(q);<br>      });<br><br>      const isRowPasteEnabled = page.rowPasteEnabled !== false;<br>      const pageRowInput = page.rowPasteInput || &#39;&#39;;<br>      const pageRowHasHeaders = Boolean(page.rowPasteHasHeaders);<br>      const parsedPreview = RowToFieldsEngine.parseSpreadsheetRow(pageRowInput, pageRowHasHeaders);<br><br>      return `<br>        &lt;!-- Main Page Selector Tabs --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2 overflow-x-auto pb-1 max-w-full&quot;&gt;<br>              ${proj.mainPages.map(mp =&gt; {<br>                const active = mp.id === page.id;<br>                const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>                return `<br>                  &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold border transition flex items-center gap-2 shrink-0 ${<br>                    active<br>                      ? &#39;bg-brand-600 text-white border-brand-600 shadow-sm&#39;<br>                      : &#39;bg-slate-50 dark:bg-slate-800/70 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>                  }&quot;&gt;<br>                    &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                    &lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold ${active ? &#39;bg-white/20 text-white&#39; : &#39;bg-slate-200 dark:bg-slate-700&#39;}&quot;&gt;${st}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center gap-2 shrink-0&quot;&gt;<br>              &lt;button onclick=&quot;addNewMainPage()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;New Main Page&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;toggleMainPageQuickList()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition ${<br>                appState.ui.mainPageQuickListOpen<br>                  ? &#39;bg-indigo-600 text-white border-indigo-600 shadow-sm&#39;<br>                  : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>              }&quot; title=&quot;View all Main Page tabs in a quick list with Select All &amp; Delete All&quot;&gt;<br>                &lt;i data-lucide=&quot;list-checks&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick List (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;duplicateActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Duplicate Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>              ${proj.mainPages.length &gt; 1 ? `<br>                &lt;button onclick=&quot;deleteActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-rose-500/30 text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete Main Page&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${appState.ui.mainPageQuickListOpen ? renderMainPageQuickListPanel(proj, page) : &#39;&#39;}<br><br>          &lt;!-- Isolated Main Page Metadata --&gt;<br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-3 gap-3 pt-2 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Main Page Name (Isolated Record)&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.name)}&quot; onchange=&quot;updateMainPageMeta(&#39;name&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;md:col-span-2&quot;&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Page Scenario Description&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.description)}&quot; onchange=&quot;updateMainPageMeta(&#39;description&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- 1-Row Spreadsheet-to-Columns Expected Output Paste Studio (Per-Page Dynamic Config) --&gt;<br>        &lt;div class=&quot;bg-gradient-to-br from-brand-500/5 via-white to-indigo-500/5 dark:from-brand-950/30 dark:via-slate-900 dark:to-indigo-950/20 border ${isRowPasteEnabled ? &#39;border-brand-500/30&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 space-y-4 shadow-sm transition&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-start justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap mb-1&quot;&gt;<br>                &lt;span class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-brand-600/15 text-brand-600 dark:text-brand-400&quot;&gt;<br>                  &lt;i data-lucide=&quot;table-2&quot; class=&quot;w-3 h-3&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;Per-Page Dynamic Row Mapper • ${escapeHtml(page.name)}&lt;/span&gt;<br>                &lt;/span&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[11px] font-semibold border cursor-pointer ${isRowPasteEnabled ? &#39;bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${isRowPasteEnabled ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteConfig(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;${isRowPasteEnabled ? &#39;Enabled for this page&#39; : &#39;Not Applicable for this page&#39;}&lt;/span&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Paste Expected Receipt Row (Excel / Sheets / CSV / Pipe)&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;${isRowPasteEnabled<br>                ? &#39;Independent dynamic configuration for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Custom column names are preserved by default; header-based renaming is opt-in.&#39;<br>                : &#39;Row-paste mapping is marked &lt;strong&gt;Not Applicable&lt;/strong&gt; for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Toggle above if this page uses spreadsheet row expectations.&#39;}&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            ${isRowPasteEnabled ? `<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap&quot;&gt;<br>                &lt;button onclick=&quot;saveFieldSchemaAsTemplate()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:border-brand-500/50&quot;&gt;<br>                  Save Column Names as Template<br>                &lt;/button&gt;<br>                &lt;button onclick=&quot;clearExpectedRowValues()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold text-rose-600 dark:text-rose-400 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;<br>                  Clear This Page&#39;s Row<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          ${isRowPasteEnabled ? `<br>            &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-4&quot;&gt;<br>              &lt;div class=&quot;lg:col-span-6 space-y-2.5&quot;&gt;<br>                &lt;textarea id=&quot;row-to-fields-textarea&quot; rows=&quot;3&quot; oninput=&quot;updatePageRowPasteInput(this.value)&quot; placeholder=&quot;Paste 1 dynamic row for ${escapeHtml(page.name)} (Tab-separated, CSV, or Pipe):&amp;#10;INV-2026-88410 2026-11-15 004-892-110-000 APEX GLOBAL PHP 1250.00 50.00 1200.00&quot; class=&quot;w-full p-3 rounded-xl bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-700 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;${escapeHtml(pageRowInput)}&lt;/textarea&gt;<br><br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${pageRowHasHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;First pasted row contains column headers&lt;/span&gt;<br>                  &lt;/label&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${page.autoRenameFieldsFromHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleAutoRenameFieldsFromHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;Allow pasted headers to rename my fields&lt;/span&gt;<br>                  &lt;/label&gt;<br><br>                  &lt;button onclick=&quot;applyPastedRowToMainPageFields()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>                    &lt;i data-lucide=&quot;arrow-down-to-line&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;span&gt;Apply Dynamic Row to ${escapeHtml(page.name.split(&#39;:&#39;)[0])}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br><br>              &lt;!-- Live Column -&gt; Field Preview --&gt;<br>              &lt;div class=&quot;lg:col-span-6 bg-white/80 dark:bg-slate-950/70 border border-slate-200 dark:border-slate-800 rounded-xl p-3 flex flex-col justify-between&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between mb-2&quot;&gt;<br>                  &lt;span class=&quot;text-[11px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Live Dynamic Mapping Preview (${parsedPreview.values.length} cols • ${parsedPreview.delimiter})&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div id=&quot;row-paste-preview-grid&quot; class=&quot;flex flex-wrap gap-1.5 max-h-28 overflow-y-auto&quot;&gt;<br>                  ${renderRowPastePreviewChips(page, parsedPreview)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          ` : &#39;&#39;}<br>        &lt;/div&gt;<br><br>        &lt;!-- EIS Fee &amp; CWT Configuration Engine --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;EIS Fee &amp; CWT Line-Item Configuration&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Independent Fee Name, Amount &amp; Code per row. CWT deducts absolute magnitude without double-counting in Gross Fees.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;openQuickPasteFeeModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/20&quot;&gt;<br>                &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick Paste Fees&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(false)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add Fee&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30 hover:bg-amber-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;minus-circle&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add CWT&lt;/span&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-10&quot;&gt;#&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Fee Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Amount&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Amt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${page.fees.length === 0 ? `<br>                  &lt;tr&gt;&lt;td colspan=&quot;10&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No fees configured yet. Click &lt;strong&gt;Add Fee&lt;/strong&gt; or &lt;strong&gt;Quick Paste Fees&lt;/strong&gt;.&lt;/td&gt;&lt;/tr&gt;<br>                ` : page.fees.map((fee, idx) =&gt; {<br>                  const isCwt = FinancialCalculator.isCwtEntry(fee);<br>                  const st = fee.lastValidation ? fee.lastValidation.status : &#39;PENDING&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-slate-400&quot;&gt;${idx + 1}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;button onclick=&quot;toggleFeeCwtFlag(&#39;${fee.id}&#39;)&quot; class=&quot;px-2 py-0.5 rounded text-[10px] font-bold border ${isCwt ? &#39;bg-amber-500/15 text-amber-500 border-amber-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-200 dark:border-slate-700&#39;}&quot; title=&quot;Click to toggle Fee vs CWT Deduction&quot;&gt;<br>                          ${isCwt ? &#39;CWT (-)&#39; : &#39;FEE (+)&#39;}<br>                        &lt;/button&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedName&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-medium&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedAmount&#39;, this.value)&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedCode&#39;, this.value)&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; placeholder=&quot;OCR / Receipt&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; placeholder=&quot;0.00&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; placeholder=&quot;Code&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, -1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;&lt;i data-lucide=&quot;arrow-up&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, 1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;&lt;i data-lucide=&quot;arrow-down&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;duplicateFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Duplicate&quot;&gt;&lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;removeFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-rose-500 hover:bg-rose-500/10 rounded&quot; title=&quot;Remove&quot;&gt;&lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Gross Fees (Expected / Actual)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)} / &lt;span class=&quot;text-brand-500&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/span&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Total CWT Deduction (|CWT|)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Total (Gross - CWT)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-emerald-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Variance&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm ${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;} mt-0.5&quot;&gt;${fin.netDifference &gt; 0 ? &#39;+&#39; : &#39;&#39;}${fin.netDifference.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Configurable Columns / Numbered Main Page Fields (1-50+) --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Configurable Column Fields (1–${page.fields.length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;${proj.sharedHeaders ? &#39;&lt;strong class=&quot;text-emerald-500&quot;&gt;Shared headers ON:&lt;/strong&gt; names, Type and Req are the same on every Main Page, so editing here updates all pages. Values stay per page.&#39; : &#39;Edit professional field names directly. Names are saved per Main Page and stay unchanged when you paste rows unless header-based renaming is enabled above.&#39;}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold border cursor-pointer ${proj.sharedHeaders ? &#39;bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39; : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700&#39;}&quot; title=&quot;ON: the same Configurable Field / Column Names are used on every Main Page (new pages too). Values stay per page.&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; ${proj.sharedHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleSharedHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Same headers for all pages (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/label&gt;<br>              ${proj.sharedHeaders ? `&lt;button onclick=&quot;reapplySharedHeaders()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot; title=&quot;Push this page&#39;s headers to every Main Page again&quot;&gt;Re-apply to all&lt;/button&gt;` : &#39;&#39;}<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fieldSearchQuery)}&quot; oninput=&quot;fieldSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search fields...&quot; class=&quot;px-3 py-1.5 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;button onclick=&quot;showAll50Fields = !showAll50Fields; renderApp();&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;<br>                ${showAll50Fields ? &#39;Show Active / First 10&#39; : `Show All ${page.fields.length} Fields`}<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addMoreNumberedFields(10)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                + Add 10 More Fields<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto max-h-[420px]&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead class=&quot;sticky top-0 bg-white dark:bg-slate-900 z-10&quot;&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-14&quot;&gt;Col #&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Configurable Field / Column Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Req&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${visibleFields.map(f =&gt; {<br>                  const st = f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2 font-mono font-semibold text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.name)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;name&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-semibold&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;select onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;dataType&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700&quot;&gt;<br>                          ${[&#39;Dynamic&#39;, &#39;Text&#39;, &#39;Number&#39;, &#39;Currency&#39;, &#39;Date&#39;, &#39;Percentage&#39;, &#39;Code&#39;, &#39;Reference&#39;, &#39;Boolean&#39;].map(t =&gt; `&lt;option value=&quot;${t}&quot; ${f.dataType === t ? &#39;selected&#39; : &#39;&#39;}&gt;${t}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.expectedValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;expectedValue&#39;, this.value)&quot; placeholder=&quot;Expected&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; placeholder=&quot;Receipt value&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${f.required ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;required&#39;, this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderRowPastePreviewChips(page, parsed) {<br>      if (!parsed.values.length) {<br>        return `&lt;span class=&quot;text-xs text-slate-400 italic&quot;&gt;Paste a row on the left to preview how each column maps into C01, C02, C03...&lt;/span&gt;`;<br>      }<br>      return parsed.values.map((val, idx) =&gt; {<br>        const colNum = idx + 1;<br>        const existingField = page.fields[idx];<br>        const colName = parsed.headers[idx] || (existingField ? existingField.name : `Custom Field ${colNum}`);<br>        return `<br>          &lt;div class=&quot;px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot;&gt;<br>            &lt;div class=&quot;text-[10px] font-bold text-brand-500&quot;&gt;C${String(colNum).padStart(2, &#39;0&#39;)}: ${escapeHtml(colName)}&lt;/div&gt;<br>            &lt;div class=&quot;font-mono font-semibold truncate max-w-[160px]&quot;&gt;${escapeHtml(val || &#39;(blank)&#39;)}&lt;/div&gt;<br>          &lt;/div&gt;<br>        `;<br>      }).join(&#39;&#39;);<br>    }<br><br>    function updateRowPastePreviewOnly() {<br>      const page = getActiveMainPage();<br>      const grid = document.getElementById(&#39;row-paste-preview-grid&#39;);<br>      if (!page || !grid) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      grid.innerHTML = renderRowPastePreviewChips(page, parsed);<br>    }<br><br>    function togglePageRowPasteConfig(enabled) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteEnabled = Boolean(enabled);<br>      scheduleAutosave(`Updated row mapper config on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function updatePageRowPasteInput(val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteInput = val;<br>      updateRowPastePreviewOnly();<br>      scheduleAutosave(`Updated dynamic row input on ${page.name}`);<br>    }<br><br>    function togglePageRowPasteHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteHasHeaders = Boolean(checked);<br>      scheduleAutosave(`Toggled row headers on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function toggleAutoRenameFieldsFromHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.autoRenameFieldsFromHeaders = Boolean(checked);<br>      scheduleAutosave(&#39;Updated column header rename preference on &#39; + page.name);<br>      showToast(checked<br>        ? &#39;Pasted headers can now rename fields on this page.&#39;<br>        : &#39;Custom field names are protected from pasted headers.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyPastedRowToMainPageFields() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      if (!parsed.values.length) {<br>        return showToast(&#39;Paste at least 1 row of values first.&#39;, &#39;warning&#39;);<br>      }<br><br>      while (page.fields.length &lt; parsed.values.length) {<br>        const num = page.fields.length + 1;<br>        page.fields.push({<br>          id: `fld_${num}_${Date.now()}_${num}`,<br>          number: num,<br>          name: `Custom Field ${num}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: true,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${num}`,<br>          pageOverride: true,<br>          enabled: true<br>        });<br>      }<br><br>      parsed.values.forEach((val, idx) =&gt; {<br>        const fld = page.fields[idx];<br>        if (parsed.headers[idx] &amp;&amp; page.autoRenameFieldsFromHeaders === true) {<br>          fld.name = parsed.headers[idx];<br>        }<br>        fld.expectedValue = val;<br>        fld.enabled = true;<br>        fld.pageOverride = true;<br>        if (val !== &#39;&#39;) {<br>          fld.required = true;<br>          fld.dataType = &#39;Dynamic&#39;;<br>        }<br>      });<br><br>      pushSharedHeadersFrom(page);<br><br>      let matchInfo = &#39;&#39;;<br>      if (page.receipt &amp;&amp; page.receipt.ocrRawText) {<br>        const m = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>        matchInfo = ` • Auto-matched ${m.matched}/${m.total} against attached receipt`;<br>      } else {<br>        ValidationEngine.validateMainPage(page);<br>      }<br><br>      logActivity(&#39;Pasted Dynamic Row&#39;, `Applied ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`);<br>      scheduleAutosave(&#39;Applied dynamic expected row&#39;);<br>      showToast(`Mapped ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function clearExpectedRowValues() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fields.forEach(f =&gt; {<br>        f.expectedValue = &#39;&#39;;<br>        f.actualValue = &#39;&#39;;<br>        if (f.number &gt; 10) f.enabled = false;<br>      });<br>      page.rowPasteInput = &#39;&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Cleared expected row values&#39;);<br>      showToast(&#39;Cleared expected &amp; actual field values on &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function saveFieldSchemaAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const activeCols = page.fields.filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10);<br>      openModal({<br>        title: &#39;Save Configurable Column Names as Reusable Template&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Save your current &lt;strong&gt;${activeCols.length} configurable column headers&lt;/strong&gt; (plus any fee rows) so you can apply this exact column layout to future Main Pages with one click.&lt;/p&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Template Name&lt;/label&gt;<br>              &lt;input id=&quot;col-schema-tpl-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Standard 8-Column Export Layout&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmSaveFieldSchemaTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Schema Template&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmSaveFieldSchemaTemplate() {<br>      const page = getActiveMainPage();<br>      const name = document.getElementById(&#39;col-schema-tpl-name&#39;).value.trim();<br>      if (!page || !name) return showToast(&#39;Enter a template name.&#39;, &#39;warning&#39;);<br><br>      const activeCols = page.fields<br>        .filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10)<br>        .map(f =&gt; ({ number: f.number, name: f.name, dataType: f.dataType, required: f.required }));<br><br>      appState.templates.push({<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name,<br>        description: `${activeCols.length} configured columns + ${page.fees.length} fee rows`,<br>        columns: activeCols,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Saved column schema template&#39;);<br>      showToast(`Saved template &quot;${name}&quot;`, &#39;success&#39;);<br>    }<br><br>    function renderMainPageQuickListPanel(proj, activePage, closeHandler = &#39;toggleMainPageQuickList()&#39;, boxCountFn = null) {<br>      const selectedIds = new Set((appState.ui.selectedMainPageIds || []).filter(id =&gt; proj.mainPages.some(mp =&gt; mp.id === id)));<br>      const q = (mainPageQuickListSearch || &#39;&#39;).trim().toLowerCase();<br>      const filteredPages = proj.mainPages.filter(mp =&gt;<br>        !q ||<br>        mp.name.toLowerCase().includes(q) ||<br>        (mp.description || &#39;&#39;).toLowerCase().includes(q)<br>      );<br>      const allFilteredSelected = filteredPages.length &gt; 0 &amp;&amp; filteredPages.every(mp =&gt; selectedIds.has(mp.id));<br><br>      return `<br>        &lt;div class=&quot;rounded-xl border border-indigo-500/30 bg-slate-50/90 dark:bg-slate-950/80 p-3.5 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>              &lt;span class=&quot;text-xs font-bold text-indigo-600 dark:text-indigo-400 flex items-center gap-1.5&quot;&gt;<br>                &lt;i data-lucide=&quot;layers&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;All Main Page Tabs (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/span&gt;<br>              &lt;span class=&quot;text-[11px] px-2 py-0.5 rounded-full bg-slate-200 dark:bg-slate-800 font-semibold&quot;&gt;<br>                ${selectedIds.size} selected<br>              &lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;div class=&quot;relative&quot;&gt;<br>                &lt;i data-lucide=&quot;search&quot; class=&quot;w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(mainPageQuickListSearch)}&quot; oninput=&quot;mainPageQuickListSearch = this.value; renderApp();&quot; placeholder=&quot;Filter tabs...&quot; class=&quot;pl-8 pr-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-xs w-44 focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;button onclick=&quot;selectAllMainPagesInQuickList()&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:border-brand-500/50&quot;&gt;<br>                ${allFilteredSelected ? &#39;Deselect All&#39; : &#39;Select All&#39;}<br>              &lt;/button&gt;<br><br>              ${selectedIds.size &gt; 0 ? `<br>                &lt;button onclick=&quot;deleteSelectedMainPages()&quot; class=&quot;inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white shadow-xs&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;${selectedIds.size === proj.mainPages.length ? &#39;Delete All (&#39; + selectedIds.size + &#39;)&#39; : &#39;Delete Selected (&#39; + selectedIds.size + &#39;)&#39;}&lt;/span&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br><br>              &lt;button onclick=&quot;confirmDeleteAllMainPages()&quot; class=&quot;inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-rose-500/40 text-rose-600 dark:text-rose-400 hover:bg-rose-500/10&quot; title=&quot;Delete all tabs and reset to a single clean Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;trash&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Delete All&lt;/span&gt;<br>              &lt;/button&gt;<br><br>              &lt;button onclick=&quot;${closeHandler}&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-800&quot; title=&quot;Close Quick List&quot;&gt;<br>                &lt;i data-lucide=&quot;x&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;max-h-60 overflow-y-auto divide-y divide-slate-200/70 dark:divide-slate-800 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900&quot;&gt;<br>            ${filteredPages.length === 0 ? `<br>              &lt;div class=&quot;py-6 text-center text-xs text-slate-400&quot;&gt;No tabs match &quot;${escapeHtml(mainPageQuickListSearch)}&quot;.&lt;/div&gt;<br>            ` : filteredPages.map((mp) =&gt; {<br>              const isCurrent = mp.id === activePage.id;<br>              const isChecked = selectedIds.has(mp.id);<br>              const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>              const realIndex = proj.mainPages.findIndex(item =&gt; item.id === mp.id) + 1;<br>              return `<br>                &lt;div class=&quot;flex items-center justify-between gap-3 px-3 py-2 text-xs transition ${isCurrent ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                  &lt;div class=&quot;flex items-center gap-2.5 min-w-0 flex-1&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleMainPageQuickSelect(&#39;${mp.id}&#39;)&quot; class=&quot;rounded text-brand-600 cursor-pointer shrink-0&quot; /&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] text-slate-400 shrink-0&quot;&gt;#${realIndex}&lt;/span&gt;<br>                    &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;text-left min-w-0 flex-1 group&quot;&gt;<br>                      &lt;div class=&quot;font-semibold truncate group-hover:text-brand-500 transition flex items-center gap-2&quot;&gt;<br>                        &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                        ${isCurrent ? &#39;&lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold bg-brand-600 text-white&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      &lt;/div&gt;<br>                      &lt;div class=&quot;text-[11px] text-slate-400 truncate&quot;&gt;<br>                        ${mp.fees.length} fees • ${boxCountFn ? boxCountFn(mp) + &#39; QA boxes • &#39; : &#39;&#39;}${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;No receipt&#39;} ${mp.description ? &#39;• &#39; + escapeHtml(mp.description) : &#39;&#39;}<br>                      &lt;/div&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br><br>                  &lt;div class=&quot;flex items-center gap-2 shrink-0&quot;&gt;<br>                    ${statusBadge(st)}<br>                    &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-brand-600 hover:text-white transition&quot;&gt;<br>                      Open<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;deleteSingleMainPageFromList(&#39;${mp.id}&#39;)&quot; class=&quot;p-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete this tab&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            }).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function toggleMainPageQuickList() {<br>      appState.ui.mainPageQuickListOpen = !appState.ui.mainPageQuickListOpen;<br>      renderApp();<br>    }<br><br>    function toggleMainPageQuickSelect(pageId) {<br>      appState.ui.selectedMainPageIds = appState.ui.selectedMainPageIds || [];<br>      const idx = appState.ui.selectedMainPageIds.indexOf(pageId);<br>      if (idx &gt;= 0) appState.ui.selectedMainPageIds.splice(idx, 1);<br>      else appState.ui.selectedMainPageIds.push(pageId);<br>      renderApp();<br>    }<br><br>    function selectAllMainPagesInQuickList() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const q = (mainPageQuickListSearch || &#39;&#39;).trim().toLowerCase();<br>      const targetIds = proj.mainPages<br>        .filter(mp =&gt; !q || mp.name.toLowerCase().includes(q) || (mp.description || &#39;&#39;).toLowerCase().includes(q))<br>        .map(mp =&gt; mp.id);<br><br>      const currentSet = new Set(appState.ui.selectedMainPageIds || []);<br>      const allSelected = targetIds.length &gt; 0 &amp;&amp; targetIds.every(id =&gt; currentSet.has(id));<br>      if (allSelected) {<br>        targetIds.forEach(id =&gt; currentSet.delete(id));<br>      } else {<br>        targetIds.forEach(id =&gt; currentSet.add(id));<br>      }<br>      appState.ui.selectedMainPageIds = Array.from(currentSet);<br>      renderApp();<br>    }<br><br>    function createFreshDefaultMainPage(index = 1) {<br>      const fresh = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + index,<br>        name: `MP-0${index}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      applySharedSchemaToPage(getActiveProject(), fresh);<br>      ValidationEngine.validateMainPage(fresh);<br>      return fresh;<br>    }<br><br>    function deleteSingleMainPageFromList(pageId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const target = proj.mainPages.find(mp =&gt; mp.id === pageId);<br>      if (!target) return;<br><br>      if (proj.mainPages.length &lt;= 1) {<br>        openModal({<br>          title: &#39;Reset Last Main Page&#39;,<br>          bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;&lt;strong&gt;${escapeHtml(target.name)}&lt;/strong&gt; is the only remaining tab. Deleting it will replace it with a clean blank &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;. Continue?&lt;/p&gt;`,<br>          footerHtml: `<br>            &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>            &lt;button onclick=&quot;executeBulkDeleteMainPages([&#39;${pageId}&#39;])&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Reset Tab&lt;/button&gt;<br>          `<br>        });<br>        return;<br>      }<br><br>      proj.mainPages = proj.mainPages.filter(mp =&gt; mp.id !== pageId);<br>      appState.ui.selectedMainPageIds = (appState.ui.selectedMainPageIds || []).filter(id =&gt; id !== pageId);<br>      if (appState.activeMainPageId === pageId) {<br>        appState.activeMainPageId = proj.mainPages[0].id;<br>      }<br>      logActivity(&#39;Deleted Main Page&#39;, target.name);<br>      scheduleAutosave(&#39;Deleted Main Page from Quick List&#39;);<br>      showToast(`Deleted &quot;${target.name}&quot;`, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function deleteSelectedMainPages() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const toDelete = (appState.ui.selectedMainPageIds || []).filter(id =&gt; proj.mainPages.some(mp =&gt; mp.id === id));<br>      if (!toDelete.length) return showToast(&#39;Select at least one tab first.&#39;, &#39;warning&#39;);<br><br>      const deletingAll = toDelete.length &gt;= proj.mainPages.length;<br>      openModal({<br>        title: deletingAll ? &#39;Delete All Main Page Tabs&#39; : `Delete ${toDelete.length} Selected Tab(s)`,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;${<br>          deletingAll<br>            ? `Delete all &lt;strong&gt;${proj.mainPages.length}&lt;/strong&gt; Main Page tabs and start fresh with a clean &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;?`<br>            : `Permanently delete &lt;strong&gt;${toDelete.length}&lt;/strong&gt; selected Main Page tab(s) along with their attached receipts and fee rules?`<br>        }&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;executeBulkDeleteMainPages(${escapeHtml(JSON.stringify(toDelete))})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Confirm Delete&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteAllMainPages() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const allIds = proj.mainPages.map(mp =&gt; mp.id);<br>      openModal({<br>        title: &#39;Delete All Main Page Tabs&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to delete all &lt;strong&gt;${allIds.length}&lt;/strong&gt; Main Page tab(s) and reset to a single clean &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;executeBulkDeleteMainPages(${escapeHtml(JSON.stringify(allIds))})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete All Tabs&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function executeBulkDeleteMainPages(idsToDelete) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const removeSet = new Set(idsToDelete || []);<br>      const removedCount = proj.mainPages.filter(mp =&gt; removeSet.has(mp.id)).length;<br>      proj.mainPages = proj.mainPages.filter(mp =&gt; !removeSet.has(mp.id));<br><br>      if (proj.mainPages.length === 0) {<br>        proj.mainPages.push(createFreshDefaultMainPage(1));<br>      }<br><br>      if (!proj.mainPages.some(mp =&gt; mp.id === appState.activeMainPageId)) {<br>        appState.activeMainPageId = proj.mainPages[0].id;<br>      }<br><br>      appState.ui.selectedMainPageIds = [];<br>      closeModal();<br>      logActivity(&#39;Bulk Deleted Main Pages&#39;, `Removed ${removedCount} tab(s)`);<br>      scheduleAutosave(&#39;Bulk deleted Main Pages&#39;);<br>      showToast(`Deleted ${removedCount} Main Page tab(s).`, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function addNewMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const idx = proj.mainPages.length + 1;<br>      const newPage = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + idx,<br>        name: `MP-0${idx}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      applySharedSchemaToPage(proj, newPage);<br>      ValidationEngine.validateMainPage(newPage);<br>      proj.mainPages.push(newPage);<br>      appState.activeMainPageId = newPage.id;<br>      logActivity(&#39;Added Main Page&#39;, newPage.name);<br>      scheduleAutosave(&#39;Added Main Page&#39;);<br>      showToast(`Created ${newPage.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      const copy = JSON.parse(JSON.stringify(page));<br>      copy.id = &#39;mp_&#39; + Date.now();<br>      copy.name = page.name + &#39; (Copy)&#39;;<br>      proj.mainPages.push(copy);<br>      appState.activeMainPageId = copy.id;<br>      scheduleAutosave(&#39;Duplicated Main Page&#39;);<br>      showToast(`Duplicated &quot;${page.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function deleteActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page || proj.mainPages.length &lt;= 1) return;<br>      openModal({<br>        title: &#39;Delete Main Page&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Delete &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; and its attached receipt &amp; fee rules?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmDeleteMainPage(&#39;${page.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Delete Page&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteMainPage(pageId) {<br>      const proj = getActiveProject();<br>      proj.mainPages = proj.mainPages.filter(p =&gt; p.id !== pageId);<br>      appState.activeMainPageId = proj.mainPages[0].id;<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted Main Page&#39;);<br>      showToast(&#39;Main Page deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function updateMainPageMeta(key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page[key] = val;<br>      scheduleAutosave(&#39;Updated Main Page metadata&#39;);<br>      renderApp();<br>    }<br><br>    function addFeeRow(isCwt = false) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const idx = page.fees.length + 1;<br>      page.fees.push({<br>        id: &#39;fee_&#39; + Date.now() + &#39;_&#39; + idx,<br>        expectedName: isCwt ? &#39;CWT&#39; : `Fee ${idx} Charge`,<br>        expectedAmount: isCwt ? &#39;50&#39; : &#39;100&#39;,<br>        expectedCode: isCwt ? &#39;CWT&#39; : &#39;NC&#39;,<br>        actualName: &#39;&#39;,<br>        actualAmount: &#39;&#39;,<br>        actualCode: &#39;&#39;,<br>        isCwt,<br>        ocrConfidence: null,<br>        sourceLocation: &#39;&#39;<br>      });<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Added fee row&#39;);<br>      renderApp();<br>    }<br><br>    function updateFeeField(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const fee = page.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee[key] = val;<br>      if (key === &#39;expectedCode&#39; &amp;&amp; val.trim().toUpperCase() === &#39;CWT&#39;) fee.isCwt = true;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated fee&#39;);<br>      renderApp();<br>    }<br><br>    function toggleFeeCwtFlag(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee.isCwt = !FinancialCalculator.isCwtEntry(fee);<br>      if (fee.isCwt &amp;&amp; !fee.expectedCode) fee.expectedCode = &#39;CWT&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Toggled CWT flag&#39;);<br>      renderApp();<br>    }<br><br>    function moveFeeRow(idx, dir) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const target = idx + dir;<br>      if (target &lt; 0 || target &gt;= page.fees.length) return;<br>      const temp = page.fees[idx];<br>      page.fees[idx] = page.fees[target];<br>      page.fees[target] = temp;<br>      scheduleAutosave(&#39;Reordered fees&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const copy = JSON.parse(JSON.stringify(fee));<br>      copy.id = &#39;fee_&#39; + Date.now();<br>      page.fees.push(copy);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Duplicated fee&#39;);<br>      renderApp();<br>    }<br><br>    function removeFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fees = page.fees.filter(f =&gt; f.id !== feeId);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Removed fee&#39;);<br>      renderApp();<br>    }<br><br>    function openQuickPasteFeeModal() {<br>      openModal({<br>        title: &#39;Quick Paste EIS Fees &amp; CWT&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Paste multi-line blocks (Name / Amount / Code) or pipe-delimited rows. CWT entries are automatically recognized.&lt;/p&gt;<br>            &lt;textarea id=&quot;quick-paste-fee-input&quot; rows=&quot;9&quot; placeholder=&quot;Fee 1 Charge&amp;#10;1000&amp;#10;NC&amp;#10;Fee 2 Charge&amp;#10;250&amp;#10;IC&amp;#10;CWT&amp;#10;50&quot; class=&quot;w-full p-3 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;div class=&quot;flex items-center gap-4 text-xs&quot;&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;expected&quot; checked /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Expected&lt;/strong&gt; Main Page Fees&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;actual&quot; /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Actual / Receipt&lt;/strong&gt; Values&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;applyQuickPasteFees()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Parse &amp; Apply Fees&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function applyQuickPasteFees() {<br>      const page = getActiveMainPage();<br>      const raw = document.getElementById(&#39;quick-paste-fee-input&#39;).value;<br>      const target = document.querySelector(&#39;input[name=&quot;qp-target&quot;]:checked&#39;)?.value || &#39;expected&#39;;<br>      const parsed = OcrMappingEngine.parseQuickPasteFees(raw);<br>      if (!parsed.length) return showToast(&#39;No valid fee rows detected.&#39;, &#39;warning&#39;);<br><br>      if (target === &#39;expected&#39;) {<br>        parsed.forEach((p, idx) =&gt; {<br>          page.fees.push({<br>            id: `fee_qp_${Date.now()}_${idx}`,<br>            expectedName: p.name,<br>            expectedAmount: p.amount,<br>            expectedCode: p.code,<br>            actualName: &#39;&#39;,<br>            actualAmount: &#39;&#39;,<br>            actualCode: &#39;&#39;,<br>            isCwt: p.isCwt,<br>            ocrConfidence: null,<br>            sourceLocation: &#39;Quick Paste&#39;<br>          });<br>        });<br>      } else {<br>        parsed.forEach((p, idx) =&gt; {<br>          if (page.fees[idx]) {<br>            page.fees[idx].actualName = p.name;<br>            page.fees[idx].actualAmount = p.amount;<br>            page.fees[idx].actualCode = p.code;<br>            page.fees[idx].sourceLocation = &#39;Quick Paste Receipt&#39;;<br>          } else {<br>            page.fees.push({<br>              id: `fee_qp_${Date.now()}_${idx}`,<br>              expectedName: p.name,<br>              expectedAmount: &#39;&#39;,<br>              expectedCode: p.code,<br>              actualName: p.name,<br>              actualAmount: p.amount,<br>              actualCode: p.code,<br>              isCwt: p.isCwt,<br>              ocrConfidence: 100,<br>              sourceLocation: &#39;Quick Paste Receipt&#39;<br>            });<br>          }<br>        });<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      closeModal();<br>      scheduleAutosave(&#39;Quick pasted fees&#39;);<br>      showToast(`Imported ${parsed.length} fee entries.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateNumberedField(fieldId, key, val) {<br>      const page = getActiveMainPage();<br>      const fld = page?.fields.find(f =&gt; f.id === fieldId);<br>      if (!fld) return;<br>      fld[key] = val;<br>      if (key === &#39;expectedValue&#39; || key === &#39;actualValue&#39;) fld.enabled = true;<br>      if (key === &#39;name&#39; || key === &#39;dataType&#39; || key === &#39;required&#39;) pushSharedHeadersFrom(page);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated numbered field&#39;);<br>      renderApp();<br>    }<br><br>    function addMoreNumberedFields(count = 10) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const start = page.fields.length + 1;<br>      for (let i = start; i &lt; start + count; i++) {<br>        page.fields.push({<br>          id: `fld_${i}_${Date.now()}`,<br>          number: i,<br>          name: `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: false,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: true<br>        });<br>      }<br>      showAll50Fields = true;<br>      pushSharedHeadersFrom(page);<br>      scheduleAutosave(&#39;Added numbered fields&#39;);<br>      showToast(`Added ${count} fields (Total: ${page.fields.length}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 4 VIEW: SIDE-BY-SIDE RECEIPT VALIDATION WORKSPACE<br>     ****************************************************************************/<br>    function renderValidationWorkspaceModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      if (!page.validationSummary) ValidationEngine.validateMainPage(page);<br>      const summary = page.validationSummary;<br>      const fin = summary.financials;<br>      const rec = page.receipt;<br>      const currentImg = rec &amp;&amp; rec.pages &amp;&amp; rec.pages[rec.currentPage - 1] ? rec.pages[rec.currentPage - 1] : null;<br>      const selectedRowId = appState.ui.selectedComparisonRowId;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[10px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Active Main Page (Isolated)&lt;/label&gt;<br>              &lt;select onchange=&quot;switchActiveMainPage(this.value)&quot; class=&quot;mt-0.5 text-xs font-bold bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-1.5&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; `&lt;option value=&quot;${mp.id}&quot; ${mp.id === page.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(mp.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;pt-3&quot;&gt;${statusBadge(summary.overallStatus)}&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;${rec ? &#39;Replace Receipt&#39; : &#39;Upload Receipt (PNG/JPG/WEBP/PDF)&#39;}&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.png,.jpg,.jpeg,.webp,.pdf,image/*,application/pdf&quot; onchange=&quot;handleReceiptUpload(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;pasteReceiptFromClipboardButton()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700&quot; title=&quot;Or press Ctrl+V / Cmd+V anywhere on this screen&quot;&gt;<br>              &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Paste Image (Ctrl+V)&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;evidence&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-violet-500/15 text-violet-600 dark:text-violet-400 border border-violet-500/30 hover:bg-violet-500/25&quot; title=&quot;Evidence screenshots of this Main Page. QA-n box value fills Expected Value or Found on Receipt of field Cn (toggle inside)&quot;&gt;<br>              &lt;i data-lucide=&quot;images&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Evidence Screenshots (${(page.evidenceShots || []).length})&lt;/span&gt;<br>            &lt;/button&gt;<br>            ${rec ? `<br>              &lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;scan-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Re-Run OCR &amp; Auto-Match&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;removeReceiptAttachment()&quot; class=&quot;p-2 rounded-xl text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Remove Receipt Attachment&quot;&gt;<br>                &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl flex flex-col overflow-hidden&quot;&gt;<br>            &lt;div class=&quot;px-4 py-3 border-b border-slate-200 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div class=&quot;text-xs font-bold flex items-center gap-2&quot;&gt;<br>                &lt;i data-lucide=&quot;file-check-2&quot; class=&quot;w-4 h-4 text-brand-500&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Original Receipt (${escapeHtml(page.name)})&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(-0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom Out&quot;&gt;&lt;i data-lucide=&quot;zoom-out&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;span class=&quot;text-[11px] font-mono px-1&quot;&gt;${Math.round(appState.ui.viewerZoom * 100)}%&lt;/span&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom In&quot;&gt;&lt;i data-lucide=&quot;zoom-in&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;rotateViewer()&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Rotate 90°&quot;&gt;&lt;i data-lucide=&quot;rotate-cw&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.showOcrBoxes = !appState.ui.showOcrBoxes; renderApp();&quot; class=&quot;px-2 py-1 rounded-lg text-[10px] font-bold border ${appState.ui.showOcrBoxes ? &#39;bg-brand-500/15 text-brand-500 border-brand-500/30&#39; : &#39;border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  OCR Boxes<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div ondragover=&quot;event.preventDefault()&quot; ondrop=&quot;handleReceiptDrop(event)&quot; class=&quot;relative flex-1 min-h-[420px] max-h-[600px] overflow-auto bg-slate-100 dark:bg-slate-950 flex items-center justify-center p-4&quot;&gt;<br>              ${currentImg ? `<br>                &lt;div class=&quot;relative inline-block transition-transform duration-150&quot; style=&quot;transform: scale(${appState.ui.viewerZoom}) rotate(${appState.ui.viewerRotation}deg);&quot;&gt;<br>                  &lt;img src=&quot;${currentImg}&quot; alt=&quot;Original Receipt&quot; class=&quot;max-w-full rounded-lg shadow-lg border border-slate-300 dark:border-slate-700&quot; /&gt;<br>                  ${appState.ui.showOcrBoxes ? (rec.ocrBlocks || []).filter(b =&gt; b.page === rec.currentPage).map(blk =&gt; {<br>                    const isHighlighted = selectedRowId &amp;&amp; blk.mappedToFeeId === selectedRowId;<br>                    return `<br>                      &lt;div onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${blk.mappedToFeeId || &#39;&#39;}&#39;; renderApp();&quot;<br>                           style=&quot;left:${blk.bbox.x}%; top:${blk.bbox.y}%; width:${blk.bbox.w}%; height:${blk.bbox.h}%;&quot;<br>                           title=&quot;${escapeHtml(blk.rawLine)} (${blk.confidence}% conf)&quot;<br>                           class=&quot;absolute cursor-pointer rounded border-2 transition ${<br>                             isHighlighted<br>                               ? &#39;border-rose-500 bg-rose-500/25 ring-2 ring-rose-400&#39;<br>                               : &#39;border-brand-500/70 bg-brand-500/10 hover:bg-brand-500/25&#39;<br>                           }&quot;&gt;<br>                      &lt;/div&gt;<br>                    `;<br>                  }).join(&#39;&#39;) : &#39;&#39;}<br>                &lt;/div&gt;<br>              ` : `<br>                &lt;div class=&quot;text-center max-w-xs space-y-2 p-6 border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-2xl&quot;&gt;<br>                  &lt;i data-lucide=&quot;file-up&quot; class=&quot;w-8 h-8 text-slate-400 mx-auto&quot;&gt;&lt;/i&gt;<br>                  &lt;div class=&quot;text-xs font-bold&quot;&gt;No Receipt Attached to ${escapeHtml(page.name)}&lt;/div&gt;<br>                  &lt;p class=&quot;text-[11px] text-slate-500&quot;&gt;Drag &amp; drop a PNG, JPG, WEBP, or multi-page PDF receipt here, or press &lt;strong&gt;Ctrl+V&lt;/strong&gt; to paste a receipt screenshot.&lt;/p&gt;<br>                &lt;/div&gt;<br>              `}<br>            &lt;/div&gt;<br><br>            ${rec ? `<br>              &lt;div class=&quot;px-4 py-2.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between text-xs bg-slate-50 dark:bg-slate-900&quot;&gt;<br>                &lt;span class=&quot;truncate text-slate-500&quot;&gt;${escapeHtml(rec.fileName)} • Conf: &lt;strong&gt;${rec.ocrConfidence}%&lt;/strong&gt;&lt;/span&gt;<br>                &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(-1)&quot; ${rec.currentPage &lt;= 1 ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;lt;&lt;/button&gt;<br>                  &lt;span class=&quot;font-mono&quot;&gt;Page ${rec.currentPage}/${rec.totalPages}&lt;/span&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(1)&quot; ${rec.currentPage &gt;= rec.totalPages ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;xl:col-span-7 space-y-5&quot;&gt;<br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Side-by-Side EIS Fee &amp; CWT Comparison&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] text-slate-400&quot;&gt;Click any row to highlight OCR location&lt;/span&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                  &lt;thead&gt;<br>                    &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Fee Item&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Receipt Actual (Editable)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-right&quot;&gt;Diff&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                    &lt;/tr&gt;<br>                  &lt;/thead&gt;<br>                  &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                    ${page.fees.map(fee =&gt; {<br>                      const val = fee.lastValidation || ValidationEngine.validateFeeRow(fee);<br>                      const isSel = selectedRowId === fee.id;<br>                      return `<br>                        &lt;tr onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${fee.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer transition ${isSel ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/40&#39;}&quot;&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-semibold&quot;&gt;<br>                            ${escapeHtml(fee.expectedName)}<br>                            ${val.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 py-0.2 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-mono text-[11px]&quot;&gt;<br>                            &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                            &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 space-y-1&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                            &lt;div class=&quot;flex gap-1&quot;&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; class=&quot;w-24 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; class=&quot;w-16 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase text-[11px]&quot; /&gt;<br>                            &lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-right font-mono font-bold ${val.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;<br>                            ${escapeHtml(val.amountComparison.difference)}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;<br>                            ${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(val.status)}&lt;/td&gt;<br>                        &lt;/tr&gt;<br>                        &lt;tr class=&quot;bg-slate-50/60 dark:bg-slate-950/40 text-[11px] text-slate-500&quot;&gt;<br>                          &lt;td colspan=&quot;6&quot; class=&quot;px-3 py-1.5&quot;&gt;<br>                            &lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(val.explanation)}<br>                          &lt;/td&gt;<br>                        &lt;/tr&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/tbody&gt;<br>                &lt;/table&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;!-- Pasted Dynamic Column Fields Verification --&gt;<br>            ${(() =&gt; {<br>              const configuredCols = page.fields.filter(f =&gt; f.expectedValue !== &#39;&#39; || f.actualValue !== &#39;&#39;);<br>              if (!configuredCols.length) return &#39;&#39;;<br>              const matchedCols = configuredCols.filter(f =&gt; f.lastValidation &amp;&amp; f.lastValidation.status === &#39;PASS&#39;).length;<br>              return `<br>                &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>                  &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h3&gt;<br>                      &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Auto-searches uploaded/pasted receipt text for every expected column value.&lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                      &lt;span class=&quot;px-2.5 py-1 rounded-full text-xs font-bold ${matchedCols === configuredCols.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;<br>                        ${matchedCols} / ${configuredCols.length} Expected Columns Matched<br>                      &lt;/span&gt;<br>                      &lt;button onclick=&quot;reMatchExpectedColumnsNow()&quot; class=&quot;px-2.5 py-1 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                        Re-Scan Receipt<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                    &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                      &lt;thead&gt;<br>                        &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Col&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Configurable Field Name&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Expected Row Value&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Found on Receipt (Editable)&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                        &lt;/tr&gt;<br>                      &lt;/thead&gt;<br>                      &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                        ${configuredCols.map(f =&gt; {<br>                          const st = f.lastValidation ? f.lastValidation.status : &#39;PENDING&#39;;<br>                          return `<br>                            &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(f.name)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(f.expectedValue)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;/td&gt;<br>                              &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                            &lt;/tr&gt;<br>                          `;<br>                        }).join(&#39;&#39;)}<br>                      &lt;/tbody&gt;<br>                    &lt;/table&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            })()}<br><br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;CWT &amp; Net Settlement Reconciliation&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] font-mono text-slate-400&quot;&gt;Deterministic Engine&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs&quot;&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Expected Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-indigo-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Actual Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-emerald-500 mt-0.5&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;<br>                Formula: ${escapeHtml(fin.formulaExplanation)}<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function correctReceiptFeeValue(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const oldVal = fee[key];<br>      fee[key] = val;<br>      fee.manuallyVerified = true;<br>      fee.ocrConfidence = 100;<br>      logActivity(&#39;Manual OCR Correction&#39;, `${page.name}: ${fee.expectedName} (${key}: &quot;${oldVal}&quot; → &quot;${val}&quot;)`);<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manual receipt value correction&#39;);<br>      showToast(&#39;Updated receipt value &amp; recalculated validation.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function adjustViewerZoom(delta) {<br>      appState.ui.viewerZoom = Math.min(2.5, Math.max(0.5, Number((appState.ui.viewerZoom + delta).toFixed(2))));<br>      renderApp();<br>    }<br><br>    function rotateViewer() {<br>      appState.ui.viewerRotation = (appState.ui.viewerRotation + 90) % 360;<br>      renderApp();<br>    }<br><br>    function changeReceiptPage(delta) {<br>      const rec = getActiveMainPage()?.receipt;<br>      if (!rec) return;<br>      const next = rec.currentPage + delta;<br>      if (next &gt;= 1 &amp;&amp; next &lt;= rec.totalPages) {<br>        rec.currentPage = next;<br>        renderApp();<br>      }<br>    }<br><br>    function removeReceiptAttachment() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.receipt = null;<br>      scheduleAutosave(&#39;Removed receipt attachment&#39;);<br>      showToast(&#39;Receipt removed from &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function handleReceiptDrop(e) {<br>      e.preventDefault();<br>      const file = e.dataTransfer?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    function handleReceiptUpload(e) {<br>      const file = e.target?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    async function processUploadedReceiptFile(file) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br><br>      const allowed = [&#39;image/png&#39;, &#39;image/jpeg&#39;, &#39;image/webp&#39;, &#39;image/svg+xml&#39;, &#39;application/pdf&#39;];<br>      if (!allowed.includes(file.type) &amp;&amp; !/\.(png|jpg|jpeg|webp|pdf)$/i.test(file.name)) {<br>        return showToast(&#39;Unsupported file type. Upload PNG, JPG, WEBP, or PDF.&#39;, &#39;error&#39;);<br>      }<br><br>      showToast(`Processing &quot;${file.name}&quot; for ${page.name}...`, &#39;info&#39;);<br>      const now = new Date().toISOString();<br><br>      if (file.type === &#39;application/pdf&#39; || /\.pdf$/i.test(file.name)) {<br>        try {<br>          if (!window.pdfjsLib) {<br>            throw new Error(&#39;PDF.js is unavailable in this environment.&#39;);<br>          }<br>          const arrayBuf = await file.arrayBuffer();<br>          const pdf = await pdfjsLib.getDocument({ data: arrayBuf }).promise;<br>          const pageImages = [];<br>          let combinedText = &#39;&#39;;<br><br>          for (let pNum = 1; pNum &lt;= pdf.numPages; pNum++) {<br>            const pdfPage = await pdf.getPage(pNum);<br>            const viewport = pdfPage.getViewport({ scale: 1.5 });<br>            const canvas = document.createElement(&#39;canvas&#39;);<br>            canvas.width = viewport.width;<br>            canvas.height = viewport.height;<br>            const ctx = canvas.getContext(&#39;2d&#39;);<br>            await pdfPage.render({ canvasContext: ctx, viewport }).promise;<br>            pageImages.push(canvas.toDataURL(&#39;image/png&#39;));<br><br>            const txtContent = await pdfPage.getTextContent();<br>            const pageText = txtContent.items.map(it =&gt; it.str).join(&#39; &#39;);<br>            combinedText += pageText + &#39;\n&#39;;<br>          }<br><br>          const blocks = OcrMappingEngine.parseReceiptTextToBlocks(combinedText, 1, 94);<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: &#39;application/pdf&#39;,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: pdf.numPages,<br>            pages: pageImages,<br>            ocrRawText: combinedText.trim(),<br>            ocrConfidence: 94,<br>            ocrBlocks: blocks,<br>            history: [{ action: `Uploaded ${pdf.numPages}-page PDF &amp; Extracted Text`, timestamp: now }]<br>          };<br><br>          const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>          logActivity(&#39;Uploaded PDF Receipt&#39;, `${file.name} (${pdf.numPages} pages) → ${page.name}`);<br>          scheduleAutosave(&#39;Uploaded PDF receipt&#39;);<br>          showToast(`PDF loaded (${pdf.numPages} pages). Auto-mapped ${mapRes.autoAccepted} items.`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;PDF parsing error: &#39; + err.message, &#39;error&#39;);<br>        }<br>      } else {<br>        const reader = new FileReader();<br>        reader.onload = async (ev) =&gt; {<br>          const dataUrl = ev.target.result;<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: file.type,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: 1,<br>            pages: [dataUrl],<br>            ocrRawText: &#39;&#39;,<br>            ocrConfidence: 0,<br>            ocrBlocks: [],<br>            history: [{ action: &#39;Uploaded Image Receipt&#39;, timestamp: now }]<br>          };<br>          scheduleAutosave(&#39;Uploaded receipt image&#39;);<br>          renderApp();<br>          await runOcrOnActiveReceipt();<br>        };<br>        reader.onerror = () =&gt; {<br>          showToast(&#39;Unable to read the selected image file.&#39;, &#39;error&#39;);<br>        };<br>        reader.readAsDataURL(file);<br>      }<br>    }<br><br>    async function runOcrOnActiveReceipt() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Attach a receipt first.&#39;, &#39;warning&#39;);<br><br>      const rec = page.receipt;<br>      const imgUrl = rec.pages[rec.currentPage - 1];<br>      if (!imgUrl) return;<br><br>      showToast(&#39;Running local OCR preprocessing &amp; extraction...&#39;, &#39;info&#39;);<br>      try {<br>        const preprocessed = await OcrMappingEngine.preprocessImageCanvas(imgUrl, { grayscale: true, contrast: true, scale: 1.5 });<br>        const ocrOut = await OcrMappingEngine.runRealTesseractOCR(preprocessed);<br>        rec.ocrRawText = ocrOut.text;<br>        rec.ocrConfidence = ocrOut.confidence;<br>        rec.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(ocrOut.text, rec.currentPage, ocrOut.confidence);<br>        rec.history.unshift({ action: `OCR Re-run (${ocrOut.confidence}% confidence)`, timestamp: new Date().toISOString() });<br><br>        const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>        scheduleAutosave(&#39;Completed OCR extraction&#39;);<br>        showToast(`OCR complete (${ocrOut.confidence}% conf). Auto-mapped: ${mapRes.autoAccepted}, Review: ${mapRes.reviewNeeded}`, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;OCR notice: &#39; + err.message + &#39;. You can also enter/edit extracted text in OCR &amp; Doc Intel.&#39;, &#39;warning&#39;);<br>      }<br>    }<br><br>    function reMatchExpectedColumnsNow() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Upload or paste a receipt first.&#39;, &#39;warning&#39;);<br>      const res = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>      scheduleAutosave(&#39;Re-matched expected columns against receipt&#39;);<br>      showToast(`Matched ${res.matched} of ${res.total} expected columns against receipt.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    async function pasteReceiptFromClipboardButton() {<br>      try {<br>        if (!navigator.clipboard || !navigator.clipboard.read) {<br>          return showToast(&#39;Press Ctrl+V (or Cmd+V) directly on the page to paste your receipt screenshot.&#39;, &#39;info&#39;);<br>        }<br>        const items = await navigator.clipboard.read();<br>        for (const item of items) {<br>          const imgType = item.types.find(t =&gt; t.startsWith(&#39;image/&#39;));<br>          if (imgType) {<br>            const blob = await item.getType(imgType);<br>            const file = new File([blob], `pasted_receipt_${Date.now()}.png`, { type: imgType });<br>            await processUploadedReceiptFile(file);<br>            return;<br>          }<br>        }<br>        showToast(&#39;No image found in clipboard. Copy a receipt screenshot first, then press Ctrl+V.&#39;, &#39;warning&#39;);<br>      } catch (e) {<br>        showToast(&#39;Press Ctrl+V (or Cmd+V) anywhere in Receipt Validation to paste your clipboard image.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 5 VIEW: OCR &amp; DOCUMENT INTELLIGENCE<br>     ****************************************************************************/<br>    function renderOcrIntelligenceModule() {<br>      const page = getActiveMainPage();<br>      const rec = page?.receipt;<br>      if (!page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;OCR Preprocessing &amp; Raw Text Editor&lt;/h3&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Edit or paste raw receipt OCR text for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; to re-parse blocks and test smart field mapping.&lt;/p&gt;<br><br>            &lt;div class=&quot;grid grid-cols-2 gap-2 text-xs&quot;&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Grayscale Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Contrast Enhancement (1.35x)&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;1.5x Resolution Upscale&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;CWT Sign Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Extracted / Manual Receipt Text&lt;/label&gt;<br>              &lt;textarea id=&quot;ocr-manual-raw-text&quot; rows=&quot;10&quot; placeholder=&quot;Fee 1 Charge | 1000.00 | NC&amp;#10;Fee 2 Charge | 250.00 | IC&amp;#10;CWT | -50.00 | CWT&quot; class=&quot;w-full p-3 rounded-xl bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono text-xs&quot;&gt;${escapeHtml(rec ? rec.ocrRawText : &#39;&#39;)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;applyManualOcrTextAndMap()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                Parse Text &amp; Auto-Map to Main Page<br>              &lt;/button&gt;<br>              ${rec ? `&lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Re-Run Image OCR&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Detected Document Structure &amp; Smart Mapping&lt;/h3&gt;<br>              &lt;span class=&quot;text-xs text-slate-400&quot;&gt;Auto-Accept Threshold: ≥${appState.settings.autoAcceptConfidenceThreshold}%&lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>              &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                &lt;thead&gt;<br>                  &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Page&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Detected Label&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Amount&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Code&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Mapped Main Page Fee&lt;/th&gt;<br>                  &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                  ${!rec || !(rec.ocrBlocks || []).length ? `<br>                    &lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No OCR blocks detected yet. Upload a receipt or parse raw text on the left.&lt;/td&gt;&lt;/tr&gt;<br>                  ` : rec.ocrBlocks.map(blk =&gt; `<br>                    &lt;tr&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;P${blk.page}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-medium&quot;&gt;${escapeHtml(blk.detectedName)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;${escapeHtml(blk.detectedAmount || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-indigo-500&quot;&gt;${escapeHtml(blk.detectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center font-mono ${blk.confidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-emerald-500&#39;}&quot;&gt;${blk.confidence}%&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;select onchange=&quot;manuallyMapOcrBlock(&#39;${blk.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                          &lt;option value=&quot;&quot;&gt;-- Unmapped --&lt;/option&gt;<br>                          ${page.fees.map(f =&gt; `&lt;option value=&quot;${f.id}&quot; ${blk.mappedToFeeId === f.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(f.expectedName)} (${escapeHtml(f.expectedCode)})&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `).join(&#39;&#39;)}<br>                &lt;/tbody&gt;<br>              &lt;/table&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function applyManualOcrTextAndMap() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const rawText = document.getElementById(&#39;ocr-manual-raw-text&#39;).value;<br>      const now = new Date().toISOString();<br>      if (!page.receipt) {<br>        page.receipt = {<br>          id: &#39;rec_manual_&#39; + Date.now(),<br>          fileName: &#39;manual_ocr_transcript.txt&#39;,<br>          mimeType: &#39;text/plain&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [],<br>          ocrRawText: rawText,<br>          ocrConfidence: 95,<br>          ocrBlocks: [],<br>          history: []<br>        };<br>      }<br>      page.receipt.ocrRawText = rawText;<br>      page.receipt.ocrConfidence = 95;<br>      page.receipt.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(rawText, page.receipt.currentPage || 1, 95);<br>      page.receipt.history.unshift({ action: &#39;Manual Text Parsed &amp; Mapped&#39;, timestamp: now });<br><br>      const res = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>      scheduleAutosave(&#39;Mapped manual OCR text&#39;);<br>      showToast(`Parsed ${page.receipt.ocrBlocks.length} blocks. Auto-mapped: ${res.autoAccepted}, Review: ${res.reviewNeeded}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function manuallyMapOcrBlock(blockId, feeId) {<br>      const page = getActiveMainPage();<br>      const blk = page?.receipt?.ocrBlocks.find(b =&gt; b.id === blockId);<br>      if (!blk) return;<br>      blk.mappedToFeeId = feeId || null;<br>      if (feeId) {<br>        const fee = page.fees.find(f =&gt; f.id === feeId);<br>        if (fee) {<br>          fee.actualName = blk.detectedName;<br>          fee.actualAmount = blk.detectedAmount;<br>          fee.actualCode = blk.detectedCode || fee.actualCode;<br>          fee.ocrConfidence = blk.confidence;<br>          fee.sourceLocation = `Page ${blk.page} (Manual Map)`;<br>        }<br>      }<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manually mapped OCR block&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 6 VIEW: QA SCREENSHOT STUDIO &amp; EVIDENCE ANNOTATIONS (1-200+)<br>     ****************************************************************************/<br>    let activeStudioScreenshotIdx = 0;<br><br>    function getNextAvailableQaLabel(page) {<br>      const used = new Set((page?.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      const max = appState.settings.qaLabelMax || 200;<br>      for (let i = 1; i &lt;= max; i++) {<br>        if (!used.has(i)) return i;<br>      }<br>      return max + 1;<br>    }<br><br>    function renderScreenshotStudioModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No active project.&lt;/div&gt;`;<br><br>      const screenshots = proj.screenshots || [];<br>      if (activeStudioScreenshotIdx &gt;= screenshots.length) activeStudioScreenshotIdx = Math.max(0, screenshots.length - 1);<br>      const activeShot = screenshots[activeStudioScreenshotIdx] || null;<br>      const nextLabel = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br><br>      const labelOptions = [];<br>      const maxLbl = appState.settings.qaLabelMax || 200;<br>      const usedLabels = new Set((page.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      for (let i = 1; i &lt;= maxLbl; i++) {<br>        labelOptions.push(`&lt;option value=&quot;${i}&quot; ${i === nextLabel ? &#39;selected&#39; : &#39;&#39;}&gt;QA-${i} ${usedLabels.has(i) ? &#39;(Assigned)&#39; : &#39;&#39;}&lt;/option&gt;`);<br>      }<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;image-plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Upload Screenshots&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; multiple onchange=&quot;handleUploadScreenshots(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;captureBrowserScreen()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>              &lt;i data-lucide=&quot;monitor-dot&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Capture Screen (Browser Permission)&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;vertical&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Vertical (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;horizontal&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Horizontal (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;resetMergeHistory()&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Reset Merge History (${(proj.mergeHistory || []).length})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Captures (${screenshots.length})&lt;/h3&gt;<br>              &lt;span class=&quot;text-[10px] text-slate-400&quot;&gt;Check to merge&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${screenshots.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No screenshots yet.&lt;/div&gt;` : screenshots.map((scr, idx) =&gt; {<br>                const isChecked = appState.ui.selectedScreenshotsForMerge.includes(scr.id);<br>                const isActive = idx === activeStudioScreenshotIdx;<br>                return `<br>                  &lt;div onclick=&quot;activeStudioScreenshotIdx = ${idx}; renderApp();&quot; class=&quot;p-2.5 rounded-xl border cursor-pointer transition ${isActive ? &#39;border-brand-500 bg-brand-500/10&#39; : &#39;border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                    &lt;div class=&quot;flex items-center justify-between gap-2 mb-1.5&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                      &lt;label class=&quot;inline-flex items-center gap-1.5 text-[11px] font-semibold truncate&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleScreenshotMergeSelect(&#39;${scr.id}&#39;)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                        &lt;span class=&quot;truncate&quot;&gt;${escapeHtml(scr.name)}&lt;/span&gt;<br>                      &lt;/label&gt;<br>                      &lt;div class=&quot;flex items-center gap-1 shrink-0&quot;&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, -1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;↑&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, 1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;↓&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteScreenshot(&#39;${scr.id}&#39;)&quot; class=&quot;text-rose-500 hover:opacity-80&quot; title=&quot;Delete&quot;&gt;&amp;times;&lt;/button&gt;<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;img src=&quot;${scr.dataUrl}&quot; alt=&quot;${escapeHtml(scr.name)}&quot; class=&quot;w-full h-24 object-cover rounded-lg bg-slate-950&quot; /&gt;<br>                    &lt;div class=&quot;flex items-center justify-between text-[10px] text-slate-400 mt-1&quot;&gt;<br>                      &lt;span&gt;${scr.isMerged ? &#39;Merged Output&#39; : escapeHtml(scr.source)}&lt;/span&gt;<br>                      &lt;a href=&quot;${scr.dataUrl}&quot; download=&quot;${escapeHtml(scr.name)}.png&quot; onclick=&quot;event.stopPropagation()&quot; class=&quot;text-brand-500 hover:underline&quot;&gt;Download&lt;/a&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 pb-2 border-b border-slate-200 dark:border-slate-800&quot;&gt;<br>              &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;rect&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;rect&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Rectangle&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;circle&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;circle&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Circle&lt;/button&gt;<br>                &lt;input type=&quot;color&quot; value=&quot;${appState.ui.annotationColor}&quot; onchange=&quot;appState.ui.annotationColor = this.value&quot; class=&quot;w-8 h-8 rounded cursor-pointer bg-transparent&quot; title=&quot;Annotation Color&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;flex items-center gap-2 text-xs&quot;&gt;<br>                &lt;select onchange=&quot;appState.ui.selectedQaLabel = Number(this.value)&quot; class=&quot;px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot;&gt;<br>                  ${labelOptions.join(&#39;&#39;)}<br>                &lt;/select&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1 cursor-pointer&quot; title=&quot;Auto-increment to next unused QA label&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${appState.settings.qaAutoIncrement ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.qaAutoIncrement = this.checked; scheduleAutosave(&#39;Toggled QA auto-increment&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;Auto-Inc&lt;/span&gt;<br>                &lt;/label&gt;<br>                &lt;button onclick=&quot;increaseQaLabelLimit()&quot; class=&quot;px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[11px]&quot; title=&quot;Increase Max QA Labels&quot;&gt;+50&lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div id=&quot;annotation-stage&quot; class=&quot;relative min-h-[420px] bg-slate-950 rounded-xl overflow-auto flex items-center justify-center p-2 select-none&quot;&gt;<br>              ${activeShot ? `<br>                &lt;div id=&quot;annotation-canvas-wrapper&quot; class=&quot;relative inline-block cursor-crosshair&quot;&gt;<br>                  &lt;img id=&quot;annotation-base-img&quot; src=&quot;${activeShot.dataUrl}&quot; alt=&quot;Evidence Canvas&quot; class=&quot;max-w-full rounded-lg pointer-events-none&quot; /&gt;<br>                  &lt;svg id=&quot;annotation-svg-overlay&quot; class=&quot;absolute inset-0 w-full h-full&quot;&gt;<br>                    ${(page.annotations || []).map(ann =&gt; {<br>                      const isSel = appState.ui.selectedAnnotationId === ann.id;<br>                      const shape = ann.type === &#39;circle&#39;<br>                        ? `&lt;ellipse cx=&quot;${ann.x + ann.w / 2}&quot; cy=&quot;${ann.y + ann.h / 2}&quot; rx=&quot;${Math.abs(ann.w / 2)}&quot; ry=&quot;${Math.abs(ann.h / 2)}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`<br>                        : `&lt;rect x=&quot;${ann.x}&quot; y=&quot;${ann.y}&quot; width=&quot;${ann.w}&quot; height=&quot;${ann.h}&quot; rx=&quot;4&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`;<br>                      return `<br>                        &lt;g onclick=&quot;event.stopPropagation(); appState.ui.selectedAnnotationId = &#39;${ann.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer&quot;&gt;<br>                          ${shape}<br>                          &lt;rect x=&quot;${ann.x}&quot; y=&quot;${Math.max(0, ann.y - 20)}&quot; width=&quot;${Math.max(68, ann.label.length * 7 + 12)}&quot; height=&quot;18&quot; rx=&quot;4&quot; fill=&quot;${ann.color}&quot; /&gt;<br>                          &lt;text x=&quot;${ann.x + 6}&quot; y=&quot;${Math.max(13, ann.y - 7)}&quot; font-family=&quot;sans-serif&quot; font-size=&quot;11&quot; font-weight=&quot;bold&quot; fill=&quot;#ffffff&quot;&gt;${escapeHtml(ann.label)}&lt;/text&gt;<br>                        &lt;/g&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/svg&gt;<br>                &lt;/div&gt;<br>              ` : `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;Upload or capture a screenshot to draw QA annotations.&lt;/div&gt;`}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center justify-between text-[11px] text-slate-400&quot;&gt;<br>              &lt;span&gt;Click &amp; drag on the image to draw a QA annotation for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt;.&lt;/span&gt;<br>              ${activeShot ? `&lt;button onclick=&quot;exportAnnotatedEvidenceImage()&quot; class=&quot;text-brand-500 font-semibold hover:underline&quot;&gt;Export Annotated PNG&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Page Annotations (${(page.annotations || []).length})&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${(page.annotations || []).length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No annotations on this Main Page yet.&lt;/div&gt;` : (page.annotations || []).map(ann =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${appState.ui.selectedAnnotationId === ann.id ? &#39;border-brand-500 bg-brand-500/5&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} space-y-2 text-xs&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                    &lt;span class=&quot;font-bold&quot; style=&quot;color:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/span&gt;<br>                    &lt;button onclick=&quot;deleteAnnotation(&#39;${ann.id}&#39;)&quot; class=&quot;text-rose-500 hover:underline text-[11px]&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                  &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.comment || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;comment&#39;, this.value)&quot; placeholder=&quot;Evidence comment...&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                  &lt;div class=&quot;grid grid-cols-2 gap-1.5&quot;&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.fieldRef || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;fieldRef&#39;, this.value)&quot; placeholder=&quot;Linked Field&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.defectId || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;defectId&#39;, this.value)&quot; placeholder=&quot;Defect ID&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-1 pt-1&quot;&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, -10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;←&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;→&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, -10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↑&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↓&lt;/button&gt;<br>                    &lt;button onclick=&quot;resizeAnnotation(&#39;${ann.id}&#39;, 15, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;+Size&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initAnnotationCanvasEvents() {<br>      const wrapper = document.getElementById(&#39;annotation-canvas-wrapper&#39;);<br>      if (!wrapper) return;<br>      let startX = 0, startY = 0, drawing = false;<br><br>      wrapper.onmousedown = (e) =&gt; {<br>        const rect = wrapper.getBoundingClientRect();<br>        startX = e.clientX - rect.left;<br>        startY = e.clientY - rect.top;<br>        drawing = true;<br>      };<br><br>      wrapper.onmouseup = (e) =&gt; {<br>        if (!drawing) return;<br>        drawing = false;<br>        const rect = wrapper.getBoundingClientRect();<br>        const endX = e.clientX - rect.left;<br>        const endY = e.clientY - rect.top;<br>        const w = Math.abs(endX - startX);<br>        const h = Math.abs(endY - startY);<br>        if (w &lt; 12 || h &lt; 12) return;<br><br>        const page = getActiveMainPage();<br>        if (!page) return;<br>        const qaNum = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br>        if ((page.annotations || []).some(a =&gt; Number(a.qaLabel) === Number(qaNum))) {<br>          return showToast(`QA-${qaNum} is already assigned on ${page.name}. Pick an unused label.`, &#39;warning&#39;);<br>        }<br><br>        page.annotations = page.annotations || [];<br>        const newAnn = {<br>          id: &#39;ann_&#39; + Date.now(),<br>          qaLabel: qaNum,<br>          type: appState.ui.annotationTool,<br>          x: Math.round(Math.min(startX, endX)),<br>          y: Math.round(Math.min(startY, endY)),<br>          w: Math.round(w),<br>          h: Math.round(h),<br>          color: appState.ui.annotationColor,<br>          label: `QA-${qaNum}`,<br>          comment: &#39;&#39;,<br>          fieldRef: &#39;&#39;,<br>          testCaseId: &#39;&#39;,<br>          defectId: &#39;&#39;<br>        };<br>        page.annotations.push(newAnn);<br>        appState.ui.selectedAnnotationId = newAnn.id;<br>        if (appState.settings.qaAutoIncrement) {<br>          appState.ui.selectedQaLabel = getNextAvailableQaLabel(page);<br>        }<br>        scheduleAutosave(&#39;Added evidence annotation&#39;);<br>        renderApp();<br>      };<br>    }<br><br>    function nudgeAnnotation(annId, dx, dy) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.x = Math.max(0, ann.x + dx);<br>      ann.y = Math.max(0, ann.y + dy);<br>      scheduleAutosave(&#39;Moved annotation&#39;);<br>      renderApp();<br>    }<br><br>    function resizeAnnotation(annId, dw, dh) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.w = Math.max(20, ann.w + dw);<br>      ann.h = Math.max(20, ann.h + dh);<br>      scheduleAutosave(&#39;Resized annotation&#39;);<br>      renderApp();<br>    }<br><br>    function updateAnnotationProp(annId, key, val) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann[key] = val;<br>      scheduleAutosave(&#39;Updated annotation metadata&#39;);<br>    }<br><br>    function deleteAnnotation(annId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.annotations = (page.annotations || []).filter(a =&gt; a.id !== annId);<br>      scheduleAutosave(&#39;Deleted annotation&#39;);<br>      renderApp();<br>    }<br><br>    function increaseQaLabelLimit() {<br>      appState.settings.qaLabelMax = (appState.settings.qaLabelMax || 200) + 50;<br>      scheduleAutosave(&#39;Increased QA label count&#39;);<br>      showToast(`QA label pool increased to 1–${appState.settings.qaLabelMax}.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function handleUploadScreenshots(e) {<br>      const proj = getActiveProject();<br>      const files = Array.from(e.target.files || []);<br>      if (!proj || !files.length) return;<br>      files.forEach(file =&gt; {<br>        const reader = new FileReader();<br>        reader.onload = (ev) =&gt; {<br>          proj.screenshots.push({<br>            id: &#39;scr_&#39; + Date.now() + &#39;_&#39; + Math.random().toString(36).slice(2, 5),<br>            name: file.name,<br>            dataUrl: ev.target.result,<br>            capturedAt: new Date().toISOString(),<br>            source: &#39;Uploaded File&#39;,<br>            isMerged: false<br>          });<br>          scheduleAutosave(&#39;Uploaded screenshot&#39;);<br>          renderApp();<br>        };<br>        reader.readAsDataURL(file);<br>      });<br>    }<br><br>    async function captureBrowserScreen() {<br>      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {<br>        return showToast(&#39;Screen capture API is not supported in this browser context.&#39;, &#39;warning&#39;);<br>      }<br>      try {<br>        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br>        const video = document.createElement(&#39;video&#39;);<br>        video.srcObject = stream;<br>        await video.play();<br><br>        const canvas = document.createElement(&#39;canvas&#39;);<br>        canvas.width = video.videoWidth;<br>        canvas.height = video.videoHeight;<br>        canvas.getContext(&#39;2d&#39;).drawImage(video, 0, 0);<br>        stream.getTracks().forEach(t =&gt; t.stop());<br><br>        const proj = getActiveProject();<br>        proj.screenshots.push({<br>          id: &#39;scr_cap_&#39; + Date.now(),<br>          name: `Screen_Capture_${new Date().toISOString().slice(11, 19).replace(/:/g, &#39;-&#39;)}.png`,<br>          dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>          capturedAt: new Date().toISOString(),<br>          source: &#39;Browser Screen Share&#39;,<br>          isMerged: false<br>        });<br>        activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>        scheduleAutosave(&#39;Captured browser screen&#39;);<br>        showToast(&#39;Screen captured and added to QA Studio.&#39;, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;Screen capture cancelled or permission denied.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    function toggleScreenshotMergeSelect(scrId) {<br>      const sel = appState.ui.selectedScreenshotsForMerge;<br>      const idx = sel.indexOf(scrId);<br>      if (idx &gt;= 0) sel.splice(idx, 1);<br>      else sel.push(scrId);<br>      renderApp();<br>    }<br><br>    function moveScreenshot(idx, dir) {<br>      const proj = getActiveProject();<br>      const target = idx + dir;<br>      if (!proj || target &lt; 0 || target &gt;= proj.screenshots.length) return;<br>      const tmp = proj.screenshots[idx];<br>      proj.screenshots[idx] = proj.screenshots[target];<br>      proj.screenshots[target] = tmp;<br>      scheduleAutosave(&#39;Reordered screenshots&#39;);<br>      renderApp();<br>    }<br><br>    function deleteScreenshot(scrId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.screenshots = proj.screenshots.filter(s =&gt; s.id !== scrId);<br>      appState.ui.selectedScreenshotsForMerge = appState.ui.selectedScreenshotsForMerge.filter(id =&gt; id !== scrId);<br>      scheduleAutosave(&#39;Deleted screenshot&#39;);<br>      renderApp();<br>    }<br><br>    async function mergeSelectedScreenshots(direction = &#39;vertical&#39;) {<br>      const proj = getActiveProject();<br>      const ids = appState.ui.selectedScreenshotsForMerge;<br>      if (!proj || ids.length &lt; 2) {<br>        return showToast(&#39;Select at least 2 screenshots using the checkboxes to merge.&#39;, &#39;warning&#39;);<br>      }<br>      const chosen = ids.map(id =&gt; proj.screenshots.find(s =&gt; s.id === id)).filter(Boolean);<br>      const loadedImgs = await Promise.all(chosen.map(s =&gt; new Promise(res =&gt; {<br>        const img = new Image();<br>        img.onload = () =&gt; res(img);<br>        img.src = s.dataUrl;<br>      })));<br><br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      if (direction === &#39;vertical&#39;) {<br>        canvas.width = Math.max(...loadedImgs.map(i =&gt; i.width));<br>        canvas.height = loadedImgs.reduce((sum, i) =&gt; sum + i.height, 0);<br>      } else {<br>        canvas.width = loadedImgs.reduce((sum, i) =&gt; sum + i.width, 0);<br>        canvas.height = Math.max(...loadedImgs.map(i =&gt; i.height));<br>      }<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      let offset = 0;<br>      loadedImgs.forEach(img =&gt; {<br>        if (direction === &#39;vertical&#39;) {<br>          ctx.drawImage(img, 0, offset);<br>          offset += img.height;<br>        } else {<br>          ctx.drawImage(img, offset, 0);<br>          offset += img.width;<br>        }<br>      });<br><br>      const mergedObj = {<br>        id: &#39;scr_merged_&#39; + Date.now(),<br>        name: `Merged_${direction}_${chosen.length}imgs.png`,<br>        dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>        capturedAt: new Date().toISOString(),<br>        source: `Merged (${direction})`,<br>        isMerged: true<br>      };<br>      proj.screenshots.push(mergedObj);<br>      proj.mergeHistory = proj.mergeHistory || [];<br>      proj.mergeHistory.push({ id: mergedObj.id, sourceIds: [...ids], direction, timestamp: mergedObj.capturedAt });<br>      activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>      scheduleAutosave(&#39;Merged screenshots&#39;);<br>      showToast(`Merged ${chosen.length} screenshots (${direction}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function resetMergeHistory() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.mergeHistory = [];<br>      appState.ui.selectedScreenshotsForMerge = [];<br>      scheduleAutosave(&#39;Reset merge history&#39;);<br>      showToast(&#39;Merge selection &amp; history cleared.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportAnnotatedEvidenceImage() {<br>      const img = document.getElementById(&#39;annotation-base-img&#39;);<br>      const page = getActiveMainPage();<br>      if (!img || !page) return;<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      canvas.width = img.naturalWidth || img.width;<br>      canvas.height = img.naturalHeight || img.height;<br>      const scaleX = canvas.width / img.width;<br>      const scaleY = canvas.height / img.height;<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>      (page.annotations || []).forEach(ann =&gt; {<br>        ctx.strokeStyle = ann.color;<br>        ctx.lineWidth = 3 * scaleX;<br>        if (ann.type === &#39;circle&#39;) {<br>          ctx.beginPath();<br>          ctx.ellipse((ann.x + ann.w / 2) * scaleX, (ann.y + ann.h / 2) * scaleY, Math.abs(ann.w / 2) * scaleX, Math.abs(ann.h / 2) * scaleY, 0, 0, Math.PI * 2);<br>          ctx.stroke();<br>        } else {<br>          ctx.strokeRect(ann.x * scaleX, ann.y * scaleY, ann.w * scaleX, ann.h * scaleY);<br>        }<br>        ctx.fillStyle = ann.color;<br>        ctx.fillRect(ann.x * scaleX, Math.max(0, (ann.y - 22) * scaleY), 110 * scaleX, 22 * scaleY);<br>        ctx.fillStyle = &#39;#ffffff&#39;;<br>        ctx.font = `bold ${Math.round(12 * scaleX)}px sans-serif`;<br>        ctx.fillText(ann.label, (ann.x + 6) * scaleX, Math.max(15 * scaleY, (ann.y - 6) * scaleY));<br>      });<br><br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = canvas.toDataURL(&#39;image/png&#39;);<br>      a.download = `${page.name.replace(/[^a-z0-9]/gi, &#39;_&#39;)}_annotated_evidence.png`;<br>      a.click();<br>      showToast(&#39;Exported annotated evidence PNG.&#39;, &#39;success&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 7 VIEW: TEST CASE MANAGEMENT<br>     ****************************************************************************/<br><br>    /****************************************************************************<br>     * EVIDENCE SCREENSHOTS (opened from Receipt Validation)<br>     * Copy of the QA Screenshot Studio workflow, with its own screenshots &amp; boxes.<br>     * QA-n box  &lt;-&gt;  column Cn.  The text read inside a box fills the field&#39;s<br>     * &quot;Found on Receipt (Editable)&quot; value, same value Re-Run OCR &amp; Auto-Match fills.<br>     ****************************************************************************/<br>    let evActiveShotIdx = 0;<br>    let evFieldMapShowAll = false;<br>    const evReadingIds = new Set();<br><br>    // Main toggle (global setting, so it follows every Main Page): where a box value is written<br>    function evTarget() { return appState.settings.evTarget === &#39;actual&#39; ? &#39;actual&#39; : &#39;expected&#39;; }<br>    function evTargetKey() { return evTarget() === &#39;actual&#39; ? &#39;actualValue&#39; : &#39;expectedValue&#39;; }<br>    function evSourceKey() { return evTarget() === &#39;actual&#39; ? &#39;actualSource&#39; : &#39;expectedSource&#39;; }<br>    function evTargetLabel() { return evTarget() === &#39;actual&#39; ? &#39;Found on Receipt&#39; : &#39;Expected Value&#39;; }<br><br>    function evSetTarget(t) {<br>      appState.settings.evTarget = t === &#39;actual&#39; ? &#39;actual&#39; : &#39;expected&#39;;<br>      scheduleAutosave(&#39;Changed evidence box target&#39;);<br>      showToast(`Box values now go to ${evTargetLabel()} on every Main Page.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function evApplyStored() {<br>      const page = getActiveMainPage();<br>      const list = evAnns(page).filter(a =&gt; String(a.value || &#39;&#39;).trim() !== &#39;&#39;);<br>      if (!list.length) return showToast(&#39;No stored box values on this Main Page yet. Use Read all boxes first.&#39;, &#39;warning&#39;);<br>      list.forEach(a =&gt; evAssign(page, a));<br>      scheduleAutosave(&#39;Applied stored box values&#39;);<br>      showToast(`Applied ${list.length} box value(s) to ${evTargetLabel()}.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function padC(n) { return &#39;C&#39; + String(n).padStart(2, &#39;0&#39;); }<br>    function evShots(page) { page.evidenceShots = page.evidenceShots || []; return page.evidenceShots; }<br>    function evAnns(page) { page.evidenceAnnotations = page.evidenceAnnotations || []; return page.evidenceAnnotations; }<br>    function evVisible(ann, shot) { return !ann.screenshotId || !shot || ann.screenshotId === shot.id; }<br>    function evField(page, n) { return (page.fields || []).find(f =&gt; Number(f.number) === Number(n)) || null; }<br>    function evTag(ann) { return `${ann.label} ▸ ${padC(ann.qaLabel)}`; }<br>    function evRerender() { if (appState.activeModule === &#39;evidence&#39;) renderApp(); }<br><br>    function evNextLabel(page) {<br>      const used = new Set(evAnns(page).map(a =&gt; Number(a.qaLabel)));<br>      const max = appState.settings.qaLabelMax || 200;<br>      for (let i = 1; i &lt;= max; i++) if (!used.has(i)) return i;<br>      return max + 1;<br>    }<br><br>    function evEnsureFields(page, n) {<br>      page.fields = page.fields || [];<br>      while (page.fields.length &lt; n) {<br>        const num = page.fields.length + 1;<br>        page.fields.push({<br>          id: `fld_${num}_${Date.now()}_${Math.random().toString(36).slice(2, 5)}`,<br>          number: num, name: `Custom Field ${num}`, expectedValue: &#39;&#39;, actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;, validationRule: &#39;Exact / Tolerance Match&#39;, ocrEnabled: true,<br>          required: false, tolerance: 0.01, description: `Dynamic Column #${num}`,<br>          pageOverride: false, enabled: true<br>        });<br>      }<br>    }<br><br>    function evLink(page, ann) {<br>      evEnsureFields(page, Number(ann.qaLabel));<br>      const f = evField(page, ann.qaLabel);<br>      if (f) ann.fieldId = f.id;<br>      pushSharedHeadersFrom(page);<br>      return f;<br>    }<br><br>    // Box value -&gt; Expected Value of the matching column<br>    function evAssign(page, ann) {<br>      const f = evLink(page, ann);<br>      if (!f) return;<br>      f[evTargetKey()] = ann.value || &#39;&#39;;<br>      f[evSourceKey()] = ann.id;<br>      f.enabled = true;<br>      ValidationEngine.validateMainPage(page);<br>    }<br><br>    function evAddShot(name, dataUrl, source, merged = false, targetPage = null) {<br>      const page = targetPage || getActiveMainPage();<br>      if (!page) return;<br>      const shot = {<br>        id: &#39;evs_&#39; + Date.now() + &#39;_&#39; + Math.random().toString(36).slice(2, 5),<br>        name, dataUrl, source, isMerged: merged, capturedAt: new Date().toISOString()<br>      };<br>      evShots(page).push(shot);<br>      evActiveShotIdx = page.evidenceShots.length - 1;<br>      page.evidenceShotId = shot.id;<br>      scheduleAutosave(&#39;Added evidence screenshot&#39;);<br>      evRerender();<br>    }<br><br>    function evAddShotFromFile(file, nameOverride) {<br>      const target = getActiveMainPage();<br>      return new Promise(resolve =&gt; {<br>        const reader = new FileReader();<br>        reader.onload = ev =&gt; { evAddShot(nameOverride || file.name, ev.target.result, &#39;Uploaded File&#39;, false, target); resolve(); };<br>        reader.onerror = () =&gt; { showToast(&#39;Unable to read the image file.&#39;, &#39;error&#39;); resolve(); };<br>        reader.readAsDataURL(file);<br>      });<br>    }<br><br>    function evUpload(e) {<br>      Array.from(e.target.files || []).forEach(f =&gt; evAddShotFromFile(f));<br>    }<br><br>    async function evPasteButton() {<br>      try {<br>        if (!navigator.clipboard || !navigator.clipboard.read) return showToast(&#39;Press Ctrl+V on this screen to paste an image.&#39;, &#39;info&#39;);<br>        const items = await navigator.clipboard.read();<br>        for (const item of items) {<br>          const t = item.types.find(x =&gt; x.startsWith(&#39;image/&#39;));<br>          if (t) { const blob = await item.getType(t); await evAddShotFromFile(blob, `pasted_evidence_${Date.now()}.png`); return; }<br>        }<br>        showToast(&#39;No image in clipboard. Copy a screenshot, then press Ctrl+V.&#39;, &#39;warning&#39;);<br>      } catch (e) { showToast(&#39;Press Ctrl+V on this screen to paste your clipboard image.&#39;, &#39;info&#39;); }<br>    }<br><br>    async function evCapture() {<br>      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) return showToast(&#39;Screen capture is not supported here.&#39;, &#39;warning&#39;);<br>      try {<br>        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br>        const video = document.createElement(&#39;video&#39;);<br>        video.srcObject = stream;<br>        await video.play();<br>        const canvas = document.createElement(&#39;canvas&#39;);<br>        canvas.width = video.videoWidth; canvas.height = video.videoHeight;<br>        canvas.getContext(&#39;2d&#39;).drawImage(video, 0, 0);<br>        stream.getTracks().forEach(t =&gt; t.stop());<br>        evAddShot(`Evidence_Capture_${new Date().toISOString().slice(11, 19).replace(/:/g, &#39;-&#39;)}.png`, canvas.toDataURL(&#39;image/png&#39;), &#39;Browser Screen Share&#39;);<br>        showToast(&#39;Screen captured into Evidence Screenshots.&#39;, &#39;success&#39;);<br>      } catch (err) { showToast(&#39;Screen capture cancelled or permission denied.&#39;, &#39;info&#39;); }<br>    }<br><br>    function evSelectShot(idx) {<br>      evActiveShotIdx = idx;<br>      const page = getActiveMainPage();<br>      const shot = evShots(page)[idx];<br>      if (page &amp;&amp; shot) page.evidenceShotId = shot.id;<br>      scheduleAutosave(&#39;Selected evidence screenshot&#39;);<br>      renderApp();<br>    }<br><br>    function evToggleMerge(id) {<br>      const sel = appState.ui.evMergeSel = appState.ui.evMergeSel || [];<br>      const i = sel.indexOf(id);<br>      if (i &gt;= 0) sel.splice(i, 1); else sel.push(id);<br>      renderApp();<br>    }<br><br>    function evMoveShot(idx, dir) {<br>      const shots = evShots(getActiveMainPage());<br>      const t = idx + dir;<br>      if (t &lt; 0 || t &gt;= shots.length) return;<br>      [shots[idx], shots[t]] = [shots[t], shots[idx]];<br>      scheduleAutosave(&#39;Reordered evidence screenshots&#39;);<br>      renderApp();<br>    }<br><br>    function evDeleteShot(id) {<br>      const page = getActiveMainPage();<br>      page.evidenceShots = evShots(page).filter(s =&gt; s.id !== id);<br>      appState.ui.evMergeSel = (appState.ui.evMergeSel || []).filter(x =&gt; x !== id);<br>      scheduleAutosave(&#39;Deleted evidence screenshot&#39;);<br>      renderApp();<br>    }<br><br>    async function evMerge(direction) {<br>      const page = getActiveMainPage();<br>      const ids = appState.ui.evMergeSel || [];<br>      if (ids.length &lt; 2) return showToast(&#39;Tick at least 2 evidence screenshots to merge.&#39;, &#39;warning&#39;);<br>      const chosen = ids.map(id =&gt; evShots(page).find(s =&gt; s.id === id)).filter(Boolean);<br>      const imgs = await Promise.all(chosen.map(sh =&gt; new Promise(res =&gt; { const im = new Image(); im.onload = () =&gt; res(im); im.src = sh.dataUrl; })));<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      if (direction === &#39;vertical&#39;) { canvas.width = Math.max(...imgs.map(i =&gt; i.width)); canvas.height = imgs.reduce((a, i) =&gt; a + i.height, 0); }<br>      else { canvas.width = imgs.reduce((a, i) =&gt; a + i.width, 0); canvas.height = Math.max(...imgs.map(i =&gt; i.height)); }<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      let off = 0;<br>      imgs.forEach(im =&gt; { if (direction === &#39;vertical&#39;) { ctx.drawImage(im, 0, off); off += im.height; } else { ctx.drawImage(im, off, 0); off += im.width; } });<br>      page.evidenceMergeHistory = page.evidenceMergeHistory || [];<br>      page.evidenceMergeHistory.push({ sourceIds: [...ids], direction, timestamp: new Date().toISOString() });<br>      evAddShot(`Evidence_Merged_${direction}_${chosen.length}imgs.png`, canvas.toDataURL(&#39;image/png&#39;), `Merged (${direction})`, true, page);<br>      showToast(`Merged ${chosen.length} evidence screenshots (${direction}).`, &#39;success&#39;);<br>    }<br><br>    function evResetMerge() {<br>      const page = getActiveMainPage();<br>      page.evidenceMergeHistory = [];<br>      appState.ui.evMergeSel = [];<br>      scheduleAutosave(&#39;Reset evidence merge history&#39;);<br>      renderApp();<br>    }<br><br>    function evToggleQuickList() { appState.ui.evQuickListOpen = appState.ui.evQuickListOpen === false; renderApp(); }<br>    function evStepPage(dir) {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.mainPages.length) return;<br>      const idx = proj.mainPages.findIndex(mp =&gt; mp.id === appState.activeMainPageId);<br>      switchActiveMainPage(proj.mainPages[(Math.max(0, idx) + dir + proj.mainPages.length) % proj.mainPages.length].id);<br>    }<br>    function evToggleAutoAssign(c) { appState.settings.evAutoAssign = Boolean(c); scheduleAutosave(&#39;Toggled evidence auto-read&#39;); renderApp(); }<br>    function evToggleShowAll() { evFieldMapShowAll = !evFieldMapShowAll; renderApp(); }<br>    function evStartDraw(n) { appState.ui.evPendingLabel = Number(n); showToast(`Draw a box on the screenshot: it becomes QA-${n} and fills ${evTargetLabel()} of ${padC(n)}. (Esc to cancel)`, &#39;info&#39;); renderApp(); }<br>    function evCancelPending() { appState.ui.evPendingLabel = null; renderApp(); }<br><br>    function evFocus(annId) {<br>      const proj = getActiveProject(); const page = getActiveMainPage();<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      appState.ui.evSelectedAnnId = annId;<br>      const si = ann.screenshotId ? evShots(page).findIndex(s =&gt; s.id === ann.screenshotId) : -1;<br>      if (si &gt;= 0) { evActiveShotIdx = si; page.evidenceShotId = ann.screenshotId; }<br>      renderApp();<br>    }<br><br>    function evNudge(annId, dx, dy) { const a = evAnns(getActiveMainPage()).find(x =&gt; x.id === annId); if (!a) return; a.x = Math.max(0, a.x + dx); a.y = Math.max(0, a.y + dy); scheduleAutosave(&#39;Moved evidence box&#39;); renderApp(); }<br>    function evResize(annId, dw, dh) { const a = evAnns(getActiveMainPage()).find(x =&gt; x.id === annId); if (!a) return; a.w = Math.max(20, a.w + dw); a.h = Math.max(20, a.h + dh); scheduleAutosave(&#39;Resized evidence box&#39;); renderApp(); }<br>    function evUpdateProp(annId, key, val) { const a = evAnns(getActiveMainPage()).find(x =&gt; x.id === annId); if (!a) return; a[key] = val; scheduleAutosave(&#39;Updated evidence box&#39;); }<br>    function evDeleteAnn(annId) {<br>      const page = getActiveMainPage();<br>      (page.fields || []).forEach(f =&gt; { if (f.expectedSource === annId) delete f.expectedSource; if (f.actualSource === annId) delete f.actualSource; });<br>      page.evidenceAnnotations = evAnns(page).filter(a =&gt; a.id !== annId);<br>      scheduleAutosave(&#39;Deleted evidence box&#39;);<br>      renderApp();<br>    }<br><br>    function evSetBoxValue(annId, val) {<br>      const page = getActiveMainPage();<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.value = val;<br>      evAssign(page, ann);<br>      scheduleAutosave(&#39;Edited evidence box value&#39;);<br>      renderApp();<br>    }<br><br>    function evSetFieldValue(fieldId, val) {<br>      const page = getActiveMainPage();<br>      const f = (page.fields || []).find(x =&gt; x.id === fieldId);<br>      if (!f) return;<br>      f[evTargetKey()] = val;<br>      f.enabled = true;<br>      const ann = evAnns(page).find(a =&gt; Number(a.qaLabel) === Number(f.number));<br>      if (ann) { ann.value = val; f[evSourceKey()] = ann.id; }<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Edited box target value from evidence map&#39;);<br>      renderApp();<br>    }<br><br>    function evRelabel(annId, raw) {<br>      const page = getActiveMainPage();<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      const n = Math.floor(Number(raw));<br>      if (!Number.isFinite(n) || n &lt; 1) { renderApp(); return showToast(&#39;QA number must be 1 or higher.&#39;, &#39;warning&#39;); }<br>      if (evAnns(page).some(a =&gt; a.id !== annId &amp;&amp; Number(a.qaLabel) === n)) { renderApp(); return showToast(`QA-${n} (${padC(n)}) is already used on ${page.name}.`, &#39;warning&#39;); }<br>      const oldF = evField(page, ann.qaLabel);<br>      if (oldF &amp;&amp; oldF[evSourceKey()] === ann.id) { oldF[evTargetKey()] = &#39;&#39;; delete oldF[evSourceKey()]; }<br>      if (n &gt; (appState.settings.qaLabelMax || 200)) appState.settings.qaLabelMax = n;<br>      ann.qaLabel = n; ann.label = `QA-${n}`;<br>      evLink(page, ann);<br>      if (ann.value) evAssign(page, ann); else ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Relabelled evidence box&#39;);<br>      renderApp();<br>    }<br><br>    function evCrop(shot, ann) {<br>      return new Promise((resolve, reject) =&gt; {<br>        const img = new Image();<br>        img.onload = () =&gt; {<br>          try {<br>            const nW = img.naturalWidth || img.width, nH = img.naturalHeight || img.height;<br>            const base = document.getElementById(&#39;ev-base-img&#39;);<br>            const refW = ann.refW || (base &amp;&amp; base.clientWidth) || nW;<br>            const refH = ann.refH || (base &amp;&amp; base.clientHeight) || nH;<br>            const kx = nW / refW, ky = nH / refH, pad = 2;<br>            const sx = Math.max(0, Math.floor(ann.x * kx - pad)), sy = Math.max(0, Math.floor(ann.y * ky - pad));<br>            const sw = Math.min(nW - sx, Math.ceil(ann.w * kx + pad * 2)), sh = Math.min(nH - sy, Math.ceil(ann.h * ky + pad * 2));<br>            if (sw &lt; 2 || sh &lt; 2) throw new Error(&#39;Box is outside the screenshot area.&#39;);<br>            const c = document.createElement(&#39;canvas&#39;);<br>            c.width = sw; c.height = sh;<br>            c.getContext(&#39;2d&#39;).drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);<br>            resolve(c.toDataURL(&#39;image/png&#39;));<br>          } catch (err) { reject(err); }<br>        };<br>        img.onerror = () =&gt; reject(new Error(&#39;Could not load the screenshot for OCR.&#39;));<br>        img.src = shot.dataUrl;<br>      });<br>    }<br><br>    async function evReadBox(page, annId, silent = false) {<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      const proj = getActiveProject();<br>      const shot = evShots(page).find(s =&gt; s.id === ann.screenshotId) || evShots(page)[evActiveShotIdx];<br>      if (!shot) { if (!silent) showToast(&#39;No evidence screenshot to read from.&#39;, &#39;warning&#39;); return; }<br>      evReadingIds.add(annId);<br>      evRerender();<br>      try {<br>        const crop = await evCrop(shot, ann);<br>        const pre = await OcrMappingEngine.preprocessImageCanvas(crop, { grayscale: true, contrast: true, scale: 2 });<br>        const out = await OcrMappingEngine.runRealTesseractOCR(pre);<br>        const text = String(out.text || &#39;&#39;).replace(/\s+/g, &#39; &#39;).replace(/^[\s|_~&#39;&quot;`]+|[\s|_~&#39;&quot;`]+$/g, &#39;&#39;).trim();<br>        ann.value = text;<br>        ann.ocrConfidence = out.confidence;<br>        if (text) evAssign(page, ann);<br>        else if (!silent) showToast(`${ann.label}: no text found inside the box.`, &#39;warning&#39;);<br>      } catch (err) {<br>        if (!silent) showToast(`${ann.label} OCR: ${err.message}`, &#39;warning&#39;);<br>      } finally {<br>        evReadingIds.delete(annId);<br>      }<br>      scheduleAutosave(&#39;Read evidence box value&#39;);<br>      evRerender();<br>    }<br><br>    async function evReadAll() {<br>      const page = getActiveMainPage();<br>      const shot = evShots(getActiveMainPage())[evActiveShotIdx];<br>      const list = evAnns(page).filter(a =&gt; evVisible(a, shot));<br>      if (!list.length) return showToast(&#39;Draw at least one box first.&#39;, &#39;warning&#39;);<br>      showToast(`Reading ${list.length} box(es) on ${page.name}...`, &#39;info&#39;);<br>      for (const a of list) await evReadBox(page, a.id, true);<br>      showToast(`Finished reading boxes into ${evTargetLabel()}.`, &#39;success&#39;);<br>    }<br><br>    /* ---- Zoom / pan / precise drawing -------------------------------------<br>     * Boxes are stored in the screenshot&#39;s NATURAL pixel space (ann.nat = true,<br>     * refW/refH = natural size), so they stay exact at any zoom level.<br>     * Zoom is a % of the &quot;fit to width&quot; size (100% = fit).<br>     * ----------------------------------------------------------------------- */<br>    let evZoom = 1;<br>    const evScroll = { shotId: null, l: 0, t: 0 };<br>    let evSpaceDown = false;<br>    let evPanning = null;<br>    let evGlobalKeysBound = false;<br>    const evDimLoading = new Set();<br><br>    function evClampZoom(z) { return Math.min(8, Math.max(0.25, z)); }<br><br>    function evSyncZoomUi() {<br>      const lbl = document.getElementById(&#39;ev-zoom-label&#39;);<br>      const rng = document.getElementById(&#39;ev-zoom-range&#39;);<br>      if (lbl) lbl.textContent = Math.round(evZoom * 100) + &#39;%&#39;;<br>      if (rng) rng.value = Math.round(evZoom * 100);<br>    }<br><br>    function evSetZoom(z, cx, cy) {<br>      const stage = document.getElementById(&#39;ev-stage&#39;);<br>      const wrapper = document.getElementById(&#39;ev-canvas-wrapper&#39;);<br>      evZoom = evClampZoom(Number(z) || 1);<br>      if (!stage || !wrapper) return evSyncZoomUi();<br>      const sr = stage.getBoundingClientRect();<br>      if (cx == null) { cx = sr.left + sr.width / 2; cy = sr.top + sr.height / 2; }<br>      const r0 = wrapper.getBoundingClientRect();<br>      const fx = r0.width ? (cx - r0.left) / r0.width : 0.5;<br>      const fy = r0.height ? (cy - r0.top) / r0.height : 0.5;<br>      wrapper.style.width = (evZoom * 100) + &#39;%&#39;;<br>      const r1 = wrapper.getBoundingClientRect();<br>      stage.scrollLeft += (r1.left + fx * r1.width) - cx;<br>      stage.scrollTop += (r1.top + fy * r1.height) - cy;<br>      evSyncZoomUi();<br>    }<br><br>    function evZoomStep(dir) { evSetZoom(evZoom * (dir &gt; 0 ? 1.25 : 1 / 1.25)); }<br>    function evZoomFit() {<br>      evSetZoom(1);<br>      const stage = document.getElementById(&#39;ev-stage&#39;);<br>      if (stage) { stage.scrollLeft = 0; stage.scrollTop = 0; }<br>    }<br>    function evZoomActual() {<br>      const stage = document.getElementById(&#39;ev-stage&#39;);<br>      const shot = evShots(getActiveMainPage())[evActiveShotIdx];<br>      if (!stage || !shot || !shot.natW) return;<br>      const avail = Math.max(50, stage.clientWidth - 16);<br>      evSetZoom(shot.natW / avail);<br>    }<br><br>    // natural size of every screenshot is needed once; older boxes are converted to it<br>    function evMigrateAnns(page, shot) {<br>      if (!shot || !shot.natW) return;<br>      evAnns(page).forEach(a =&gt; {<br>        if (a.nat === true) return;<br>        if (a.screenshotId &amp;&amp; a.screenshotId !== shot.id) return;<br>        const kx = shot.natW / (a.refW || shot.natW);<br>        const ky = shot.natH / (a.refH || shot.natH);<br>        a.x = Math.round(a.x * kx); a.y = Math.round(a.y * ky);<br>        a.w = Math.round(a.w * kx); a.h = Math.round(a.h * ky);<br>        a.screenshotId = shot.id;<br>        a.refW = shot.natW; a.refH = shot.natH; a.nat = true;<br>      });<br>    }<br><br>    function evLoadDims(page, shot) {<br>      if (!shot || shot.natW || evDimLoading.has(shot.id)) return;<br>      evDimLoading.add(shot.id);<br>      const img = new Image();<br>      img.onload = () =&gt; {<br>        shot.natW = img.naturalWidth || img.width;<br>        shot.natH = img.naturalHeight || img.height;<br>        evDimLoading.delete(shot.id);<br>        evMigrateAnns(page, shot);<br>        scheduleAutosave(&#39;Measured evidence screenshot&#39;);<br>        evRerender();<br>      };<br>      img.onerror = () =&gt; evDimLoading.delete(shot.id);<br>      img.src = shot.dataUrl;<br>    }<br><br>    function evBindGlobalKeys() {<br>      if (evGlobalKeysBound) return;<br>      evGlobalKeysBound = true;<br>      const typing = e =&gt; { const t = e.target; return t &amp;&amp; (t.tagName === &#39;INPUT&#39; || t.tagName === &#39;TEXTAREA&#39; || t.tagName === &#39;SELECT&#39; || t.isContentEditable); };<br>      document.addEventListener(&#39;keydown&#39;, e =&gt; {<br>        if (appState.activeModule !== &#39;evidence&#39; || typing(e)) return;<br>        if (e.code === &#39;Space&#39;) { evSpaceDown = true; e.preventDefault(); const w = document.getElementById(&#39;ev-canvas-wrapper&#39;); if (w) w.style.cursor = &#39;grab&#39;; }<br>        else if (e.key === &#39;+&#39; || e.key === &#39;=&#39;) { e.preventDefault(); evZoomStep(1); }<br>        else if (e.key === &#39;-&#39; || e.key === &#39;_&#39;) { e.preventDefault(); evZoomStep(-1); }<br>        else if (e.key === &#39;0&#39;) { e.preventDefault(); evZoomFit(); }<br>      });<br>      document.addEventListener(&#39;keyup&#39;, e =&gt; {<br>        if (e.code === &#39;Space&#39;) { evSpaceDown = false; const w = document.getElementById(&#39;ev-canvas-wrapper&#39;); if (w) w.style.cursor = &#39;&#39;; }<br>      });<br>    }<br><br>    function evExport() {<br>      const img = document.getElementById(&#39;ev-base-img&#39;);<br>      const page = getActiveMainPage();<br>      if (!img || !page) return;<br>      const shot = evShots(page)[evActiveShotIdx];<br>      if (!shot || !shot.natW) return showToast(&#39;Screenshot is still loading, try again.&#39;, &#39;info&#39;);<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      canvas.width = shot.natW; canvas.height = shot.natH;<br>      const fs = Math.max(12, canvas.width / 90);<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br>      evAnns(page).filter(a =&gt; evVisible(a, shot)).forEach(ann =&gt; {<br>        ctx.strokeStyle = ann.color; ctx.lineWidth = Math.max(2, fs / 4);<br>        if (ann.type === &#39;circle&#39;) { ctx.beginPath(); ctx.ellipse(ann.x + ann.w / 2, ann.y + ann.h / 2, Math.abs(ann.w / 2), Math.abs(ann.h / 2), 0, 0, Math.PI * 2); ctx.stroke(); }<br>        else ctx.strokeRect(ann.x, ann.y, ann.w, ann.h);<br>        const tag = evTag(ann);<br>        ctx.font = `bold ${Math.round(fs)}px sans-serif`;<br>        const tw = ctx.measureText(tag).width + fs;<br>        ctx.fillStyle = ann.color;<br>        ctx.fillRect(ann.x, Math.max(0, ann.y - fs * 1.6), tw, fs * 1.6);<br>        ctx.fillStyle = &#39;#ffffff&#39;;<br>        ctx.fillText(tag, ann.x + fs / 2, Math.max(fs * 1.15, ann.y - fs * 0.4));<br>      });<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = canvas.toDataURL(&#39;image/png&#39;);<br>      a.download = `${page.name.replace(/[^a-z0-9]/gi, &#39;_&#39;)}_evidence_annotated.png`;<br>      a.click();<br>      showToast(&#39;Exported annotated evidence PNG.&#39;, &#39;success&#39;);<br>    }<br><br>    function initEvidenceCanvasEvents() {<br>      evBindGlobalKeys();<br>      const stage = document.getElementById(&#39;ev-stage&#39;);<br>      const wrapper = document.getElementById(&#39;ev-canvas-wrapper&#39;);<br>      if (!stage) return;<br><br>      // keep the zoomed view where it was after every re-render (same screenshot only)<br>      const curShot = evShots(getActiveMainPage())[evActiveShotIdx];<br>      if (curShot &amp;&amp; evScroll.shotId === curShot.id) { stage.scrollLeft = evScroll.l; stage.scrollTop = evScroll.t; }<br>      stage.onscroll = () =&gt; { if (curShot) { evScroll.shotId = curShot.id; evScroll.l = stage.scrollLeft; evScroll.t = stage.scrollTop; } };<br><br>      stage.onwheel = e =&gt; {<br>        if (!(e.ctrlKey || e.metaKey)) return;<br>        e.preventDefault();<br>        evSetZoom(evZoom * (e.deltaY &lt; 0 ? 1.15 : 1 / 1.15), e.clientX, e.clientY);<br>      };<br>      if (!wrapper) return;<br>      const shot = evShots(getActiveMainPage())[evActiveShotIdx];<br>      if (!shot || !shot.natW) return;<br>      const preview = document.getElementById(&#39;ev-preview&#39;);<br>      const toNat = e =&gt; {<br>        const r = wrapper.getBoundingClientRect();<br>        return {<br>          x: Math.min(shot.natW, Math.max(0, (e.clientX - r.left) / r.width * shot.natW)),<br>          y: Math.min(shot.natH, Math.max(0, (e.clientY - r.top) / r.height * shot.natH)),<br>          scale: r.width / shot.natW<br>        };<br>      };<br><br>      wrapper.onmousedown = e =&gt; {<br>        if (e.button === 1 || (e.button === 0 &amp;&amp; evSpaceDown)) {<br>          e.preventDefault();<br>          evPanning = { x: e.clientX, y: e.clientY, sl: stage.scrollLeft, st: stage.scrollTop };<br>          wrapper.style.cursor = &#39;grabbing&#39;;<br>          const move = ev =&gt; { stage.scrollLeft = evPanning.sl - (ev.clientX - evPanning.x); stage.scrollTop = evPanning.st - (ev.clientY - evPanning.y); };<br>          const up = () =&gt; { evPanning = null; wrapper.style.cursor = evSpaceDown ? &#39;grab&#39; : &#39;&#39;; document.removeEventListener(&#39;mousemove&#39;, move); document.removeEventListener(&#39;mouseup&#39;, up); };<br>          document.addEventListener(&#39;mousemove&#39;, move);<br>          document.addEventListener(&#39;mouseup&#39;, up);<br>          return;<br>        }<br>        if (e.button !== 0) return;<br>        e.preventDefault();<br>        const start = toNat(e);<br>        let last = start;<br>        const show = () =&gt; {<br>          if (!preview) return;<br>          preview.setAttribute(&#39;x&#39;, Math.min(start.x, last.x)); preview.setAttribute(&#39;y&#39;, Math.min(start.y, last.y));<br>          preview.setAttribute(&#39;width&#39;, Math.abs(last.x - start.x)); preview.setAttribute(&#39;height&#39;, Math.abs(last.y - start.y));<br>          preview.setAttribute(&#39;visibility&#39;, &#39;visible&#39;);<br>        };<br>        const move = ev =&gt; { last = toNat(ev); show(); };<br>        const up = ev =&gt; {<br>          document.removeEventListener(&#39;mousemove&#39;, move);<br>          document.removeEventListener(&#39;mouseup&#39;, up);<br>          if (preview) preview.setAttribute(&#39;visibility&#39;, &#39;hidden&#39;);<br>          last = toNat(ev);<br>          const w = Math.abs(last.x - start.x), h = Math.abs(last.y - start.y);<br>          if (w * start.scale &lt; 8 || h * start.scale &lt; 8) return;<br><br>          const page = getActiveMainPage();<br>          if (!page) return;<br>          const anns = evAnns(page);<br>          const qaNum = Number(appState.ui.evPendingLabel) || (appState.settings.qaAutoIncrement ? evNextLabel(page) : (appState.ui.evSelectedLabel || 1));<br>          if (anns.some(a =&gt; Number(a.qaLabel) === qaNum)) return showToast(`QA-${qaNum} (${padC(qaNum)}) is already used on ${page.name}. Pick an unused label.`, &#39;warning&#39;);<br>          const ann = {<br>            id: &#39;evann_&#39; + Date.now(), qaLabel: qaNum, type: appState.ui.annotationTool,<br>            x: Math.round(Math.min(start.x, last.x)), y: Math.round(Math.min(start.y, last.y)), w: Math.round(w), h: Math.round(h),<br>            color: appState.ui.annotationColor, label: `QA-${qaNum}`, comment: &#39;&#39;, defectId: &#39;&#39;, value: &#39;&#39;,<br>            screenshotId: shot.id, refW: shot.natW, refH: shot.natH, nat: true<br>          };<br>          anns.push(ann);<br>          appState.ui.evSelectedAnnId = ann.id;<br>          appState.ui.evPendingLabel = null;<br>          evLink(page, ann);<br>          if (appState.settings.qaAutoIncrement) appState.ui.evSelectedLabel = evNextLabel(page);<br>          scheduleAutosave(&#39;Added evidence box&#39;);<br>          renderApp();<br>          if (appState.settings.evAutoAssign !== false) setTimeout(() =&gt; evReadBox(page, ann.id, false), 0);<br>        };<br>        document.addEventListener(&#39;mousemove&#39;, move);<br>        document.addEventListener(&#39;mouseup&#39;, up);<br>      };<br>    }<br><br>    function evPageBar(proj, page) {<br>      const open = appState.ui.evQuickListOpen !== false;<br>      const tExp = evTarget() === &#39;expected&#39;;<br>      const pending = Number(appState.ui.evPendingLabel) || 0;<br>      const nextN = pending || (appState.settings.qaAutoIncrement ? evNextLabel(page) : (appState.ui.evSelectedLabel || 1));<br>      const nf = evField(page, nextN);<br>      const st = page.validationSummary ? page.validationSummary.overallStatus : &#39;PENDING&#39;;<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;navigateTo(&#39;validation&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                &lt;i data-lucide=&quot;arrow-left&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;span&gt;Receipt Validation&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;evStepPage(-1)&quot; class=&quot;px-2.5 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800&quot; title=&quot;Previous Main Page (Alt+←)&quot;&gt;◀&lt;/button&gt;<br>              &lt;select onchange=&quot;switchActiveMainPage(this.value)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 max-w-[260px]&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; `&lt;option value=&quot;${mp.id}&quot; ${mp.id === page.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(mp.name)} (${(mp.evidenceAnnotations || []).length} QA)&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>              &lt;button onclick=&quot;evStepPage(1)&quot; class=&quot;px-2.5 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800&quot; title=&quot;Next Main Page (Alt+→)&quot;&gt;▶&lt;/button&gt;<br>              ${statusBadge(st)}<br>              &lt;span class=&quot;text-[11px] text-slate-500 dark:text-slate-400&quot;&gt;QA-1 = C01, QA-2 = C02 … box value fills &lt;strong&gt;${evTargetLabel()}&lt;/strong&gt;&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;div class=&quot;inline-flex items-center rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden text-xs font-semibold&quot; title=&quot;Main toggle: applies to every Main Page and stays when you switch pages&quot;&gt;<br>                &lt;span class=&quot;px-2.5 py-2 text-slate-400&quot;&gt;Box value →&lt;/span&gt;<br>                &lt;button onclick=&quot;evSetTarget(&#39;expected&#39;)&quot; class=&quot;px-3 py-2 ${tExp ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-50 dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700&#39;}&quot;&gt;Expected Value&lt;/button&gt;<br>                &lt;button onclick=&quot;evSetTarget(&#39;actual&#39;)&quot; class=&quot;px-3 py-2 ${!tExp ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-50 dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700&#39;}&quot;&gt;Found on Receipt&lt;/button&gt;<br>              &lt;/div&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 cursor-pointer&quot; title=&quot;When ON, each drawn box is read with OCR and its text fills the field chosen by the Box value toggle&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; ${appState.settings.evAutoAssign !== false ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;evToggleAutoAssign(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Auto-read box into field&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;button onclick=&quot;evToggleQuickList()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition ${open ? &#39;bg-indigo-600 text-white border-indigo-600&#39; : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700&#39;}&quot;&gt;<br>                &lt;i data-lucide=&quot;list-checks&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;span&gt;Quick List (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2 text-xs px-3 py-2 rounded-xl ${pending ? &#39;bg-amber-500/15 border border-amber-500/40 text-amber-700 dark:text-amber-300&#39; : &#39;bg-slate-50 dark:bg-slate-800/60 text-slate-600 dark:text-slate-300&#39;}&quot;&gt;<br>            &lt;span class=&quot;font-bold&quot;&gt;Next box you draw:&lt;/span&gt;<br>            &lt;span class=&quot;font-mono font-bold&quot;&gt;QA-${nextN} ▸ ${padC(nextN)}${nf ? &#39; · &#39; + escapeHtml(nf.name) : &#39;&#39;}&lt;/span&gt;<br>            ${pending ? `&lt;button onclick=&quot;evCancelPending()&quot; class=&quot;ml-auto px-2 py-0.5 rounded-lg bg-white/70 dark:bg-slate-900/60 text-[11px] font-semibold&quot;&gt;Cancel (Esc)&lt;/button&gt;` : &#39;&lt;span class=&quot;ml-auto text-[11px] text-slate-400&quot;&gt;Alt+←/→ switches page&lt;/span&gt;&#39;}<br>          &lt;/div&gt;<br>          ${open ? renderMainPageQuickListPanel(proj, page, &#39;evToggleQuickList()&#39;, mp =&gt; (mp.evidenceAnnotations || []).length) : &#39;&#39;}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function evAnnCard(page, ann) {<br>      const reading = evReadingIds.has(ann.id);<br>      const f = evField(page, ann.qaLabel);<br>      return `<br>        &lt;div class=&quot;p-3 rounded-xl border ${appState.ui.evSelectedAnnId === ann.id ? &#39;border-brand-500 bg-brand-500/5&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} space-y-2 text-xs&quot;&gt;<br>          &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;button onclick=&quot;evFocus(&#39;${ann.id}&#39;)&quot; class=&quot;font-bold&quot; style=&quot;color:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/button&gt;<br>            &lt;button onclick=&quot;evDeleteAnn(&#39;${ann.id}&#39;)&quot; class=&quot;text-rose-500 hover:underline text-[11px]&quot;&gt;Delete&lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;px-2 py-1 rounded bg-indigo-500/10 text-indigo-500 font-mono text-[10px] font-bold truncate&quot;&gt;▸ ${padC(ann.qaLabel)}${f ? &#39; · &#39; + escapeHtml(f.name) : &#39;&#39;}&lt;/div&gt;<br>          &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.comment || &#39;&#39;)}&quot; onchange=&quot;evUpdateProp(&#39;${ann.id}&#39;, &#39;comment&#39;, this.value)&quot; placeholder=&quot;Evidence comment...&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>          &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>            &lt;span class=&quot;text-[10px] font-bold text-slate-400&quot;&gt;QA #&lt;/span&gt;<br>            &lt;input type=&quot;number&quot; min=&quot;1&quot; value=&quot;${Number(ann.qaLabel)}&quot; onchange=&quot;evRelabel(&#39;${ann.id}&#39;, this.value)&quot; class=&quot;w-16 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; title=&quot;Changing the number moves this box to another column&quot; /&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.defectId || &#39;&#39;)}&quot; onchange=&quot;evUpdateProp(&#39;${ann.id}&#39;, &#39;defectId&#39;, this.value)&quot; placeholder=&quot;Defect ID&quot; class=&quot;flex-1 min-w-0 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.value || &#39;&#39;)}&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} onchange=&quot;evSetBoxValue(&#39;${ann.id}&#39;, this.value)&quot; placeholder=&quot;${reading ? &#39;Reading box...&#39; : &#39;Value read from box&#39;}&quot; class=&quot;flex-1 min-w-0 px-2 py-1 rounded bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono text-[11px]&quot; /&gt;<br>            &lt;button onclick=&quot;evReadBox(getActiveMainPage(), &#39;${ann.id}&#39;)&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-brand-500/10 text-brand-500 text-[10px] font-semibold disabled:opacity-50&quot;&gt;${reading ? &#39;…&#39; : &#39;Read&#39;}&lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex items-center gap-1 pt-1&quot;&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, -10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;←&lt;/button&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, 10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;→&lt;/button&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, 0, -10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↑&lt;/button&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, 0, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↓&lt;/button&gt;<br>            &lt;button onclick=&quot;evResize(&#39;${ann.id}&#39;, 15, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;+Size&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br><br>    /****************************************************************************<br>     * EVIDENCE FIELD MAP EXPORT: copy / CSV / Excel (one sheet per Main Page)<br>     * Excel is written by a tiny built-in XLSX writer, so it works offline.<br>     ****************************************************************************/<br>    const EV_EXPORT_HEADERS = [&#39;Col&#39;, &#39;QA Box&#39;, &#39;Field Name&#39;, &#39;Type&#39;, &#39;Expected Value&#39;, &#39;Found on Receipt&#39;, &#39;OCR Confidence %&#39;, &#39;Status&#39;, &#39;Evidence Comment&#39;, &#39;Defect ID&#39;, &#39;Evidence Screenshot&#39;];<br><br>    function evExportRows(page) {<br>      if (!page.validationSummary || !page.fields.some(f =&gt; f.lastValidation)) ValidationEngine.validateMainPage(page);<br>      const byLabel = {};<br>      evAnns(page).forEach(a =&gt; { byLabel[Number(a.qaLabel)] = a; });<br>      const shots = evShots(page);<br>      return (page.fields || [])<br>        .filter(f =&gt; f.number &lt;= 10 || f.enabled || f.expectedValue || f.actualValue || byLabel[f.number])<br>        .map(f =&gt; {<br>          const ann = byLabel[f.number];<br>          const shot = ann ? shots.find(x =&gt; x.id === ann.screenshotId) : null;<br>          return [<br>            padC(f.number),<br>            ann ? ann.label : &#39;&#39;,<br>            f.name || &#39;&#39;,<br>            f.dataType || &#39;&#39;,<br>            f.expectedValue || &#39;&#39;,<br>            f.actualValue || &#39;&#39;,<br>            ann &amp;&amp; ann.ocrConfidence != null ? ann.ocrConfidence : &#39;&#39;,<br>            f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;,<br>            ann ? (ann.comment || &#39;&#39;) : &#39;&#39;,<br>            ann ? (ann.defectId || &#39;&#39;) : &#39;&#39;,<br>            shot ? shot.name : &#39;&#39;<br>          ];<br>        });<br>    }<br><br>    function evExportPages(scope) {<br>      const proj = getActiveProject();<br>      const cur = getActiveMainPage();<br>      return scope === &#39;all&#39; ? (proj.mainPages || []) : (cur ? [cur] : []);<br>    }<br><br>    function evCsvCell(v) {<br>      const t = String(v == null ? &#39;&#39; : v);<br>      return /[&quot;,\r\n]/.test(t) ? &#39;&quot;&#39; + t.replace(/&quot;/g, &#39;&quot;&quot;&#39;) + &#39;&quot;&#39; : t;<br>    }<br>    function evTsvCell(v) {<br>      const t = String(v == null ? &#39;&#39; : v).replace(/[\t\r\n]+/g, &#39; &#39;);<br>      return t;<br>    }<br><br>    function evBuildTable(scope, cell) {<br>      const pages = evExportPages(scope);<br>      const head = [&#39;Main Page&#39;, ...EV_EXPORT_HEADERS];<br>      const lines = [head.map(cell).join(cell === evCsvCell ? &#39;,&#39; : &#39;\t&#39;)];<br>      pages.forEach(p =&gt; {<br>        evExportRows(p).forEach(r =&gt; lines.push([p.name, ...r].map(cell).join(cell === evCsvCell ? &#39;,&#39; : &#39;\t&#39;)));<br>      });<br>      return { text: lines.join(&#39;\r\n&#39;), pages: pages.length, rows: lines.length - 1 };<br>    }<br><br>    async function evCopyText(text) {<br>      try {<br>        if (navigator.clipboard &amp;&amp; navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); return true; }<br>      } catch (e) { /* fall through */ }<br>      try {<br>        const ta = document.createElement(&#39;textarea&#39;);<br>        ta.value = text; ta.style.position = &#39;fixed&#39;; ta.style.opacity = &#39;0&#39;;<br>        document.body.appendChild(ta); ta.select();<br>        const ok = document.execCommand(&#39;copy&#39;);<br>        document.body.removeChild(ta);<br>        return ok;<br>      } catch (e) { return false; }<br>    }<br><br>    async function evCopyMap(scope) {<br>      const t = evBuildTable(scope, evTsvCell);<br>      if (!t.rows) return showToast(&#39;Nothing to copy yet.&#39;, &#39;warning&#39;);<br>      const ok = await evCopyText(t.text);<br>      showToast(ok ? `Copied ${t.rows} row(s) from ${t.pages} page(s). Paste into Excel or Sheets.` : &#39;Copy was blocked by the browser. Use the CSV download instead.&#39;, ok ? &#39;success&#39; : &#39;warning&#39;);<br>    }<br><br>    function evStamp() { return new Date().toISOString().slice(0, 19).replace(/[:T]/g, &#39;-&#39;); }<br><br>    function evDownloadCsv(scope) {<br>      const proj = getActiveProject();<br>      const t = evBuildTable(scope, evCsvCell);<br>      if (!t.rows) return showToast(&#39;Nothing to export yet.&#39;, &#39;warning&#39;);<br>      const name = scope === &#39;all&#39; ? `${proj.name}_evidence_field_map_all_pages` : `${getActiveMainPage().name}_evidence_field_map`;<br>      downloadBlob(&#39; &#39; + t.text, `${name.replace(/[^a-z0-9._-]+/gi, &#39;_&#39;)}_${evStamp()}.csv`, &#39;text/csv;charset=utf-8&#39;);<br>      showToast(`Downloaded CSV with ${t.rows} row(s) from ${t.pages} page(s).`, &#39;success&#39;);<br>    }<br><br>    // ---------- minimal XLSX writer (zip &quot;stored&quot;, inline strings) ----------<br>    const EV_CRC_TABLE = (() =&gt; { const t = new Uint32Array(256); for (let n = 0; n &lt; 256; n++) { let c = n; for (let k = 0; k &lt; 8; k++) c = c &amp; 1 ? 0xEDB88320 ^ (c &gt;&gt;&gt; 1) : c &gt;&gt;&gt; 1; t[n] = c &gt;&gt;&gt; 0; } return t; })();<br>    function evCrc32(bytes) { let c = 0xFFFFFFFF; for (let i = 0; i &lt; bytes.length; i++) c = EV_CRC_TABLE[(c ^ bytes[i]) &amp; 255] ^ (c &gt;&gt;&gt; 8); return (c ^ 0xFFFFFFFF) &gt;&gt;&gt; 0; }<br><br>    function evZip(files) {<br>      const enc = new TextEncoder();<br>      const chunks = [], central = [];<br>      let offset = 0;<br>      const d = new Date();<br>      const dosTime = (d.getHours() &lt;&lt; 11) | (d.getMinutes() &lt;&lt; 5) | (d.getSeconds() &gt;&gt; 1);<br>      const dosDate = ((d.getFullYear() - 1980) &lt;&lt; 9) | ((d.getMonth() + 1) &lt;&lt; 5) | d.getDate();<br>      files.forEach(f =&gt; {<br>        const name = enc.encode(f.name), data = enc.encode(f.content), crc = evCrc32(data);<br>        const lh = new DataView(new ArrayBuffer(30));<br>        lh.setUint32(0, 0x04034b50, true); lh.setUint16(4, 20, true); lh.setUint16(6, 0x0800, true); lh.setUint16(8, 0, true);<br>        lh.setUint16(10, dosTime, true); lh.setUint16(12, dosDate, true); lh.setUint32(14, crc, true);<br>        lh.setUint32(18, data.length, true); lh.setUint32(22, data.length, true); lh.setUint16(26, name.length, true); lh.setUint16(28, 0, true);<br>        chunks.push(new Uint8Array(lh.buffer), name, data);<br>        const ch = new DataView(new ArrayBuffer(46));<br>        ch.setUint32(0, 0x02014b50, true); ch.setUint16(4, 20, true); ch.setUint16(6, 20, true); ch.setUint16(8, 0x0800, true); ch.setUint16(10, 0, true);<br>        ch.setUint16(12, dosTime, true); ch.setUint16(14, dosDate, true); ch.setUint32(16, crc, true);<br>        ch.setUint32(20, data.length, true); ch.setUint32(24, data.length, true); ch.setUint16(28, name.length, true);<br>        ch.setUint32(42, offset, true);<br>        central.push(new Uint8Array(ch.buffer), name);<br>        offset += 30 + name.length + data.length;<br>      });<br>      const cdSize = central.reduce((a, c) =&gt; a + c.length, 0);<br>      const end = new DataView(new ArrayBuffer(22));<br>      end.setUint32(0, 0x06054b50, true); end.setUint16(8, files.length, true); end.setUint16(10, files.length, true);<br>      end.setUint32(12, cdSize, true); end.setUint32(16, offset, true);<br>      const all = [...chunks, ...central, new Uint8Array(end.buffer)];<br>      const out = new Uint8Array(all.reduce((a, c) =&gt; a + c.length, 0));<br>      let p = 0; all.forEach(c =&gt; { out.set(c, p); p += c.length; });<br>      return out;<br>    }<br><br>    function evXml(v) {<br>      return String(v == null ? &#39;&#39; : v).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, &#39;&#39;)<br>        .replace(/&amp;/g, &#39;&amp;amp;&#39;).replace(/&lt;/g, &#39;&amp;lt;&#39;).replace(/&gt;/g, &#39;&amp;gt;&#39;).replace(/&quot;/g, &#39;&amp;quot;&#39;);<br>    }<br>    function evColName(i) { let n = i + 1, s = &#39;&#39;; while (n &gt; 0) { const m = (n - 1) % 26; s = String.fromCharCode(65 + m) + s; n = Math.floor((n - 1) / 26); } return s; }<br><br>    function evSheetXml(headers, rows) {<br>      const widths = headers.map((h, i) =&gt; Math.min(60, Math.max(String(h).length + 2, ...rows.map(r =&gt; String(r[i] == null ? &#39;&#39; : r[i]).length + 2), 8)));<br>      const cell = (v, r, c, style) =&gt; {<br>        const ref = evColName(c) + (r + 1);<br>        if (typeof v === &#39;number&#39; &amp;&amp; Number.isFinite(v)) return `&lt;c r=&quot;${ref}&quot;${style ? ` s=&quot;${style}&quot;` : &#39;&#39;}&gt;&lt;v&gt;${v}&lt;/v&gt;&lt;/c&gt;`;<br>        return `&lt;c r=&quot;${ref}&quot; t=&quot;inlineStr&quot;${style ? ` s=&quot;${style}&quot;` : &#39;&#39;}&gt;&lt;is&gt;&lt;t xml:space=&quot;preserve&quot;&gt;${evXml(v)}&lt;/t&gt;&lt;/is&gt;&lt;/c&gt;`;<br>      };<br>      const all = [headers, ...rows];<br>      const body = all.map((row, r) =&gt; `&lt;row r=&quot;${r + 1}&quot;&gt;${row.map((v, c) =&gt; cell(v, r, c, r === 0 ? 1 : 0)).join(&#39;&#39;)}&lt;/row&gt;`).join(&#39;&#39;);<br>      return `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;worksheet xmlns=&quot;http://schemas.openxmlformats.org/spreadsheetml/2006/main&quot;&gt;&lt;sheetViews&gt;&lt;sheetView workbookViewId=&quot;0&quot;&gt;&lt;pane ySplit=&quot;1&quot; topLeftCell=&quot;A2&quot; activePane=&quot;bottomLeft&quot; state=&quot;frozen&quot;/&gt;&lt;/sheetView&gt;&lt;/sheetViews&gt;&lt;cols&gt;${widths.map((w, i) =&gt; `&lt;col min=&quot;${i + 1}&quot; max=&quot;${i + 1}&quot; width=&quot;${w}&quot; customWidth=&quot;1&quot;/&gt;`).join(&#39;&#39;)}&lt;/cols&gt;&lt;sheetData&gt;${body}&lt;/sheetData&gt;&lt;/worksheet&gt;`;<br>    }<br><br>    function evSheetName(name, used) {<br>      let base = String(name || &#39;Page&#39;).replace(/[\\\/\?\*\[\]:]/g, &#39;-&#39;).replace(/^&#39;+|&#39;+$/g, &#39;&#39;).trim().slice(0, 31) || &#39;Page&#39;;<br>      let out = base, n = 2;<br>      while (used.has(out.toLowerCase())) { const suf = ` (${n++})`; out = base.slice(0, 31 - suf.length) + suf; }<br>      used.add(out.toLowerCase());<br>      return out;<br>    }<br><br>    function evBuildXlsx(sheets) {<br>      const n = sheets.length;<br>      const files = [<br>        { name: &#39;[Content_Types].xml&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;Types xmlns=&quot;http://schemas.openxmlformats.org/package/2006/content-types&quot;&gt;&lt;Default Extension=&quot;rels&quot; ContentType=&quot;application/vnd.openxmlformats-package.relationships+xml&quot;/&gt;&lt;Default Extension=&quot;xml&quot; ContentType=&quot;application/xml&quot;/&gt;&lt;Override PartName=&quot;/xl/workbook.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml&quot;/&gt;&lt;Override PartName=&quot;/xl/styles.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml&quot;/&gt;${sheets.map((_, i) =&gt; `&lt;Override PartName=&quot;/xl/worksheets/sheet${i + 1}.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml&quot;/&gt;`).join(&#39;&#39;)}&lt;/Types&gt;` },<br>        { name: &#39;_rels/.rels&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;&lt;Relationship Id=&quot;rId1&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument&quot; Target=&quot;xl/workbook.xml&quot;/&gt;&lt;/Relationships&gt;` },<br>        { name: &#39;xl/workbook.xml&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;workbook xmlns=&quot;http://schemas.openxmlformats.org/spreadsheetml/2006/main&quot; xmlns:r=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships&quot;&gt;&lt;sheets&gt;${sheets.map((sh, i) =&gt; `&lt;sheet name=&quot;${evXml(sh.name)}&quot; sheetId=&quot;${i + 1}&quot; r:id=&quot;rId${i + 1}&quot;/&gt;`).join(&#39;&#39;)}&lt;/sheets&gt;&lt;/workbook&gt;` },<br>        { name: &#39;xl/_rels/workbook.xml.rels&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;${sheets.map((_, i) =&gt; `&lt;Relationship Id=&quot;rId${i + 1}&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet&quot; Target=&quot;worksheets/sheet${i + 1}.xml&quot;/&gt;`).join(&#39;&#39;)}&lt;Relationship Id=&quot;rId${n + 1}&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles&quot; Target=&quot;styles.xml&quot;/&gt;&lt;/Relationships&gt;` },<br>        { name: &#39;xl/styles.xml&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;styleSheet xmlns=&quot;http://schemas.openxmlformats.org/spreadsheetml/2006/main&quot;&gt;&lt;fonts count=&quot;2&quot;&gt;&lt;font&gt;&lt;sz val=&quot;11&quot;/&gt;&lt;name val=&quot;Calibri&quot;/&gt;&lt;/font&gt;&lt;font&gt;&lt;b/&gt;&lt;sz val=&quot;11&quot;/&gt;&lt;color rgb=&quot;FFFFFFFF&quot;/&gt;&lt;name val=&quot;Calibri&quot;/&gt;&lt;/font&gt;&lt;/fonts&gt;&lt;fills count=&quot;3&quot;&gt;&lt;fill&gt;&lt;patternFill patternType=&quot;none&quot;/&gt;&lt;/fill&gt;&lt;fill&gt;&lt;patternFill patternType=&quot;gray125&quot;/&gt;&lt;/fill&gt;&lt;fill&gt;&lt;patternFill patternType=&quot;solid&quot;&gt;&lt;fgColor rgb=&quot;FF4F46E5&quot;/&gt;&lt;bgColor indexed=&quot;64&quot;/&gt;&lt;/patternFill&gt;&lt;/fill&gt;&lt;/fills&gt;&lt;borders count=&quot;1&quot;&gt;&lt;border&gt;&lt;left/&gt;&lt;right/&gt;&lt;top/&gt;&lt;bottom/&gt;&lt;diagonal/&gt;&lt;/border&gt;&lt;/borders&gt;&lt;cellStyleXfs count=&quot;1&quot;&gt;&lt;xf numFmtId=&quot;0&quot; fontId=&quot;0&quot; fillId=&quot;0&quot; borderId=&quot;0&quot;/&gt;&lt;/cellStyleXfs&gt;&lt;cellXfs count=&quot;2&quot;&gt;&lt;xf numFmtId=&quot;0&quot; fontId=&quot;0&quot; fillId=&quot;0&quot; borderId=&quot;0&quot; xfId=&quot;0&quot;/&gt;&lt;xf numFmtId=&quot;0&quot; fontId=&quot;1&quot; fillId=&quot;2&quot; borderId=&quot;0&quot; xfId=&quot;0&quot; applyFont=&quot;1&quot; applyFill=&quot;1&quot;/&gt;&lt;/cellXfs&gt;&lt;cellStyles count=&quot;1&quot;&gt;&lt;cellStyle name=&quot;Normal&quot; xfId=&quot;0&quot; builtinId=&quot;0&quot;/&gt;&lt;/cellStyles&gt;&lt;/styleSheet&gt;` },<br>        ...sheets.map((sh, i) =&gt; ({ name: `xl/worksheets/sheet${i + 1}.xml`, content: evSheetXml(sh.headers, sh.rows) }))<br>      ];<br>      return evZip(files);<br>    }<br><br>    function evDownloadXlsx(scope) {<br>      const proj = getActiveProject();<br>      const pages = evExportPages(scope);<br>      if (!pages.length) return showToast(&#39;Nothing to export yet.&#39;, &#39;warning&#39;);<br>      const used = new Set();<br>      const sheets = pages.map(p =&gt; ({ name: evSheetName(p.name, used), headers: EV_EXPORT_HEADERS, rows: evExportRows(p) }));<br>      const bytes = evBuildXlsx(sheets);<br>      const name = scope === &#39;all&#39; ? `${proj.name}_evidence_field_map_all_pages` : `${getActiveMainPage().name}_evidence_field_map`;<br>      downloadBlob(bytes, `${name.replace(/[^a-z0-9._-]+/gi, &#39;_&#39;)}_${evStamp()}.xlsx`, &#39;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;);<br>      showToast(`Downloaded Excel with ${sheets.length} sheet(s), one per Main Page.`, &#39;success&#39;);<br>    }<br><br>    function evFieldMap(page) {<br>      if (!page.validationSummary) ValidationEngine.validateMainPage(page);<br>      const byLabel = {};<br>      evAnns(page).forEach(a =&gt; { byLabel[Number(a.qaLabel)] = a; });<br>      const pending = Number(appState.ui.evPendingLabel) || 0;<br>      const rows = (page.fields || []).filter(f =&gt; evFieldMapShowAll || f.number &lt;= 10 || f.enabled || f.expectedValue || f.actualValue || byLabel[f.number]);<br>      const withBox = rows.filter(f =&gt; byLabel[f.number]);<br>      const filled = withBox.filter(f =&gt; String(f[evTargetKey()] || &#39;&#39;).trim() !== &#39;&#39;).length;<br>      const passed = withBox.filter(f =&gt; f.lastValidation &amp;&amp; f.lastValidation.status === &#39;PASS&#39;).length;<br>      const thr = appState.settings.autoAcceptConfidenceThreshold;<br>      const tExp = evTarget() === &#39;expected&#39;;<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Evidence Box ⇄ Field Map — ${escapeHtml(page.name)}&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;QA-n is column Cn. The value read in a box goes to &lt;strong&gt;${evTargetLabel()}&lt;/strong&gt; (change it with the “Box value →” toggle above; it applies to every Main Page). The other column is read-only here: Found on Receipt is normally filled in Receipt Validation (auto or Re-Run OCR &amp;amp; Auto-Match). Evidence screenshots and boxes belong to this Main Page only.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2 text-xs&quot;&gt;<br>              &lt;span class=&quot;px-2.5 py-1 rounded-full font-bold bg-slate-100 dark:bg-slate-800&quot;&gt;${withBox.length} boxes&lt;/span&gt;<br>              &lt;span class=&quot;px-2.5 py-1 rounded-full font-bold bg-sky-500/15 text-sky-500&quot;&gt;${filled} filled&lt;/span&gt;<br>              &lt;span class=&quot;px-2.5 py-1 rounded-full font-bold ${withBox.length &amp;&amp; passed === withBox.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;${passed} matched on receipt&lt;/span&gt;<br>              &lt;button onclick=&quot;evReadAll()&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;Read all boxes&lt;/button&gt;<br>              &lt;button onclick=&quot;evApplyStored()&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700&quot; title=&quot;Write the values already read from the boxes into the selected target without running OCR again&quot;&gt;Apply values → ${evTargetLabel()}&lt;/button&gt;<br>              &lt;button onclick=&quot;evToggleShowAll()&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;${evFieldMapShowAll ? &#39;Active fields only&#39; : &#39;Show all fields&#39;}&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2 text-xs px-3 py-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>            &lt;span class=&quot;font-bold text-slate-500 mr-1&quot;&gt;Export / Copy&lt;/span&gt;<br>            &lt;button onclick=&quot;evCopyMap(&#39;page&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot; title=&quot;Copy this page&#39;s table (tab-separated) to paste into Excel or Sheets&quot;&gt;Copy this page&lt;/button&gt;<br>            &lt;button onclick=&quot;evCopyMap(&#39;all&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot; title=&quot;Copy all pages in one table with a Main Page column&quot;&gt;Copy all pages (${getActiveProject().mainPages.length})&lt;/button&gt;<br>            &lt;span class=&quot;w-px h-5 bg-slate-300 dark:bg-slate-700 mx-1&quot;&gt;&lt;/span&gt;<br>            &lt;button onclick=&quot;evDownloadCsv(&#39;page&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot;&gt;CSV this page&lt;/button&gt;<br>            &lt;button onclick=&quot;evDownloadCsv(&#39;all&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot; title=&quot;One CSV with a Main Page column&quot;&gt;CSV all pages&lt;/button&gt;<br>            &lt;span class=&quot;w-px h-5 bg-slate-300 dark:bg-slate-700 mx-1&quot;&gt;&lt;/span&gt;<br>            &lt;button onclick=&quot;evDownloadXlsx(&#39;page&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot;&gt;Excel this page&lt;/button&gt;<br>            &lt;button onclick=&quot;evDownloadXlsx(&#39;all&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold bg-emerald-600 hover:bg-emerald-700 text-white&quot; title=&quot;One .xlsx file, one sheet per Main Page&quot;&gt;Excel all pages (1 sheet per page)&lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;overflow-x-auto max-h-[520px]&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead class=&quot;sticky top-0 bg-white dark:bg-slate-900 z-10&quot;&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2 w-14&quot;&gt;Col&lt;/th&gt;&lt;th class=&quot;pb-2 w-20&quot;&gt;QA Box&lt;/th&gt;&lt;th class=&quot;pb-2&quot;&gt;Field Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2&quot;&gt;${tExp ? &#39;Expected Value (from box, editable)&#39; : &#39;Expected Value&#39;}&lt;/th&gt;&lt;th class=&quot;pb-2&quot;&gt;${tExp ? &#39;Found on Receipt&#39; : &#39;Found on Receipt (from box, editable)&#39;}&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;&lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;&lt;th class=&quot;pb-2 text-right&quot;&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${rows.map(f =&gt; {<br>                  const ann = byLabel[f.number];<br>                  const reading = ann &amp;&amp; evReadingIds.has(ann.id);<br>                  const st = f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;;<br>                  const isSel = ann &amp;&amp; appState.ui.evSelectedAnnId === ann.id;<br>                  const conf = ann &amp;&amp; ann.ocrConfidence != null ? ann.ocrConfidence : null;<br>                  return `<br>                    &lt;tr class=&quot;${isSel ? &#39;bg-brand-500/10&#39; : pending === f.number ? &#39;bg-amber-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/40&#39;}&quot;&gt;<br>                      &lt;td class=&quot;py-2 font-mono font-semibold text-slate-400&quot;&gt;${padC(f.number)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2&quot;&gt;${ann ? `&lt;button onclick=&quot;evFocus(&#39;${ann.id}&#39;)&quot; class=&quot;px-2 py-0.5 rounded text-[11px] font-bold text-white&quot; style=&quot;background:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/button&gt;` : &#39;&lt;span class=&quot;text-slate-300 dark:text-slate-600&quot;&gt;—&lt;/span&gt;&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.name)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;name&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-semibold&quot; /&gt;&lt;/td&gt;<br>                      ${tExp ? `&lt;td class=&quot;py-2 pr-2 font-mono text-emerald-500&quot;&gt;${escapeHtml(f.actualValue || &#39;-&#39;)}&lt;/td&gt;` : `&lt;td class=&quot;py-2 pr-2&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue || &#39;&#39;)}&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} placeholder=&quot;${reading ? &#39;Reading box...&#39; : ann ? &#39;Click Re-read or type&#39; : &#39;Draw a box or type&#39;}&quot; onchange=&quot;evSetFieldValue(&#39;${f.id}&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;&lt;/td&gt;`}<br>                      ${tExp ? `&lt;td class=&quot;py-2 pr-2&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.expectedValue || &#39;&#39;)}&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} placeholder=&quot;${reading ? &#39;Reading box...&#39; : ann ? &#39;Click Re-read or type&#39; : &#39;Draw a box or type&#39;}&quot; onchange=&quot;evSetFieldValue(&#39;${f.id}&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;&lt;/td&gt;` : `&lt;td class=&quot;py-2 pr-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(f.expectedValue || &#39;-&#39;)}&lt;/td&gt;`}<br>                      &lt;td class=&quot;py-2 text-center font-mono text-[11px] ${conf != null &amp;&amp; conf &lt; thr ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;${conf != null ? conf + &#39;%&#39; : &#39;-&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-right whitespace-nowrap&quot;&gt;<br>                        ${ann ? `<br>                          &lt;button onclick=&quot;evReadBox(getActiveMainPage(), &#39;${ann.id}&#39;)&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded-lg bg-brand-500/10 text-brand-500 font-semibold disabled:opacity-50&quot;&gt;${reading ? &#39;Reading…&#39; : &#39;Re-read&#39;}&lt;/button&gt;<br>                          &lt;button onclick=&quot;evDeleteAnn(&#39;${ann.id}&#39;)&quot; class=&quot;px-2 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Remove box&lt;/button&gt;<br>                        ` : `<br>                          &lt;button onclick=&quot;evStartDraw(${f.number})&quot; class=&quot;px-2 py-1 rounded-lg ${pending === f.number ? &#39;bg-amber-500 text-slate-950&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;} font-semibold&quot;&gt;${pending === f.number ? &#39;Drawing…&#39; : &#39;Draw box&#39;}&lt;/button&gt;<br>                        `}<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderEvidenceModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No active project.&lt;/div&gt;`;<br>      const shots = evShots(page);<br>      const rememberedIdx = page.evidenceShotId ? shots.findIndex(s =&gt; s.id === page.evidenceShotId) : -1;<br>      evActiveShotIdx = rememberedIdx &gt;= 0 ? rememberedIdx : Math.max(0, shots.length - 1);<br>      const activeShot = shots[evActiveShotIdx] || null;<br>      const anns = evAnns(page);<br>      if (activeShot) { if (activeShot.natW) evMigrateAnns(page, activeShot); else evLoadDims(page, activeShot); }<br>      const mergeSel = appState.ui.evMergeSel = (appState.ui.evMergeSel || []).filter(id =&gt; shots.some(s =&gt; s.id === id));<br>      const nextLabel = appState.settings.qaAutoIncrement ? evNextLabel(page) : (appState.ui.evSelectedLabel || 1);<br>      const used = new Set(anns.map(a =&gt; Number(a.qaLabel)));<br>      const maxLbl = appState.settings.qaLabelMax || 200;<br>      const labelOptions = [];<br>      for (let i = 1; i &lt;= maxLbl; i++) labelOptions.push(`&lt;option value=&quot;${i}&quot; ${i === nextLabel ? &#39;selected&#39; : &#39;&#39;}&gt;QA-${i} ${used.has(i) ? &#39;(Assigned)&#39; : &#39;&#39;}&lt;/option&gt;`);<br><br>      return `<br>        ${evPageBar(proj, page)}<br><br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;image-plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;&lt;span&gt;Upload Evidence Screenshots&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; multiple onchange=&quot;evUpload(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;evPasteButton()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-slate-100 dark:bg-slate-800&quot;&gt;<br>              &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;&lt;span&gt;Paste Image (Ctrl+V)&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;evCapture()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>              &lt;i data-lucide=&quot;monitor-dot&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;&lt;span&gt;Capture Screen (Browser Permission)&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;evMerge(&#39;vertical&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Merge Vertical (${mergeSel.length})&lt;/button&gt;<br>            &lt;button onclick=&quot;evMerge(&#39;horizontal&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Merge Horizontal (${mergeSel.length})&lt;/button&gt;<br>            &lt;button onclick=&quot;evResetMerge()&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold text-slate-500&quot;&gt;Reset Merge History (${(page.evidenceMergeHistory || []).length})&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot; title=&quot;${escapeHtml(page.name)}&quot;&gt;Evidence of this page (${shots.length})&lt;/h3&gt;<br>              &lt;span class=&quot;text-[10px] text-slate-400&quot;&gt;Check to merge&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${shots.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No evidence screenshots for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; yet. Upload, paste (Ctrl+V) or capture one.&lt;/div&gt;` : shots.map((scr, idx) =&gt; `<br>                &lt;div onclick=&quot;evSelectShot(${idx})&quot; class=&quot;p-2.5 rounded-xl border cursor-pointer transition ${idx === evActiveShotIdx ? &#39;border-brand-500 bg-brand-500/10&#39; : &#39;border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between gap-2 mb-1.5&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                    &lt;label class=&quot;inline-flex items-center gap-1.5 text-[11px] font-semibold truncate&quot;&gt;<br>                      &lt;input type=&quot;checkbox&quot; ${mergeSel.includes(scr.id) ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;evToggleMerge(&#39;${scr.id}&#39;)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                      &lt;span class=&quot;truncate&quot;&gt;${escapeHtml(scr.name)}&lt;/span&gt;<br>                    &lt;/label&gt;<br>                    &lt;div class=&quot;flex items-center gap-1 shrink-0&quot;&gt;<br>                      &lt;button onclick=&quot;evMoveShot(${idx}, -1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;↑&lt;/button&gt;<br>                      &lt;button onclick=&quot;evMoveShot(${idx}, 1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;↓&lt;/button&gt;<br>                      &lt;button onclick=&quot;evDeleteShot(&#39;${scr.id}&#39;)&quot; class=&quot;text-rose-500 hover:opacity-80&quot; title=&quot;Delete&quot;&gt;&amp;times;&lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;img src=&quot;${scr.dataUrl}&quot; alt=&quot;${escapeHtml(scr.name)}&quot; class=&quot;w-full h-24 object-cover rounded-lg bg-slate-950&quot; /&gt;<br>                  &lt;div class=&quot;flex items-center justify-between text-[10px] text-slate-400 mt-1&quot;&gt;<br>                    &lt;span&gt;${scr.isMerged ? &#39;Merged Output&#39; : escapeHtml(scr.source)}&lt;/span&gt;<br>                    &lt;a href=&quot;${scr.dataUrl}&quot; download=&quot;${escapeHtml(scr.name)}&quot; onclick=&quot;event.stopPropagation()&quot; class=&quot;text-brand-500 hover:underline&quot;&gt;Download&lt;/a&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 pb-2 border-b border-slate-200 dark:border-slate-800&quot;&gt;<br>              &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;rect&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;rect&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Rectangle&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;circle&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;circle&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Circle&lt;/button&gt;<br>                &lt;input type=&quot;color&quot; value=&quot;${appState.ui.annotationColor}&quot; onchange=&quot;appState.ui.annotationColor = this.value&quot; class=&quot;w-8 h-8 rounded cursor-pointer bg-transparent&quot; title=&quot;Annotation Color&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex items-center gap-2 text-xs&quot;&gt;<br>                &lt;select onchange=&quot;appState.ui.evSelectedLabel = Number(this.value)&quot; class=&quot;px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot;&gt;${labelOptions.join(&#39;&#39;)}&lt;/select&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1 cursor-pointer&quot; title=&quot;Auto-increment to next unused QA label&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${appState.settings.qaAutoIncrement ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.qaAutoIncrement = this.checked; scheduleAutosave(&#39;Toggled QA auto-increment&#39;); renderApp();&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;Auto-Inc&lt;/span&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-1.5 text-xs&quot;&gt;<br>              &lt;span class=&quot;font-bold text-slate-400 mr-1&quot;&gt;Zoom&lt;/span&gt;<br>              &lt;button onclick=&quot;evZoomStep(-1)&quot; class=&quot;w-8 h-8 rounded-lg bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 font-bold text-base leading-none&quot; title=&quot;Zoom out (-)&quot;&gt;−&lt;/button&gt;<br>              &lt;input id=&quot;ev-zoom-range&quot; type=&quot;range&quot; min=&quot;25&quot; max=&quot;800&quot; step=&quot;5&quot; value=&quot;${Math.round(evZoom * 100)}&quot; oninput=&quot;evSetZoom(this.value / 100)&quot; class=&quot;w-28 accent-indigo-500&quot; /&gt;<br>              &lt;button onclick=&quot;evZoomStep(1)&quot; class=&quot;w-8 h-8 rounded-lg bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 font-bold text-base leading-none&quot; title=&quot;Zoom in (+)&quot;&gt;+&lt;/button&gt;<br>              &lt;span id=&quot;ev-zoom-label&quot; class=&quot;w-12 text-center font-mono font-semibold&quot;&gt;${Math.round(evZoom * 100)}%&lt;/span&gt;<br>              &lt;button onclick=&quot;evZoomFit()&quot; class=&quot;px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 font-semibold&quot; title=&quot;Fit to width (0)&quot;&gt;Fit&lt;/button&gt;<br>              &lt;button onclick=&quot;evZoomActual()&quot; class=&quot;px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 font-semibold&quot; title=&quot;Show the screenshot at its real pixel size&quot;&gt;1:1&lt;/button&gt;<br>              &lt;span class=&quot;ml-auto text-[10px] text-slate-400&quot;&gt;Ctrl + scroll = zoom • Space or middle mouse + drag = move&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div id=&quot;ev-stage&quot; class=&quot;relative bg-slate-950 rounded-xl overflow-auto p-2 select-none&quot; style=&quot;min-height:420px;max-height:72vh&quot;&gt;<br>              ${activeShot ? `<br>                &lt;div id=&quot;ev-canvas-wrapper&quot; class=&quot;relative mx-auto cursor-crosshair&quot; style=&quot;width:${evZoom * 100}%&quot;&gt;<br>                  &lt;img id=&quot;ev-base-img&quot; src=&quot;${activeShot.dataUrl}&quot; alt=&quot;Evidence Canvas&quot; draggable=&quot;false&quot; class=&quot;block w-full h-auto pointer-events-none&quot; /&gt;<br>                  ${activeShot.natW ? (() =&gt; {<br>                    const W = activeShot.natW, H = activeShot.natH;<br>                    const fs = Math.max(10, W / 90);<br>                    return `&lt;svg class=&quot;absolute inset-0 w-full h-full&quot; viewBox=&quot;0 0€{W} ${H}&quot; preserveAspectRatio=&quot;none&quot;&gt;<br>                      ${anns.filter(a =&gt; evVisible(a, activeShot)).map(ann =&gt; {<br>                        const isSel = appState.ui.evSelectedAnnId === ann.id;<br>                        const sw = isSel ? 3.5 : 2.5;<br>                        const shape = ann.type === &#39;circle&#39;<br>                          ? `&lt;ellipse cx=&quot;${ann.x + ann.w / 2}&quot; cy=&quot;${ann.y + ann.h / 2}&quot; rx=&quot;${Math.abs(ann.w / 2)}&quot; ry=&quot;${Math.abs(ann.h / 2)}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${sw}&quot; vector-effect=&quot;non-scaling-stroke&quot; /&gt;`<br>                          : `&lt;rect x=&quot;${ann.x}&quot; y=&quot;${ann.y}&quot; width=&quot;${ann.w}&quot; height=&quot;${ann.h}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${sw}&quot; vector-effect=&quot;non-scaling-stroke&quot; /&gt;`;<br>                        const tag = evTag(ann);<br>                        const tw = tag.length * fs * 0.62 + fs;<br>                        return `<br>                          &lt;g onclick=&quot;event.stopPropagation(); appState.ui.evSelectedAnnId = &#39;${ann.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer&quot;&gt;<br>                            ${shape}<br>                            &lt;rect x=&quot;${ann.x}&quot; y=&quot;${Math.max(0, ann.y - fs * 1.6)}&quot; width=&quot;${tw}&quot; height=&quot;${fs * 1.6}&quot; rx=&quot;${fs * 0.25}&quot; fill=&quot;${ann.color}&quot; /&gt;<br>                            &lt;text x=&quot;${ann.x + fs * 0.5}&quot; y=&quot;${Math.max(fs * 1.15, ann.y - fs * 0.4)}&quot; font-family=&quot;sans-serif&quot; font-size=&quot;${fs}&quot; font-weight=&quot;bold&quot; fill=&quot;#ffffff&quot;&gt;${escapeHtml(tag)}&lt;/text&gt;<br>                          &lt;/g&gt;`;<br>                      }).join(&#39;&#39;)}<br>                      &lt;rect id=&quot;ev-preview&quot; x=&quot;0&quot; y=&quot;0&quot; width=&quot;0&quot; height=&quot;0&quot; visibility=&quot;hidden&quot; fill=&quot;${appState.ui.annotationColor}22&quot; stroke=&quot;${appState.ui.annotationColor}&quot; stroke-width=&quot;2&quot; stroke-dasharray=&quot;6 4&quot; vector-effect=&quot;non-scaling-stroke&quot; pointer-events=&quot;none&quot; /&gt;<br>                    &lt;/svg&gt;`;<br>                  })() : &#39;&#39;}<br>                &lt;/div&gt;<br>              ` : `&lt;div class=&quot;text-xs text-slate-400 p-6 text-center&quot;&gt;Upload, paste or capture an evidence screenshot to draw QA boxes.&lt;/div&gt;`}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center justify-between text-[11px] text-slate-400&quot;&gt;<br>              &lt;span&gt;Click &amp;amp; drag on the image to draw a box for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt;. Zoom in first for a precise box.&lt;/span&gt;<br>              ${activeShot ? `&lt;button onclick=&quot;evExport()&quot; class=&quot;text-brand-500 font-semibold hover:underline&quot;&gt;Export Annotated PNG&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Evidence Boxes (${anns.length})&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${anns.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No evidence boxes on this Main Page yet.&lt;/div&gt;` : anns.map(a =&gt; evAnnCard(page, a)).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        ${evFieldMap(page)}<br>      `;<br>    }<br><br>    let tcSearchQuery = &#39;&#39;;<br>    let tcStatusFilter = &#39;ALL&#39;;<br><br>    function renderTestCasesModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br>      const list = (proj.testCases || []).filter(tc =&gt; {<br>        const matchText = tc.id.toLowerCase().includes(tcSearchQuery.toLowerCase()) || tc.title.toLowerCase().includes(tcSearchQuery.toLowerCase());<br>        const matchStatus = tcStatusFilter === &#39;ALL&#39; || tc.status === tcStatusFilter;<br>        return matchText &amp;&amp; matchStatus;<br>      });<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(tcSearchQuery)}&quot; oninput=&quot;tcSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search test cases...&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;select onchange=&quot;tcStatusFilter = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;ALL&quot; ${tcStatusFilter === &#39;ALL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Statuses&lt;/option&gt;<br>                &lt;option value=&quot;PASS&quot; ${tcStatusFilter === &#39;PASS&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PASS&lt;/option&gt;<br>                &lt;option value=&quot;FAIL&quot; ${tcStatusFilter === &#39;FAIL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;FAIL&lt;/option&gt;<br>                &lt;option value=&quot;PENDING&quot; ${tcStatusFilter === &#39;PENDING&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PENDING&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openTestCaseModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Test Case&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;ID&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Title &amp; Module&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Linked Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Priority&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${list.map(tc =&gt; {<br>                  const mp = proj.mainPages.find(m =&gt; m.id === tc.mainPageId);<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-mono font-bold&quot;&gt;${escapeHtml(tc.id)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 pr-3&quot;&gt;<br>                        &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(tc.title)}&lt;/div&gt;<br>                        &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;${escapeHtml(tc.module)} • Tester: ${escapeHtml(tc.tester)}&lt;/div&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp ? escapeHtml(mp.name) : &#39;-&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 font-medium&quot;&gt;${escapeHtml(tc.priority)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;<br>                        &lt;select onchange=&quot;updateTestCaseStatus(&#39;${tc.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-bold&quot;&gt;<br>                          ${[&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;, &#39;BLOCKED&#39;].map(st =&gt; `&lt;option value=&quot;${st}&quot; ${tc.status === st ? &#39;selected&#39; : &#39;&#39;}&gt;${st}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;openTestCaseModal(&#39;${tc.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 font-semibold mr-1&quot;&gt;Edit&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteTestCase(&#39;${tc.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Delete&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openTestCaseModal(tcId = null) {<br>      const proj = getActiveProject();<br>      const existing = tcId ? proj.testCases.find(t =&gt; t.id === tcId) : null;<br>      const tc = existing || {<br>        id: `TC-${String((proj.testCases?.length || 0) + 1).padStart(3, &#39;0&#39;)}`,<br>        title: &#39;&#39;,<br>        module: &#39;EIS Settlement&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: &#39;&#39;,<br>        expectedResult: &#39;&#39;,<br>        actualResult: &#39;&#39;,<br>        status: &#39;PENDING&#39;,<br>        priority: &#39;High&#39;,<br>        tester: proj.owner || &#39;QA Analyst&#39;,<br>        mainPageId: appState.activeMainPageId || &#39;&#39;<br>      };<br><br>      openModal({<br>        title: existing ? `Edit Test Case (${tc.id})` : &#39;Create Test Case&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Test Case ID&lt;/label&gt;&lt;input id=&quot;tc-id&quot; value=&quot;${escapeHtml(tc.id)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Priority&lt;/label&gt;&lt;select id=&quot;tc-prio&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;${[&#39;Critical&#39;, &#39;High&#39;, &#39;Medium&#39;, &#39;Low&#39;].map(p =&gt; `&lt;option ${tc.priority === p ? &#39;selected&#39; : &#39;&#39;}&gt;${p}&lt;/option&gt;`).join(&#39;&#39;)}&lt;/select&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Title *&lt;/label&gt;&lt;input id=&quot;tc-title&quot; value=&quot;${escapeHtml(tc.title)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Linked Main Page&lt;/label&gt;&lt;select id=&quot;tc-mp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option value=&quot;&quot;&gt;None&lt;/option&gt;${proj.mainPages.map(m =&gt; `&lt;option value=&quot;${m.id}&quot; ${tc.mainPageId === m.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(m.name)}&lt;/option&gt;`).join(&#39;&#39;)}&lt;/select&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Steps&lt;/label&gt;&lt;textarea id=&quot;tc-steps&quot; rows=&quot;3&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot;&gt;${escapeHtml(tc.steps)}&lt;/textarea&gt;&lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Expected Result&lt;/label&gt;&lt;input id=&quot;tc-exp&quot; value=&quot;${escapeHtml(tc.expectedResult)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Actual Result&lt;/label&gt;&lt;input id=&quot;tc-act&quot; value=&quot;${escapeHtml(tc.actualResult)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveTestCaseFromModal(${existing ? `&#39;${existing.id}&#39;` : &#39;null&#39;})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Test Case&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveTestCaseFromModal(existingId) {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;tc-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Test case title is required.&#39;, &#39;warning&#39;);<br><br>      const record = {<br>        id: document.getElementById(&#39;tc-id&#39;).value.trim() || `TC-${Date.now()}`,<br>        title,<br>        module: &#39;EIS Settlement&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: document.getElementById(&#39;tc-steps&#39;).value,<br>        expectedResult: document.getElementById(&#39;tc-exp&#39;).value,<br>        actualResult: document.getElementById(&#39;tc-act&#39;).value,<br>        status: existingId ? (proj.testCases.find(t =&gt; t.id === existingId)?.status || &#39;PENDING&#39;) : &#39;PENDING&#39;,<br>        priority: document.getElementById(&#39;tc-prio&#39;).value,<br>        tester: proj.owner || &#39;QA Analyst&#39;,<br>        executionDate: new Date().toISOString().slice(0, 10),<br>        mainPageId: document.getElementById(&#39;tc-mp&#39;).value<br>      };<br><br>      if (existingId) {<br>        const idx = proj.testCases.findIndex(t =&gt; t.id === existingId);<br>        if (idx &gt;= 0) proj.testCases[idx] = record;<br>      } else {<br>        proj.testCases.unshift(record);<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Saved test case&#39;);<br>      showToast(&#39;Saved test case.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateTestCaseStatus(tcId, status) {<br>      const proj = getActiveProject();<br>      const tc = proj?.testCases.find(t =&gt; t.id === tcId);<br>      if (!tc) return;<br>      tc.status = status;<br>      scheduleAutosave(&#39;Updated test case status&#39;);<br>      renderApp();<br>    }<br><br>    function deleteTestCase(tcId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.testCases = proj.testCases.filter(t =&gt; t.id !== tcId);<br>      scheduleAutosave(&#39;Deleted test case&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 8 VIEW: DEFECT MANAGEMENT<br>     ****************************************************************************/<br>    function renderDefectsModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;QA Defects &amp; Discrepancies (${(proj.defects || []).length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Log EIS receipt calculation errors, CWT mismatches, or UI/OCR issues and copy formatted bug summaries.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openDefectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;bug&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Log New Defect&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            ${(proj.defects || []).length === 0 ? `&lt;div class=&quot;py-8 text-center text-xs text-slate-400&quot;&gt;No defects logged in this project.&lt;/div&gt;` : (proj.defects || []).map(def =&gt; `<br>              &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 bg-slate-50/60 dark:bg-slate-950/40 space-y-2 text-xs&quot;&gt;<br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono font-bold text-rose-500&quot;&gt;${escapeHtml(def.id)}&lt;/span&gt;<br>                    &lt;span class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(def.title)}&lt;/span&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                    &lt;span class=&quot;px-2 py-0.5 rounded bg-slate-200 dark:bg-slate-800 font-semibold&quot;&gt;${escapeHtml(def.severity)}&lt;/span&gt;<br>                    ${statusBadge(def.status)}<br>                    &lt;button onclick=&quot;copyDefectSummary(&#39;${def.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 font-semibold hover:bg-brand-500/20&quot;&gt;Copy Summary&lt;/button&gt;<br>                    &lt;button onclick=&quot;deleteDefect(&#39;${def.id}&#39;)&quot; class=&quot;px-2 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(def.description)}&lt;/p&gt;<br>                &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-2 font-mono text-[11px] bg-white dark:bg-slate-900 p-2.5 rounded-xl border border-slate-200 dark:border-slate-800&quot;&gt;<br>                  &lt;div&gt;&lt;span class=&quot;text-slate-400&quot;&gt;Expected:&lt;/span&gt; ${escapeHtml(def.expectedResult)}&lt;/div&gt;<br>                  &lt;div&gt;&lt;span class=&quot;text-slate-400&quot;&gt;Actual:&lt;/span&gt; &lt;span class=&quot;text-rose-500&quot;&gt;${escapeHtml(def.actualResult)}&lt;/span&gt;&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openDefectModal() {<br>      const proj = getActiveProject();<br>      const nextId = `DEF-${101 + (proj.defects?.length || 0)}`;<br>      openModal({<br>        title: &#39;Log New QA Defect&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-3 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Defect ID&lt;/label&gt;&lt;input id=&quot;def-id&quot; value=&quot;${nextId}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Severity&lt;/label&gt;&lt;select id=&quot;def-sev&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option&gt;Critical&lt;/option&gt;&lt;option selected&gt;High&lt;/option&gt;&lt;option&gt;Medium&lt;/option&gt;&lt;option&gt;Low&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Status&lt;/label&gt;&lt;select id=&quot;def-st&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option selected&gt;Open&lt;/option&gt;&lt;option&gt;In Progress&lt;/option&gt;&lt;option&gt;Fixed&lt;/option&gt;&lt;option&gt;Closed&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Defect Title *&lt;/label&gt;&lt;input id=&quot;def-title&quot; placeholder=&quot;e.g. CWT deduction not subtracted from Net Total&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Description&lt;/label&gt;&lt;textarea id=&quot;def-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;/textarea&gt;&lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Expected Result&lt;/label&gt;&lt;input id=&quot;def-exp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Actual Result&lt;/label&gt;&lt;input id=&quot;def-act&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveDefectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Save Defect&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveDefectFromModal() {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;def-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Defect title is required.&#39;, &#39;warning&#39;);<br><br>      proj.defects.unshift({<br>        id: document.getElementById(&#39;def-id&#39;).value.trim() || `DEF-${Date.now()}`,<br>        title,<br>        description: document.getElementById(&#39;def-desc&#39;).value.trim(),<br>        severity: document.getElementById(&#39;def-sev&#39;).value,<br>        priority: &#39;P1&#39;,<br>        status: document.getElementById(&#39;def-st&#39;).value,<br>        expectedResult: document.getElementById(&#39;def-exp&#39;).value.trim(),<br>        actualResult: document.getElementById(&#39;def-act&#39;).value.trim(),<br>        mainPageId: appState.activeMainPageId,<br>        dateReported: new Date().toISOString().slice(0, 10)<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Logged defect&#39;);<br>      showToast(&#39;Defect logged.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function copyDefectSummary(defId) {<br>      const def = getActiveProject()?.defects.find(d =&gt; d.id === defId);<br>      if (!def) return;<br>      const text = `[${def.id}] ${def.title} (Severity: ${def.severity}, Status: ${def.status})\nExpected: ${def.expectedResult}\nActual: ${def.actualResult}\nDetails: ${def.description}`;<br>      const ta = document.createElement(&#39;textarea&#39;);<br>      ta.value = text;<br>      document.body.appendChild(ta);<br>      ta.select();<br>      try { document.execCommand(&#39;copy&#39;); showToast(&#39;Copied defect summary to clipboard.&#39;, &#39;success&#39;); }<br>      catch (e) { showToast(&#39;Copy failed.&#39;, &#39;error&#39;); }<br>      ta.remove();<br>    }<br><br>    function deleteDefect(defId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.defects = proj.defects.filter(d =&gt; d.id !== defId);<br>      scheduleAutosave(&#39;Deleted defect&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 9 VIEW: TEMPLATES<br>     ****************************************************************************/<br>    function renderTemplatesModule() {<br>      const page = getActiveMainPage();<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Reusable EIS Fee &amp; Column Templates&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Apply a template to &lt;strong&gt;${escapeHtml(page ? page.name : &#39;Active Main Page&#39;)}&lt;/strong&gt; or save your current fee structure as a template.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;saveCurrentPageFeesAsTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              + Save Current Page Fees as Template<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 gap-4&quot;&gt;<br>            ${appState.templates.map(tpl =&gt; `<br>              &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 space-y-3&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                  &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(tpl.name)}&lt;/h4&gt;<br>                  &lt;button onclick=&quot;applyTemplateToActivePage(&#39;${tpl.id}&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                    Apply to ${escapeHtml(page ? page.name.split(&#39;:&#39;)[0] : &#39;Page&#39;)}<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(tpl.description)}&lt;/p&gt;<br>                ${tpl.columns &amp;&amp; tpl.columns.length ? `<br>                  &lt;div class=&quot;text-[11px] text-indigo-500 font-medium&quot;&gt;<br>                    Includes ${tpl.columns.length} saved column names: ${tpl.columns.slice(0, 6).map(c =&gt; escapeHtml(c.name)).join(&#39;, &#39;)}${tpl.columns.length &gt; 6 ? &#39;...&#39; : &#39;&#39;}<br>                  &lt;/div&gt;<br>                ` : &#39;&#39;}<br>                &lt;div class=&quot;text-xs font-mono bg-slate-50 dark:bg-slate-800/60 p-2.5 rounded-xl space-y-1&quot;&gt;<br>                  ${(tpl.fees || []).map(f =&gt; `&lt;div&gt;• ${escapeHtml(f.expectedName)} : &lt;strong&gt;${escapeHtml(f.expectedAmount)}&lt;/strong&gt; [${escapeHtml(f.expectedCode || (f.isCwt ? &#39;CWT&#39; : &#39;FEE&#39;))}]&lt;/div&gt;`).join(&#39;&#39;)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function saveCurrentPageFeesAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.fees.length) return showToast(&#39;Add at least one fee row first.&#39;, &#39;warning&#39;);<br>      const tpl = {<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name: `${page.name} Schema`,<br>        description: `Saved from ${page.name} (${page.fees.length} items)`,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      };<br>      appState.templates.push(tpl);<br>      scheduleAutosave(&#39;Saved template&#39;);<br>      showToast(`Saved template &quot;${tpl.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyTemplateToActivePage(tplId) {<br>      const page = getActiveMainPage();<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br>      if (!page || !tpl) return;<br><br>      if (tpl.columns &amp;&amp; tpl.columns.length) {<br>        tpl.columns.forEach((col, idx) =&gt; {<br>          if (page.fields[idx]) {<br>            page.fields[idx].name = col.name;<br>            page.fields[idx].dataType = col.dataType || page.fields[idx].dataType;<br>            page.fields[idx].required = Boolean(col.required);<br>            page.fields[idx].enabled = true;<br>          }<br>        });<br>      }<br><br>      if (tpl.fees &amp;&amp; tpl.fees.length) {<br>        page.fees = tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_tpl_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;Template&#39;<br>        }));<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Applied template&#39;);<br>      showToast(`Applied &quot;${tpl.name}&quot; to ${page.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 10 VIEW: SETTINGS, DIAGNOSTICS &amp; 12-POINT SELF-TEST SUITE<br>     ****************************************************************************/<br>    let diagnosticTestResults = [];<br><br>    function renderSettingsModule() {<br>      const s = appState.settings;<br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4 text-xs&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Validation &amp; OCR Settings&lt;/h3&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;font-semibold block mb-1&quot;&gt;Numeric Tolerance (±)&lt;/label&gt;<br>              &lt;input type=&quot;number&quot; step=&quot;0.01&quot; value=&quot;${s.numericTolerance}&quot; onchange=&quot;appState.settings.numericTolerance = parseFloat(this.value) || 0.01; scheduleAutosave(&#39;Updated tolerance&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;font-semibold block mb-1&quot;&gt;Auto-Accept OCR Confidence Threshold (%)&lt;/label&gt;<br>              &lt;input type=&quot;number&quot; min=&quot;0&quot; max=&quot;100&quot; value=&quot;${s.autoAcceptConfidenceThreshold}&quot; onchange=&quot;appState.settings.autoAcceptConfidenceThreshold = parseInt(this.value, 10) || 88; scheduleAutosave(&#39;Updated OCR threshold&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;label class=&quot;flex items-center justify-between p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60 cursor-pointer&quot;&gt;<br>              &lt;span class=&quot;font-medium&quot;&gt;Case-Sensitive Fee &amp; Field Names&lt;/span&gt;<br>              &lt;input type=&quot;checkbox&quot; ${s.caseSensitiveNames ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.caseSensitiveNames = this.checked; scheduleAutosave(&#39;Updated case sensitivity&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>            &lt;/label&gt;<br><br>            &lt;label class=&quot;flex items-center justify-between p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60 cursor-pointer&quot;&gt;<br>              &lt;span class=&quot;font-medium&quot;&gt;Normalize Whitespace During Comparison&lt;/span&gt;<br>              &lt;input type=&quot;checkbox&quot; ${s.normalizeWhitespace ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.normalizeWhitespace = this.checked; scheduleAutosave(&#39;Updated whitespace setting&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>            &lt;/label&gt;<br><br>            &lt;div class=&quot;pt-2 border-t border-slate-200 dark:border-slate-800 flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;exportFullWorkspaceBackup()&quot; class=&quot;px-3.5 py-2 rounded-xl font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-slate-200&quot;&gt;Export Full Backup JSON&lt;/button&gt;<br>              &lt;button onclick=&quot;confirmResetSampleData()&quot; class=&quot;px-3.5 py-2 rounded-xl font-semibold text-rose-500 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;Reset to Sample Data&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;12-Point Automated Acceptance &amp; Math Test Suite&lt;/h3&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Verifies CWT math, negative/parenthetical signs, missing-info rules, multi-page isolation, and IndexedDB persistence.&lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;button onclick=&quot;runTwelvePointDiagnostics()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-bold bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm&quot;&gt;<br>                Run All 12 Checks<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;space-y-2 max-h-[460px] overflow-y-auto&quot;&gt;<br>              ${diagnosticTestResults.length === 0 ? `<br>                &lt;div class=&quot;p-8 text-center text-xs text-slate-400 border border-dashed border-slate-200 dark:border-slate-800 rounded-xl&quot;&gt;<br>                  Click &lt;strong&gt;Run All 12 Checks&lt;/strong&gt; to execute automated verification tests on the calculation, validation, and persistence engines.<br>                &lt;/div&gt;<br>              ` : diagnosticTestResults.map((r, i) =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${r.passed ? &#39;border-emerald-500/30 bg-emerald-500/5&#39; : &#39;border-rose-500/30 bg-rose-500/5&#39;} flex items-start justify-between gap-3 text-xs&quot;&gt;<br>                  &lt;div&gt;<br>                    &lt;div class=&quot;font-bold&quot;&gt;#${i + 1}. ${escapeHtml(r.name)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 mt-0.5&quot;&gt;${escapeHtml(r.detail)}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;span class=&quot;px-2 py-0.5 rounded font-bold text-[10px] shrink-0€{r.passed ? &#39;bg-emerald-500/20 text-emerald-500&#39; : &#39;bg-rose-500/20 text-rose-500&#39;}&quot;&gt;${r.passed ? &#39;PASS&#39; : &#39;FAIL&#39;}&lt;/span&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    async function runTwelvePointDiagnostics() {<br>      const results = [];<br><br>      const t1 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;1000&#39;, actualAmount: &#39;1000&#39;, isCwt: false },<br>        { expectedAmount: &#39;250&#39;, actualAmount: &#39;250&#39;, isCwt: false },<br>        { expectedAmount: &#39;-50&#39;, actualAmount: &#39;-50&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;Fee 1 (1000) + Fee 2 (250) with CWT (-50) = Net 1200&#39;, passed: t1.actualGross === 1250 &amp;&amp; t1.actualCwt === 50 &amp;&amp; t1.actualNet === 1200, detail: `Gross=${t1.actualGross}, CWT=${t1.actualCwt}, Net=${t1.actualNet}` });<br><br>      const t2 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;1000&#39;, actualAmount: &#39;1000&#39;, isCwt: false },<br>        { expectedAmount: &#39;250&#39;, actualAmount: &#39;250&#39;, isCwt: false },<br>        { expectedAmount: &#39;(50)&#39;, actualAmount: &#39;(50)&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;Parenthetical CWT (50) deducted cleanly as 50&#39;, passed: t2.actualCwt === 50 &amp;&amp; t2.actualNet === 1200, detail: `CWT=${t2.actualCwt}, Net=${t2.actualNet}` });<br><br>      const t3 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;1200&#39;, actualCode: &#39;NC&#39;, isCwt: false });<br>      results.push({ name: &#39;Fee 1 Mismatch (1000 vs 1200) flags FAIL with +200.00 diff&#39;, passed: t3.status === &#39;FAIL&#39; &amp;&amp; t3.amountComparison.difference === &#39;200.00&#39;, detail: t3.explanation });<br><br>      const t4 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;&#39;, actualCode: &#39;NC&#39;, isCwt: false });<br>      results.push({ name: &#39;Missing Actual Amount evaluates as PENDING (not false PASS)&#39;, passed: t4.status === &#39;PENDING&#39;, detail: `Status=${t4.status}` });<br><br>      const t5 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;1000&#39;, actualCode: &#39;&#39;, isCwt: false });<br>      results.push({ name: &#39;Missing Required Fee Code evaluates as PENDING&#39;, passed: t5.status === &#39;PENDING&#39;, detail: `Status=${t5.status}` });<br><br>      const t6 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;500&#39;, actualAmount: &#39;500&#39;, isCwt: false },<br>        { expectedAmount: &#39;25&#39;, actualAmount: &#39;25&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;CWT excluded from Gross Fees sum&#39;, passed: t6.actualGross === 500 &amp;&amp; t6.actualNet === 475, detail: `Gross=${t6.actualGross}, Net=${t6.actualNet}` });<br><br>      const qp = OcrMappingEngine.parseQuickPasteFees(&#39;Fee 1\n1000\nNC\nCWT\n50&#39;);<br>      results.push({ name: &#39;Quick Paste parser extracts multi-line fee &amp; CWT blocks&#39;, passed: qp.length === 2 &amp;&amp; qp[1].isCwt === true, detail: `Parsed ${qp.length} items` });<br><br>      const proj = getActiveProject();<br>      results.push({ name: &#39;Multi-Main-Page isolation within active project&#39;, passed: proj &amp;&amp; proj.mainPages.length &gt;= 2 &amp;&amp; proj.mainPages[0].id !== proj.mainPages[1].id, detail: `${proj?.mainPages.length || 0} isolated pages` });<br><br>      const savedOk = await PersistenceEngine.saveState(appState);<br>      const loadedState = await PersistenceEngine.loadState();<br>      results.push({ name: &#39;IndexedDB save &amp; reload persistence round-trip&#39;, passed: Boolean(savedOk &amp;&amp; loadedState &amp;&amp; loadedState.projects.length &gt; 0), detail: `Projects persisted: ${loadedState?.projects?.length || 0}` });<br><br>      results.push({ name: &#39;Configurable numbered fields initialized (1-50+)&#39;, passed: Boolean(proj?.mainPages[0]?.fields?.length &gt;= 50), detail: `Field count: ${proj?.mainPages[0]?.fields?.length || 0}` });<br><br>      results.push({ name: &#39;Dynamic QA label pool supports 1–200+ labels&#39;, passed: (appState.settings.qaLabelMax || 200) &gt;= 200, detail: `Max QA label: ${appState.settings.qaLabelMax}` });<br><br>      results.push({ name: &#39;Report export generator function available&#39;, passed: typeof exportReportFile === &#39;function&#39;, detail: &#39;CSV, HTML, DOC, JSON, TXT &amp; Print ready&#39; });<br><br>      diagnosticTestResults = results;<br>      const passCnt = results.filter(r =&gt; r.passed).length;<br>      showToast(`Diagnostics complete: ${passCnt}/${results.length} passed.`, passCnt === results.length ? &#39;success&#39; : &#39;warning&#39;);<br>      renderApp();<br>    }<br><br>    function exportFullWorkspaceBackup() {<br>      const blob = new Blob([JSON.stringify(appState, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `SMART_full_workspace_backup_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full workspace JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function confirmResetSampleData() {<br>      openModal({<br>        title: &#39;Reset Workspace to Sample Seed Data&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;This will replace current workspace projects with fresh sample EIS &amp; QA seed data. Export a JSON backup first if you wish to keep current edits.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;resetToSampleSeedData()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Reset Sample Data&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    async function resetToSampleSeedData() {<br>      appState = createSampleSeedState();<br>      closeModal();<br>      await PersistenceEngine.saveState(appState);<br>      showToast(&#39;Workspace reset to fresh sample data.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 11 VIEW: REPORTS HUB (ALL RESULTS, PROJECTS &amp; QA REPORTS)<br>     * Includes toggle control for embedding/excluding receipt images in HTML &amp; DOC exports.<br>     ****************************************************************************/<br>    let reportScope = &#39;active_page&#39;; // &#39;active_page&#39; | &#39;all_pages&#39; | &#39;all_projects&#39;<br>    let reportIncludeReceipts = true; // Toggle state for embedding receipt images in HTML &amp; Word (.doc) exports<br><br>    function setReportIncludeReceipts(checked) {<br>      reportIncludeReceipts = Boolean(checked);<br>      scheduleAutosave(&#39;Updated report receipt image export preference&#39;);<br>      renderApp();<br>    }<br><br>    function getReportDataset() {<br>      const activeProj = getActiveProject();<br>      const activePage = getActiveMainPage();<br><br>      if (reportScope === &#39;active_page&#39;) {<br>        return {<br>          title: `Main Page Validation &amp; QA Report — ${activePage?.name || &#39;Page&#39;}`,<br>          projects: activeProj ? [{<br>            ...activeProj,<br>            mainPages: activePage ? [activePage] : []<br>          }] : []<br>        };<br>      }<br>      if (reportScope === &#39;all_pages&#39;) {<br>        return {<br>          title: `Full Project EIS &amp; QA Report — ${activeProj?.name || &#39;Project&#39;}`,<br>          projects: activeProj ? [activeProj] : []<br>        };<br>      }<br>      return {<br>        title: `All Projects Master EIS &amp; QA Audit Report (${appState.projects.length} Projects)`,<br>        projects: appState.projects<br>      };<br>    }<br><br><br>    /****************************************************************************<br>     * REPORT SECTION BUILDERS: Side-by-Side Fee/CWT Comparison &amp;<br>     * Expected Row Columns vs Receipt Verification (used by preview + all exports)<br>     ****************************************************************************/<br>    function getReportRows(mp) {<br>      if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>      const feeRows = (mp.fees || []).map(f =&gt; ({ fee: f, v: f.lastValidation || ValidationEngine.validateFeeRow(f) }));<br>      const colRows = (mp.fields || [])<br>        .filter(f =&gt; (f.expectedValue !== &#39;&#39; &amp;&amp; f.expectedValue != null) || (f.actualValue !== &#39;&#39; &amp;&amp; f.actualValue != null))<br>        .map(f =&gt; ({ field: f, v: f.lastValidation || ValidationEngine.validateField(f) }));<br>      const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees || []);<br>      return { feeRows, colRows, fin };<br>    }<br><br>    function fmtSigned(n) {<br>      return `${n &gt; 0 ? &#39;+&#39; : &#39;&#39;}${Number(n).toFixed(2)}`;<br>    }<br><br>    function renderReportSideBySideApp(mp) {<br>      const { feeRows, fin } = getReportRows(mp);<br>      const threshold = appState.settings.autoAcceptConfidenceThreshold;<br>      return `<br>        &lt;div class=&quot;space-y-2&quot;&gt;<br>          &lt;h5 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Side-by-Side EIS Fee &amp;amp; CWT Comparison&lt;/h5&gt;<br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Fee Item&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Receipt Actual (Name / Amt / Code)&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-right&quot;&gt;Diff&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Conf&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody&gt;<br>                ${feeRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-4 text-center text-slate-400&quot;&gt;No fee rows configured on this Main Page.&lt;/td&gt;&lt;/tr&gt;` : feeRows.map(({ fee, v }) =&gt; `<br>                  &lt;tr class=&quot;border-t border-slate-100 dark:border-slate-800/70&quot;&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-semibold&quot;&gt;${escapeHtml(fee.expectedName)} ${v.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-mono text-[11px]&quot;&gt;<br>                      &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-mono text-[11px]&quot;&gt;<br>                      &lt;div&gt;${escapeHtml(fee.actualName || &#39;-&#39;)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.actualAmount || &#39;-&#39;)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.actualCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 text-right font-mono font-bold ${v.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;${escapeHtml(v.amountComparison.difference)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; threshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(v.status)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                  &lt;tr class=&quot;text-[11px] text-slate-500 bg-slate-50/60 dark:bg-slate-950/40&quot;&gt;<br>                    &lt;td colspan=&quot;6&quot; class=&quot;px-2 py-1&quot;&gt;&lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(v.explanation)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-3 gap-2 text-xs pt-1&quot;&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold&quot;&gt;${fin.expectedGross.toFixed(2)} / ${fin.actualGross.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;CWT Deduction (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold text-amber-500&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Net Total (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold text-emerald-500&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)} &lt;span class=&quot;${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;(${fmtSigned(fin.netDifference)})&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;Formula: ${escapeHtml(fin.formulaExplanation)}&lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderReportColumnsApp(mp) {<br>      const { colRows } = getReportRows(mp);<br>      const matched = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>      return `<br>        &lt;div class=&quot;space-y-2&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>            &lt;h5 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h5&gt;<br>            &lt;span class=&quot;px-2.5 py-0.5 rounded-full text-[11px] font-bold ${colRows.length &amp;&amp; matched === colRows.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;${matched} / ${colRows.length} Expected Columns Matched&lt;/span&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Col&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Field Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Expected Row Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Explanation&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${colRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-4 text-center text-slate-400&quot;&gt;No expected row columns pasted or configured for this Main Page.&lt;/td&gt;&lt;/tr&gt;` : colRows.map(({ field, v }) =&gt; `<br>                  &lt;tr&gt;<br>                    &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(field.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(field.name)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(field.expectedValue || &#39;-&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-mono&quot;&gt;${escapeHtml(field.actualValue || &#39;-&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(v.status)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-[11px] text-slate-500&quot;&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderReportSideBySideStandalone(mp) {<br>      const { feeRows, fin } = getReportRows(mp);<br>      return `<br>        &lt;div class=&quot;section-title&quot;&gt;Side-by-Side EIS Fee &amp;amp; CWT Comparison&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th&gt;#&lt;/th&gt;<br>              &lt;th&gt;Fee Item&lt;/th&gt;<br>              &lt;th&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>              &lt;th&gt;Receipt Actual (Name / Amt / Code)&lt;/th&gt;<br>              &lt;th&gt;Diff&lt;/th&gt;<br>              &lt;th&gt;Conf&lt;/th&gt;<br>              &lt;th&gt;Status&lt;/th&gt;<br>              &lt;th&gt;Rule Evaluation&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            ${feeRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;8&quot; class=&quot;muted&quot;&gt;No fee rows configured on this Main Page.&lt;/td&gt;&lt;/tr&gt;` : feeRows.map(({ fee, v }, i) =&gt; `<br>              &lt;tr&gt;<br>                &lt;td&gt;${i + 1}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.expectedName)}${v.isCwt ? &#39; &lt;span class=&quot;badge REVIEW&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.expectedName)} / ${escapeHtml(fee.expectedAmount)} / ${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.actualName || &#39;-&#39;)} / ${escapeHtml(fee.actualAmount || &#39;-&#39;)} / ${escapeHtml(fee.actualCode || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td class=&quot;num&quot;&gt;${escapeHtml(v.amountComparison.difference)}&lt;/td&gt;<br>                &lt;td class=&quot;num&quot;&gt;${fee.ocrConfidence ? escapeHtml(fee.ocrConfidence) + &#39;%&#39; : &#39;Manual&#39;}&lt;/td&gt;<br>                &lt;td&gt;&lt;span class=&quot;badge ${escapeHtml(v.status)}&quot;&gt;${escapeHtml(v.status)}&lt;/span&gt;&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>              &lt;/tr&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>        &lt;div class=&quot;section-title&quot;&gt;CWT &amp;amp; Net Settlement Reconciliation&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Measure&lt;/th&gt;&lt;th&gt;Expected&lt;/th&gt;&lt;th&gt;Receipt&lt;/th&gt;&lt;th&gt;Variance&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>          &lt;tbody&gt;<br>            &lt;tr&gt;&lt;td&gt;Gross Fees (non-CWT)&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.grossDifference)}&lt;/td&gt;&lt;/tr&gt;<br>            &lt;tr&gt;&lt;td&gt;Total CWT Deduction&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.cwtDifference)}&lt;/td&gt;&lt;/tr&gt;<br>            &lt;tr&gt;&lt;td&gt;&lt;strong&gt;Net Total&lt;/strong&gt;&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.netDifference)}&lt;/td&gt;&lt;/tr&gt;<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>        &lt;p class=&quot;muted&quot;&gt;Formula: ${escapeHtml(fin.formulaExplanation)}&lt;/p&gt;<br>      `;<br>    }<br><br>    function renderReportColumnsStandalone(mp) {<br>      const { colRows } = getReportRows(mp);<br>      const matched = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>      return `<br>        &lt;div class=&quot;section-title&quot;&gt;Expected Row Columns vs Receipt Verification — ${matched} / ${colRows.length} Expected Columns Matched&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th&gt;Col&lt;/th&gt;<br>              &lt;th&gt;Field Name&lt;/th&gt;<br>              &lt;th&gt;Expected Row Value&lt;/th&gt;<br>              &lt;th&gt;Found on Receipt&lt;/th&gt;<br>              &lt;th&gt;Status&lt;/th&gt;<br>              &lt;th&gt;Explanation&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            ${colRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;muted&quot;&gt;No expected row columns pasted or configured for this Main Page.&lt;/td&gt;&lt;/tr&gt;` : colRows.map(({ field, v }) =&gt; `<br>              &lt;tr&gt;<br>                &lt;td&gt;C${String(field.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.name)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.expectedValue || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.actualValue || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;&lt;span class=&quot;badge ${escapeHtml(v.status)}&quot;&gt;${escapeHtml(v.status)}&lt;/span&gt;&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>              &lt;/tr&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>      `;<br>    }<br><br>    function renderReportsModule() {<br>      const dataset = getReportDataset();<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br><br>      let totalPages = 0, totalFees = 0, totalPass = 0, totalFail = 0, totalReview = 0, totalPending = 0;<br>      let totalGross = 0, totalCwt = 0, totalNet = 0;<br><br>      dataset.projects.forEach(p =&gt; {<br>        (p.mainPages || []).forEach(mp =&gt; {<br>          totalPages++;<br>          if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>          const s = mp.validationSummary;<br>          totalFees += (mp.fees || []).length;<br>          totalPass += s.counts.pass;<br>          totalFail += s.counts.fail;<br>          totalReview += s.counts.review;<br>          totalPending += s.counts.pending;<br>          totalGross += s.financials.actualGross;<br>          totalCwt += s.financials.actualCwt;<br>          totalNet += s.financials.actualNet;<br>        });<br>      });<br><br>      const allTestCases = dataset.projects.flatMap(p =&gt; (p.testCases || []).map(tc =&gt; ({ ...tc, projectName: p.name })));<br>      const allDefects = dataset.projects.flatMap(p =&gt; (p.defects || []).map(df =&gt; ({ ...df, projectName: p.name })));<br><br>      return `<br>        &lt;!-- Report Scope &amp; Export Controls --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4 no-print&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Unified EIS &amp; QA Reporting Center&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Export all validation results, CWT calculations, test cases, defects, and project summaries.&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;label class=&quot;text-xs font-semibold text-slate-500&quot;&gt;Report Scope:&lt;/label&gt;<br>              &lt;select onchange=&quot;reportScope = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot;&gt;<br>                &lt;option value=&quot;active_page&quot; ${reportScope === &#39;active_page&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;Active Main Page (${escapeHtml(page?.name || &#39;&#39;)})&lt;/option&gt;<br>                &lt;option value=&quot;all_pages&quot; ${reportScope === &#39;all_pages&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Main Pages in Active Project (${escapeHtml(proj?.name || &#39;&#39;)})&lt;/option&gt;<br>                &lt;option value=&quot;all_projects&quot; ${reportScope === &#39;all_projects&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Projects (${appState.projects.length})&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;!-- Toggle for Including/Excluding Receipt Images in HTML &amp; Word (.doc) Exports --&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-2.5 px-3.5 py-2 rounded-xl bg-slate-50 dark:bg-slate-800/80 border border-slate-200 dark:border-slate-700 cursor-pointer select-none text-xs font-semibold&quot;&gt;<br>              &lt;input id=&quot;toggle-include-receipts&quot; type=&quot;checkbox&quot; ${reportIncludeReceipts ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;setReportIncludeReceipts(this.checked)&quot; class=&quot;rounded text-brand-600 focus:ring-brand-500 cursor-pointer&quot; /&gt;<br>              &lt;span&gt;Include receipt images in HTML &amp;amp; Word (.doc) exports&lt;/span&gt;<br>              &lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold ${reportIncludeReceipts ? &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400&#39; : &#39;bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300&#39;}&quot;&gt;${reportIncludeReceipts ? &#39;INCLUDED&#39; : &#39;EXCLUDED&#39;}&lt;/span&gt;<br>            &lt;/label&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;csv&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-spreadsheet&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export CSV&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;html&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-code&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export HTML&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;doc&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-600 hover:bg-indigo-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export Word (.doc)&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;window.print()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-900 text-white dark:bg-slate-700&quot;&gt;<br>                &lt;i data-lucide=&quot;printer&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Print / Save PDF&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;json&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                JSON<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;txt&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                TXT<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Live Printable / Previewable Report Document --&gt;<br>        &lt;div id=&quot;printable-report-area&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-6 space-y-6&quot;&gt;<br>          &lt;div class=&quot;border-b border-slate-200 dark:border-slate-800 pb-4 flex flex-col sm:flex-row sm:items-center justify-between gap-2&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;text-[11px] font-bold uppercase tracking-wider text-brand-500&quot;&gt;SMART EIS &amp; QA VALIDATION STUDIO&lt;/div&gt;<br>              &lt;h2 class=&quot;text-lg font-extrabold mt-0.5&quot;&gt;${escapeHtml(dataset.title)}&lt;/h2&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Generated: ${new Date().toLocaleString()} • Schema v${APP_SCHEMA_VERSION}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;text-xs font-mono text-slate-500&quot;&gt;<br>              Pages: &lt;strong&gt;${totalPages}&lt;/strong&gt; • Fee Rows: &lt;strong&gt;${totalFees}&lt;/strong&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;PASS&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-emerald-500&quot;&gt;${totalPass}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;FAIL&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-rose-500&quot;&gt;${totalFail}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;REVIEW&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-amber-500&quot;&gt;${totalReview}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;PENDING&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-sky-500&quot;&gt;${totalPending}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Gross Actual&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold&quot;&gt;${totalGross.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;CWT Deducted&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold text-amber-500&quot;&gt;-${totalCwt.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Net Actual&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold text-emerald-500&quot;&gt;${totalNet.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${dataset.projects.map(p =&gt; `<br>            &lt;div class=&quot;space-y-4&quot;&gt;<br>              &lt;div class=&quot;bg-slate-100 dark:bg-slate-800/80 px-4 py-2.5 rounded-xl flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                &lt;div&gt;&lt;strong&gt;Project:&lt;/strong&gt; ${escapeHtml(p.name)} &lt;span class=&quot;font-mono text-slate-500&quot;&gt;(${escapeHtml(p.reference)})&lt;/span&gt;&lt;/div&gt;<br>                &lt;div&gt;&lt;strong&gt;Owner:&lt;/strong&gt; ${escapeHtml(p.owner)} • &lt;strong&gt;Status:&lt;/strong&gt; ${escapeHtml(p.status)}&lt;/div&gt;<br>              &lt;/div&gt;<br><br>              ${(p.mainPages || []).map(mp =&gt; {<br>                const fin = mp.validationSummary.financials;<br>                return `<br>                  &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-3&quot;&gt;<br>                    &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                      &lt;div&gt;<br>                        &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(mp.name)}&lt;/h4&gt;<br>                        &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(mp.description)}&lt;/p&gt;<br>                      &lt;/div&gt;<br>                      &lt;div class=&quot;flex items-center gap-3 text-xs&quot;&gt;<br>                        &lt;span class=&quot;font-mono&quot;&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; | CWT: &lt;strong class=&quot;text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; | Net: &lt;strong class=&quot;text-emerald-500&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt;&lt;/span&gt;<br>                        ${statusBadge(mp.validationSummary.overallStatus)}<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br><br>                    ${renderReportSideBySideApp(mp)}<br>                    ${renderReportColumnsApp(mp)}<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          `).join(&#39;&#39;)}<br><br>          &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-2 gap-5 pt-2&quot;&gt;<br>            &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2&quot;&gt;<br>              &lt;h4 class=&quot;font-bold text-xs uppercase tracking-wider text-slate-400&quot;&gt;Test Cases (${allTestCases.length})&lt;/h4&gt;<br>              ${allTestCases.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;No test cases in scope.&lt;/div&gt;` : allTestCases.map(tc =&gt; `<br>                &lt;div class=&quot;flex items-center justify-between text-xs py-1.5 border-b border-slate-100 dark:divide-slate-800&quot;&gt;<br>                  &lt;span class=&quot;truncate pr-2&quot;&gt;&lt;strong class=&quot;font-mono&quot;&gt;${escapeHtml(tc.id)}&lt;/strong&gt;: ${escapeHtml(tc.title)}&lt;/span&gt;<br>                  ${statusBadge(tc.status)}<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2&quot;&gt;<br>              &lt;h4 class=&quot;font-bold text-xs uppercase tracking-wider text-slate-400&quot;&gt;Defects (${allDefects.length})&lt;/h4&gt;<br>              ${allDefects.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;No defects in scope.&lt;/div&gt;` : allDefects.map(df =&gt; `<br>                &lt;div class=&quot;flex items-center justify-between text-xs py-1.5 border-b border-slate-100 dark:divide-slate-800&quot;&gt;<br>                  &lt;span class=&quot;truncate pr-2&quot;&gt;&lt;strong class=&quot;font-mono text-rose-500&quot;&gt;${escapeHtml(df.id)}&lt;/strong&gt;: ${escapeHtml(df.title)}&lt;/span&gt;<br>                  ${statusBadge(df.status)}<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function buildStandaloneHtmlReport(dataset, includeReceipts = true) {<br>      const receiptNotice = includeReceipts<br>        ? &#39;Receipt &amp;amp; evidence images: &lt;strong&gt;Included&lt;/strong&gt;&#39;<br>        : &#39;Receipt &amp;amp; evidence images: &lt;strong&gt;Excluded by user toggle&lt;/strong&gt;&#39;;<br><br>      const pagesHtml = dataset.projects.map(p =&gt; `<br>        &lt;div class=&quot;project-block&quot;&gt;<br>          &lt;h2&gt;Project: ${escapeHtml(p.name)} (${escapeHtml(p.reference)})&lt;/h2&gt;<br>          &lt;p class=&quot;meta&quot;&gt;Owner: ${escapeHtml(p.owner)} | Status: ${escapeHtml(p.status)} | ${receiptNotice}&lt;/p&gt;<br>          ${(p.mainPages || []).map(mp =&gt; {<br>            const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees);<br>            const overall = mp.validationSummary?.overallStatus || &#39;PENDING&#39;;<br>            const receiptPages = (mp.receipt?.pages || []).map(sanitizeImageSrc).filter(Boolean);<br><br>            const receiptSectionHtml = includeReceipts ? `<br>              &lt;div class=&quot;receipt-section&quot;&gt;<br>                &lt;div class=&quot;receipt-title&quot;&gt;Attached Receipt Evidence (${escapeHtml(mp.receipt?.fileName || &#39;Receipt&#39;)} — ${receiptPages.length ? receiptPages.length + &#39; page(s)&#39; : &#39;No image attached&#39;})&lt;/div&gt;<br>                ${receiptPages.length ? receiptPages.map((src, idx) =&gt; `<br>                  &lt;div class=&quot;receipt-img-wrap&quot;&gt;<br>                    &lt;div class=&quot;receipt-page-label&quot;&gt;Page ${idx + 1}&lt;/div&gt;<br>                    &lt;img src=&quot;${src}&quot; alt=&quot;Receipt Page ${idx + 1} for ${escapeHtml(mp.name)}&quot; class=&quot;receipt-img&quot; /&gt;<br>                  &lt;/div&gt;<br>                `).join(&#39;&#39;) : `&lt;p class=&quot;muted&quot;&gt;No receipt image file attached to this Main Page.&lt;/p&gt;`}<br>              &lt;/div&gt;<br>            ` : &#39;&#39;;<br><br>            return `<br>              &lt;div class=&quot;page-block&quot;&gt;<br>                &lt;div class=&quot;page-header&quot;&gt;<br>                  &lt;h3&gt;${escapeHtml(mp.name)}&lt;/h3&gt;<br>                  &lt;span class=&quot;badge ${escapeHtml(overall)}&quot;&gt;${escapeHtml(overall)}&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;desc&quot;&gt;${escapeHtml(mp.description || &#39;&#39;)}&lt;/p&gt;<br>                &lt;p class=&quot;fin&quot;&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; | CWT: &lt;strong&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; | Net Actual: &lt;strong&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt; (Expected Net: ${fin.expectedNet.toFixed(2)})&lt;/p&gt;<br>                ${renderReportSideBySideStandalone(mp)}<br>                ${renderReportColumnsStandalone(mp)}<br>                ${receiptSectionHtml}<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `).join(&#39;&#39;);<br><br>      return `&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;title&gt;${escapeHtml(dataset.title)}&lt;/title&gt;<br>  &lt;style&gt;<br>    body { font-family: Arial, Helvetica, sans-serif; color: #0f172a; background: #ffffff; margin: 24px; line-height: 1.45; }<br>    h1 { margin: 0 0 6px; font-size: 20px; }<br>    h2 { font-size: 16px; margin: 20px 0 6px; color: #1e293b; border-bottom: 2px solid #e2e8f0; padding-bottom: 4px; }<br>    h3 { font-size: 14px; margin: 0; }<br>    .meta, .desc, .muted { font-size: 12px; color: #64748b; margin: 4px 0 10px; }<br>    .fin { font-size: 12px; background: #f8fafc; padding: 8px 10px; border-radius: 6px; border: 1px solid #e2e8f0; }<br>    .page-block { border: 1px solid #cbd5e1; border-radius: 8px; padding: 14px; margin: 14px 0; }<br>    .page-header { display: flex; justify-content: space-between; align-items: center; }<br>    table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 12px; }<br>    th, td { border: 1px solid #cbd5e1; padding: 6px 8px; text-align: left; }<br>    th { background: #f1f5f9; font-weight: bold; }<br>    td.num { text-align: right; font-family: Consolas, monospace; }<br>    .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 10px; font-weight: bold; background: #e2e8f0; color: #1e293b; }<br>    .badge.PASS { background: #dcfce7; color: #166534; }<br>    .badge.FAIL { background: #fee2e2; color: #991b1b; }<br>    .badge.REVIEW { background: #fef3c7; color: #92400e; }<br>    .badge.PENDING { background: #e0f2fe; color: #075985; }<br>    .receipt-section { margin-top: 12px; padding-top: 10px; border-top: 1px dashed #cbd5e1; }<br>    .receipt-title { font-size: 12px; font-weight: bold; margin-bottom: 8px; color: #334155; }<br>    .receipt-img-wrap { margin-bottom: 10px; }<br>    .receipt-page-label { font-size: 11px; color: #64748b; margin-bottom: 4px; }<br>    .receipt-img { max-width: 460px; width: 100%; height: auto; border: 1px solid #cbd5e1; border-radius: 6px; display: block; }<br>    .section-title { font-size: 13px; font-weight: bold; margin: 16px 0 4px; color: #334155; }<br>    td.muted { text-align: center; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;${escapeHtml(dataset.title)}&lt;/h1&gt;<br>  &lt;div class=&quot;meta&quot;&gt;Generated: ${escapeHtml(new Date().toLocaleString())} | ${receiptNotice}&lt;/div&gt;<br>  ${pagesHtml}<br>&lt;/body&gt;<br>&lt;/html&gt;`;<br>    }<br><br>    function exportReportFile(format) {<br>      const dataset = getReportDataset();<br>      const stamp = new Date().toISOString().slice(0, 10);<br>      const includeReceipts = Boolean(reportIncludeReceipts);<br><br>      if (format === &#39;json&#39;) {<br>        const payload = {<br>          title: dataset.title,<br>          exportedAt: new Date().toISOString(),<br>          includeReceiptImages: includeReceipts,<br>          projects: dataset.projects,<br>          reportSections: dataset.projects.flatMap(p =&gt; (p.mainPages || []).map(mp =&gt; {<br>            const { feeRows, colRows, fin } = getReportRows(mp);<br>            return {<br>              project: p.name,<br>              mainPage: mp.name,<br>              sideBySideFeeCwtComparison: feeRows.map(({ fee, v }) =&gt; ({ feeItem: fee.expectedName, isCwt: v.isCwt, expected: { name: fee.expectedName, amount: fee.expectedAmount, code: fee.expectedCode }, receipt: { name: fee.actualName, amount: fee.actualAmount, code: fee.actualCode }, difference: v.amountComparison.difference, confidence: fee.ocrConfidence ?? null, status: v.status, explanation: v.explanation })),<br>              netReconciliation: fin,<br>              expectedRowColumnsVerification: colRows.map(({ field, v }) =&gt; ({ column: &#39;C&#39; + String(field.number).padStart(2, &#39;0&#39;), fieldName: field.name, expectedValue: field.expectedValue, foundOnReceipt: field.actualValue, status: v.status, explanation: v.explanation }))<br>            };<br>          }))<br>        };<br>        downloadBlob(JSON.stringify(payload, null, 2), `SMART_report_${stamp}.json`, &#39;application/json&#39;);<br>      } else if (format === &#39;csv&#39;) {<br>        const rows = [[&#39;Section&#39;, &#39;Project&#39;, &#39;Main Page&#39;, &#39;Fee / Field Name&#39;, &#39;Expected Name&#39;, &#39;Expected Amount&#39;, &#39;Expected Code&#39;, &#39;Receipt Name&#39;, &#39;Receipt Amount&#39;, &#39;Receipt Code&#39;, &#39;Diff&#39;, &#39;Confidence&#39;, &#39;Status&#39;, &#39;Explanation&#39;]];<br>        dataset.projects.forEach(p =&gt; {<br>          (p.mainPages || []).forEach(mp =&gt; {<br>            const { feeRows, colRows } = getReportRows(mp);<br>            feeRows.forEach(({ fee: f, v }) =&gt; {<br>              rows.push([&#39;Fee &amp; CWT Comparison&#39;, p.name, mp.name, f.expectedName, f.expectedName, f.expectedAmount, f.expectedCode, f.actualName, f.actualAmount, f.actualCode, v.amountComparison.difference, f.ocrConfidence ?? &#39;Manual&#39;, v.status, v.explanation]);<br>            });<br>            colRows.forEach(({ field, v }) =&gt; {<br>              rows.push([&#39;Expected Row Column Verification&#39;, p.name, mp.name, `C${String(field.number).padStart(2, &#39;0&#39;)} ${field.name}`, &#39;&#39;, field.expectedValue, &#39;&#39;, &#39;&#39;, field.actualValue, &#39;&#39;, v.difference ?? &#39;&#39;, &#39;&#39;, v.status, v.explanation]);<br>            });<br>          });<br>        });<br>        const csv = rows.map(r =&gt; r.map(c =&gt; `&quot;${String(c ?? &#39;&#39;).replace(/&quot;/g, &#39;&quot;&quot;&#39;)}&quot;`).join(&#39;,&#39;)).join(&#39;\n&#39;);<br>        downloadBlob(csv, `SMART_report_${stamp}.csv`, &#39;text/csv&#39;);<br>      } else if (format === &#39;txt&#39;) {<br>        const lines = [dataset.title, `Generated: ${new Date().toLocaleString()}`, &#39;========================================&#39;];<br>        dataset.projects.forEach(p =&gt; {<br>          lines.push(`\nProject: ${p.name} (${p.reference})`);<br>          (p.mainPages || []).forEach(mp =&gt; {<br>            const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees);<br>            lines.push(`  Main Page: ${mp.name} [${mp.validationSummary?.overallStatus || &#39;PENDING&#39;}] — Gross ${fin.actualGross.toFixed(2)}, CWT -${fin.actualCwt.toFixed(2)}, Net ${fin.actualNet.toFixed(2)}`);<br>            const { feeRows, colRows } = getReportRows(mp);<br>            lines.push(&#39;    [Side-by-Side EIS Fee &amp; CWT Comparison]&#39;);<br>            feeRows.forEach(({ fee: f, v }) =&gt; {<br>              lines.push(`    - ${f.expectedName}${v.isCwt ? &#39; (CWT)&#39; : &#39;&#39;}: Expected ${f.expectedName} / ${f.expectedAmount} / ${f.expectedCode || &#39;-&#39;} | Receipt ${f.actualName || &#39;-&#39;} / ${f.actualAmount || &#39;-&#39;} / ${f.actualCode || &#39;-&#39;} | Diff=${v.amountComparison.difference} | ${v.status}`);<br>              lines.push(`        Rule: ${v.explanation}`);<br>            });<br>            const matchedCols = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>            lines.push(`    [Expected Row Columns vs Receipt Verification: ${matchedCols}/${colRows.length} matched]`);<br>            colRows.forEach(({ field, v }) =&gt; {<br>              lines.push(`    - C${String(field.number).padStart(2, &#39;0&#39;)} ${field.name}: Expected=${field.expectedValue || &#39;-&#39;} | Receipt=${field.actualValue || &#39;-&#39;} | ${v.status}`);<br>            });<br>          });<br>        });<br>        downloadBlob(lines.join(&#39;\n&#39;), `SMART_report_${stamp}.txt`, &#39;text/plain&#39;);<br>      } else if (format === &#39;html&#39;) {<br>        const htmlContent = buildStandaloneHtmlReport(dataset, includeReceipts);<br>        downloadBlob(htmlContent, `SMART_report_${stamp}.html`, &#39;text/html&#39;);<br>      } else if (format === &#39;doc&#39;) {<br>        // Word-compatible HTML document (.doc) honoring receipt image toggle<br>        const docBodyHtml = buildStandaloneHtmlReport(dataset, includeReceipts);<br>        const wordHtml = `&lt;html xmlns:o=&quot;urn:schemas-microsoft-com:office:office&quot; xmlns:w=&quot;urn:schemas-microsoft-com:office:word&quot; xmlns=&quot;http://www.w3.org/TR/REC-html40&quot;&gt;${docBodyHtml.replace(/^[\s\S]*&lt;html[^&gt;]*&gt;|&lt;\/html&gt;\s*$/gi, &#39;&#39;)}&lt;/html&gt;`;<br>        downloadBlob(wordHtml, `SMART_report_${stamp}.doc`, &#39;application/msword&#39;);<br>      }<br><br>      showToast(`Exported ${format.toUpperCase()} report${(format === &#39;html&#39; || format === &#39;doc&#39;) ? (includeReceipts ? &#39; (with receipt images)&#39; : &#39; (receipt images excluded)&#39;) : &#39;&#39;}.`, &#39;success&#39;);<br>    }<br><br>    function downloadBlob(content, filename, mimeType) {<br>      const blob = new Blob([content], { type: mimeType });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = filename;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>    }<br><br>    /****************************************************************************<br>     * GLOBAL KEYBOARD SHORTCUTS &amp; PASTE LISTENER<br>     ****************************************************************************/<br>    document.addEventListener(&#39;keydown&#39;, (e) =&gt; {<br>      if ((e.ctrlKey || e.metaKey) &amp;&amp; e.key.toLowerCase() === &#39;s&#39;) {<br>        e.preventDefault();<br>        manualSaveProject();<br>      }<br>      if (e.key === &#39;Escape&#39;) {<br>        closeModal();<br>        if (appState.ui.evPendingLabel) { appState.ui.evPendingLabel = null; if (appState.activeModule === &#39;evidence&#39;) renderApp(); }<br>      }<br>      if (e.altKey &amp;&amp; (e.key === &#39;ArrowRight&#39; || e.key === &#39;ArrowLeft&#39;) &amp;&amp; appState.activeModule === &#39;evidence&#39;) {<br>        e.preventDefault();<br>        evStepPage(e.key === &#39;ArrowRight&#39; ? 1 : -1);<br>      }<br>    });<br><br>    document.addEventListener(&#39;paste&#39;, async (e) =&gt; {<br>      const activeTag = document.activeElement?.tagName?.toLowerCase();<br>      if (activeTag === &#39;input&#39; || activeTag === &#39;textarea&#39;) return;<br>      const items = e.clipboardData?.items;<br>      if (!items) return;<br>      for (const item of items) {<br>        if (item.type &amp;&amp; item.type.startsWith(&#39;image/&#39;)) {<br>          const blob = item.getAsFile();<br>          if (blob &amp;&amp; appState.activeModule === &#39;evidence&#39;) {<br>            e.preventDefault();<br>            await evAddShotFromFile(blob, `clipboard_evidence_${Date.now()}.png`);<br>          } else if (blob &amp;&amp; appState.activeModule === &#39;validation&#39;) {<br>            e.preventDefault();<br>            const file = new File([blob], `clipboard_receipt_${Date.now()}.png`, { type: item.type });<br>            await processUploadedReceiptFile(file);<br>          }<br>        }<br>      }<br>    });<br><br>    /****************************************************************************<br>     * APPLICATION BOOTSTRAP<br>     ****************************************************************************/<br>    async function bootApplication() {<br>      try {<br>        const rawLoaded = await PersistenceEngine.loadState();<br>        const migrated = PersistenceEngine.migrateState(rawLoaded);<br>        if (migrated &amp;&amp; Array.isArray(migrated.projects) &amp;&amp; migrated.projects.length &gt; 0) {<br>          appState = migrated;<br>        } else {<br>          appState = createSampleSeedState();<br>          await PersistenceEngine.saveState(appState);<br>        }<br><br>        if (!appState.activeProjectId || !appState.projects.some(p =&gt; p.id === appState.activeProjectId)) {<br>          appState.activeProjectId = appState.projects[0]?.id || null;<br>        }<br>        const proj = getActiveProject();<br>        if (proj &amp;&amp; (!appState.activeMainPageId || !proj.mainPages.some(mp =&gt; mp.id === appState.activeMainPageId))) {<br>          appState.activeMainPageId = proj.mainPages[0]?.id || null;<br>        }<br><br>        proj?.mainPages?.forEach(mp =&gt; {<br>          if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        });<br><br>        renderApp();<br>        updateSaveIndicator(&#39;saved&#39;);<br>      } catch (err) {<br>        console.error(&#39;Boot error:&#39;, err);<br>        appState = createSampleSeedState();<br>        renderApp();<br>        showToast(&#39;Loaded fallback seed state due to storage notice: &#39; + err.message, &#39;warning&#39;);<br>      }<br>    }<br><br>    window.addEventListener(&#39;DOMContentLoaded&#39;, bootApplication);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ea3ecb73153" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart_eis_qa_validation_studio_v11 Developed By: Jansen B.]]></title>
            <link>https://medium.com/@barabonajansen/smart-eis-qa-validation-studio-v11-developed-by-jansen-b-fc8dc70f841c?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc8dc70f841c</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 09:41:57 GMT</pubDate>
            <atom:updated>2026-11-20T09:41:57.189Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot; class=&quot;dark&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>  &lt;title&gt;SMART EIS &amp; QA Validation Studio&lt;/title&gt;<br><br>  &lt;!-- Google Fonts: Inter &amp; JetBrains Mono --&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt;<br>  &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&amp;family=JetBrains+Mono:wght@400;500;600&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br><br>  &lt;!-- Tailwind CSS --&gt;<br>  &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    tailwind.config = {<br>      darkMode: &#39;class&#39;,<br>      theme: {<br>        extend: {<br>          fontFamily: {<br>            sans: [&#39;Inter&#39;, &#39;system-ui&#39;, &#39;sans-serif&#39;],<br>            mono: [&#39;JetBrains Mono&#39;, &#39;monospace&#39;]<br>          },<br>          colors: {<br>            brand: {<br>              50: &#39;#eef2ff&#39;,<br>              100: &#39;#e0e7ff&#39;,<br>              400: &#39;#818cf8&#39;,<br>              500: &#39;#6366f1&#39;,<br>              600: &#39;#4f46e5&#39;,<br>              700: &#39;#4338ca&#39;,<br>              900: &#39;#312e81&#39;,<br>              950: &#39;#1e1b4b&#39;<br>            }<br>          }<br>        }<br>      }<br>    };<br>  &lt;/script&gt;<br><br>  &lt;!-- Lucide Icons --&gt;<br>  &lt;script src=&quot;https://unpkg.com/lucide@latest&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Chart.js for Dashboard Analytics --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- PDF.js for Multi-Page PDF Receipt Rendering &amp; Text Extraction --&gt;<br>  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Tesseract.js for Client-Side Local-First OCR --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;style&gt;<br>    * { box-sizing: border-box; }<br>    body { font-family: &#39;Inter&#39;, system-ui, sans-serif; overflow-x: hidden; }<br>    ::-webkit-scrollbar { width: 6px; height: 6px; }<br>    ::-webkit-scrollbar-track { background: transparent; }<br>    ::-webkit-scrollbar-thumb { background: rgba(100, 116, 139, 0.35); border-radius: 9999px; }<br>    ::-webkit-scrollbar-thumb:hover { background: rgba(100, 116, 139, 0.6); }<br><br>    @media print {<br>      body * { visibility: hidden; }<br>      #printable-report-area, #printable-report-area * { visibility: visible; }<br>      #printable-report-area {<br>        position: absolute;<br>        left: 0;<br>        top: 0;<br>        width: 100%;<br>        background: #ffffff !important;<br>        color: #0f172a !important;<br>        padding: 20px;<br>      }<br>      .no-print { display: none !important; }<br>      .page-break { page-break-before: always; }<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100 antialiased selection:bg-brand-500 selection:text-white&quot;&gt;<br><br>  &lt;!-- Main Application Shell --&gt;<br>  &lt;div id=&quot;app-shell&quot; class=&quot;min-h-screen flex flex-col lg:flex-row&quot;&gt;<br><br>    &lt;!-- Mobile Top Header --&gt;<br>    &lt;header class=&quot;lg:hidden flex items-center justify-between px-4 py-3 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 sticky top-0 z-40&quot;&gt;<br>      &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>        &lt;button id=&quot;mobile-menu-btn&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; aria-label=&quot;Toggle Menu&quot;&gt;<br>          &lt;i data-lucide=&quot;menu&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>          &lt;div class=&quot;w-8 h-8 rounded-xl bg-gradient-to-br from-brand-500 to-indigo-600 flex items-center justify-center text-white font-bold shadow-md&quot;&gt;N&lt;/div&gt;<br>          &lt;span class=&quot;font-bold tracking-tight text-sm&quot;&gt;SMART EIS &amp; QA&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>        &lt;span id=&quot;mobile-save-badge&quot; class=&quot;text-xs px-2 py-1 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium&quot;&gt;Saved&lt;/span&gt;<br>        &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Toggle Theme&quot;&gt;<br>          &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/header&gt;<br><br>    &lt;!-- Collapsible Navigation Sidebar --&gt;<br>    &lt;aside id=&quot;sidebar&quot; class=&quot;fixed inset-y-0 left-0 z-50 w-72 lg:w-64 transform -translate-x-full lg:translate-x-0 lg:static transition-all duration-200 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col shrink-0&quot;&gt;<br>      &lt;!-- Brand Header --&gt;<br>      &lt;div class=&quot;p-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 overflow-hidden&quot;&gt;<br>          &lt;div class=&quot;w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500 via-indigo-600 to-violet-600 flex items-center justify-center text-white font-extrabold shadow-lg shrink-0&quot;&gt;<br>            N<br>          &lt;/div&gt;<br>          &lt;div class=&quot;sidebar-label truncate&quot;&gt;<br>            &lt;div class=&quot;font-bold text-sm tracking-tight&quot;&gt;SMART Studio&lt;/div&gt;<br>            &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;EIS Receipt &amp; QA Engine&lt;/div&gt;<br>   &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;Developed By: Jansen B.&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;button onclick=&quot;toggleSidebarCollapse()&quot; class=&quot;hidden lg:flex p-1.5 rounded-lg text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Collapse Sidebar&quot;&gt;<br>          &lt;i data-lucide=&quot;panel-left-close&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;button onclick=&quot;toggleMobileSidebar()&quot; class=&quot;lg:hidden p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- Active Project Quick Switcher --&gt;<br>      &lt;div class=&quot;p-3 border-b border-slate-200 dark:border-slate-800 sidebar-label&quot;&gt;<br>        &lt;label class=&quot;block text-[10px] font-semibold uppercase tracking-wider text-slate-400 mb-1&quot;&gt;Active Project&lt;/label&gt;<br>        &lt;select id=&quot;sidebar-project-select&quot; onchange=&quot;switchActiveProject(this.value)&quot; class=&quot;w-full text-xs font-medium bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-2.5 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- 11 Core Modules Navigation --&gt;<br>      &lt;nav id=&quot;sidebar-nav&quot; class=&quot;flex-1 overflow-y-auto p-2.5 space-y-1&quot;&gt;<br>        &lt;!-- Populated dynamically --&gt;<br>      &lt;/nav&gt;<br><br>      &lt;!-- Footer Status &amp; Privacy Badge --&gt;<br>      &lt;div class=&quot;p-3 border-t border-slate-200 dark:border-slate-800 sidebar-label space-y-2&quot;&gt;<br>        &lt;div class=&quot;flex items-center justify-between text-xs&quot;&gt;<br>          &lt;span class=&quot;text-slate-500 dark:text-slate-400 flex items-center gap-1.5&quot;&gt;<br>            &lt;span class=&quot;w-2 h-2 rounded-full bg-emerald-500 animate-pulse&quot;&gt;&lt;/span&gt;<br>            IndexedDB Local<br>          &lt;/span&gt;<br>          &lt;span id=&quot;sidebar-version-tag&quot; class=&quot;font-mono text-[11px] text-slate-400&quot;&gt;v2.4.0&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-800/70 rounded-xl p-2 flex items-center gap-2&quot;&gt;<br>          &lt;i data-lucide=&quot;shield-check&quot; class=&quot;w-4 h-4 text-emerald-500 shrink-0&quot;&gt;&lt;/i&gt;<br>          &lt;span&gt;Local-first storage. Zero external receipt uploads.&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/aside&gt;<br><br>    &lt;!-- Backdrop for mobile drawer --&gt;<br>    &lt;div id=&quot;mobile-backdrop&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;fixed inset-0 bg-slate-950/60 backdrop-blur-xs z-40 hidden lg:hidden&quot;&gt;&lt;/div&gt;<br><br>    &lt;!-- Main Content Workspace --&gt;<br>    &lt;div class=&quot;flex-1 flex flex-col min-w-0&quot;&gt;<br><br>      &lt;!-- Desktop Top Workspace Bar --&gt;<br>      &lt;header class=&quot;hidden lg:flex items-center justify-between px-6 py-3.5 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 sticky top-0 z-30&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 min-w-0&quot;&gt;<br>          &lt;h1 id=&quot;topbar-title&quot; class=&quot;text-base font-bold tracking-tight truncate&quot;&gt;Dashboard&lt;/h1&gt;<br>          &lt;span id=&quot;topbar-subtitle&quot; class=&quot;text-xs text-slate-500 dark:text-slate-400 hidden xl:inline truncate&quot;&gt;Enterprise EIS Receipt &amp; QA Evidence Overview&lt;/span&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>          &lt;!-- Autosave Status Pill --&gt;<br>          &lt;div id=&quot;save-status-pill&quot; class=&quot;flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20&quot;&gt;<br>            &lt;i data-lucide=&quot;check-circle-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span id=&quot;save-status-text&quot;&gt;All changes saved&lt;/span&gt;<br>          &lt;/div&gt;<br><br>          &lt;!-- Manual Save Button --&gt;<br>          &lt;button onclick=&quot;manualSaveProject()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Save Project Now (Ctrl+S)&quot;&gt;<br>            &lt;i data-lucide=&quot;save&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Save&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Run Validation CTA --&gt;<br>          &lt;button onclick=&quot;runActivePageValidation(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm transition&quot;&gt;<br>            &lt;i data-lucide=&quot;play&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Validate Active Page&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Theme Switcher --&gt;<br>          &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Toggle Dark/Light Theme&quot;&gt;<br>            &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br><br>      &lt;!-- Dynamic Module Viewport --&gt;<br>      &lt;main id=&quot;main-viewport&quot; class=&quot;flex-1 p-4 sm:p-6 max-w-[1600px] w-full mx-auto space-y-6&quot;&gt;<br>        &lt;!-- Active module renders here --&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Toast Notification Container --&gt;<br>  &lt;div id=&quot;toast-container&quot; class=&quot;fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-sm w-full pointer-events-none px-4 sm:px-0&quot;&gt;&lt;/div&gt;<br><br>  &lt;!-- Reusable Modal Container --&gt;<br>  &lt;div id=&quot;modal-overlay&quot; class=&quot;fixed inset-0 z-50 bg-slate-950/70 backdrop-blur-xs hidden items-center justify-center p-4&quot;&gt;<br>    &lt;div id=&quot;modal-box&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] flex flex-col overflow-hidden&quot;&gt;<br>      &lt;div class=&quot;px-5 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;h3 id=&quot;modal-title&quot; class=&quot;font-bold text-base&quot;&gt;Modal Title&lt;/h3&gt;<br>        &lt;button onclick=&quot;closeModal()&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;modal-body&quot; class=&quot;p-5 overflow-y-auto space-y-4 text-sm&quot;&gt;&lt;/div&gt;<br>      &lt;div id=&quot;modal-footer&quot; class=&quot;px-5 py-3.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-end gap-2 bg-slate-50 dark:bg-slate-900/50&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;script&gt;<br>    /****************************************************************************<br>     * SMART EIS &amp; QA VALIDATION STUDIO — MODULAR ARCHITECTURE<br>     * 1. Persistence &amp; Backup Engine (IndexedDB + Versioned Migration)<br>     * 2. Financial Calculator &amp; EIS Fee Validation Engine (Deterministic)<br>     * 3. Intelligent OCR &amp; Smart Field Mapping Engine (PDF.js + Tesseract.js)<br>     * 4. QA Screenshot &amp; Vector Annotation Engine<br>     * 5. Test Case, Defect &amp; Unified Reporting Engine<br>     * 6. Automated 12-Point Acceptance Test Suite<br>     ****************************************************************************/<br><br>    // Configure PDF.js worker with safe error guard<br>    try {<br>      if (window.pdfjsLib) {<br>        pdfjsLib.GlobalWorkerOptions.workerSrc = &#39;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js&#39;;<br>      }<br>    } catch (pdfInitErr) {<br>      console.warn(&#39;PDF.js worker initialization warning:&#39;, pdfInitErr);<br>    }<br><br>    const APP_SCHEMA_VERSION = 3;<br>    const DB_NAME = &#39;SMARTEisQaStudioDB&#39;;<br>    const DB_VERSION = 1;<br>    const STORE_NAME = &#39;workspaceState&#39;;<br><br>    const MODULES = [<br>      { id: &#39;dashboard&#39;, label: &#39;Dashboard&#39;, icon: &#39;layout-dashboard&#39;, subtitle: &#39;Real-time EIS validation metrics &amp; QA progress&#39; },<br>      { id: &#39;projects&#39;, label: &#39;Projects&#39;, icon: &#39;folder-kanban&#39;, subtitle: &#39;Manage isolated audit workspaces, backups &amp; imports&#39; },<br>      { id: &#39;main-pages&#39;, label: &#39;Main Pages&#39;, icon: &#39;file-spreadsheet&#39;, subtitle: &#39;Configure numbered fields (1–50+), per-page dynamic rows &amp; fees&#39; },<br>      { id: &#39;validation&#39;, label: &#39;Receipt Validation&#39;, icon: &#39;split-square-horizontal&#39;, subtitle: &#39;Side-by-side receipt comparison, OCR boxes &amp; mismatch review&#39; },<br>      { id: &#39;ocr-intel&#39;, label: &#39;OCR &amp; Doc Intel&#39;, icon: &#39;scan-text&#39;, subtitle: &#39;Preprocessing pipeline, confidence inspection &amp; block mapping&#39; },<br>      { id: &#39;screenshots&#39;, label: &#39;QA Screenshot Studio&#39;, icon: &#39;camera&#39;, subtitle: &#39;Screen capture, image merging &amp; dynamic QA evidence labels (1–200+)&#39; },<br>      { id: &#39;evidence&#39;, label: &#39;Evidence Screenshots&#39;, icon: &#39;images&#39;, hidden: true, subtitle: &#39;Per-Main-Page evidence screenshots: QA-n box value fills Expected Value or Found on Receipt of field Cn (main toggle)&#39; },<br>      { id: &#39;test-cases&#39;, label: &#39;Test Cases&#39;, icon: &#39;check-square&#39;, subtitle: &#39;QA test execution, preconditions &amp; linked receipt evidence&#39; },<br>      { id: &#39;defects&#39;, label: &#39;Defect Management&#39;, icon: &#39;bug&#39;, subtitle: &#39;Issue tracking, severity triage &amp; copy-ready Jira markup&#39; },<br>      { id: &#39;templates&#39;, label: &#39;Templates&#39;, icon: &#39;copy-plus&#39;, subtitle: &#39;Reusable EIS fee schemas, column mappings &amp; project templates&#39; },<br>      { id: &#39;settings&#39;, label: &#39;Settings &amp; Diagnostics&#39;, icon: &#39;settings&#39;, subtitle: &#39;Validation tolerances, OCR rules &amp; 12-point self-test suite&#39; },<br>      { id: &#39;reports&#39;, label: &#39;Reports&#39;, icon: &#39;file-bar-chart-2&#39;, subtitle: &#39;All results, projects &amp; QA reports (CSV, HTML, PDF, Word/DOC, JSON, TXT)&#39; }<br>    ];<br><br>    // Global Application State<br>    let appState = {<br>      schemaVersion: APP_SCHEMA_VERSION,<br>      theme: &#39;dark&#39;,<br>      sidebarCollapsed: false,<br>      activeModule: &#39;dashboard&#39;,<br>      activeProjectId: null,<br>      activeMainPageId: null,<br>      lastSavedAt: null,<br>      settings: {<br>        numericTolerance: 0.01,<br>        caseSensitiveNames: false,<br>        normalizeWhitespace: true,<br>        autoAcceptConfidenceThreshold: 88,<br>        cwtDeductionMode: &#39;absolute&#39;,<br>        qaLabelMax: 200,<br>        qaAutoIncrement: true<br>      },<br>      templates: [],<br>      projects: [],<br>      ui: {<br>        viewerZoom: 1,<br>        viewerRotation: 0,<br>        showOcrBoxes: true,<br>        selectedComparisonRowId: null,<br>        selectedScreenshotsForMerge: [],<br>        annotationTool: &#39;rect&#39;,<br>        annotationColor: &#39;#ef4444&#39;,<br>        selectedAnnotationId: null,<br>        selectedQaLabel: 1,<br>        mainPageQuickListOpen: false,<br>        selectedMainPageIds: []<br>      }<br>    };<br><br>    let chartInstances = {};<br>    let autosaveTimer = null;<br><br>    /**<br>     * Escapes HTML special characters safely for UI templates and exported HTML/DOC files.<br>     */<br>    function escapeHtml(str) {<br>      if (str === null || str === undefined) return &#39;&#39;;<br>      return String(str)<br>        .replace(/&amp;/g, &#39;&amp;amp;&#39;)<br>        .replace(/&lt;/g, &#39;&amp;lt;&#39;)<br>        .replace(/&gt;/g, &#39;&amp;gt;&#39;)<br>        .replace(/&quot;/g, &#39;&amp;quot;&#39;)<br>        .replace(/&#39;/g, &#39;&amp;#039;&#39;);<br>    }<br><br>    /**<br>     * Sanitizes image URLs or data URIs for safe embedding in HTML and Word (.doc) reports.<br>     */<br>    function sanitizeImageSrc(src) {<br>      if (!src || typeof src !== &#39;string&#39;) return &#39;&#39;;<br>      const trimmed = src.trim();<br>      if (/^data:image\/(png|jpeg|jpg|webp|gif|svg\+xml);/i.test(trimmed)) return trimmed;<br>      if (/^https?:\/\//i.test(trimmed)) return trimmed;<br>      return &#39;&#39;;<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1: PERSISTENCE &amp; BACKUP ENGINE (IndexedDB)<br>     ****************************************************************************/<br>    const PersistenceEngine = {<br>      openDB() {<br>        return new Promise((resolve, reject) =&gt; {<br>          if (!window.indexedDB) {<br>            reject(new Error(&#39;IndexedDB is unavailable in this browser environment.&#39;));<br>            return;<br>          }<br>          const req = indexedDB.open(DB_NAME, DB_VERSION);<br>          req.onupgradeneeded = (e) =&gt; {<br>            const db = e.target.result;<br>            if (!db.objectStoreNames.contains(STORE_NAME)) {<br>              db.createObjectStore(STORE_NAME, { keyPath: &#39;id&#39; });<br>            }<br>          };<br>          req.onsuccess = () =&gt; resolve(req.result);<br>          req.onerror = () =&gt; reject(req.error);<br>        });<br>      },<br><br>      async saveState(stateObj) {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readwrite&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const payload = {<br>            id: &#39;primary_workspace&#39;,<br>            updatedAt: new Date().toISOString(),<br>            data: JSON.parse(JSON.stringify(stateObj))<br>          };<br>          store.put(payload);<br>          return new Promise((resolve, reject) =&gt; {<br>            tx.oncomplete = () =&gt; {<br>              appState.lastSavedAt = payload.updatedAt;<br>              updateSaveIndicator(&#39;saved&#39;);<br>              resolve(true);<br>            };<br>            tx.onerror = () =&gt; reject(tx.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Save Error:&#39;, err);<br>          updateSaveIndicator(&#39;error&#39;);<br>          return false;<br>        }<br>      },<br><br>      async loadState() {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readonly&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const req = store.get(&#39;primary_workspace&#39;);<br>          return new Promise((resolve, reject) =&gt; {<br>            req.onsuccess = () =&gt; resolve(req.result ? req.result.data : null);<br>            req.onerror = () =&gt; reject(req.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Load Error:&#39;, err);<br>          return null;<br>        }<br>      },<br><br>      migrateState(raw) {<br>        if (!raw) return null;<br>        if (!raw.schemaVersion || raw.schemaVersion &lt; APP_SCHEMA_VERSION) {<br>          raw.schemaVersion = APP_SCHEMA_VERSION;<br>          raw.settings = Object.assign({<br>            numericTolerance: 0.01,<br>            caseSensitiveNames: false,<br>            normalizeWhitespace: true,<br>            autoAcceptConfidenceThreshold: 88,<br>            cwtDeductionMode: &#39;absolute&#39;,<br>            qaLabelMax: 200,<br>            qaAutoIncrement: true<br>          }, raw.settings || {});<br>        }<br>        (raw.projects || []).forEach(proj =&gt; {<br>          const migPages = proj.mainPages || [];<br>          if (Array.isArray(proj.evidenceShots) &amp;&amp; proj.evidenceShots.length) {<br>            proj.evidenceShots.forEach(sh =&gt; {<br>              const owner = migPages.find(mp =&gt; (mp.evidenceAnnotations || []).some(a =&gt; a.screenshotId === sh.id)) || migPages[0];<br>              if (owner) { owner.evidenceShots = owner.evidenceShots || []; owner.evidenceShots.push(sh); }<br>            });<br>          }<br>          delete proj.evidenceShots;<br>          if (proj.evidenceMergeHistory) {<br>            if (migPages[0] &amp;&amp; !migPages[0].evidenceMergeHistory) migPages[0].evidenceMergeHistory = proj.evidenceMergeHistory;<br>            delete proj.evidenceMergeHistory;<br>          }<br>          migPages.forEach(mp =&gt; {<br>            const evIds = new Set((mp.evidenceAnnotations || []).map(a =&gt; a.id));<br>            (mp.fields || []).forEach(f =&gt; {<br>              if (f.actualSource &amp;&amp; evIds.has(f.actualSource)) {<br>                f.expectedValue = f.actualValue || f.expectedValue || &#39;&#39;;<br>                f.actualValue = &#39;&#39;;<br>                f.expectedSource = f.actualSource;<br>                delete f.actualSource;<br>              }<br>            });<br>          });<br>          (proj.mainPages || []).forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>          });<br>        });<br>        return raw;<br>      }<br>    };<br><br>    function scheduleAutosave(reason = &#39;&#39;) {<br>      updateSaveIndicator(&#39;saving&#39;);<br>      if (autosaveTimer) clearTimeout(autosaveTimer);<br>      autosaveTimer = setTimeout(async () =&gt; {<br>        try {<br>          const proj = getActiveProject();<br>          if (proj) proj.lastModified = new Date().toISOString();<br>          await PersistenceEngine.saveState(appState);<br>        } catch (err) {<br>          console.error(&#39;Autosave error:&#39;, err);<br>        }<br>      }, 450);<br>    }<br><br>    async function manualSaveProject() {<br>      try {<br>        const proj = getActiveProject();<br>        if (proj) proj.lastModified = new Date().toISOString();<br>        const saved = await PersistenceEngine.saveState(appState);<br>        if (saved) {<br>          showToast(&#39;Project state persisted to IndexedDB.&#39;, &#39;success&#39;);<br>        } else {<br>          showToast(&#39;Unable to persist project state to IndexedDB.&#39;, &#39;error&#39;);<br>        }<br>      } catch (err) {<br>        showToast(&#39;Save failed: &#39; + err.message, &#39;error&#39;);<br>      }<br>    }<br><br>    function updateSaveIndicator(status) {<br>      const textEl = document.getElementById(&#39;save-status-text&#39;);<br>      const mobileBadge = document.getElementById(&#39;mobile-save-badge&#39;);<br>      if (status === &#39;saving&#39;) {<br>        if (textEl) textEl.textContent = &#39;Saving...&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saving...&#39;;<br>      } else if (status === &#39;saved&#39;) {<br>        const t = new Date().toLocaleTimeString([], { hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39;, second: &#39;2-digit&#39; });<br>        if (textEl) textEl.textContent = `Saved ${t}`;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saved&#39;;<br>      } else {<br>        if (textEl) textEl.textContent = &#39;Save error&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Error&#39;;<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2: FINANCIAL CALCULATOR &amp; EIS FEE VALIDATION ENGINE<br>     ****************************************************************************/<br>    const FinancialCalculator = {<br>      parseAmount(raw) {<br>        if (raw === null || raw === undefined || raw === &#39;&#39;) return null;<br>        if (typeof raw === &#39;number&#39;) return Number.isFinite(raw) ? raw : null;<br>        let str = String(raw).trim();<br>        if (!str) return null;<br><br>        let isNegative = false;<br>        if (/^\(.*\)$/.test(str)) {<br>          isNegative = true;<br>          str = str.replace(/^\(|\)$/g, &#39;&#39;).trim();<br>        }<br>        if (str.startsWith(&#39;-&#39;)) {<br>          isNegative = true;<br>          str = str.slice(1).trim();<br>        }<br>        str = str.replace(/[^0-9.\-]/g, &#39;&#39;);<br>        if (!str || str === &#39;.&#39; || str === &#39;-&#39;) return null;<br>        const val = parseFloat(str);<br>        if (!Number.isFinite(val)) return null;<br>        return isNegative ? -Math.abs(val) : val;<br>      },<br><br>      isCwtEntry(fee) {<br>        if (!fee) return false;<br>        if (fee.isCwt === true) return true;<br>        const code = String(fee.code || fee.actualCode || &#39;&#39;).trim().toUpperCase();<br>        const name = String(fee.name || fee.actualName || &#39;&#39;).trim().toUpperCase();<br>        return code === &#39;CWT&#39; || /\bCWT\b|WITHHOLDING/.test(name);<br>      },<br><br>      calculateTotals(fees = []) {<br>        let expectedGross = 0;<br>        let expectedCwt = 0;<br>        let actualGross = 0;<br>        let actualCwt = 0;<br>        let hasMissingActual = false;<br><br>        fees.forEach(fee =&gt; {<br>          const isCwt = this.isCwtEntry(fee);<br>          const expAmt = this.parseAmount(fee.expectedAmount);<br>          const actAmt = this.parseAmount(fee.actualAmount);<br><br>          if (expAmt !== null) {<br>            if (isCwt) {<br>              expectedCwt += Math.abs(expAmt);<br>            } else {<br>              expectedGross += expAmt;<br>            }<br>          }<br><br>          if (actAmt !== null) {<br>            if (isCwt) {<br>              actualCwt += Math.abs(actAmt);<br>            } else {<br>              actualGross += actAmt;<br>            }<br>          } else {<br>            hasMissingActual = true;<br>          }<br>        });<br><br>        expectedGross = Number(expectedGross.toFixed(2));<br>        expectedCwt = Number(expectedCwt.toFixed(2));<br>        actualGross = Number(actualGross.toFixed(2));<br>        actualCwt = Number(actualCwt.toFixed(2));<br><br>        const expectedNet = Number((expectedGross - expectedCwt).toFixed(2));<br>        const actualNet = Number((actualGross - actualCwt).toFixed(2));<br>        const netDifference = Number((actualNet - expectedNet).toFixed(2));<br>        const grossDifference = Number((actualGross - expectedGross).toFixed(2));<br>        const cwtDifference = Number((actualCwt - expectedCwt).toFixed(2));<br><br>        return {<br>          expectedGross,<br>          expectedCwt,<br>          expectedNet,<br>          actualGross,<br>          actualCwt,<br>          actualNet,<br>          grossDifference,<br>          cwtDifference,<br>          netDifference,<br>          hasMissingActual,<br>          formulaExplanation: `Gross Fees (non-CWT sum) - |CWT Deductions| = Net Total (${actualGross.toFixed(2)} - ${actualCwt.toFixed(2)} = ${actualNet.toFixed(2)})`<br>        };<br>      }<br>    };<br><br>    const ValidationEngine = {<br>      normalizeText(str, settings = appState.settings) {<br>        if (str === null || str === undefined) return &#39;&#39;;<br>        let s = String(str);<br>        if (settings.normalizeWhitespace) s = s.replace(/\s+/g, &#39; &#39;).trim();<br>        if (!settings.caseSensitiveNames) s = s.toLowerCase();<br>        return s;<br>      },<br><br>      validateFeeRow(fee, settings = appState.settings) {<br>        const tolerance = Number(settings.numericTolerance ?? 0.01);<br>        const timestamp = new Date().toISOString();<br>        const isCwt = FinancialCalculator.isCwtEntry(fee);<br><br>        const expName = String(fee.expectedName || &#39;&#39;).trim();<br>        const actName = String(fee.actualName || &#39;&#39;).trim();<br>        const expCode = String(fee.expectedCode || &#39;&#39;).trim();<br>        const actCode = String(fee.actualCode || &#39;&#39;).trim();<br>        const expAmt = FinancialCalculator.parseAmount(fee.expectedAmount);<br>        const actAmt = FinancialCalculator.parseAmount(fee.actualAmount);<br><br>        const nameResult = this.compareTextAttribute(&#39;Fee Name&#39;, expName, actName, true, fee.ocrConfidence, settings);<br><br>        let amtStatus = &#39;PENDING&#39;;<br>        let amtDiff = null;<br>        let amtExplanation = &#39;&#39;;<br>        if (expAmt === null &amp;&amp; actAmt === null) {<br>          amtStatus = &#39;NOT APPLICABLE&#39;;<br>          amtExplanation = &#39;No expected or receipt amount configured.&#39;;<br>        } else if (expAmt === null) {<br>          amtStatus = &#39;REVIEW&#39;;<br>          amtExplanation = `Receipt has ${actAmt.toFixed(2)} but Expected Amount is blank.`;<br>        } else if (actAmt === null) {<br>          amtStatus = &#39;PENDING&#39;;<br>          amtExplanation = `Missing receipt amount for expected ${expAmt.toFixed(2)}.`;<br>        } else {<br>          const cmpExp = isCwt ? Math.abs(expAmt) : expAmt;<br>          const cmpAct = isCwt ? Math.abs(actAmt) : actAmt;<br>          amtDiff = Number((cmpAct - cmpExp).toFixed(2));<br>          if (Math.abs(amtDiff) &lt;= tolerance) {<br>            amtStatus = (fee.ocrConfidence !== null &amp;&amp; fee.ocrConfidence !== undefined &amp;&amp; fee.ocrConfidence &lt; settings.autoAcceptConfidenceThreshold &amp;&amp; !fee.manuallyVerified)<br>              ? &#39;REVIEW&#39;<br>              : &#39;PASS&#39;;<br>            amtExplanation = isCwt<br>              ? `CWT deduction magnitude matches (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`<br>              : `Amount matches within ±${tolerance} tolerance (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`;<br>          } else {<br>            amtStatus = &#39;FAIL&#39;;<br>            amtExplanation = `Amount mismatch: Expected ${cmpExp.toFixed(2)}, Receipt ${cmpAct.toFixed(2)}, Difference ${amtDiff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${amtDiff.toFixed(2)}.`;<br>          }<br>        }<br><br>        const codeResult = this.compareTextAttribute(&#39;Fee Code&#39;, expCode, actCode, true, fee.ocrConfidence, settings, true);<br><br>        const statuses = [nameResult.status, amtStatus, codeResult.status];<br>        let overallStatus = &#39;PASS&#39;;<br>        if (statuses.includes(&#39;FAIL&#39;)) overallStatus = &#39;FAIL&#39;;<br>        else if (statuses.includes(&#39;PENDING&#39;)) overallStatus = &#39;PENDING&#39;;<br>        else if (statuses.includes(&#39;REVIEW&#39;)) overallStatus = &#39;REVIEW&#39;;<br>        else if (statuses.every(s =&gt; s === &#39;NOT APPLICABLE&#39;)) overallStatus = &#39;NOT APPLICABLE&#39;;<br><br>        const explanations = [nameResult.explanation, amtExplanation, codeResult.explanation].filter(Boolean);<br><br>        return {<br>          feeId: fee.id,<br>          isCwt,<br>          nameComparison: nameResult,<br>          amountComparison: {<br>            rule: isCwt ? &#39;CWT Absolute Value Match&#39; : `Numeric Tolerance (±${tolerance})`,<br>            expected: expAmt !== null ? expAmt.toFixed(2) : &#39;&#39;,<br>            actual: actAmt !== null ? actAmt.toFixed(2) : &#39;&#39;,<br>            difference: amtDiff !== null ? amtDiff.toFixed(2) : &#39;N/A&#39;,<br>            status: amtStatus,<br>            explanation: amtExplanation<br>          },<br>          codeComparison: codeResult,<br>          status: overallStatus,<br>          explanation: explanations.join(&#39; | &#39;),<br>          ocrConfidence: fee.ocrConfidence ?? null,<br>          sourceLocation: fee.sourceLocation || &#39;Manual / Unmapped&#39;,<br>          evaluatedAt: timestamp<br>        };<br>      },<br><br>      compareTextAttribute(label, expected, actual, required, confidence, settings, exactCode = false) {<br>        if (!expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual: &#39;&#39;,<br>            difference: &#39;0&#39;,<br>            status: required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            explanation: required ? `${label} is missing on both Expected and Receipt.` : `${label} not configured.`<br>          };<br>        }<br>        if (!expected &amp;&amp; actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual,<br>            difference: &#39;Unconfigured expected&#39;,<br>            status: &#39;REVIEW&#39;,<br>            explanation: `${label} &quot;${actual}&quot; found on receipt, but expected value is empty.`<br>          };<br>        }<br>        if (expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual: &#39;&#39;,<br>            difference: &#39;Missing on receipt&#39;,<br>            status: &#39;PENDING&#39;,<br>            explanation: `Required ${label} &quot;${expected}&quot; is missing from receipt extraction.`<br>          };<br>        }<br><br>        const normExp = exactCode ? expected.trim().toUpperCase() : this.normalizeText(expected, settings);<br>        const normAct = exactCode ? actual.trim().toUpperCase() : this.normalizeText(actual, settings);<br><br>        if (normExp === normAct) {<br>          const lowConf = confidence !== null &amp;&amp; confidence !== undefined &amp;&amp; confidence &lt; settings.autoAcceptConfidenceThreshold;<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual,<br>            difference: &#39;0&#39;,<br>            status: lowConf ? &#39;REVIEW&#39; : &#39;PASS&#39;,<br>            explanation: lowConf ? `${label} matched (&quot;${actual}&quot;), flagged REVIEW due to ${confidence}% OCR confidence.` : `${label} matched (&quot;${actual}&quot;).`<br>          };<br>        }<br><br>        return {<br>          rule: `${label} Match`,<br>          expected,<br>          actual,<br>          difference: `&quot;${expected}&quot; ≠ &quot;${actual}&quot;`,<br>          status: &#39;FAIL&#39;,<br>          explanation: `${label} mismatch: Expected &quot;${expected}&quot;, Receipt &quot;${actual}&quot;.`<br>        };<br>      },<br><br>      validateField(field, settings = appState.settings) {<br>        if (!field.enabled &amp;&amp; !field.expectedValue &amp;&amp; !field.actualValue) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: &#39;Field disabled / unused.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        const exp = String(field.expectedValue ?? &#39;&#39;).trim();<br>        const act = String(field.actualValue ?? &#39;&#39;).trim();<br><br>        if (!exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: field.required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: field.required ? &#39;Required field has no expected or actual value.&#39; : &#39;Optional field blank.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;PENDING&#39;,<br>            difference: &#39;Missing actual&#39;,<br>            explanation: `Expected &quot;${exp}&quot;, awaiting receipt/system value.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (!exp &amp;&amp; act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;REVIEW&#39;,<br>            difference: &#39;Missing expected&#39;,<br>            explanation: `Actual &quot;${act}&quot; present, but Expected value is blank.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        if (field.dataType === &#39;Currency&#39; || field.dataType === &#39;Number&#39; || field.dataType === &#39;Percentage&#39;) {<br>          const nExp = FinancialCalculator.parseAmount(exp);<br>          const nAct = FinancialCalculator.parseAmount(act);<br>          const tol = Number(field.tolerance ?? settings.numericTolerance ?? 0.01);<br>          if (nExp !== null &amp;&amp; nAct !== null) {<br>            const diff = Number((nAct - nExp).toFixed(4));<br>            const pass = Math.abs(diff) &lt;= tol;<br>            return {<br>              fieldId: field.id,<br>              status: pass ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>              difference: diff === 0 ? &#39;0.00&#39; : `${diff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${diff.toFixed(2)}`,<br>              explanation: pass ? `Numeric match within ±${tol}.` : `Expected ${nExp}, found ${nAct} (Diff: ${diff}).`,<br>              evaluatedAt: new Date().toISOString()<br>            };<br>          }<br>        }<br><br>        const normExp = this.normalizeText(exp, settings);<br>        const normAct = this.normalizeText(act, settings);<br>        const match = normExp === normAct;<br>        return {<br>          fieldId: field.id,<br>          status: match ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>          difference: match ? &#39;0&#39; : `&quot;${exp}&quot; ≠ &quot;${act}&quot;`,<br>          explanation: match ? &#39;Value matched.&#39; : `Expected &quot;${exp}&quot;, got &quot;${act}&quot;.`,<br>          evaluatedAt: new Date().toISOString()<br>        };<br>      },<br><br>      validateMainPage(mainPage, recordHistory = false) {<br>        if (!mainPage) return null;<br>        const feeResults = (mainPage.fees || []).map(f =&gt; {<br>          const res = this.validateFeeRow(f);<br>          f.lastValidation = res;<br>          return res;<br>        });<br><br>        const fieldResults = (mainPage.fields || []).map(fld =&gt; {<br>          const res = this.validateField(fld);<br>          fld.lastValidation = res;<br>          return res;<br>        });<br><br>        const financials = FinancialCalculator.calculateTotals(mainPage.fees || []);<br><br>        const activeStatuses = [<br>          ...feeResults.map(r =&gt; r.status),<br>          ...fieldResults.filter(r =&gt; r.status !== &#39;NOT APPLICABLE&#39;).map(r =&gt; r.status)<br>        ];<br><br>        let overallStatus = &#39;PENDING&#39;;<br>        if (activeStatuses.length === 0) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;FAIL&#39;)) {<br>          overallStatus = &#39;FAIL&#39;;<br>        } else if (activeStatuses.includes(&#39;PENDING&#39;)) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;REVIEW&#39;)) {<br>          overallStatus = &#39;REVIEW&#39;;<br>        } else {<br>          overallStatus = &#39;PASS&#39;;<br>        }<br><br>        const summary = {<br>          overallStatus,<br>          feeResults,<br>          fieldResults,<br>          financials,<br>          counts: {<br>            pass: activeStatuses.filter(s =&gt; s === &#39;PASS&#39;).length,<br>            fail: activeStatuses.filter(s =&gt; s === &#39;FAIL&#39;).length,<br>            review: activeStatuses.filter(s =&gt; s === &#39;REVIEW&#39;).length,<br>            pending: activeStatuses.filter(s =&gt; s === &#39;PENDING&#39;).length<br>          },<br>          validatedAt: new Date().toISOString()<br>        };<br><br>        mainPage.validationSummary = summary;<br><br>        if (recordHistory) {<br>          mainPage.validationHistory = mainPage.validationHistory || [];<br>          mainPage.validationHistory.unshift({<br>            id: &#39;vh_&#39; + Date.now(),<br>            timestamp: summary.validatedAt,<br>            overallStatus: summary.overallStatus,<br>            counts: { ...summary.counts },<br>            netTotal: financials.actualNet<br>          });<br>          if (mainPage.validationHistory.length &gt; 25) mainPage.validationHistory.pop();<br>        }<br><br>        return summary;<br>      }<br>    };<br><br>    /****************************************************************************<br>     * MODULE 3: INTELLIGENT OCR, ROW PARSER &amp; SMART FIELD MAPPING ENGINE<br>     ****************************************************************************/<br>    const RowToFieldsEngine = {<br>      parseSpreadsheetRow(rawText, hasHeaderRow = false) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br>        if (!lines.length) return { headers: [], values: [], delimiter: &#39;None&#39; };<br><br>        const detectDelimiter = (line) =&gt; {<br>          if (line.includes(&#39;\t&#39;)) return &#39;\t&#39;;<br>          if (line.includes(&#39;|&#39;)) return &#39;|&#39;;<br>          if (line.includes(&#39;,&#39;)) return &#39;,&#39;;<br>          return &#39;\t&#39;;<br>        };<br><br>        const splitLine = (line, delim) =&gt; {<br>          if (delim === &#39;,&#39;) {<br>            const matches = line.match(/(&quot;.*?&quot;|[^&quot;,]+)(?=\s*,|\s*$)/g);<br>            return matches ? matches.map(c =&gt; c.replace(/^&quot;|&quot;$/g, &#39;&#39;).trim()) : line.split(&#39;,&#39;).map(c =&gt; c.trim());<br>          }<br>          return line.split(delim).map(c =&gt; c.trim());<br>        };<br><br>        const delim = detectDelimiter(lines[0]);<br>        const delimLabel = delim === &#39;\t&#39; ? &#39;Tab (Excel/Sheets)&#39; : delim === &#39;|&#39; ? &#39;Pipe (|)&#39; : &#39;CSV (,)&#39;;<br><br>        if (hasHeaderRow &amp;&amp; lines.length &gt;= 2) {<br>          return {<br>            headers: splitLine(lines[0], delim),<br>            values: splitLine(lines[1], delim),<br>            delimiter: delimLabel<br>          };<br>        }<br><br>        return {<br>          headers: [],<br>          values: splitLine(lines[0], delim),<br>          delimiter: delimLabel<br>        };<br>      },<br><br>      inferDataType(val) {<br>        const s = String(val || &#39;&#39;).trim();<br>        if (!s) return &#39;Dynamic&#39;;<br>        if (/^\d{4}-\d{2}-\d{2}$/.test(s) || /^\d{1,2}\/\d{1,2}\/\d{2,4}$/.test(s)) return &#39;Date&#39;;<br>        if (/^[$₱€£]?\s*\(?-?\d{1,3}(,\d{3})*(\.\d+)?\)?$/.test(s)) return &#39;Currency&#39;;<br>        if (/^[A-Z]{2,5}$/.test(s)) return &#39;Code&#39;;<br>        return &#39;Dynamic&#39;;<br>      },<br><br>      autoMatchReceiptAgainstExpectedFields(mainPage) {<br>        if (!mainPage || !mainPage.receipt || !mainPage.receipt.ocrRawText) {<br>          return { matched: 0, total: 0 };<br>        }<br>        const rawText = mainPage.receipt.ocrRawText;<br>        const normReceipt = rawText.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>        const compactReceipt = rawText.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br>        const lines = rawText.split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br><br>        let matched = 0;<br>        let total = 0;<br><br>        (mainPage.fields || []).forEach(f =&gt; {<br>          const exp = String(f.expectedValue || &#39;&#39;).trim();<br>          if (!exp) return;<br>          total++;<br><br>          const normExp = exp.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>          const compactExp = exp.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br><br>          if (normReceipt.includes(normExp) || (compactExp.length &gt;= 2 &amp;&amp; compactReceipt.includes(compactExp))) {<br>            f.actualValue = exp;<br>            f.enabled = true;<br>            matched++;<br>            return;<br>          }<br><br>          const labelNorm = f.name.toLowerCase();<br>          const labelLine = lines.find(l =&gt; l.toLowerCase().includes(labelNorm));<br>          if (labelLine) {<br>            const afterColon = labelLine.split(/[:\-]/).slice(1).join(&#39;:&#39;).trim();<br>            if (afterColon) {<br>              f.actualValue = afterColon;<br>              f.enabled = true;<br>            }<br>          }<br>        });<br><br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { matched, total };<br>      }<br>    };<br><br>    const OcrMappingEngine = {<br>      parseQuickPasteFees(rawText) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br><br>        const parsed = [];<br>        let i = 0;<br><br>        while (i &lt; lines.length) {<br>          const line = lines[i];<br><br>          if (line.includes(&#39;|&#39;) || line.includes(&#39;\t&#39;)) {<br>            const parts = line.split(/\||\t/).map(p =&gt; p.trim()).filter(Boolean);<br>            const name = parts[0] || `Fee ${parsed.length + 1}`;<br>            const amount = parts[1] || &#39;0&#39;;<br>            const isCwt = /\bcwt\b|withholding/i.test(name) || (parts[2] &amp;&amp; parts[2].toUpperCase() === &#39;CWT&#39;);<br>            const code = parts[2] || (isCwt ? &#39;CWT&#39; : &#39;&#39;);<br>            parsed.push({ name, amount, code, isCwt });<br>            i += 1;<br>            continue;<br>          }<br><br>          const name = line;<br>          const amount = lines[i + 1] !== undefined ? lines[i + 1] : &#39;&#39;;<br>          const isCwtName = /\bcwt\b|withholding/i.test(name);<br>          const possibleCode = lines[i + 2];<br><br>          const looksLikeCode = possibleCode !== undefined &amp;&amp;<br>            /^[A-Za-z0-9_-]{1,12}$/.test(possibleCode) &amp;&amp;<br>            !/^\d+(\.\d+)?$/.test(possibleCode);<br><br>          if (looksLikeCode) {<br>            const isCwt = isCwtName || possibleCode.toUpperCase() === &#39;CWT&#39;;<br>            parsed.push({ name, amount, code: possibleCode.toUpperCase(), isCwt });<br>            i += 3;<br>          } else {<br>            parsed.push({<br>              name,<br>              amount,<br>              code: isCwtName ? &#39;CWT&#39; : &#39;&#39;,<br>              isCwt: isCwtName<br>            });<br>            i += 2;<br>          }<br>        }<br><br>        return parsed;<br>      },<br><br>      parseReceiptTextToBlocks(rawText, pageNum = 1, baseConfidence = 92) {<br>        const lines = String(rawText || &#39;&#39;).split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br>        const blocks = [];<br><br>        lines.forEach((line, idx) =&gt; {<br>          const yPct = Math.min(92, 8 + idx * 7);<br>          const pipeOrCol = line.split(/\||\t|\s{2,}/).map(s =&gt; s.trim()).filter(Boolean);<br>          if (pipeOrCol.length &gt;= 2) {<br>            const name = pipeOrCol[0];<br>            const amtMatch = pipeOrCol.find(p =&gt; /^\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?$/.test(p)) || pipeOrCol[1];<br>            const codeMatch = pipeOrCol.find(p =&gt; /^[A-Z0-9]{2,8}$/.test(p) &amp;&amp; p !== amtMatch) || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;);<br>            blocks.push({<br>              id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>              page: pageNum,<br>              rawLine: line,<br>              detectedName: name,<br>              detectedAmount: amtMatch,<br>              detectedCode: codeMatch,<br>              confidence: baseConfidence,<br>              bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>              mappedToFeeId: null,<br>              status: &#39;UNMAPPED&#39;<br>            });<br>          } else {<br>            const regex = /^(.+?)\s+(\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?)(?:\s+([A-Za-z0-9_-]{2,10}))?$/;<br>            const m = line.match(regex);<br>            if (m) {<br>              const name = m[1].trim();<br>              const amt = m[2].trim();<br>              const code = (m[4] || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;)).toUpperCase();<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: name,<br>                detectedAmount: amt,<br>                detectedCode: code,<br>                confidence: baseConfidence,<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;UNMAPPED&#39;<br>              });<br>            } else {<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: line,<br>                detectedAmount: &#39;&#39;,<br>                detectedCode: &#39;&#39;,<br>                confidence: Math.max(65, baseConfidence - 10),<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;TEXT_ONLY&#39;<br>              });<br>            }<br>          }<br>        });<br><br>        return blocks;<br>      },<br><br>      autoMapBlocksToMainPage(mainPage) {<br>        if (!mainPage || !mainPage.receipt) return { autoAccepted: 0, reviewNeeded: 0 };<br>        const blocks = (mainPage.receipt.ocrBlocks || []).filter(b =&gt; b.detectedAmount !== &#39;&#39;);<br>        const fees = mainPage.fees || [];<br>        let autoAccepted = 0;<br>        let reviewNeeded = 0;<br><br>        const usedBlockIds = new Set();<br><br>        fees.forEach((fee, feeIdx) =&gt; {<br>          const expNameNorm = ValidationEngine.normalizeText(fee.expectedName);<br>          const expCodeNorm = String(fee.expectedCode || &#39;&#39;).trim().toUpperCase();<br><br>          let bestBlock = null;<br>          let bestScore = 0;<br><br>          blocks.forEach(blk =&gt; {<br>            if (usedBlockIds.has(blk.id)) return;<br>            let score = 0;<br>            const blkNameNorm = ValidationEngine.normalizeText(blk.detectedName);<br>            const blkCodeNorm = String(blk.detectedCode || &#39;&#39;).trim().toUpperCase();<br><br>            if (expNameNorm &amp;&amp; blkNameNorm === expNameNorm) score += 50;<br>            else if (expNameNorm &amp;&amp; (blkNameNorm.includes(expNameNorm) || expNameNorm.includes(blkNameNorm))) score += 30;<br><br>            if (expCodeNorm &amp;&amp; blkCodeNorm === expCodeNorm) score += 40;<br>            if (blocks.indexOf(blk) === feeIdx) score += 15;<br><br>            if (score &gt; bestScore) {<br>              bestScore = score;<br>              bestBlock = blk;<br>            }<br>          });<br><br>          if (bestBlock &amp;&amp; bestScore &gt;= 30) {<br>            usedBlockIds.add(bestBlock.id);<br>            fee.actualName = bestBlock.detectedName;<br>            fee.actualAmount = bestBlock.detectedAmount;<br>            fee.actualCode = bestBlock.detectedCode || fee.actualCode;<br>            fee.ocrConfidence = bestBlock.confidence;<br>            fee.sourceLocation = `Page ${bestBlock.page} (Y:${Math.round(bestBlock.bbox.y)}%)`;<br>            bestBlock.mappedToFeeId = fee.id;<br><br>            if (bestScore &gt;= 65 &amp;&amp; bestBlock.confidence &gt;= appState.settings.autoAcceptConfidenceThreshold) {<br>              bestBlock.status = &#39;AUTO_ACCEPTED&#39;;<br>              autoAccepted++;<br>            } else {<br>              bestBlock.status = &#39;REVIEW&#39;;<br>              reviewNeeded++;<br>            }<br>          }<br>        });<br><br>        RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(mainPage);<br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { autoAccepted, reviewNeeded };<br>      },<br><br>      async preprocessImageCanvas(imageDataUrl, opts = {}) {<br>        return new Promise((resolve) =&gt; {<br>          const img = new Image();<br>          img.onload = () =&gt; {<br>            try {<br>              const scale = opts.scale || 1.5;<br>              const canvas = document.createElement(&#39;canvas&#39;);<br>              canvas.width = Math.max(1, Math.round((img.naturalWidth || img.width || 400) * scale));<br>              canvas.height = Math.max(1, Math.round((img.naturalHeight || img.height || 400) * scale));<br>              const ctx = canvas.getContext(&#39;2d&#39;);<br>              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>              if (opts.grayscale || opts.contrast || opts.sharpen) {<br>                const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);<br>                const d = imgData.data;<br>                const contrastFactor = opts.contrast ? 1.35 : 1.0;<br>                for (let i = 0; i &lt; d.length; i += 4) {<br>                  let r = d[i], g = d[i + 1], b = d[i + 2];<br>                  if (opts.grayscale) {<br>                    const gray = 0.299 * r + 0.587 * g + 0.114 * b;<br>                    r = g = b = gray;<br>                  }<br>                  if (opts.contrast) {<br>                    r = Math.min(255, Math.max(0, (r - 128) * contrastFactor + 128));<br>                    g = Math.min(255, Math.max(0, (g - 128) * contrastFactor + 128));<br>                    b = Math.min(255, Math.max(0, (b - 128) * contrastFactor + 128));<br>                  }<br>                  d[i] = r; d[i + 1] = g; d[i + 2] = b;<br>                }<br>                ctx.putImageData(imgData, 0, 0);<br>              }<br>              resolve(canvas.toDataURL(&#39;image/png&#39;));<br>            } catch (canvasErr) {<br>              console.warn(&#39;Preprocessing canvas fallback:&#39;, canvasErr);<br>              resolve(imageDataUrl);<br>            }<br>          };<br>          img.onerror = () =&gt; resolve(imageDataUrl);<br>          img.src = imageDataUrl;<br>        });<br>      },<br><br>      async runRealTesseractOCR(imageDataUrl, onProgress) {<br>        if (!window.Tesseract) {<br>          throw new Error(&#39;Tesseract.js library is unavailable offline.&#39;);<br>        }<br>        const worker = await Tesseract.createWorker(&#39;eng&#39;, 1, {<br>          logger: m =&gt; {<br>            if (onProgress &amp;&amp; m.status === &#39;recognizing text&#39;) {<br>              onProgress(Math.round((m.progress || 0) * 100));<br>            }<br>          }<br>        });<br>        try {<br>          const ret = await worker.recognize(imageDataUrl);<br>          return {<br>            text: ret.data.text || &#39;&#39;,<br>            confidence: Math.round(ret.data.confidence || 85)<br>          };<br>        } finally {<br>          await worker.terminate();<br>        }<br>      }<br>    };<br><br>    /****************************************************************************<br>     * SAMPLE DATA &amp; SVG RECEIPT GENERATOR (100% SELF-CONTAINED)<br>     ****************************************************************************/<br>    function generateSyntheticReceiptSvgDataUrl({ title, invoiceNo, date, lines, footer }) {<br>      const lineRows = lines.map((l, idx) =&gt; {<br>        const y = 135 + idx * 32;<br>        return `<br>          &lt;text x=&quot;28&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; fill=&quot;#1e293b&quot;&gt;${escapeHtml(l.label)}&lt;/text&gt;<br>          &lt;text x=&quot;315&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(l.amount)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;13&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#4f46e5&quot;&gt;${escapeHtml(l.code)}&lt;/text&gt;<br>        `;<br>      }).join(&#39;&#39;);<br><br>      const svg = `<br>        &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;400&quot; height=&quot;420&quot; viewBox=&quot;0 0 400 420&quot;&gt;<br>          &lt;rect width=&quot;400&quot; height=&quot;420&quot; fill=&quot;#ffffff&quot; rx=&quot;8&quot;/&gt;<br>          &lt;rect x=&quot;12&quot; y=&quot;12&quot; width=&quot;376&quot; height=&quot;396&quot; fill=&quot;none&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1.5&quot; stroke-dasharray=&quot;4 3&quot; rx=&quot;6&quot;/&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;45&quot; font-family=&quot;sans-serif&quot; font-size=&quot;16&quot; font-weight=&quot;800&quot; text-anchor=&quot;middle&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(title)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;66&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;middle&quot; fill=&quot;#64748b&quot;&gt;OFFICIAL EIS ELECTRONIC RECEIPT&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;80&quot; x2=&quot;376&quot; y2=&quot;80&quot; stroke=&quot;#94a3b8&quot; stroke-width=&quot;1&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; fill=&quot;#334155&quot;&gt;REF: ${escapeHtml(invoiceNo)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;end&quot; fill=&quot;#334155&quot;&gt;${escapeHtml(date)}&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;112&quot; x2=&quot;376&quot; y2=&quot;112&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1&quot;/&gt;<br>          ${lineRows}<br>          &lt;line x1=&quot;24&quot; y1=&quot;315&quot; x2=&quot;376&quot; y2=&quot;315&quot; stroke=&quot;#0f172a&quot; stroke-width=&quot;1.5&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(footer.label)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;15&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#059669&quot;&gt;${escapeHtml(footer.value)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;385&quot; font-family=&quot;monospace&quot; font-size=&quot;10&quot; text-anchor=&quot;middle&quot; fill=&quot;#94a3b8&quot;&gt;EIS-AUTH-HASH: 9F82-77C1-SMART-QA&lt;/text&gt;<br>        &lt;/svg&gt;<br>      `;<br>      return &#39;data:image/svg+xml;charset=utf-8,&#39; + encodeURIComponent(svg);<br>    }<br><br><br>    /****************************************************************************<br>     * SHARED HEADERS: one set of Configurable Field / Column Names for all Main Pages<br>     * proj.sharedHeaders (toggle) + proj.sharedSchema [{number,name,dataType,required}]<br>     * Values (Expected / Found on Receipt) always stay per page.<br>     ****************************************************************************/<br>    function buildFieldStub(num, entry) {<br>      return {<br>        id: `fld_${num}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,<br>        number: num,<br>        name: entry ? entry.name : `Custom Field ${num}`,<br>        expectedValue: &#39;&#39;, actualValue: &#39;&#39;,<br>        dataType: entry ? entry.dataType : &#39;Dynamic&#39;,<br>        validationRule: &#39;Exact / Tolerance Match&#39;,<br>        ocrEnabled: true,<br>        required: entry ? Boolean(entry.required) : false,<br>        tolerance: 0.01,<br>        description: `Dynamic Column #${num}`,<br>        pageOverride: false,<br>        enabled: false<br>      };<br>    }<br><br>    // Copy the shared headers onto one page (rename/type/required only, never values)<br>    function applySharedSchemaToPage(proj, page) {<br>      if (!proj || !page || !proj.sharedHeaders || !Array.isArray(proj.sharedSchema)) return;<br>      page.fields = page.fields || [];<br>      proj.sharedSchema.forEach((entry, i) =&gt; {<br>        const num = i + 1;<br>        let f = page.fields[i];<br>        if (!f) { f = buildFieldStub(num, entry); page.fields.push(f); }<br>        f.name = entry.name;<br>        f.dataType = entry.dataType;<br>        f.required = Boolean(entry.required);<br>      });<br>    }<br><br>    // Make `sourcePage` the master: merge its headers into the schema, then push to all pages<br>    function pushSharedHeadersFrom(sourcePage) {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.sharedHeaders || !sourcePage) return;<br>      const old = Array.isArray(proj.sharedSchema) ? proj.sharedSchema : [];<br>      const len = Math.max(old.length, (sourcePage.fields || []).length);<br>      const next = [];<br>      for (let i = 0; i &lt; len; i++) {<br>        const f = (sourcePage.fields || [])[i];<br>        next.push(f<br>          ? { number: i + 1, name: f.name, dataType: f.dataType, required: Boolean(f.required) }<br>          : old[i]);<br>      }<br>      proj.sharedSchema = next;<br>      (proj.mainPages || []).forEach(p =&gt; {<br>        if (p.id === sourcePage.id) return;<br>        applySharedSchemaToPage(proj, p);<br>        ValidationEngine.validateMainPage(p);<br>      });<br>    }<br><br>    function toggleSharedHeaders(checked) {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      if (!checked) {<br>        proj.sharedHeaders = false;<br>        scheduleAutosave(&#39;Turned off shared headers&#39;);<br>        showToast(&#39;Shared headers OFF. Each Main Page now keeps its own copy of the headers.&#39;, &#39;info&#39;);<br>        return renderApp();<br>      }<br>      if (proj.mainPages.length &lt;= 1) {<br>        proj.sharedHeaders = true;<br>        proj.sharedSchema = [];<br>        pushSharedHeadersFrom(page);<br>        scheduleAutosave(&#39;Turned on shared headers&#39;);<br>        showToast(&#39;Shared headers ON. Every new Main Page will use these headers.&#39;, &#39;success&#39;);<br>        return renderApp();<br>      }<br>      openModal({<br>        title: &#39;Use the same headers on every Main Page?&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;p&gt;The Configurable Field / Column Names, Type and Req of &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; become the default for &lt;strong&gt;all ${proj.mainPages.length} Main Pages&lt;/strong&gt; and for every new Main Page you add.&lt;/p&gt;<br>            &lt;ul class=&quot;list-disc pl-5 space-y-1 text-slate-500 dark:text-slate-400&quot;&gt;<br>              &lt;li&gt;Headers on the other pages are overwritten with this page&#39;s headers.&lt;/li&gt;<br>              &lt;li&gt;Expected Values, Found on Receipt values, fees, receipts and evidence are &lt;strong&gt;not touched&lt;/strong&gt;.&lt;/li&gt;<br>              &lt;li&gt;From now on, renaming a header on any page updates all pages.&lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/div&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmSharedHeadersOn()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Apply to all pages&lt;/button&gt;`<br>      });<br>    }<br><br>    function confirmSharedHeadersOn() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      proj.sharedHeaders = true;<br>      proj.sharedSchema = [];<br>      pushSharedHeadersFrom(page);<br>      closeModal();<br>      logActivity(&#39;Shared Headers&#39;, `Applied headers of ${page.name} to ${proj.mainPages.length} Main Pages`);<br>      scheduleAutosave(&#39;Turned on shared headers&#39;);<br>      showToast(`Headers of ${page.name} applied to all ${proj.mainPages.length} Main Pages.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function reapplySharedHeaders() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      pushSharedHeadersFrom(page);<br>      scheduleAutosave(&#39;Re-applied shared headers&#39;);<br>      showToast(`Headers of ${page.name} re-applied to all Main Pages.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function createDefaultFields(count = 50) {<br>      const presets = [<br>        { name: &#39;Invoice / Receipt Number&#39;, type: &#39;Reference&#39;, req: true },<br>        { name: &#39;Transaction Date&#39;, type: &#39;Date&#39;, req: true },<br>        { name: &#39;Merchant / Taxpayer TIN&#39;, type: &#39;Reference&#39;, req: false },<br>        { name: &#39;Currency Code&#39;, type: &#39;Code&#39;, req: true },<br>        { name: &#39;Gross Settlement Total&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;CWT Withholding Amount&#39;, type: &#39;Currency&#39;, req: false },<br>        { name: &#39;Net Payable Amount&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;EIS Acknowledgement ID&#39;, type: &#39;Reference&#39;, req: false }<br>      ];<br>      const list = [];<br>      for (let i = 1; i &lt;= count; i++) {<br>        const p = presets[i - 1];<br>        list.push({<br>          id: `fld_${i}_${Math.random().toString(36).slice(2, 6)}`,<br>          number: i,<br>          name: p ? p.name : `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: p ? p.type : &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: p ? p.req : false,<br>          tolerance: 0.01,<br>          description: p ? `Standard EIS ${p.name}` : `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: i &lt;= 8<br>        });<br>      }<br>      return list;<br>    }<br><br>    function createSampleSeedState() {<br>      const now = new Date().toISOString();<br><br>      // Page 1: PASS (Fee 1 = 1000/NC, Fee 2 = 250/IC, CWT = -50 -&gt; Gross 1250, CWT 50, Net 1200)<br>      const p1ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;MANILA LOGISTICS &amp; FREIGHT CORP.&#39;,<br>        invoiceNo: &#39;EIS-2026-1001&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Fee 1 Charge&#39;, amount: &#39;1,000.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Fee 2 Charge&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;-50.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,200.00&#39; }<br>      });<br><br>      const p1RawText = `Fee 1 Charge | 1000.00 | NC\nFee 2 Charge | 250.00 | IC\nCWT | -50.00 | CWT`;<br>      const page1 = {<br>        id: &#39;mp_manila_01&#39;,<br>        name: &#39;MP-01: Manila HQ Settlement&#39;,<br>        description: &#39;Standard two-fee transaction with negative CWT notation (-50).&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;EIS-2026-1001\t2026-11-19\t004-892-110-000\tPHP\t1250.00\t50.00\t1200.00&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_01&#39;,<br>          fileName: &#39;manila_eis_receipt_1001.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p1ReceiptImg],<br>          ocrRawText: p1RawText,<br>          ocrConfidence: 96,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p1RawText, 1, 96),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_1a&#39;, expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1 Charge&#39;, actualAmount: &#39;1000.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 97, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_1b&#39;, expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 2 Charge&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 95, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_1c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;-50&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;-50.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 96, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_1&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#10b981&#39;, label: &#39;QA-1: Fee 1 Verified&#39;, comment: &#39;Matches 1000.00 NC&#39;, fieldRef: &#39;Fee 1 Charge&#39;, testCaseId: &#39;TC-001&#39;, defectId: &#39;&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page1.fields[0].expectedValue = &#39;EIS-2026-1001&#39;; page1.fields[0].actualValue = &#39;EIS-2026-1001&#39;;<br>      page1.fields[1].expectedValue = &#39;2026-11-19&#39;; page1.fields[1].actualValue = &#39;2026-11-19&#39;;<br>      page1.fields[2].expectedValue = &#39;004-892-110-000&#39;; page1.fields[2].actualValue = &#39;004-892-110-000&#39;;<br>      page1.fields[3].expectedValue = &#39;PHP&#39;; page1.fields[3].actualValue = &#39;PHP&#39;;<br>      page1.fields[4].expectedValue = &#39;1250.00&#39;; page1.fields[4].actualValue = &#39;1250.00&#39;;<br>      page1.fields[5].expectedValue = &#39;50.00&#39;; page1.fields[5].actualValue = &#39;50.00&#39;;<br>      page1.fields[6].expectedValue = &#39;1200.00&#39;; page1.fields[6].actualValue = &#39;1200.00&#39;;<br><br>      // Page 2: FAIL (Fee 1 Expected 1000 vs Receipt 1200 -&gt; Diff +200, CWT = (50))<br>      const p2ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;CEBU PORT TERMINAL SERVICES&#39;,<br>        invoiceNo: &#39;EIS-2026-2044&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Terminal Handling&#39;, amount: &#39;1,200.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Documentation Fee&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;(50.00)&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,400.00&#39; }<br>      });<br>      const p2RawText = `Terminal Handling | 1200.00 | NC\nDocumentation Fee | 250.00 | IC\nCWT | (50.00) | CWT`;<br>      const page2 = {<br>        id: &#39;mp_cebu_02&#39;,<br>        name: &#39;MP-02: Cebu Hub Clearance&#39;,<br>        description: &#39;Demonstrates Fee 1 amount mismatch (Expected 1000 vs Receipt 1200) &amp; parenthetical CWT (50).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_02&#39;,<br>          fileName: &#39;cebu_eis_receipt_2044.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p2ReceiptImg],<br>          ocrRawText: p2RawText,<br>          ocrConfidence: 93,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p2RawText, 1, 93),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_2a&#39;, expectedName: &#39;Terminal Handling&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Terminal Handling&#39;, actualAmount: &#39;1200.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 94, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_2b&#39;, expectedName: &#39;Documentation Fee&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Documentation Fee&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 93, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_2c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;(50)&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;(50.00)&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 92, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_2&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#ef4444&#39;, label: &#39;QA-1: Overcharge +200&#39;, comment: &#39;Expected 1000.00, Receipt shows 1200.00&#39;, fieldRef: &#39;Terminal Handling&#39;, testCaseId: &#39;TC-002&#39;, defectId: &#39;DEF-101&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page2.fields[0].expectedValue = &#39;EIS-2026-2044&#39;; page2.fields[0].actualValue = &#39;EIS-2026-2044&#39;;<br>      page2.fields[3].expectedValue = &#39;PHP&#39;; page2.fields[3].actualValue = &#39;PHP&#39;;<br><br>      // Page 3: PENDING (Missing Fee Code on Inspection Fee -&gt; verifies missing info never auto-passes)<br>      const p3ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;DAVAO AGRI-EXPORT GATEWAY&#39;,<br>        invoiceNo: &#39;EIS-2026-3099&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Export Inspection&#39;, amount: &#39;800.00&#39;, code: &#39;&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;40.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 760.00&#39; }<br>      });<br>      const p3RawText = `Export Inspection | 800.00\nCWT | 40.00 | CWT`;<br>      const page3 = {<br>        id: &#39;mp_davao_03&#39;,<br>        name: &#39;MP-03: Davao Branch Export&#39;,<br>        description: &#39;Demonstrates missing required fee code evaluation (PENDING rather than false PASS).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_03&#39;,<br>          fileName: &#39;davao_eis_receipt_3099.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p3ReceiptImg],<br>          ocrRawText: p3RawText,<br>          ocrConfidence: 89,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p3RawText, 1, 89),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_3a&#39;, expectedName: &#39;Export Inspection&#39;, expectedAmount: &#39;800&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Export Inspection&#39;, actualAmount: &#39;800.00&#39;, actualCode: &#39;&#39;, isCwt: false, ocrConfidence: 89, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_3b&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;40&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;40.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 91, sourceLocation: &#39;Page 1 Row 2&#39; }<br>        ],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      page3.fields[0].expectedValue = &#39;EIS-2026-3099&#39;; page3.fields[0].actualValue = &#39;EIS-2026-3099&#39;;<br><br>      [page1, page2, page3].forEach(p =&gt; ValidationEngine.validateMainPage(p, true));<br><br>      const sampleProject = {<br>        id: &#39;proj_eis_2026_q4&#39;,<br>        name: &#39;EIS Q4 Release — Core Settlement &amp; CWT Audit&#39;,<br>        reference: &#39;PRJ-EIS-2026-04&#39;,<br>        description: &#39;End-to-end EIS electronic receipt validation, CWT deduction accuracy, and QA screenshot evidence suite.&#39;,<br>        owner: &#39;Jansen B. (Lead QA Analyst)&#39;,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [page1, page2, page3],<br>        screenshots: [<br>          {<br>            id: &#39;scr_01&#39;,<br>            name: &#39;EIS_Portal_Manila_Settlement.svg&#39;,<br>            dataUrl: p1ReceiptImg,<br>            capturedAt: now,<br>            source: &#39;Sample Evidence&#39;,<br>            isMerged: false<br>          }<br>        ],<br>        mergeHistory: [],<br>        testCases: [<br>          {<br>            id: &#39;TC-001&#39;,<br>            title: &#39;Verify Standard 2-Fee Gross &amp; Negative CWT (-50) Net Settlement&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Manila HQ Settlement Main Page configured with Fee 1 (1000/NC), Fee 2 (250/IC), CWT (-50).&#39;,<br>            steps: &#39;1. Upload official EIS receipt.\n2. Run OCR extraction &amp; auto-mapping.\n3. Verify Gross = 1250.00, CWT = 50.00, Net = 1200.00.&#39;,<br>            expectedResult: &#39;All fee names, amounts, and codes PASS; Net Total equals 1200.00.&#39;,<br>            actualResult: &#39;Gross 1250.00 - CWT 50.00 = Net 1200.00. Status: PASS.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_manila_01&#39;,<br>            linkedDefectId: &#39;&#39;<br>          },<br>          {<br>            id: &#39;TC-002&#39;,<br>            title: &#39;Detect Fee 1 Overcharge Mismatch &amp; Parenthetical CWT (50)&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Cebu Hub Main Page expects Terminal Handling = 1000.00 NC.&#39;,<br>            steps: &#39;1. Attach Cebu receipt showing 1200.00 NC.\n2. Execute validation engine.&#39;,<br>            expectedResult: &#39;System flags FAIL with +200.00 difference while deducting 50.00 for (50) CWT.&#39;,<br>            actualResult: &#39;Flagged FAIL (+200.00 variance). Defect DEF-101 logged.&#39;,<br>            status: &#39;FAIL&#39;,<br>            priority: &#39;Critical&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            linkedDefectId: &#39;DEF-101&#39;<br>          },<br>          {<br>            id: &#39;TC-003&#39;,<br>            title: &#39;Verify Missing Fee Code Triggers PENDING Instead of False PASS&#39;,<br>            module: &#39;Validation Rules&#39;,<br>            preconditions: &#39;Davao Branch receipt omits IC fee code on Export Inspection.&#39;,<br>            steps: &#39;1. Validate Davao Branch Main Page.&#39;,<br>            expectedResult: &#39;Status evaluates to PENDING until code is verified.&#39;,<br>            actualResult: &#39;Evaluated as PENDING as expected.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_davao_03&#39;,<br>            linkedDefectId: &#39;&#39;<br>          }<br>        ],<br>        defects: [<br>          {<br>            id: &#39;DEF-101&#39;,<br>            title: &#39;Terminal Handling Fee billed at 1,200.00 instead of contracted 1,000.00 (+200.00 variance)&#39;,<br>            description: &#39;EIS receipt #EIS-2026-2044 reflects 1,200.00 NC for Terminal Handling, exceeding Main Page expected tariff by 200.00.&#39;,<br>            stepsToReproduce: &#39;1. Open MP-02: Cebu Hub Clearance.\n2. Compare Fee 1 expected (1000.00 NC) against uploaded receipt.\n3. Observe +200.00 variance.&#39;,<br>            expectedResult: &#39;Terminal Handling = 1,000.00 NC; Net Payable = 1,200.00&#39;,<br>            actualResult: &#39;Terminal Handling = 1,200.00 NC; Net Payable = 1,400.00&#39;,<br>            severity: &#39;High&#39;,<br>            priority: &#39;P1&#39;,<br>            status: &#39;Open&#39;,<br>            environment: &#39;EIS Staging v4.12&#39;,<br>            linkedTestCaseId: &#39;TC-002&#39;,<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            annotationRef: &#39;QA-1: Overcharge +200&#39;,<br>            dateReported: now.slice(0, 10),<br>            assignee: &#39;M. Santos (Billing Dev)&#39;<br>          }<br>        ],<br>        activityLog: [<br>          { timestamp: now, action: &#39;Initialized Workspace&#39;, detail: &#39;Loaded sample project PRJ-EIS-2026-04 with 3 isolated Main Pages.&#39; }<br>        ]<br>      };<br><br>      const defaultTemplates = [<br>        {<br>          id: &#39;tpl_standard_cwt&#39;,<br>          name: &#39;Standard 2-Fee + CWT Settlement&#39;,<br>          description: &#39;Includes Fee 1 (NC), Fee 2 (IC), and CWT deduction rule.&#39;,<br>          fees: [<br>            { expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, isCwt: false },<br>            { expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;50&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        },<br>        {<br>          id: &#39;tpl_brokerage_3fee&#39;,<br>          name: &#39;Customs Brokerage 3-Fee + 2% CWT&#39;,<br>          description: &#39;Brokerage, Arrastre, Wharfage, and Withholding Tax.&#39;,<br>          fees: [<br>            { expectedName: &#39;Brokerage Fee&#39;, expectedAmount: &#39;2500&#39;, expectedCode: &#39;BRK&#39;, isCwt: false },<br>            { expectedName: &#39;Arrastre Charge&#39;, expectedAmount: &#39;850&#39;, expectedCode: &#39;ARR&#39;, isCwt: false },<br>            { expectedName: &#39;Wharfage Fee&#39;, expectedAmount: &#39;400&#39;, expectedCode: &#39;WHF&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;75&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        }<br>      ];<br><br>      return {<br>        schemaVersion: APP_SCHEMA_VERSION,<br>        theme: &#39;dark&#39;,<br>        sidebarCollapsed: false,<br>        activeModule: &#39;dashboard&#39;,<br>        activeProjectId: sampleProject.id,<br>        activeMainPageId: page1.id,<br>        lastSavedAt: now,<br>        settings: {<br>          numericTolerance: 0.01,<br>          caseSensitiveNames: false,<br>          normalizeWhitespace: true,<br>          autoAcceptConfidenceThreshold: 88,<br>          cwtDeductionMode: &#39;absolute&#39;,<br>          qaLabelMax: 200,<br>          qaAutoIncrement: true<br>        },<br>        templates: defaultTemplates,<br>        projects: [sampleProject],<br>        ui: {<br>          viewerZoom: 1,<br>          viewerRotation: 0,<br>          showOcrBoxes: true,<br>          selectedComparisonRowId: null,<br>          selectedScreenshotsForMerge: [],<br>          annotationTool: &#39;rect&#39;,<br>          annotationColor: &#39;#ef4444&#39;,<br>          selectedAnnotationId: null,<br>          selectedQaLabel: 1,<br>          mainPageQuickListOpen: false,<br>          selectedMainPageIds: []<br>        }<br>      };<br>    }<br><br>    /****************************************************************************<br>     * STATE HELPERS &amp; NAVIGATION<br>     ****************************************************************************/<br>    function getActiveProject() {<br>      return appState.projects.find(p =&gt; p.id === appState.activeProjectId) || appState.projects[0] || null;<br>    }<br><br>    function getActiveMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.mainPages || proj.mainPages.length === 0) return null;<br>      return proj.mainPages.find(mp =&gt; mp.id === appState.activeMainPageId) || proj.mainPages[0];<br>    }<br><br>    function logActivity(action, detail) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.activityLog = proj.activityLog || [];<br>      proj.activityLog.unshift({ timestamp: new Date().toISOString(), action, detail });<br>      if (proj.activityLog.length &gt; 40) proj.activityLog.pop();<br>    }<br><br>    function navigateTo(moduleId) {<br>      appState.activeModule = moduleId;<br>      closeMobileSidebar();<br>      renderApp();<br>    }<br><br>    function switchActiveProject(projectId) {<br>      appState.activeProjectId = projectId;<br>      const proj = getActiveProject();<br>      appState.activeMainPageId = proj &amp;&amp; proj.mainPages[0] ? proj.mainPages[0].id : null;<br>      scheduleAutosave(&#39;Switched active project&#39;);<br>      renderApp();<br>    }<br><br>    function switchActiveMainPage(pageId) {<br>      appState.activeMainPageId = pageId;<br>      appState.ui.evPendingLabel = null;<br>      appState.ui.evSelectedAnnId = null;<br>      appState.ui.selectedComparisonRowId = null;<br>      appState.ui.selectedAnnotationId = null;<br>      scheduleAutosave(&#39;Switched Main Page&#39;);<br>      renderApp();<br>    }<br><br>    function toggleTheme() {<br>      appState.theme = appState.theme === &#39;dark&#39; ? &#39;light&#39; : &#39;dark&#39;;<br>      applyTheme();<br>      scheduleAutosave(&#39;Theme changed&#39;);<br>    }<br><br>    function applyTheme() {<br>      const html = document.documentElement;<br>      if (appState.theme === &#39;dark&#39;) html.classList.add(&#39;dark&#39;);<br>      else html.classList.remove(&#39;dark&#39;);<br>    }<br><br>    function toggleSidebarCollapse() {<br>      appState.sidebarCollapsed = !appState.sidebarCollapsed;<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const labels = document.querySelectorAll(&#39;.sidebar-label&#39;);<br>      if (appState.sidebarCollapsed) {<br>        sidebar.classList.remove(&#39;lg:w-64&#39;);<br>        sidebar.classList.add(&#39;lg:w-20&#39;);<br>        labels.forEach(el =&gt; el.classList.add(&#39;lg:hidden&#39;));<br>      } else {<br>        sidebar.classList.remove(&#39;lg:w-20&#39;);<br>        sidebar.classList.add(&#39;lg:w-64&#39;);<br>        labels.forEach(el =&gt; el.classList.remove(&#39;lg:hidden&#39;));<br>      }<br>    }<br><br>    function toggleMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      const isOpen = !sidebar.classList.contains(&#39;-translate-x-full&#39;);<br>      if (isOpen) {<br>        closeMobileSidebar();<br>      } else {<br>        sidebar.classList.remove(&#39;-translate-x-full&#39;);<br>        backdrop.classList.remove(&#39;hidden&#39;);<br>      }<br>    }<br><br>    function closeMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      if (sidebar) sidebar.classList.add(&#39;-translate-x-full&#39;);<br>      if (backdrop) backdrop.classList.add(&#39;hidden&#39;);<br>    }<br><br>    function showToast(message, type = &#39;info&#39;) {<br>      const container = document.getElementById(&#39;toast-container&#39;);<br>      if (!container) return;<br>      const colors = {<br>        success: &#39;bg-emerald-600 text-white border-emerald-500&#39;,<br>        error: &#39;bg-rose-600 text-white border-rose-500&#39;,<br>        warning: &#39;bg-amber-500 text-slate-950 border-amber-400&#39;,<br>        info: &#39;bg-slate-800 text-white border-slate-700&#39;<br>      };<br>      const el = document.createElement(&#39;div&#39;);<br>      el.className = `pointer-events-auto px-4 py-3 rounded-xl shadow-xl border text-xs font-medium flex items-center justify-between gap-3 transition-all ${colors[type] || colors.info}`;<br>      el.innerHTML = `&lt;span&gt;${escapeHtml(message)}&lt;/span&gt;&lt;button onclick=&quot;this.parentElement.remove()&quot; class=&quot;opacity-75 hover:opacity-100&quot;&gt;&amp;times;&lt;/button&gt;`;<br>      container.appendChild(el);<br>      setTimeout(() =&gt; { if (el.parentElement) el.remove(); }, 4200);<br>    }<br><br>    function openModal({ title, bodyHtml, footerHtml = &#39;&#39; }) {<br>      document.getElementById(&#39;modal-title&#39;).textContent = title;<br>      document.getElementById(&#39;modal-body&#39;).innerHTML = bodyHtml;<br>      document.getElementById(&#39;modal-footer&#39;).innerHTML = footerHtml;<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.remove(&#39;hidden&#39;);<br>      overlay.classList.add(&#39;flex&#39;);<br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    function closeModal() {<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.add(&#39;hidden&#39;);<br>      overlay.classList.remove(&#39;flex&#39;);<br>    }<br><br>    function statusBadge(status) {<br>      const s = String(status || &#39;PENDING&#39;).toUpperCase();<br>      const styles = {<br>        PASS: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;,<br>        FAIL: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        REVIEW: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        PENDING: &#39;bg-sky-500/15 text-sky-600 dark:text-sky-400 border-sky-500/30&#39;,<br>        &#39;NOT APPLICABLE&#39;: &#39;bg-slate-500/15 text-slate-500 dark:text-slate-400 border-slate-500/30&#39;,<br>        OPEN: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        &#39;IN PROGRESS&#39;: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        FIXED: &#39;bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border-indigo-500/30&#39;,<br>        RETEST: &#39;bg-purple-500/15 text-purple-600 dark:text-purple-400 border-purple-500/30&#39;,<br>        CLOSED: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;<br>      };<br>      return `&lt;span class=&quot;inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide border ${styles[s] || styles.PENDING}&quot;&gt;${escapeHtml(s)}&lt;/span&gt;`;<br>    }<br><br>    function runActivePageValidation(notify = false) {<br>      const mp = getActiveMainPage();<br>      if (!mp) return showToast(&#39;No active Main Page selected.&#39;, &#39;warning&#39;);<br>      const res = ValidationEngine.validateMainPage(mp, true);<br>      logActivity(&#39;Validated Main Page&#39;, `${mp.name} → ${res.overallStatus}`);<br>      scheduleAutosave(&#39;Validated Main Page&#39;);<br>      if (notify) showToast(`${mp.name}: ${res.overallStatus} (${res.counts.pass} Pass, ${res.counts.fail} Fail, ${res.counts.review} Review, ${res.counts.pending} Pending)`, res.overallStatus === &#39;PASS&#39; ? &#39;success&#39; : res.overallStatus === &#39;FAIL&#39; ? &#39;error&#39; : &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * SHELL &amp; NAVIGATION RENDERER<br>     ****************************************************************************/<br>    function renderShellChrome() {<br>      const projSelect = document.getElementById(&#39;sidebar-project-select&#39;);<br>      if (projSelect) {<br>        projSelect.innerHTML = appState.projects.map(p =&gt;<br>          `&lt;option value=&quot;${escapeHtml(p.id)}&quot; ${p.id === appState.activeProjectId ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(p.name)} ${p.archived ? &#39;(Archived)&#39; : &#39;&#39;}&lt;/option&gt;`<br>        ).join(&#39;&#39;);<br>      }<br><br>      const nav = document.getElementById(&#39;sidebar-nav&#39;);<br>      if (nav) {<br>        nav.innerHTML = MODULES.filter(m =&gt; !m.hidden).map(m =&gt; {<br>          const active = appState.activeModule === m.id || (m.id === &#39;validation&#39; &amp;&amp; appState.activeModule === &#39;evidence&#39;);<br>          return `<br>            &lt;button onclick=&quot;navigateTo(&#39;${m.id}&#39;)&quot; class=&quot;w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-xs font-semibold transition ${<br>              active<br>                ? &#39;bg-brand-600 text-white shadow-sm&#39;<br>                : &#39;text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800/80&#39;<br>            }&quot;&gt;<br>              &lt;i data-lucide=&quot;${m.icon}&quot; class=&quot;w-4 h-4 shrink-0&quot;&gt;&lt;/i&gt;<br>              &lt;span class=&quot;sidebar-label truncate&quot;&gt;${escapeHtml(m.label)}&lt;/span&gt;<br>            &lt;/button&gt;<br>          `;<br>        }).join(&#39;&#39;);<br>      }<br><br>      const activeMod = MODULES.find(m =&gt; m.id === appState.activeModule) || MODULES[0];<br>      const topTitle = document.getElementById(&#39;topbar-title&#39;);<br>      const topSub = document.getElementById(&#39;topbar-subtitle&#39;);<br>      if (topTitle) topTitle.textContent = activeMod.label;<br>      if (topSub) topSub.textContent = activeMod.subtitle;<br>    }<br><br>    function renderApp() {<br>      applyTheme();<br>      renderShellChrome();<br>      const viewport = document.getElementById(&#39;main-viewport&#39;);<br>      if (!viewport) return;<br><br>      Object.values(chartInstances).forEach(c =&gt; { try { c.destroy(); } catch (e) {} });<br>      chartInstances = {};<br><br>      switch (appState.activeModule) {<br>        case &#39;dashboard&#39;: viewport.innerHTML = renderDashboardModule(); initDashboardCharts(); break;<br>        case &#39;projects&#39;: viewport.innerHTML = renderProjectsModule(); break;<br>        case &#39;main-pages&#39;: viewport.innerHTML = renderMainPagesModule(); break;<br>        case &#39;validation&#39;: viewport.innerHTML = renderValidationWorkspaceModule(); break;<br>        case &#39;ocr-intel&#39;: viewport.innerHTML = renderOcrIntelligenceModule(); break;<br>        case &#39;screenshots&#39;: viewport.innerHTML = renderScreenshotStudioModule(); initAnnotationCanvasEvents(); break;<br>        case &#39;evidence&#39;: viewport.innerHTML = renderEvidenceModule(); initEvidenceCanvasEvents(); break;<br>        case &#39;test-cases&#39;: viewport.innerHTML = renderTestCasesModule(); break;<br>        case &#39;defects&#39;: viewport.innerHTML = renderDefectsModule(); break;<br>        case &#39;reports&#39;: viewport.innerHTML = renderReportsModule(); break;<br>        case &#39;templates&#39;: viewport.innerHTML = renderTemplatesModule(); break;<br>        case &#39;settings&#39;: viewport.innerHTML = renderSettingsModule(); break;<br>        default: viewport.innerHTML = renderDashboardModule();<br>      }<br><br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1 VIEW: DASHBOARD<br>     ****************************************************************************/<br>    function renderDashboardModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return `&lt;div class=&quot;p-8 text-center&quot;&gt;No project found. Create one in Projects.&lt;/div&gt;`;<br><br>      const totalProjects = appState.projects.length;<br>      const totalMainPages = proj.mainPages.length;<br>      const totalReceipts = proj.mainPages.filter(mp =&gt; mp.receipt).length;<br>      const totalScreenshots = (proj.screenshots || []).length;<br><br>      let passCount = 0, failCount = 0, reviewCount = 0, pendingCount = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        const c = mp.validationSummary.counts;<br>        passCount += c.pass;<br>        failCount += c.fail;<br>        reviewCount += c.review;<br>        pendingCount += c.pending;<br>      });<br>      const totalChecks = passCount + failCount + reviewCount + pendingCount;<br><br>      const totalTC = (proj.testCases || []).length;<br>      const passedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>      const failedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>      const openDefects = (proj.defects || []).filter(d =&gt; d.status !== &#39;Closed&#39; &amp;&amp; d.status !== &#39;Rejected&#39;).length;<br><br>      return `<br>        &lt;div class=&quot;bg-gradient-to-r from-brand-600 via-indigo-600 to-violet-700 rounded-2xl p-6 text-white shadow-lg flex flex-col lg:flex-row lg:items-center justify-between gap-4&quot;&gt;<br>          &lt;div class=&quot;space-y-1&quot;&gt;<br>            &lt;div class=&quot;inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-white/15 text-xs font-semibold&quot;&gt;<br>              &lt;span&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>              &lt;span&gt;•&lt;/span&gt;<br>              &lt;span&gt;${escapeHtml(proj.status)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;h2 class=&quot;text-xl sm:text-2xl font-extrabold tracking-tight&quot;&gt;${escapeHtml(proj.name)}&lt;/h2&gt;<br>            &lt;p class=&quot;text-xs sm:text-sm text-indigo-100 max-w-2xl&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap gap-2.5 shrink-0&quot;&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;validation&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white text-brand-700 font-bold text-xs shadow hover:bg-indigo-50 transition&quot;&gt;<br>              Open Side-by-Side Validator<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white/15 hover:bg-white/25 text-white font-semibold text-xs border border-white/20 transition&quot;&gt;<br>              Configure Main Pages (${totalMainPages})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3.5&quot;&gt;<br>          ${renderKpiCard(&#39;Projects&#39;, totalProjects, &#39;folder-kanban&#39;, &#39;text-brand-500&#39;)}<br>          ${renderKpiCard(&#39;Main Pages&#39;, totalMainPages, &#39;file-spreadsheet&#39;, &#39;text-indigo-500&#39;)}<br>          ${renderKpiCard(&#39;Receipts Attached&#39;, totalReceipts, &#39;receipt&#39;, &#39;text-emerald-500&#39;)}<br>          ${renderKpiCard(&#39;QA Screenshots&#39;, totalScreenshots, &#39;camera&#39;, &#39;text-violet-500&#39;)}<br>          ${renderKpiCard(&#39;Test Cases Passed&#39;, `${passedTC}/${totalTC}`, &#39;check-square&#39;, &#39;text-sky-500&#39;)}<br>          ${renderKpiCard(&#39;Open Defects&#39;, openDefects, &#39;bug&#39;, &#39;text-rose-500&#39;)}<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 lg:grid-cols-5 gap-3.5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;Total Checks&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold mt-1&quot;&gt;${totalChecks}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-emerald-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-emerald-600 dark:text-emerald-400 font-semibold&quot;&gt;PASS&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-emerald-600 dark:text-emerald-400 mt-1&quot;&gt;${passCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-rose-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-rose-600 dark:text-rose-400 font-semibold&quot;&gt;FAIL&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-rose-600 dark:text-rose-400 mt-1&quot;&gt;${failCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-amber-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-amber-600 dark:text-amber-400 font-semibold&quot;&gt;REVIEW&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-amber-600 dark:text-amber-400 mt-1&quot;&gt;${reviewCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-sky-500/30 rounded-2xl p-4 col-span-2 lg:col-span-1&quot;&gt;<br>            &lt;div class=&quot;text-xs text-sky-600 dark:text-sky-400 font-semibold&quot;&gt;PENDING&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-sky-600 dark:text-sky-400 mt-1&quot;&gt;${pendingCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Validation Status Distribution&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-validation-dist&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Main Page Net Totals (Expected vs Actual)&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-page-financials&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;QA Execution &amp; Defects&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-qa-health&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 overflow-x-auto&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between mb-4&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Main Pages Validation Matrix&lt;/h3&gt;<br>              &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;text-xs font-semibold text-brand-500 hover:underline&quot;&gt;+ Add Main Page&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Gross&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;CWT&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Net Actual&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; {<br>                  const fin = mp.validationSummary.financials;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-semibold&quot;&gt;${escapeHtml(mp.name)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;&lt;span class=&quot;text-amber-500&quot;&gt;None&lt;/span&gt;&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono font-bold&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(mp.validationSummary.overallStatus)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right&quot;&gt;<br>                        &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;); navigateTo(&#39;validation&#39;);&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 hover:bg-brand-500/20 font-semibold&quot;&gt;Inspect&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-4&quot;&gt;Recent Audit Activity&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-3 max-h-72 overflow-y-auto pr-1&quot;&gt;<br>              ${(proj.activityLog || []).slice(0, 12).map(item =&gt; `<br>                &lt;div class=&quot;flex items-start gap-2.5 text-xs border-b border-slate-100 dark:border-slate-800/60 pb-2.5&quot;&gt;<br>                  &lt;span class=&quot;w-2 h-2 rounded-full bg-brand-500 mt-1.5 shrink-0&quot;&gt;&lt;/span&gt;<br>                  &lt;div class=&quot;min-w-0 flex-1&quot;&gt;<br>                    &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(item.action)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 truncate&quot;&gt;${escapeHtml(item.detail)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-[10px] text-slate-400 mt-0.5&quot;&gt;${new Date(item.timestamp).toLocaleString()}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderKpiCard(label, value, icon, colorClass) {<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex items-center justify-between&quot;&gt;<br>          &lt;div&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;${escapeHtml(label)}&lt;/div&gt;<br>            &lt;div class=&quot;text-xl font-extrabold mt-1&quot;&gt;${escapeHtml(value)}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;w-10 h-10 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center ${colorClass}&quot;&gt;<br>            &lt;i data-lucide=&quot;${icon}&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initDashboardCharts() {<br>      const proj = getActiveProject();<br>      if (!proj || !window.Chart) return;<br><br>      let pass = 0, fail = 0, review = 0, pending = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        pass += mp.validationSummary.counts.pass;<br>        fail += mp.validationSummary.counts.fail;<br>        review += mp.validationSummary.counts.review;<br>        pending += mp.validationSummary.counts.pending;<br>      });<br><br>      const ctx1 = document.getElementById(&#39;chart-validation-dist&#39;);<br>      if (ctx1) {<br>        chartInstances.dist = new Chart(ctx1, {<br>          type: &#39;doughnut&#39;,<br>          data: {<br>            labels: [&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;],<br>            datasets: [{<br>              data: [pass, fail, review, pending],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f59e0b&#39;, &#39;#0ea5e9&#39;],<br>              borderWidth: 0<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: &#39;bottom&#39;, labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx2 = document.getElementById(&#39;chart-page-financials&#39;);<br>      if (ctx2) {<br>        chartInstances.fin = new Chart(ctx2, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: proj.mainPages.map(p =&gt; p.name.split(&#39;:&#39;)[0]),<br>            datasets: [<br>              { label: &#39;Expected Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.expectedNet), backgroundColor: &#39;#6366f1&#39;, borderRadius: 6 },<br>              { label: &#39;Actual Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.actualNet), backgroundColor: &#39;#10b981&#39;, borderRadius: 6 }<br>            ]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39; } } }, plugins: { legend: { labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx3 = document.getElementById(&#39;chart-qa-health&#39;);<br>      if (ctx3) {<br>        const tcPass = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>        const tcFail = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>        const defOpen = (proj.defects || []).filter(d =&gt; d.status === &#39;Open&#39;).length;<br>        const defClosed = (proj.defects || []).filter(d =&gt; d.status === &#39;Closed&#39;).length;<br>        chartInstances.qa = new Chart(ctx3, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: [&#39;TC Pass&#39;, &#39;TC Fail&#39;, &#39;Open Defects&#39;, &#39;Closed Defects&#39;],<br>            datasets: [{<br>              label: &#39;Count&#39;,<br>              data: [tcPass, tcFail, defOpen, defClosed],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f97316&#39;, &#39;#64748b&#39;],<br>              borderRadius: 6<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39;, stepSize: 1 } } } }<br>        });<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2 VIEW: PROJECT MANAGEMENT<br>     ****************************************************************************/<br>    let projectSearchQuery = &#39;&#39;;<br><br>    function renderProjectsModule() {<br>      const filtered = appState.projects.filter(p =&gt;<br>        p.name.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.reference.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.owner.toLowerCase().includes(projectSearchQuery.toLowerCase())<br>      );<br><br>      return `<br>        &lt;div class=&quot;flex flex-col sm:flex-row sm:items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;relative flex-1 max-w-md&quot;&gt;<br>            &lt;i data-lucide=&quot;search&quot; class=&quot;w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(projectSearchQuery)}&quot; oninput=&quot;projectSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search projects by name, reference, or owner...&quot; class=&quot;w-full pl-10 pr-4 py-2.5 rounded-xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-xl text-xs font-semibold bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Import Project JSON&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.json&quot; onchange=&quot;importProjectJson(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;openCreateProjectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Project&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5&quot;&gt;<br>          ${filtered.map(proj =&gt; {<br>            const isActive = proj.id === appState.activeProjectId;<br>            return `<br>              &lt;div class=&quot;bg-white dark:bg-slate-900 border ${isActive ? &#39;border-brand-500 ring-2 ring-brand-500/20&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 flex flex-col justify-between gap-4&quot;&gt;<br>                &lt;div class=&quot;space-y-2.5&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] px-2.5 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>                    &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                      ${isActive ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-brand-500/15 text-brand-500&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      ${proj.archived ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/15 text-amber-500&quot;&gt;ARCHIVED&lt;/span&gt;&#39; : &#39;&#39;}<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;h3 class=&quot;font-bold text-base leading-snug&quot;&gt;${escapeHtml(proj.name)}&lt;/h3&gt;<br>                  &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400 line-clamp-2&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>                  &lt;div class=&quot;grid grid-cols-3 gap-2 pt-2 text-center&quot;&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${proj.mainPages.length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Main Pages&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.testCases || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Test Cases&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.defects || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Defects&lt;/div&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;text-[11px] text-slate-400 pt-1&quot;&gt;<br>                    Owner: &lt;span class=&quot;text-slate-600 dark:text-slate-300 font-medium&quot;&gt;${escapeHtml(proj.owner)}&lt;/span&gt; • Updated ${new Date(proj.lastModified).toLocaleDateString()}<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;pt-3 border-t border-slate-100 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;button onclick=&quot;switchActiveProject(&#39;${proj.id}&#39;); navigateTo(&#39;dashboard&#39;);&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                    Open Workspace<br>                  &lt;/button&gt;<br>                  &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                    &lt;button onclick=&quot;openRenameProjectModal(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Rename Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;pencil&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;duplicateProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Duplicate Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;exportProjectJson(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Export Project JSON&quot;&gt;<br>                      &lt;i data-lucide=&quot;download&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;toggleArchiveProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Archive / Unarchive&quot;&gt;<br>                      &lt;i data-lucide=&quot;archive&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;confirmDeleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-rose-500/10 text-rose-500&quot; title=&quot;Delete Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openCreateProjectModal() {<br>      openModal({<br>        title: &#39;Create New EIS &amp; QA Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name *&lt;/label&gt;<br>              &lt;input id=&quot;new-proj-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Phase 2 — Regional Port Audit&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Reference&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-ref&quot; type=&quot;text&quot; value=&quot;PRJ-EIS-${Math.floor(1000 + Math.random() * 9000)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Owner / QA Lead&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-owner&quot; type=&quot;text&quot; value=&quot;QA Analyst&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Fee Template (Optional)&lt;/label&gt;<br>              &lt;select id=&quot;new-proj-template&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;&quot;&gt;Blank Main Page (No pre-configured fees)&lt;/option&gt;<br>                ${appState.templates.map(t =&gt; `&lt;option value=&quot;${t.id}&quot;&gt;${escapeHtml(t.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;new-proj-desc&quot; rows=&quot;2&quot; placeholder=&quot;Scope of receipt validation and QA evidence...&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;createNewProjectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;Create Project&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function createNewProjectFromModal() {<br>      const name = document.getElementById(&#39;new-proj-name&#39;).value.trim();<br>      if (!name) return showToast(&#39;Project name is required.&#39;, &#39;warning&#39;);<br>      const ref = document.getElementById(&#39;new-proj-ref&#39;).value.trim() || `PRJ-${Date.now()}`;<br>      const owner = document.getElementById(&#39;new-proj-owner&#39;).value.trim() || &#39;QA Tester&#39;;<br>      const desc = document.getElementById(&#39;new-proj-desc&#39;).value.trim();<br>      const tplId = document.getElementById(&#39;new-proj-template&#39;).value;<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br><br>      const now = new Date().toISOString();<br>      const firstPage = {<br>        id: &#39;mp_&#39; + Date.now(),<br>        name: &#39;MP-01: Primary Receipt Page&#39;,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: tpl ? tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;&#39;<br>        })) : [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(firstPage);<br><br>      const proj = {<br>        id: &#39;proj_&#39; + Date.now(),<br>        name,<br>        reference: ref,<br>        description: desc || &#39;EIS Receipt Validation &amp; QA Evidence Workspace&#39;,<br>        owner,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [firstPage],<br>        screenshots: [],<br>        mergeHistory: [],<br>        testCases: [],<br>        defects: [],<br>        activityLog: [{ timestamp: now, action: &#39;Project Created&#39;, detail: `Created ${name}` }]<br>      };<br><br>      appState.projects.unshift(proj);<br>      appState.activeProjectId = proj.id;<br>      appState.activeMainPageId = firstPage.id;<br>      closeModal();<br>      scheduleAutosave(&#39;Created project&#39;);<br>      showToast(`Created project &quot;${name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function openRenameProjectModal(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      openModal({<br>        title: &#39;Rename Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name&lt;/label&gt;<br>              &lt;input id=&quot;rename-proj-input&quot; type=&quot;text&quot; value=&quot;${escapeHtml(proj.name)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;rename-proj-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;${escapeHtml(proj.description)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveProjectRename(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Changes&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveProjectRename(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      const val = document.getElementById(&#39;rename-proj-input&#39;).value.trim();<br>      if (!val) return showToast(&#39;Project name cannot be empty.&#39;, &#39;warning&#39;);<br>      proj.name = val;<br>      proj.description = document.getElementById(&#39;rename-proj-desc&#39;).value.trim();<br>      closeModal();<br>      scheduleAutosave(&#39;Renamed project&#39;);<br>      showToast(&#39;Project updated.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateProject(projId) {<br>      const orig = appState.projects.find(p =&gt; p.id === projId);<br>      if (!orig) return;<br>      const copy = JSON.parse(JSON.stringify(orig));<br>      copy.id = &#39;proj_&#39; + Date.now();<br>      copy.name = orig.name + &#39; (Copy)&#39;;<br>      copy.reference = orig.reference + &#39;-COPY&#39;;<br>      copy.createdAt = new Date().toISOString();<br>      copy.lastModified = copy.createdAt;<br>      appState.projects.unshift(copy);<br>      scheduleAutosave(&#39;Duplicated project&#39;);<br>      showToast(`Duplicated &quot;${orig.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function toggleArchiveProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      proj.archived = !proj.archived;<br>      proj.status = proj.archived ? &#39;Archived&#39; : &#39;Active&#39;;<br>      scheduleAutosave(&#39;Toggled archive&#39;);<br>      showToast(proj.archived ? &#39;Project archived.&#39; : &#39;Project restored.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function confirmDeleteProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      if (appState.projects.length &lt;= 1) {<br>        return showToast(&#39;Cannot delete the only remaining project.&#39;, &#39;warning&#39;);<br>      }<br>      openModal({<br>        title: &#39;Confirm Project Deletion&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to permanently delete &lt;strong&gt;${escapeHtml(proj.name)}&lt;/strong&gt; (${proj.mainPages.length} Main Pages, receipts, and QA evidence)? This action cannot be undone unless you have exported a JSON backup.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;deleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete Permanently&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function deleteProject(projId) {<br>      appState.projects = appState.projects.filter(p =&gt; p.id !== projId);<br>      if (appState.activeProjectId === projId) {<br>        appState.activeProjectId = appState.projects[0].id;<br>        appState.activeMainPageId = appState.projects[0].mainPages[0]?.id || null;<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted project&#39;);<br>      showToast(&#39;Project deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportProjectJson(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId) || getActiveProject();<br>      if (!proj) return;<br>      const exportObj = {<br>        SMARTExportVersion: APP_SCHEMA_VERSION,<br>        exportedAt: new Date().toISOString(),<br>        project: proj<br>      };<br>      const blob = new Blob([JSON.stringify(exportObj, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `${proj.reference || &#39;SMART_project&#39;}_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full project JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function importProjectJson(event) {<br>      const file = event.target.files[0];<br>      if (!file) return;<br>      const reader = new FileReader();<br>      reader.onload = (e) =&gt; {<br>        try {<br>          const parsed = JSON.parse(e.target.result);<br>          const importedProj = parsed.project || parsed;<br>          if (!importedProj || !importedProj.name || !Array.isArray(importedProj.mainPages)) {<br>            throw new Error(&#39;Invalid SMART project JSON schema.&#39;);<br>          }<br>          importedProj.id = &#39;proj_&#39; + Date.now();<br>          importedProj.lastModified = new Date().toISOString();<br>          importedProj.mainPages.forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>            ValidationEngine.validateMainPage(mp);<br>          });<br>          appState.projects.unshift(importedProj);<br>          appState.activeProjectId = importedProj.id;<br>          appState.activeMainPageId = importedProj.mainPages[0]?.id || null;<br>          scheduleAutosave(&#39;Imported project JSON&#39;);<br>          showToast(`Imported &quot;${importedProj.name}&quot; successfully!`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;Import failed: &#39; + err.message, &#39;error&#39;);<br>        }<br>      };<br>      reader.readAsText(file);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 3 VIEW: MAIN PAGE MANAGEMENT (1-50+ Fields, Per-Page Dynamic Row &amp; Fees)<br>     ****************************************************************************/<br>    let fieldSearchQuery = &#39;&#39;;<br>    let showAll50Fields = false;<br>    let mainPageQuickListSearch = &#39;&#39;;<br><br>    function renderMainPagesModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page found.&lt;/div&gt;`;<br><br>      const fin = page.validationSummary ? page.validationSummary.financials : FinancialCalculator.calculateTotals(page.fees);<br>      const visibleFields = page.fields.filter(f =&gt; {<br>        if (!showAll50Fields &amp;&amp; !f.enabled &amp;&amp; f.number &gt; 10) return false;<br>        if (!fieldSearchQuery) return true;<br>        const q = fieldSearchQuery.toLowerCase();<br>        return String(f.number).includes(q) || f.name.toLowerCase().includes(q) || String(f.expectedValue).toLowerCase().includes(q) || String(f.actualValue).toLowerCase().includes(q);<br>      });<br><br>      const isRowPasteEnabled = page.rowPasteEnabled !== false;<br>      const pageRowInput = page.rowPasteInput || &#39;&#39;;<br>      const pageRowHasHeaders = Boolean(page.rowPasteHasHeaders);<br>      const parsedPreview = RowToFieldsEngine.parseSpreadsheetRow(pageRowInput, pageRowHasHeaders);<br><br>      return `<br>        &lt;!-- Main Page Selector Tabs --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2 overflow-x-auto pb-1 max-w-full&quot;&gt;<br>              ${proj.mainPages.map(mp =&gt; {<br>                const active = mp.id === page.id;<br>                const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>                return `<br>                  &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold border transition flex items-center gap-2 shrink-0 ${<br>                    active<br>                      ? &#39;bg-brand-600 text-white border-brand-600 shadow-sm&#39;<br>                      : &#39;bg-slate-50 dark:bg-slate-800/70 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>                  }&quot;&gt;<br>                    &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                    &lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold ${active ? &#39;bg-white/20 text-white&#39; : &#39;bg-slate-200 dark:bg-slate-700&#39;}&quot;&gt;${st}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center gap-2 shrink-0&quot;&gt;<br>              &lt;button onclick=&quot;addNewMainPage()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;New Main Page&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;toggleMainPageQuickList()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition ${<br>                appState.ui.mainPageQuickListOpen<br>                  ? &#39;bg-indigo-600 text-white border-indigo-600 shadow-sm&#39;<br>                  : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>              }&quot; title=&quot;View all Main Page tabs in a quick list with Select All &amp; Delete All&quot;&gt;<br>                &lt;i data-lucide=&quot;list-checks&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick List (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;duplicateActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Duplicate Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>              ${proj.mainPages.length &gt; 1 ? `<br>                &lt;button onclick=&quot;deleteActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-rose-500/30 text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete Main Page&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${appState.ui.mainPageQuickListOpen ? renderMainPageQuickListPanel(proj, page) : &#39;&#39;}<br><br>          &lt;!-- Isolated Main Page Metadata --&gt;<br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-3 gap-3 pt-2 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Main Page Name (Isolated Record)&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.name)}&quot; onchange=&quot;updateMainPageMeta(&#39;name&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;md:col-span-2&quot;&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Page Scenario Description&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.description)}&quot; onchange=&quot;updateMainPageMeta(&#39;description&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- 1-Row Spreadsheet-to-Columns Expected Output Paste Studio (Per-Page Dynamic Config) --&gt;<br>        &lt;div class=&quot;bg-gradient-to-br from-brand-500/5 via-white to-indigo-500/5 dark:from-brand-950/30 dark:via-slate-900 dark:to-indigo-950/20 border ${isRowPasteEnabled ? &#39;border-brand-500/30&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 space-y-4 shadow-sm transition&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-start justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap mb-1&quot;&gt;<br>                &lt;span class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-brand-600/15 text-brand-600 dark:text-brand-400&quot;&gt;<br>                  &lt;i data-lucide=&quot;table-2&quot; class=&quot;w-3 h-3&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;Per-Page Dynamic Row Mapper • ${escapeHtml(page.name)}&lt;/span&gt;<br>                &lt;/span&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[11px] font-semibold border cursor-pointer ${isRowPasteEnabled ? &#39;bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${isRowPasteEnabled ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteConfig(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;${isRowPasteEnabled ? &#39;Enabled for this page&#39; : &#39;Not Applicable for this page&#39;}&lt;/span&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Paste Expected Receipt Row (Excel / Sheets / CSV / Pipe)&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;${isRowPasteEnabled<br>                ? &#39;Independent dynamic configuration for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Custom column names are preserved by default; header-based renaming is opt-in.&#39;<br>                : &#39;Row-paste mapping is marked &lt;strong&gt;Not Applicable&lt;/strong&gt; for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Toggle above if this page uses spreadsheet row expectations.&#39;}&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            ${isRowPasteEnabled ? `<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap&quot;&gt;<br>                &lt;button onclick=&quot;saveFieldSchemaAsTemplate()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:border-brand-500/50&quot;&gt;<br>                  Save Column Names as Template<br>                &lt;/button&gt;<br>                &lt;button onclick=&quot;clearExpectedRowValues()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold text-rose-600 dark:text-rose-400 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;<br>                  Clear This Page&#39;s Row<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          ${isRowPasteEnabled ? `<br>            &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-4&quot;&gt;<br>              &lt;div class=&quot;lg:col-span-6 space-y-2.5&quot;&gt;<br>                &lt;textarea id=&quot;row-to-fields-textarea&quot; rows=&quot;3&quot; oninput=&quot;updatePageRowPasteInput(this.value)&quot; placeholder=&quot;Paste 1 dynamic row for ${escapeHtml(page.name)} (Tab-separated, CSV, or Pipe):&amp;#10;INV-2026-88410 2026-11-15 004-892-110-000 APEX GLOBAL PHP 1250.00 50.00 1200.00&quot; class=&quot;w-full p-3 rounded-xl bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-700 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;${escapeHtml(pageRowInput)}&lt;/textarea&gt;<br><br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${pageRowHasHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;First pasted row contains column headers&lt;/span&gt;<br>                  &lt;/label&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${page.autoRenameFieldsFromHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleAutoRenameFieldsFromHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;Allow pasted headers to rename my fields&lt;/span&gt;<br>                  &lt;/label&gt;<br><br>                  &lt;button onclick=&quot;applyPastedRowToMainPageFields()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>                    &lt;i data-lucide=&quot;arrow-down-to-line&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;span&gt;Apply Dynamic Row to ${escapeHtml(page.name.split(&#39;:&#39;)[0])}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br><br>              &lt;!-- Live Column -&gt; Field Preview --&gt;<br>              &lt;div class=&quot;lg:col-span-6 bg-white/80 dark:bg-slate-950/70 border border-slate-200 dark:border-slate-800 rounded-xl p-3 flex flex-col justify-between&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between mb-2&quot;&gt;<br>                  &lt;span class=&quot;text-[11px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Live Dynamic Mapping Preview (${parsedPreview.values.length} cols • ${parsedPreview.delimiter})&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div id=&quot;row-paste-preview-grid&quot; class=&quot;flex flex-wrap gap-1.5 max-h-28 overflow-y-auto&quot;&gt;<br>                  ${renderRowPastePreviewChips(page, parsedPreview)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          ` : &#39;&#39;}<br>        &lt;/div&gt;<br><br>        &lt;!-- EIS Fee &amp; CWT Configuration Engine --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;EIS Fee &amp; CWT Line-Item Configuration&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Independent Fee Name, Amount &amp; Code per row. CWT deducts absolute magnitude without double-counting in Gross Fees.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;openQuickPasteFeeModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/20&quot;&gt;<br>                &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick Paste Fees&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(false)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add Fee&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30 hover:bg-amber-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;minus-circle&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add CWT&lt;/span&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-10&quot;&gt;#&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Fee Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Amount&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Amt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${page.fees.length === 0 ? `<br>                  &lt;tr&gt;&lt;td colspan=&quot;10&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No fees configured yet. Click &lt;strong&gt;Add Fee&lt;/strong&gt; or &lt;strong&gt;Quick Paste Fees&lt;/strong&gt;.&lt;/td&gt;&lt;/tr&gt;<br>                ` : page.fees.map((fee, idx) =&gt; {<br>                  const isCwt = FinancialCalculator.isCwtEntry(fee);<br>                  const st = fee.lastValidation ? fee.lastValidation.status : &#39;PENDING&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-slate-400&quot;&gt;${idx + 1}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;button onclick=&quot;toggleFeeCwtFlag(&#39;${fee.id}&#39;)&quot; class=&quot;px-2 py-0.5 rounded text-[10px] font-bold border ${isCwt ? &#39;bg-amber-500/15 text-amber-500 border-amber-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-200 dark:border-slate-700&#39;}&quot; title=&quot;Click to toggle Fee vs CWT Deduction&quot;&gt;<br>                          ${isCwt ? &#39;CWT (-)&#39; : &#39;FEE (+)&#39;}<br>                        &lt;/button&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedName&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-medium&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedAmount&#39;, this.value)&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedCode&#39;, this.value)&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; placeholder=&quot;OCR / Receipt&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; placeholder=&quot;0.00&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; placeholder=&quot;Code&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, -1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;&lt;i data-lucide=&quot;arrow-up&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, 1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;&lt;i data-lucide=&quot;arrow-down&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;duplicateFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Duplicate&quot;&gt;&lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;removeFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-rose-500 hover:bg-rose-500/10 rounded&quot; title=&quot;Remove&quot;&gt;&lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Gross Fees (Expected / Actual)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)} / &lt;span class=&quot;text-brand-500&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/span&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Total CWT Deduction (|CWT|)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Total (Gross - CWT)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-emerald-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Variance&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm ${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;} mt-0.5&quot;&gt;${fin.netDifference &gt; 0 ? &#39;+&#39; : &#39;&#39;}${fin.netDifference.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Configurable Columns / Numbered Main Page Fields (1-50+) --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Configurable Column Fields (1–${page.fields.length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;${proj.sharedHeaders ? &#39;&lt;strong class=&quot;text-emerald-500&quot;&gt;Shared headers ON:&lt;/strong&gt; names, Type and Req are the same on every Main Page, so editing here updates all pages. Values stay per page.&#39; : &#39;Edit professional field names directly. Names are saved per Main Page and stay unchanged when you paste rows unless header-based renaming is enabled above.&#39;}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold border cursor-pointer ${proj.sharedHeaders ? &#39;bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39; : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700&#39;}&quot; title=&quot;ON: the same Configurable Field / Column Names are used on every Main Page (new pages too). Values stay per page.&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; ${proj.sharedHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleSharedHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Same headers for all pages (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/label&gt;<br>              ${proj.sharedHeaders ? `&lt;button onclick=&quot;reapplySharedHeaders()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot; title=&quot;Push this page&#39;s headers to every Main Page again&quot;&gt;Re-apply to all&lt;/button&gt;` : &#39;&#39;}<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fieldSearchQuery)}&quot; oninput=&quot;fieldSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search fields...&quot; class=&quot;px-3 py-1.5 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;button onclick=&quot;showAll50Fields = !showAll50Fields; renderApp();&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;<br>                ${showAll50Fields ? &#39;Show Active / First 10&#39; : `Show All ${page.fields.length} Fields`}<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addMoreNumberedFields(10)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                + Add 10 More Fields<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto max-h-[420px]&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead class=&quot;sticky top-0 bg-white dark:bg-slate-900 z-10&quot;&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-14&quot;&gt;Col #&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Configurable Field / Column Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Req&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${visibleFields.map(f =&gt; {<br>                  const st = f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2 font-mono font-semibold text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.name)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;name&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-semibold&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;select onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;dataType&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700&quot;&gt;<br>                          ${[&#39;Dynamic&#39;, &#39;Text&#39;, &#39;Number&#39;, &#39;Currency&#39;, &#39;Date&#39;, &#39;Percentage&#39;, &#39;Code&#39;, &#39;Reference&#39;, &#39;Boolean&#39;].map(t =&gt; `&lt;option value=&quot;${t}&quot; ${f.dataType === t ? &#39;selected&#39; : &#39;&#39;}&gt;${t}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.expectedValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;expectedValue&#39;, this.value)&quot; placeholder=&quot;Expected&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; placeholder=&quot;Receipt value&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${f.required ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;required&#39;, this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderRowPastePreviewChips(page, parsed) {<br>      if (!parsed.values.length) {<br>        return `&lt;span class=&quot;text-xs text-slate-400 italic&quot;&gt;Paste a row on the left to preview how each column maps into C01, C02, C03...&lt;/span&gt;`;<br>      }<br>      return parsed.values.map((val, idx) =&gt; {<br>        const colNum = idx + 1;<br>        const existingField = page.fields[idx];<br>        const colName = parsed.headers[idx] || (existingField ? existingField.name : `Custom Field ${colNum}`);<br>        return `<br>          &lt;div class=&quot;px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot;&gt;<br>            &lt;div class=&quot;text-[10px] font-bold text-brand-500&quot;&gt;C${String(colNum).padStart(2, &#39;0&#39;)}: ${escapeHtml(colName)}&lt;/div&gt;<br>            &lt;div class=&quot;font-mono font-semibold truncate max-w-[160px]&quot;&gt;${escapeHtml(val || &#39;(blank)&#39;)}&lt;/div&gt;<br>          &lt;/div&gt;<br>        `;<br>      }).join(&#39;&#39;);<br>    }<br><br>    function updateRowPastePreviewOnly() {<br>      const page = getActiveMainPage();<br>      const grid = document.getElementById(&#39;row-paste-preview-grid&#39;);<br>      if (!page || !grid) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      grid.innerHTML = renderRowPastePreviewChips(page, parsed);<br>    }<br><br>    function togglePageRowPasteConfig(enabled) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteEnabled = Boolean(enabled);<br>      scheduleAutosave(`Updated row mapper config on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function updatePageRowPasteInput(val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteInput = val;<br>      updateRowPastePreviewOnly();<br>      scheduleAutosave(`Updated dynamic row input on ${page.name}`);<br>    }<br><br>    function togglePageRowPasteHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteHasHeaders = Boolean(checked);<br>      scheduleAutosave(`Toggled row headers on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function toggleAutoRenameFieldsFromHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.autoRenameFieldsFromHeaders = Boolean(checked);<br>      scheduleAutosave(&#39;Updated column header rename preference on &#39; + page.name);<br>      showToast(checked<br>        ? &#39;Pasted headers can now rename fields on this page.&#39;<br>        : &#39;Custom field names are protected from pasted headers.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyPastedRowToMainPageFields() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      if (!parsed.values.length) {<br>        return showToast(&#39;Paste at least 1 row of values first.&#39;, &#39;warning&#39;);<br>      }<br><br>      while (page.fields.length &lt; parsed.values.length) {<br>        const num = page.fields.length + 1;<br>        page.fields.push({<br>          id: `fld_${num}_${Date.now()}_${num}`,<br>          number: num,<br>          name: `Custom Field ${num}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: true,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${num}`,<br>          pageOverride: true,<br>          enabled: true<br>        });<br>      }<br><br>      parsed.values.forEach((val, idx) =&gt; {<br>        const fld = page.fields[idx];<br>        if (parsed.headers[idx] &amp;&amp; page.autoRenameFieldsFromHeaders === true) {<br>          fld.name = parsed.headers[idx];<br>        }<br>        fld.expectedValue = val;<br>        fld.enabled = true;<br>        fld.pageOverride = true;<br>        if (val !== &#39;&#39;) {<br>          fld.required = true;<br>          fld.dataType = &#39;Dynamic&#39;;<br>        }<br>      });<br><br>      pushSharedHeadersFrom(page);<br><br>      let matchInfo = &#39;&#39;;<br>      if (page.receipt &amp;&amp; page.receipt.ocrRawText) {<br>        const m = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>        matchInfo = ` • Auto-matched ${m.matched}/${m.total} against attached receipt`;<br>      } else {<br>        ValidationEngine.validateMainPage(page);<br>      }<br><br>      logActivity(&#39;Pasted Dynamic Row&#39;, `Applied ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`);<br>      scheduleAutosave(&#39;Applied dynamic expected row&#39;);<br>      showToast(`Mapped ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function clearExpectedRowValues() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fields.forEach(f =&gt; {<br>        f.expectedValue = &#39;&#39;;<br>        f.actualValue = &#39;&#39;;<br>        if (f.number &gt; 10) f.enabled = false;<br>      });<br>      page.rowPasteInput = &#39;&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Cleared expected row values&#39;);<br>      showToast(&#39;Cleared expected &amp; actual field values on &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function saveFieldSchemaAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const activeCols = page.fields.filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10);<br>      openModal({<br>        title: &#39;Save Configurable Column Names as Reusable Template&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Save your current &lt;strong&gt;${activeCols.length} configurable column headers&lt;/strong&gt; (plus any fee rows) so you can apply this exact column layout to future Main Pages with one click.&lt;/p&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Template Name&lt;/label&gt;<br>              &lt;input id=&quot;col-schema-tpl-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Standard 8-Column Export Layout&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmSaveFieldSchemaTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Schema Template&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmSaveFieldSchemaTemplate() {<br>      const page = getActiveMainPage();<br>      const name = document.getElementById(&#39;col-schema-tpl-name&#39;).value.trim();<br>      if (!page || !name) return showToast(&#39;Enter a template name.&#39;, &#39;warning&#39;);<br><br>      const activeCols = page.fields<br>        .filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10)<br>        .map(f =&gt; ({ number: f.number, name: f.name, dataType: f.dataType, required: f.required }));<br><br>      appState.templates.push({<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name,<br>        description: `${activeCols.length} configured columns + ${page.fees.length} fee rows`,<br>        columns: activeCols,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Saved column schema template&#39;);<br>      showToast(`Saved template &quot;${name}&quot;`, &#39;success&#39;);<br>    }<br><br>    function renderMainPageQuickListPanel(proj, activePage, closeHandler = &#39;toggleMainPageQuickList()&#39;, boxCountFn = null) {<br>      const selectedIds = new Set((appState.ui.selectedMainPageIds || []).filter(id =&gt; proj.mainPages.some(mp =&gt; mp.id === id)));<br>      const q = (mainPageQuickListSearch || &#39;&#39;).trim().toLowerCase();<br>      const filteredPages = proj.mainPages.filter(mp =&gt;<br>        !q ||<br>        mp.name.toLowerCase().includes(q) ||<br>        (mp.description || &#39;&#39;).toLowerCase().includes(q)<br>      );<br>      const allFilteredSelected = filteredPages.length &gt; 0 &amp;&amp; filteredPages.every(mp =&gt; selectedIds.has(mp.id));<br><br>      return `<br>        &lt;div class=&quot;rounded-xl border border-indigo-500/30 bg-slate-50/90 dark:bg-slate-950/80 p-3.5 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>              &lt;span class=&quot;text-xs font-bold text-indigo-600 dark:text-indigo-400 flex items-center gap-1.5&quot;&gt;<br>                &lt;i data-lucide=&quot;layers&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;All Main Page Tabs (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/span&gt;<br>              &lt;span class=&quot;text-[11px] px-2 py-0.5 rounded-full bg-slate-200 dark:bg-slate-800 font-semibold&quot;&gt;<br>                ${selectedIds.size} selected<br>              &lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;div class=&quot;relative&quot;&gt;<br>                &lt;i data-lucide=&quot;search&quot; class=&quot;w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(mainPageQuickListSearch)}&quot; oninput=&quot;mainPageQuickListSearch = this.value; renderApp();&quot; placeholder=&quot;Filter tabs...&quot; class=&quot;pl-8 pr-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-xs w-44 focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;button onclick=&quot;selectAllMainPagesInQuickList()&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:border-brand-500/50&quot;&gt;<br>                ${allFilteredSelected ? &#39;Deselect All&#39; : &#39;Select All&#39;}<br>              &lt;/button&gt;<br><br>              ${selectedIds.size &gt; 0 ? `<br>                &lt;button onclick=&quot;deleteSelectedMainPages()&quot; class=&quot;inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white shadow-xs&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;${selectedIds.size === proj.mainPages.length ? &#39;Delete All (&#39; + selectedIds.size + &#39;)&#39; : &#39;Delete Selected (&#39; + selectedIds.size + &#39;)&#39;}&lt;/span&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br><br>              &lt;button onclick=&quot;confirmDeleteAllMainPages()&quot; class=&quot;inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-rose-500/40 text-rose-600 dark:text-rose-400 hover:bg-rose-500/10&quot; title=&quot;Delete all tabs and reset to a single clean Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;trash&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Delete All&lt;/span&gt;<br>              &lt;/button&gt;<br><br>              &lt;button onclick=&quot;${closeHandler}&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-800&quot; title=&quot;Close Quick List&quot;&gt;<br>                &lt;i data-lucide=&quot;x&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;max-h-60 overflow-y-auto divide-y divide-slate-200/70 dark:divide-slate-800 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900&quot;&gt;<br>            ${filteredPages.length === 0 ? `<br>              &lt;div class=&quot;py-6 text-center text-xs text-slate-400&quot;&gt;No tabs match &quot;${escapeHtml(mainPageQuickListSearch)}&quot;.&lt;/div&gt;<br>            ` : filteredPages.map((mp) =&gt; {<br>              const isCurrent = mp.id === activePage.id;<br>              const isChecked = selectedIds.has(mp.id);<br>              const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>              const realIndex = proj.mainPages.findIndex(item =&gt; item.id === mp.id) + 1;<br>              return `<br>                &lt;div class=&quot;flex items-center justify-between gap-3 px-3 py-2 text-xs transition ${isCurrent ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                  &lt;div class=&quot;flex items-center gap-2.5 min-w-0 flex-1&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleMainPageQuickSelect(&#39;${mp.id}&#39;)&quot; class=&quot;rounded text-brand-600 cursor-pointer shrink-0&quot; /&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] text-slate-400 shrink-0&quot;&gt;#${realIndex}&lt;/span&gt;<br>                    &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;text-left min-w-0 flex-1 group&quot;&gt;<br>                      &lt;div class=&quot;font-semibold truncate group-hover:text-brand-500 transition flex items-center gap-2&quot;&gt;<br>                        &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                        ${isCurrent ? &#39;&lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold bg-brand-600 text-white&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      &lt;/div&gt;<br>                      &lt;div class=&quot;text-[11px] text-slate-400 truncate&quot;&gt;<br>                        ${mp.fees.length} fees • ${boxCountFn ? boxCountFn(mp) + &#39; QA boxes • &#39; : &#39;&#39;}${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;No receipt&#39;} ${mp.description ? &#39;• &#39; + escapeHtml(mp.description) : &#39;&#39;}<br>                      &lt;/div&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br><br>                  &lt;div class=&quot;flex items-center gap-2 shrink-0&quot;&gt;<br>                    ${statusBadge(st)}<br>                    &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-brand-600 hover:text-white transition&quot;&gt;<br>                      Open<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;deleteSingleMainPageFromList(&#39;${mp.id}&#39;)&quot; class=&quot;p-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete this tab&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            }).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function toggleMainPageQuickList() {<br>      appState.ui.mainPageQuickListOpen = !appState.ui.mainPageQuickListOpen;<br>      renderApp();<br>    }<br><br>    function toggleMainPageQuickSelect(pageId) {<br>      appState.ui.selectedMainPageIds = appState.ui.selectedMainPageIds || [];<br>      const idx = appState.ui.selectedMainPageIds.indexOf(pageId);<br>      if (idx &gt;= 0) appState.ui.selectedMainPageIds.splice(idx, 1);<br>      else appState.ui.selectedMainPageIds.push(pageId);<br>      renderApp();<br>    }<br><br>    function selectAllMainPagesInQuickList() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const q = (mainPageQuickListSearch || &#39;&#39;).trim().toLowerCase();<br>      const targetIds = proj.mainPages<br>        .filter(mp =&gt; !q || mp.name.toLowerCase().includes(q) || (mp.description || &#39;&#39;).toLowerCase().includes(q))<br>        .map(mp =&gt; mp.id);<br><br>      const currentSet = new Set(appState.ui.selectedMainPageIds || []);<br>      const allSelected = targetIds.length &gt; 0 &amp;&amp; targetIds.every(id =&gt; currentSet.has(id));<br>      if (allSelected) {<br>        targetIds.forEach(id =&gt; currentSet.delete(id));<br>      } else {<br>        targetIds.forEach(id =&gt; currentSet.add(id));<br>      }<br>      appState.ui.selectedMainPageIds = Array.from(currentSet);<br>      renderApp();<br>    }<br><br>    function createFreshDefaultMainPage(index = 1) {<br>      const fresh = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + index,<br>        name: `MP-0${index}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      applySharedSchemaToPage(getActiveProject(), fresh);<br>      ValidationEngine.validateMainPage(fresh);<br>      return fresh;<br>    }<br><br>    function deleteSingleMainPageFromList(pageId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const target = proj.mainPages.find(mp =&gt; mp.id === pageId);<br>      if (!target) return;<br><br>      if (proj.mainPages.length &lt;= 1) {<br>        openModal({<br>          title: &#39;Reset Last Main Page&#39;,<br>          bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;&lt;strong&gt;${escapeHtml(target.name)}&lt;/strong&gt; is the only remaining tab. Deleting it will replace it with a clean blank &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;. Continue?&lt;/p&gt;`,<br>          footerHtml: `<br>            &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>            &lt;button onclick=&quot;executeBulkDeleteMainPages([&#39;${pageId}&#39;])&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Reset Tab&lt;/button&gt;<br>          `<br>        });<br>        return;<br>      }<br><br>      proj.mainPages = proj.mainPages.filter(mp =&gt; mp.id !== pageId);<br>      appState.ui.selectedMainPageIds = (appState.ui.selectedMainPageIds || []).filter(id =&gt; id !== pageId);<br>      if (appState.activeMainPageId === pageId) {<br>        appState.activeMainPageId = proj.mainPages[0].id;<br>      }<br>      logActivity(&#39;Deleted Main Page&#39;, target.name);<br>      scheduleAutosave(&#39;Deleted Main Page from Quick List&#39;);<br>      showToast(`Deleted &quot;${target.name}&quot;`, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function deleteSelectedMainPages() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const toDelete = (appState.ui.selectedMainPageIds || []).filter(id =&gt; proj.mainPages.some(mp =&gt; mp.id === id));<br>      if (!toDelete.length) return showToast(&#39;Select at least one tab first.&#39;, &#39;warning&#39;);<br><br>      const deletingAll = toDelete.length &gt;= proj.mainPages.length;<br>      openModal({<br>        title: deletingAll ? &#39;Delete All Main Page Tabs&#39; : `Delete ${toDelete.length} Selected Tab(s)`,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;${<br>          deletingAll<br>            ? `Delete all &lt;strong&gt;${proj.mainPages.length}&lt;/strong&gt; Main Page tabs and start fresh with a clean &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;?`<br>            : `Permanently delete &lt;strong&gt;${toDelete.length}&lt;/strong&gt; selected Main Page tab(s) along with their attached receipts and fee rules?`<br>        }&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;executeBulkDeleteMainPages(${escapeHtml(JSON.stringify(toDelete))})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Confirm Delete&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteAllMainPages() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const allIds = proj.mainPages.map(mp =&gt; mp.id);<br>      openModal({<br>        title: &#39;Delete All Main Page Tabs&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to delete all &lt;strong&gt;${allIds.length}&lt;/strong&gt; Main Page tab(s) and reset to a single clean &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;executeBulkDeleteMainPages(${escapeHtml(JSON.stringify(allIds))})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete All Tabs&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function executeBulkDeleteMainPages(idsToDelete) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const removeSet = new Set(idsToDelete || []);<br>      const removedCount = proj.mainPages.filter(mp =&gt; removeSet.has(mp.id)).length;<br>      proj.mainPages = proj.mainPages.filter(mp =&gt; !removeSet.has(mp.id));<br><br>      if (proj.mainPages.length === 0) {<br>        proj.mainPages.push(createFreshDefaultMainPage(1));<br>      }<br><br>      if (!proj.mainPages.some(mp =&gt; mp.id === appState.activeMainPageId)) {<br>        appState.activeMainPageId = proj.mainPages[0].id;<br>      }<br><br>      appState.ui.selectedMainPageIds = [];<br>      closeModal();<br>      logActivity(&#39;Bulk Deleted Main Pages&#39;, `Removed ${removedCount} tab(s)`);<br>      scheduleAutosave(&#39;Bulk deleted Main Pages&#39;);<br>      showToast(`Deleted ${removedCount} Main Page tab(s).`, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function addNewMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const idx = proj.mainPages.length + 1;<br>      const newPage = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + idx,<br>        name: `MP-0${idx}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      applySharedSchemaToPage(proj, newPage);<br>      ValidationEngine.validateMainPage(newPage);<br>      proj.mainPages.push(newPage);<br>      appState.activeMainPageId = newPage.id;<br>      logActivity(&#39;Added Main Page&#39;, newPage.name);<br>      scheduleAutosave(&#39;Added Main Page&#39;);<br>      showToast(`Created ${newPage.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      const copy = JSON.parse(JSON.stringify(page));<br>      copy.id = &#39;mp_&#39; + Date.now();<br>      copy.name = page.name + &#39; (Copy)&#39;;<br>      proj.mainPages.push(copy);<br>      appState.activeMainPageId = copy.id;<br>      scheduleAutosave(&#39;Duplicated Main Page&#39;);<br>      showToast(`Duplicated &quot;${page.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function deleteActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page || proj.mainPages.length &lt;= 1) return;<br>      openModal({<br>        title: &#39;Delete Main Page&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Delete &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; and its attached receipt &amp; fee rules?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmDeleteMainPage(&#39;${page.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Delete Page&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteMainPage(pageId) {<br>      const proj = getActiveProject();<br>      proj.mainPages = proj.mainPages.filter(p =&gt; p.id !== pageId);<br>      appState.activeMainPageId = proj.mainPages[0].id;<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted Main Page&#39;);<br>      showToast(&#39;Main Page deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function updateMainPageMeta(key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page[key] = val;<br>      scheduleAutosave(&#39;Updated Main Page metadata&#39;);<br>      renderApp();<br>    }<br><br>    function addFeeRow(isCwt = false) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const idx = page.fees.length + 1;<br>      page.fees.push({<br>        id: &#39;fee_&#39; + Date.now() + &#39;_&#39; + idx,<br>        expectedName: isCwt ? &#39;CWT&#39; : `Fee ${idx} Charge`,<br>        expectedAmount: isCwt ? &#39;50&#39; : &#39;100&#39;,<br>        expectedCode: isCwt ? &#39;CWT&#39; : &#39;NC&#39;,<br>        actualName: &#39;&#39;,<br>        actualAmount: &#39;&#39;,<br>        actualCode: &#39;&#39;,<br>        isCwt,<br>        ocrConfidence: null,<br>        sourceLocation: &#39;&#39;<br>      });<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Added fee row&#39;);<br>      renderApp();<br>    }<br><br>    function updateFeeField(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const fee = page.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee[key] = val;<br>      if (key === &#39;expectedCode&#39; &amp;&amp; val.trim().toUpperCase() === &#39;CWT&#39;) fee.isCwt = true;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated fee&#39;);<br>      renderApp();<br>    }<br><br>    function toggleFeeCwtFlag(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee.isCwt = !FinancialCalculator.isCwtEntry(fee);<br>      if (fee.isCwt &amp;&amp; !fee.expectedCode) fee.expectedCode = &#39;CWT&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Toggled CWT flag&#39;);<br>      renderApp();<br>    }<br><br>    function moveFeeRow(idx, dir) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const target = idx + dir;<br>      if (target &lt; 0 || target &gt;= page.fees.length) return;<br>      const temp = page.fees[idx];<br>      page.fees[idx] = page.fees[target];<br>      page.fees[target] = temp;<br>      scheduleAutosave(&#39;Reordered fees&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const copy = JSON.parse(JSON.stringify(fee));<br>      copy.id = &#39;fee_&#39; + Date.now();<br>      page.fees.push(copy);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Duplicated fee&#39;);<br>      renderApp();<br>    }<br><br>    function removeFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fees = page.fees.filter(f =&gt; f.id !== feeId);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Removed fee&#39;);<br>      renderApp();<br>    }<br><br>    function openQuickPasteFeeModal() {<br>      openModal({<br>        title: &#39;Quick Paste EIS Fees &amp; CWT&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Paste multi-line blocks (Name / Amount / Code) or pipe-delimited rows. CWT entries are automatically recognized.&lt;/p&gt;<br>            &lt;textarea id=&quot;quick-paste-fee-input&quot; rows=&quot;9&quot; placeholder=&quot;Fee 1 Charge&amp;#10;1000&amp;#10;NC&amp;#10;Fee 2 Charge&amp;#10;250&amp;#10;IC&amp;#10;CWT&amp;#10;50&quot; class=&quot;w-full p-3 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;div class=&quot;flex items-center gap-4 text-xs&quot;&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;expected&quot; checked /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Expected&lt;/strong&gt; Main Page Fees&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;actual&quot; /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Actual / Receipt&lt;/strong&gt; Values&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;applyQuickPasteFees()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Parse &amp; Apply Fees&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function applyQuickPasteFees() {<br>      const page = getActiveMainPage();<br>      const raw = document.getElementById(&#39;quick-paste-fee-input&#39;).value;<br>      const target = document.querySelector(&#39;input[name=&quot;qp-target&quot;]:checked&#39;)?.value || &#39;expected&#39;;<br>      const parsed = OcrMappingEngine.parseQuickPasteFees(raw);<br>      if (!parsed.length) return showToast(&#39;No valid fee rows detected.&#39;, &#39;warning&#39;);<br><br>      if (target === &#39;expected&#39;) {<br>        parsed.forEach((p, idx) =&gt; {<br>          page.fees.push({<br>            id: `fee_qp_${Date.now()}_${idx}`,<br>            expectedName: p.name,<br>            expectedAmount: p.amount,<br>            expectedCode: p.code,<br>            actualName: &#39;&#39;,<br>            actualAmount: &#39;&#39;,<br>            actualCode: &#39;&#39;,<br>            isCwt: p.isCwt,<br>            ocrConfidence: null,<br>            sourceLocation: &#39;Quick Paste&#39;<br>          });<br>        });<br>      } else {<br>        parsed.forEach((p, idx) =&gt; {<br>          if (page.fees[idx]) {<br>            page.fees[idx].actualName = p.name;<br>            page.fees[idx].actualAmount = p.amount;<br>            page.fees[idx].actualCode = p.code;<br>            page.fees[idx].sourceLocation = &#39;Quick Paste Receipt&#39;;<br>          } else {<br>            page.fees.push({<br>              id: `fee_qp_${Date.now()}_${idx}`,<br>              expectedName: p.name,<br>              expectedAmount: &#39;&#39;,<br>              expectedCode: p.code,<br>              actualName: p.name,<br>              actualAmount: p.amount,<br>              actualCode: p.code,<br>              isCwt: p.isCwt,<br>              ocrConfidence: 100,<br>              sourceLocation: &#39;Quick Paste Receipt&#39;<br>            });<br>          }<br>        });<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      closeModal();<br>      scheduleAutosave(&#39;Quick pasted fees&#39;);<br>      showToast(`Imported ${parsed.length} fee entries.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateNumberedField(fieldId, key, val) {<br>      const page = getActiveMainPage();<br>      const fld = page?.fields.find(f =&gt; f.id === fieldId);<br>      if (!fld) return;<br>      fld[key] = val;<br>      if (key === &#39;expectedValue&#39; || key === &#39;actualValue&#39;) fld.enabled = true;<br>      if (key === &#39;name&#39; || key === &#39;dataType&#39; || key === &#39;required&#39;) pushSharedHeadersFrom(page);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated numbered field&#39;);<br>      renderApp();<br>    }<br><br>    function addMoreNumberedFields(count = 10) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const start = page.fields.length + 1;<br>      for (let i = start; i &lt; start + count; i++) {<br>        page.fields.push({<br>          id: `fld_${i}_${Date.now()}`,<br>          number: i,<br>          name: `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: false,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: true<br>        });<br>      }<br>      showAll50Fields = true;<br>      pushSharedHeadersFrom(page);<br>      scheduleAutosave(&#39;Added numbered fields&#39;);<br>      showToast(`Added ${count} fields (Total: ${page.fields.length}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 4 VIEW: SIDE-BY-SIDE RECEIPT VALIDATION WORKSPACE<br>     ****************************************************************************/<br>    function renderValidationWorkspaceModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      if (!page.validationSummary) ValidationEngine.validateMainPage(page);<br>      const summary = page.validationSummary;<br>      const fin = summary.financials;<br>      const rec = page.receipt;<br>      const currentImg = rec &amp;&amp; rec.pages &amp;&amp; rec.pages[rec.currentPage - 1] ? rec.pages[rec.currentPage - 1] : null;<br>      const selectedRowId = appState.ui.selectedComparisonRowId;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[10px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Active Main Page (Isolated)&lt;/label&gt;<br>              &lt;select onchange=&quot;switchActiveMainPage(this.value)&quot; class=&quot;mt-0.5 text-xs font-bold bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-1.5&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; `&lt;option value=&quot;${mp.id}&quot; ${mp.id === page.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(mp.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;pt-3&quot;&gt;${statusBadge(summary.overallStatus)}&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;${rec ? &#39;Replace Receipt&#39; : &#39;Upload Receipt (PNG/JPG/WEBP/PDF)&#39;}&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.png,.jpg,.jpeg,.webp,.pdf,image/*,application/pdf&quot; onchange=&quot;handleReceiptUpload(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;pasteReceiptFromClipboardButton()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700&quot; title=&quot;Or press Ctrl+V / Cmd+V anywhere on this screen&quot;&gt;<br>              &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Paste Image (Ctrl+V)&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;evidence&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-violet-500/15 text-violet-600 dark:text-violet-400 border border-violet-500/30 hover:bg-violet-500/25&quot; title=&quot;Evidence screenshots of this Main Page. QA-n box value fills Expected Value or Found on Receipt of field Cn (toggle inside)&quot;&gt;<br>              &lt;i data-lucide=&quot;images&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Evidence Screenshots (${(page.evidenceShots || []).length})&lt;/span&gt;<br>            &lt;/button&gt;<br>            ${rec ? `<br>              &lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;scan-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Re-Run OCR &amp; Auto-Match&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;removeReceiptAttachment()&quot; class=&quot;p-2 rounded-xl text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Remove Receipt Attachment&quot;&gt;<br>                &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl flex flex-col overflow-hidden&quot;&gt;<br>            &lt;div class=&quot;px-4 py-3 border-b border-slate-200 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div class=&quot;text-xs font-bold flex items-center gap-2&quot;&gt;<br>                &lt;i data-lucide=&quot;file-check-2&quot; class=&quot;w-4 h-4 text-brand-500&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Original Receipt (${escapeHtml(page.name)})&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(-0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom Out&quot;&gt;&lt;i data-lucide=&quot;zoom-out&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;span class=&quot;text-[11px] font-mono px-1&quot;&gt;${Math.round(appState.ui.viewerZoom * 100)}%&lt;/span&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom In&quot;&gt;&lt;i data-lucide=&quot;zoom-in&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;rotateViewer()&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Rotate 90°&quot;&gt;&lt;i data-lucide=&quot;rotate-cw&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.showOcrBoxes = !appState.ui.showOcrBoxes; renderApp();&quot; class=&quot;px-2 py-1 rounded-lg text-[10px] font-bold border ${appState.ui.showOcrBoxes ? &#39;bg-brand-500/15 text-brand-500 border-brand-500/30&#39; : &#39;border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  OCR Boxes<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div ondragover=&quot;event.preventDefault()&quot; ondrop=&quot;handleReceiptDrop(event)&quot; class=&quot;relative flex-1 min-h-[420px] max-h-[600px] overflow-auto bg-slate-100 dark:bg-slate-950 flex items-center justify-center p-4&quot;&gt;<br>              ${currentImg ? `<br>                &lt;div class=&quot;relative inline-block transition-transform duration-150&quot; style=&quot;transform: scale(${appState.ui.viewerZoom}) rotate(${appState.ui.viewerRotation}deg);&quot;&gt;<br>                  &lt;img src=&quot;${currentImg}&quot; alt=&quot;Original Receipt&quot; class=&quot;max-w-full rounded-lg shadow-lg border border-slate-300 dark:border-slate-700&quot; /&gt;<br>                  ${appState.ui.showOcrBoxes ? (rec.ocrBlocks || []).filter(b =&gt; b.page === rec.currentPage).map(blk =&gt; {<br>                    const isHighlighted = selectedRowId &amp;&amp; blk.mappedToFeeId === selectedRowId;<br>                    return `<br>                      &lt;div onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${blk.mappedToFeeId || &#39;&#39;}&#39;; renderApp();&quot;<br>                           style=&quot;left:${blk.bbox.x}%; top:${blk.bbox.y}%; width:${blk.bbox.w}%; height:${blk.bbox.h}%;&quot;<br>                           title=&quot;${escapeHtml(blk.rawLine)} (${blk.confidence}% conf)&quot;<br>                           class=&quot;absolute cursor-pointer rounded border-2 transition ${<br>                             isHighlighted<br>                               ? &#39;border-rose-500 bg-rose-500/25 ring-2 ring-rose-400&#39;<br>                               : &#39;border-brand-500/70 bg-brand-500/10 hover:bg-brand-500/25&#39;<br>                           }&quot;&gt;<br>                      &lt;/div&gt;<br>                    `;<br>                  }).join(&#39;&#39;) : &#39;&#39;}<br>                &lt;/div&gt;<br>              ` : `<br>                &lt;div class=&quot;text-center max-w-xs space-y-2 p-6 border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-2xl&quot;&gt;<br>                  &lt;i data-lucide=&quot;file-up&quot; class=&quot;w-8 h-8 text-slate-400 mx-auto&quot;&gt;&lt;/i&gt;<br>                  &lt;div class=&quot;text-xs font-bold&quot;&gt;No Receipt Attached to ${escapeHtml(page.name)}&lt;/div&gt;<br>                  &lt;p class=&quot;text-[11px] text-slate-500&quot;&gt;Drag &amp; drop a PNG, JPG, WEBP, or multi-page PDF receipt here, or press &lt;strong&gt;Ctrl+V&lt;/strong&gt; to paste a receipt screenshot.&lt;/p&gt;<br>                &lt;/div&gt;<br>              `}<br>            &lt;/div&gt;<br><br>            ${rec ? `<br>              &lt;div class=&quot;px-4 py-2.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between text-xs bg-slate-50 dark:bg-slate-900&quot;&gt;<br>                &lt;span class=&quot;truncate text-slate-500&quot;&gt;${escapeHtml(rec.fileName)} • Conf: &lt;strong&gt;${rec.ocrConfidence}%&lt;/strong&gt;&lt;/span&gt;<br>                &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(-1)&quot; ${rec.currentPage &lt;= 1 ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;lt;&lt;/button&gt;<br>                  &lt;span class=&quot;font-mono&quot;&gt;Page ${rec.currentPage}/${rec.totalPages}&lt;/span&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(1)&quot; ${rec.currentPage &gt;= rec.totalPages ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;xl:col-span-7 space-y-5&quot;&gt;<br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Side-by-Side EIS Fee &amp; CWT Comparison&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] text-slate-400&quot;&gt;Click any row to highlight OCR location&lt;/span&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                  &lt;thead&gt;<br>                    &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Fee Item&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Receipt Actual (Editable)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-right&quot;&gt;Diff&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                    &lt;/tr&gt;<br>                  &lt;/thead&gt;<br>                  &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                    ${page.fees.map(fee =&gt; {<br>                      const val = fee.lastValidation || ValidationEngine.validateFeeRow(fee);<br>                      const isSel = selectedRowId === fee.id;<br>                      return `<br>                        &lt;tr onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${fee.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer transition ${isSel ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/40&#39;}&quot;&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-semibold&quot;&gt;<br>                            ${escapeHtml(fee.expectedName)}<br>                            ${val.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 py-0.2 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-mono text-[11px]&quot;&gt;<br>                            &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                            &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 space-y-1&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                            &lt;div class=&quot;flex gap-1&quot;&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; class=&quot;w-24 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; class=&quot;w-16 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase text-[11px]&quot; /&gt;<br>                            &lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-right font-mono font-bold ${val.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;<br>                            ${escapeHtml(val.amountComparison.difference)}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;<br>                            ${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(val.status)}&lt;/td&gt;<br>                        &lt;/tr&gt;<br>                        &lt;tr class=&quot;bg-slate-50/60 dark:bg-slate-950/40 text-[11px] text-slate-500&quot;&gt;<br>                          &lt;td colspan=&quot;6&quot; class=&quot;px-3 py-1.5&quot;&gt;<br>                            &lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(val.explanation)}<br>                          &lt;/td&gt;<br>                        &lt;/tr&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/tbody&gt;<br>                &lt;/table&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;!-- Pasted Dynamic Column Fields Verification --&gt;<br>            ${(() =&gt; {<br>              const configuredCols = page.fields.filter(f =&gt; f.expectedValue !== &#39;&#39; || f.actualValue !== &#39;&#39;);<br>              if (!configuredCols.length) return &#39;&#39;;<br>              const matchedCols = configuredCols.filter(f =&gt; f.lastValidation &amp;&amp; f.lastValidation.status === &#39;PASS&#39;).length;<br>              return `<br>                &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>                  &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h3&gt;<br>                      &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Auto-searches uploaded/pasted receipt text for every expected column value.&lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                      &lt;span class=&quot;px-2.5 py-1 rounded-full text-xs font-bold ${matchedCols === configuredCols.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;<br>                        ${matchedCols} / ${configuredCols.length} Expected Columns Matched<br>                      &lt;/span&gt;<br>                      &lt;button onclick=&quot;reMatchExpectedColumnsNow()&quot; class=&quot;px-2.5 py-1 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                        Re-Scan Receipt<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                    &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                      &lt;thead&gt;<br>                        &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Col&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Configurable Field Name&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Expected Row Value&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Found on Receipt (Editable)&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                        &lt;/tr&gt;<br>                      &lt;/thead&gt;<br>                      &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                        ${configuredCols.map(f =&gt; {<br>                          const st = f.lastValidation ? f.lastValidation.status : &#39;PENDING&#39;;<br>                          return `<br>                            &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(f.name)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(f.expectedValue)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;/td&gt;<br>                              &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                            &lt;/tr&gt;<br>                          `;<br>                        }).join(&#39;&#39;)}<br>                      &lt;/tbody&gt;<br>                    &lt;/table&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            })()}<br><br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;CWT &amp; Net Settlement Reconciliation&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] font-mono text-slate-400&quot;&gt;Deterministic Engine&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs&quot;&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Expected Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-indigo-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Actual Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-emerald-500 mt-0.5&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;<br>                Formula: ${escapeHtml(fin.formulaExplanation)}<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function correctReceiptFeeValue(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const oldVal = fee[key];<br>      fee[key] = val;<br>      fee.manuallyVerified = true;<br>      fee.ocrConfidence = 100;<br>      logActivity(&#39;Manual OCR Correction&#39;, `${page.name}: ${fee.expectedName} (${key}: &quot;${oldVal}&quot; → &quot;${val}&quot;)`);<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manual receipt value correction&#39;);<br>      showToast(&#39;Updated receipt value &amp; recalculated validation.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function adjustViewerZoom(delta) {<br>      appState.ui.viewerZoom = Math.min(2.5, Math.max(0.5, Number((appState.ui.viewerZoom + delta).toFixed(2))));<br>      renderApp();<br>    }<br><br>    function rotateViewer() {<br>      appState.ui.viewerRotation = (appState.ui.viewerRotation + 90) % 360;<br>      renderApp();<br>    }<br><br>    function changeReceiptPage(delta) {<br>      const rec = getActiveMainPage()?.receipt;<br>      if (!rec) return;<br>      const next = rec.currentPage + delta;<br>      if (next &gt;= 1 &amp;&amp; next &lt;= rec.totalPages) {<br>        rec.currentPage = next;<br>        renderApp();<br>      }<br>    }<br><br>    function removeReceiptAttachment() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.receipt = null;<br>      scheduleAutosave(&#39;Removed receipt attachment&#39;);<br>      showToast(&#39;Receipt removed from &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function handleReceiptDrop(e) {<br>      e.preventDefault();<br>      const file = e.dataTransfer?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    function handleReceiptUpload(e) {<br>      const file = e.target?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    async function processUploadedReceiptFile(file) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br><br>      const allowed = [&#39;image/png&#39;, &#39;image/jpeg&#39;, &#39;image/webp&#39;, &#39;image/svg+xml&#39;, &#39;application/pdf&#39;];<br>      if (!allowed.includes(file.type) &amp;&amp; !/\.(png|jpg|jpeg|webp|pdf)$/i.test(file.name)) {<br>        return showToast(&#39;Unsupported file type. Upload PNG, JPG, WEBP, or PDF.&#39;, &#39;error&#39;);<br>      }<br><br>      showToast(`Processing &quot;${file.name}&quot; for ${page.name}...`, &#39;info&#39;);<br>      const now = new Date().toISOString();<br><br>      if (file.type === &#39;application/pdf&#39; || /\.pdf$/i.test(file.name)) {<br>        try {<br>          if (!window.pdfjsLib) {<br>            throw new Error(&#39;PDF.js is unavailable in this environment.&#39;);<br>          }<br>          const arrayBuf = await file.arrayBuffer();<br>          const pdf = await pdfjsLib.getDocument({ data: arrayBuf }).promise;<br>          const pageImages = [];<br>          let combinedText = &#39;&#39;;<br><br>          for (let pNum = 1; pNum &lt;= pdf.numPages; pNum++) {<br>            const pdfPage = await pdf.getPage(pNum);<br>            const viewport = pdfPage.getViewport({ scale: 1.5 });<br>            const canvas = document.createElement(&#39;canvas&#39;);<br>            canvas.width = viewport.width;<br>            canvas.height = viewport.height;<br>            const ctx = canvas.getContext(&#39;2d&#39;);<br>            await pdfPage.render({ canvasContext: ctx, viewport }).promise;<br>            pageImages.push(canvas.toDataURL(&#39;image/png&#39;));<br><br>            const txtContent = await pdfPage.getTextContent();<br>            const pageText = txtContent.items.map(it =&gt; it.str).join(&#39; &#39;);<br>            combinedText += pageText + &#39;\n&#39;;<br>          }<br><br>          const blocks = OcrMappingEngine.parseReceiptTextToBlocks(combinedText, 1, 94);<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: &#39;application/pdf&#39;,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: pdf.numPages,<br>            pages: pageImages,<br>            ocrRawText: combinedText.trim(),<br>            ocrConfidence: 94,<br>            ocrBlocks: blocks,<br>            history: [{ action: `Uploaded ${pdf.numPages}-page PDF &amp; Extracted Text`, timestamp: now }]<br>          };<br><br>          const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>          logActivity(&#39;Uploaded PDF Receipt&#39;, `${file.name} (${pdf.numPages} pages) → ${page.name}`);<br>          scheduleAutosave(&#39;Uploaded PDF receipt&#39;);<br>          showToast(`PDF loaded (${pdf.numPages} pages). Auto-mapped ${mapRes.autoAccepted} items.`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;PDF parsing error: &#39; + err.message, &#39;error&#39;);<br>        }<br>      } else {<br>        const reader = new FileReader();<br>        reader.onload = async (ev) =&gt; {<br>          const dataUrl = ev.target.result;<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: file.type,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: 1,<br>            pages: [dataUrl],<br>            ocrRawText: &#39;&#39;,<br>            ocrConfidence: 0,<br>            ocrBlocks: [],<br>            history: [{ action: &#39;Uploaded Image Receipt&#39;, timestamp: now }]<br>          };<br>          scheduleAutosave(&#39;Uploaded receipt image&#39;);<br>          renderApp();<br>          await runOcrOnActiveReceipt();<br>        };<br>        reader.onerror = () =&gt; {<br>          showToast(&#39;Unable to read the selected image file.&#39;, &#39;error&#39;);<br>        };<br>        reader.readAsDataURL(file);<br>      }<br>    }<br><br>    async function runOcrOnActiveReceipt() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Attach a receipt first.&#39;, &#39;warning&#39;);<br><br>      const rec = page.receipt;<br>      const imgUrl = rec.pages[rec.currentPage - 1];<br>      if (!imgUrl) return;<br><br>      showToast(&#39;Running local OCR preprocessing &amp; extraction...&#39;, &#39;info&#39;);<br>      try {<br>        const preprocessed = await OcrMappingEngine.preprocessImageCanvas(imgUrl, { grayscale: true, contrast: true, scale: 1.5 });<br>        const ocrOut = await OcrMappingEngine.runRealTesseractOCR(preprocessed);<br>        rec.ocrRawText = ocrOut.text;<br>        rec.ocrConfidence = ocrOut.confidence;<br>        rec.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(ocrOut.text, rec.currentPage, ocrOut.confidence);<br>        rec.history.unshift({ action: `OCR Re-run (${ocrOut.confidence}% confidence)`, timestamp: new Date().toISOString() });<br><br>        const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>        scheduleAutosave(&#39;Completed OCR extraction&#39;);<br>        showToast(`OCR complete (${ocrOut.confidence}% conf). Auto-mapped: ${mapRes.autoAccepted}, Review: ${mapRes.reviewNeeded}`, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;OCR notice: &#39; + err.message + &#39;. You can also enter/edit extracted text in OCR &amp; Doc Intel.&#39;, &#39;warning&#39;);<br>      }<br>    }<br><br>    function reMatchExpectedColumnsNow() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Upload or paste a receipt first.&#39;, &#39;warning&#39;);<br>      const res = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>      scheduleAutosave(&#39;Re-matched expected columns against receipt&#39;);<br>      showToast(`Matched ${res.matched} of ${res.total} expected columns against receipt.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    async function pasteReceiptFromClipboardButton() {<br>      try {<br>        if (!navigator.clipboard || !navigator.clipboard.read) {<br>          return showToast(&#39;Press Ctrl+V (or Cmd+V) directly on the page to paste your receipt screenshot.&#39;, &#39;info&#39;);<br>        }<br>        const items = await navigator.clipboard.read();<br>        for (const item of items) {<br>          const imgType = item.types.find(t =&gt; t.startsWith(&#39;image/&#39;));<br>          if (imgType) {<br>            const blob = await item.getType(imgType);<br>            const file = new File([blob], `pasted_receipt_${Date.now()}.png`, { type: imgType });<br>            await processUploadedReceiptFile(file);<br>            return;<br>          }<br>        }<br>        showToast(&#39;No image found in clipboard. Copy a receipt screenshot first, then press Ctrl+V.&#39;, &#39;warning&#39;);<br>      } catch (e) {<br>        showToast(&#39;Press Ctrl+V (or Cmd+V) anywhere in Receipt Validation to paste your clipboard image.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 5 VIEW: OCR &amp; DOCUMENT INTELLIGENCE<br>     ****************************************************************************/<br>    function renderOcrIntelligenceModule() {<br>      const page = getActiveMainPage();<br>      const rec = page?.receipt;<br>      if (!page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;OCR Preprocessing &amp; Raw Text Editor&lt;/h3&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Edit or paste raw receipt OCR text for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; to re-parse blocks and test smart field mapping.&lt;/p&gt;<br><br>            &lt;div class=&quot;grid grid-cols-2 gap-2 text-xs&quot;&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Grayscale Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Contrast Enhancement (1.35x)&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;1.5x Resolution Upscale&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;CWT Sign Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Extracted / Manual Receipt Text&lt;/label&gt;<br>              &lt;textarea id=&quot;ocr-manual-raw-text&quot; rows=&quot;10&quot; placeholder=&quot;Fee 1 Charge | 1000.00 | NC&amp;#10;Fee 2 Charge | 250.00 | IC&amp;#10;CWT | -50.00 | CWT&quot; class=&quot;w-full p-3 rounded-xl bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono text-xs&quot;&gt;${escapeHtml(rec ? rec.ocrRawText : &#39;&#39;)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;applyManualOcrTextAndMap()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                Parse Text &amp; Auto-Map to Main Page<br>              &lt;/button&gt;<br>              ${rec ? `&lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Re-Run Image OCR&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Detected Document Structure &amp; Smart Mapping&lt;/h3&gt;<br>              &lt;span class=&quot;text-xs text-slate-400&quot;&gt;Auto-Accept Threshold: ≥${appState.settings.autoAcceptConfidenceThreshold}%&lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>              &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                &lt;thead&gt;<br>                  &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Page&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Detected Label&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Amount&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Code&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Mapped Main Page Fee&lt;/th&gt;<br>                  &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                  ${!rec || !(rec.ocrBlocks || []).length ? `<br>                    &lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No OCR blocks detected yet. Upload a receipt or parse raw text on the left.&lt;/td&gt;&lt;/tr&gt;<br>                  ` : rec.ocrBlocks.map(blk =&gt; `<br>                    &lt;tr&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;P${blk.page}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-medium&quot;&gt;${escapeHtml(blk.detectedName)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;${escapeHtml(blk.detectedAmount || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-indigo-500&quot;&gt;${escapeHtml(blk.detectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center font-mono ${blk.confidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-emerald-500&#39;}&quot;&gt;${blk.confidence}%&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;select onchange=&quot;manuallyMapOcrBlock(&#39;${blk.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                          &lt;option value=&quot;&quot;&gt;-- Unmapped --&lt;/option&gt;<br>                          ${page.fees.map(f =&gt; `&lt;option value=&quot;${f.id}&quot; ${blk.mappedToFeeId === f.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(f.expectedName)} (${escapeHtml(f.expectedCode)})&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `).join(&#39;&#39;)}<br>                &lt;/tbody&gt;<br>              &lt;/table&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function applyManualOcrTextAndMap() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const rawText = document.getElementById(&#39;ocr-manual-raw-text&#39;).value;<br>      const now = new Date().toISOString();<br>      if (!page.receipt) {<br>        page.receipt = {<br>          id: &#39;rec_manual_&#39; + Date.now(),<br>          fileName: &#39;manual_ocr_transcript.txt&#39;,<br>          mimeType: &#39;text/plain&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [],<br>          ocrRawText: rawText,<br>          ocrConfidence: 95,<br>          ocrBlocks: [],<br>          history: []<br>        };<br>      }<br>      page.receipt.ocrRawText = rawText;<br>      page.receipt.ocrConfidence = 95;<br>      page.receipt.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(rawText, page.receipt.currentPage || 1, 95);<br>      page.receipt.history.unshift({ action: &#39;Manual Text Parsed &amp; Mapped&#39;, timestamp: now });<br><br>      const res = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>      scheduleAutosave(&#39;Mapped manual OCR text&#39;);<br>      showToast(`Parsed ${page.receipt.ocrBlocks.length} blocks. Auto-mapped: ${res.autoAccepted}, Review: ${res.reviewNeeded}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function manuallyMapOcrBlock(blockId, feeId) {<br>      const page = getActiveMainPage();<br>      const blk = page?.receipt?.ocrBlocks.find(b =&gt; b.id === blockId);<br>      if (!blk) return;<br>      blk.mappedToFeeId = feeId || null;<br>      if (feeId) {<br>        const fee = page.fees.find(f =&gt; f.id === feeId);<br>        if (fee) {<br>          fee.actualName = blk.detectedName;<br>          fee.actualAmount = blk.detectedAmount;<br>          fee.actualCode = blk.detectedCode || fee.actualCode;<br>          fee.ocrConfidence = blk.confidence;<br>          fee.sourceLocation = `Page ${blk.page} (Manual Map)`;<br>        }<br>      }<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manually mapped OCR block&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 6 VIEW: QA SCREENSHOT STUDIO &amp; EVIDENCE ANNOTATIONS (1-200+)<br>     ****************************************************************************/<br>    let activeStudioScreenshotIdx = 0;<br><br>    function getNextAvailableQaLabel(page) {<br>      const used = new Set((page?.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      const max = appState.settings.qaLabelMax || 200;<br>      for (let i = 1; i &lt;= max; i++) {<br>        if (!used.has(i)) return i;<br>      }<br>      return max + 1;<br>    }<br><br>    function renderScreenshotStudioModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No active project.&lt;/div&gt;`;<br><br>      const screenshots = proj.screenshots || [];<br>      if (activeStudioScreenshotIdx &gt;= screenshots.length) activeStudioScreenshotIdx = Math.max(0, screenshots.length - 1);<br>      const activeShot = screenshots[activeStudioScreenshotIdx] || null;<br>      const nextLabel = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br><br>      const labelOptions = [];<br>      const maxLbl = appState.settings.qaLabelMax || 200;<br>      const usedLabels = new Set((page.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      for (let i = 1; i &lt;= maxLbl; i++) {<br>        labelOptions.push(`&lt;option value=&quot;${i}&quot; ${i === nextLabel ? &#39;selected&#39; : &#39;&#39;}&gt;QA-${i} ${usedLabels.has(i) ? &#39;(Assigned)&#39; : &#39;&#39;}&lt;/option&gt;`);<br>      }<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;image-plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Upload Screenshots&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; multiple onchange=&quot;handleUploadScreenshots(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;captureBrowserScreen()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>              &lt;i data-lucide=&quot;monitor-dot&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Capture Screen (Browser Permission)&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;vertical&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Vertical (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;horizontal&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Horizontal (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;resetMergeHistory()&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Reset Merge History (${(proj.mergeHistory || []).length})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Captures (${screenshots.length})&lt;/h3&gt;<br>              &lt;span class=&quot;text-[10px] text-slate-400&quot;&gt;Check to merge&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${screenshots.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No screenshots yet.&lt;/div&gt;` : screenshots.map((scr, idx) =&gt; {<br>                const isChecked = appState.ui.selectedScreenshotsForMerge.includes(scr.id);<br>                const isActive = idx === activeStudioScreenshotIdx;<br>                return `<br>                  &lt;div onclick=&quot;activeStudioScreenshotIdx = ${idx}; renderApp();&quot; class=&quot;p-2.5 rounded-xl border cursor-pointer transition ${isActive ? &#39;border-brand-500 bg-brand-500/10&#39; : &#39;border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                    &lt;div class=&quot;flex items-center justify-between gap-2 mb-1.5&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                      &lt;label class=&quot;inline-flex items-center gap-1.5 text-[11px] font-semibold truncate&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleScreenshotMergeSelect(&#39;${scr.id}&#39;)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                        &lt;span class=&quot;truncate&quot;&gt;${escapeHtml(scr.name)}&lt;/span&gt;<br>                      &lt;/label&gt;<br>                      &lt;div class=&quot;flex items-center gap-1 shrink-0&quot;&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, -1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;↑&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, 1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;↓&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteScreenshot(&#39;${scr.id}&#39;)&quot; class=&quot;text-rose-500 hover:opacity-80&quot; title=&quot;Delete&quot;&gt;&amp;times;&lt;/button&gt;<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;img src=&quot;${scr.dataUrl}&quot; alt=&quot;${escapeHtml(scr.name)}&quot; class=&quot;w-full h-24 object-cover rounded-lg bg-slate-950&quot; /&gt;<br>                    &lt;div class=&quot;flex items-center justify-between text-[10px] text-slate-400 mt-1&quot;&gt;<br>                      &lt;span&gt;${scr.isMerged ? &#39;Merged Output&#39; : escapeHtml(scr.source)}&lt;/span&gt;<br>                      &lt;a href=&quot;${scr.dataUrl}&quot; download=&quot;${escapeHtml(scr.name)}.png&quot; onclick=&quot;event.stopPropagation()&quot; class=&quot;text-brand-500 hover:underline&quot;&gt;Download&lt;/a&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 pb-2 border-b border-slate-200 dark:border-slate-800&quot;&gt;<br>              &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;rect&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;rect&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Rectangle&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;circle&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;circle&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Circle&lt;/button&gt;<br>                &lt;input type=&quot;color&quot; value=&quot;${appState.ui.annotationColor}&quot; onchange=&quot;appState.ui.annotationColor = this.value&quot; class=&quot;w-8 h-8 rounded cursor-pointer bg-transparent&quot; title=&quot;Annotation Color&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;flex items-center gap-2 text-xs&quot;&gt;<br>                &lt;select onchange=&quot;appState.ui.selectedQaLabel = Number(this.value)&quot; class=&quot;px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot;&gt;<br>                  ${labelOptions.join(&#39;&#39;)}<br>                &lt;/select&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1 cursor-pointer&quot; title=&quot;Auto-increment to next unused QA label&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${appState.settings.qaAutoIncrement ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.qaAutoIncrement = this.checked; scheduleAutosave(&#39;Toggled QA auto-increment&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;Auto-Inc&lt;/span&gt;<br>                &lt;/label&gt;<br>                &lt;button onclick=&quot;increaseQaLabelLimit()&quot; class=&quot;px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[11px]&quot; title=&quot;Increase Max QA Labels&quot;&gt;+50&lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div id=&quot;annotation-stage&quot; class=&quot;relative min-h-[420px] bg-slate-950 rounded-xl overflow-auto flex items-center justify-center p-2 select-none&quot;&gt;<br>              ${activeShot ? `<br>                &lt;div id=&quot;annotation-canvas-wrapper&quot; class=&quot;relative inline-block cursor-crosshair&quot;&gt;<br>                  &lt;img id=&quot;annotation-base-img&quot; src=&quot;${activeShot.dataUrl}&quot; alt=&quot;Evidence Canvas&quot; class=&quot;max-w-full rounded-lg pointer-events-none&quot; /&gt;<br>                  &lt;svg id=&quot;annotation-svg-overlay&quot; class=&quot;absolute inset-0 w-full h-full&quot;&gt;<br>                    ${(page.annotations || []).map(ann =&gt; {<br>                      const isSel = appState.ui.selectedAnnotationId === ann.id;<br>                      const shape = ann.type === &#39;circle&#39;<br>                        ? `&lt;ellipse cx=&quot;${ann.x + ann.w / 2}&quot; cy=&quot;${ann.y + ann.h / 2}&quot; rx=&quot;${Math.abs(ann.w / 2)}&quot; ry=&quot;${Math.abs(ann.h / 2)}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`<br>                        : `&lt;rect x=&quot;${ann.x}&quot; y=&quot;${ann.y}&quot; width=&quot;${ann.w}&quot; height=&quot;${ann.h}&quot; rx=&quot;4&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`;<br>                      return `<br>                        &lt;g onclick=&quot;event.stopPropagation(); appState.ui.selectedAnnotationId = &#39;${ann.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer&quot;&gt;<br>                          ${shape}<br>                          &lt;rect x=&quot;${ann.x}&quot; y=&quot;${Math.max(0, ann.y - 20)}&quot; width=&quot;${Math.max(68, ann.label.length * 7 + 12)}&quot; height=&quot;18&quot; rx=&quot;4&quot; fill=&quot;${ann.color}&quot; /&gt;<br>                          &lt;text x=&quot;${ann.x + 6}&quot; y=&quot;${Math.max(13, ann.y - 7)}&quot; font-family=&quot;sans-serif&quot; font-size=&quot;11&quot; font-weight=&quot;bold&quot; fill=&quot;#ffffff&quot;&gt;${escapeHtml(ann.label)}&lt;/text&gt;<br>                        &lt;/g&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/svg&gt;<br>                &lt;/div&gt;<br>              ` : `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;Upload or capture a screenshot to draw QA annotations.&lt;/div&gt;`}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center justify-between text-[11px] text-slate-400&quot;&gt;<br>              &lt;span&gt;Click &amp; drag on the image to draw a QA annotation for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt;.&lt;/span&gt;<br>              ${activeShot ? `&lt;button onclick=&quot;exportAnnotatedEvidenceImage()&quot; class=&quot;text-brand-500 font-semibold hover:underline&quot;&gt;Export Annotated PNG&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Page Annotations (${(page.annotations || []).length})&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${(page.annotations || []).length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No annotations on this Main Page yet.&lt;/div&gt;` : (page.annotations || []).map(ann =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${appState.ui.selectedAnnotationId === ann.id ? &#39;border-brand-500 bg-brand-500/5&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} space-y-2 text-xs&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                    &lt;span class=&quot;font-bold&quot; style=&quot;color:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/span&gt;<br>                    &lt;button onclick=&quot;deleteAnnotation(&#39;${ann.id}&#39;)&quot; class=&quot;text-rose-500 hover:underline text-[11px]&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                  &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.comment || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;comment&#39;, this.value)&quot; placeholder=&quot;Evidence comment...&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                  &lt;div class=&quot;grid grid-cols-2 gap-1.5&quot;&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.fieldRef || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;fieldRef&#39;, this.value)&quot; placeholder=&quot;Linked Field&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.defectId || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;defectId&#39;, this.value)&quot; placeholder=&quot;Defect ID&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-1 pt-1&quot;&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, -10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;←&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;→&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, -10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↑&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↓&lt;/button&gt;<br>                    &lt;button onclick=&quot;resizeAnnotation(&#39;${ann.id}&#39;, 15, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;+Size&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initAnnotationCanvasEvents() {<br>      const wrapper = document.getElementById(&#39;annotation-canvas-wrapper&#39;);<br>      if (!wrapper) return;<br>      let startX = 0, startY = 0, drawing = false;<br><br>      wrapper.onmousedown = (e) =&gt; {<br>        const rect = wrapper.getBoundingClientRect();<br>        startX = e.clientX - rect.left;<br>        startY = e.clientY - rect.top;<br>        drawing = true;<br>      };<br><br>      wrapper.onmouseup = (e) =&gt; {<br>        if (!drawing) return;<br>        drawing = false;<br>        const rect = wrapper.getBoundingClientRect();<br>        const endX = e.clientX - rect.left;<br>        const endY = e.clientY - rect.top;<br>        const w = Math.abs(endX - startX);<br>        const h = Math.abs(endY - startY);<br>        if (w &lt; 12 || h &lt; 12) return;<br><br>        const page = getActiveMainPage();<br>        if (!page) return;<br>        const qaNum = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br>        if ((page.annotations || []).some(a =&gt; Number(a.qaLabel) === Number(qaNum))) {<br>          return showToast(`QA-${qaNum} is already assigned on ${page.name}. Pick an unused label.`, &#39;warning&#39;);<br>        }<br><br>        page.annotations = page.annotations || [];<br>        const newAnn = {<br>          id: &#39;ann_&#39; + Date.now(),<br>          qaLabel: qaNum,<br>          type: appState.ui.annotationTool,<br>          x: Math.round(Math.min(startX, endX)),<br>          y: Math.round(Math.min(startY, endY)),<br>          w: Math.round(w),<br>          h: Math.round(h),<br>          color: appState.ui.annotationColor,<br>          label: `QA-${qaNum}`,<br>          comment: &#39;&#39;,<br>          fieldRef: &#39;&#39;,<br>          testCaseId: &#39;&#39;,<br>          defectId: &#39;&#39;<br>        };<br>        page.annotations.push(newAnn);<br>        appState.ui.selectedAnnotationId = newAnn.id;<br>        if (appState.settings.qaAutoIncrement) {<br>          appState.ui.selectedQaLabel = getNextAvailableQaLabel(page);<br>        }<br>        scheduleAutosave(&#39;Added evidence annotation&#39;);<br>        renderApp();<br>      };<br>    }<br><br>    function nudgeAnnotation(annId, dx, dy) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.x = Math.max(0, ann.x + dx);<br>      ann.y = Math.max(0, ann.y + dy);<br>      scheduleAutosave(&#39;Moved annotation&#39;);<br>      renderApp();<br>    }<br><br>    function resizeAnnotation(annId, dw, dh) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.w = Math.max(20, ann.w + dw);<br>      ann.h = Math.max(20, ann.h + dh);<br>      scheduleAutosave(&#39;Resized annotation&#39;);<br>      renderApp();<br>    }<br><br>    function updateAnnotationProp(annId, key, val) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann[key] = val;<br>      scheduleAutosave(&#39;Updated annotation metadata&#39;);<br>    }<br><br>    function deleteAnnotation(annId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.annotations = (page.annotations || []).filter(a =&gt; a.id !== annId);<br>      scheduleAutosave(&#39;Deleted annotation&#39;);<br>      renderApp();<br>    }<br><br>    function increaseQaLabelLimit() {<br>      appState.settings.qaLabelMax = (appState.settings.qaLabelMax || 200) + 50;<br>      scheduleAutosave(&#39;Increased QA label count&#39;);<br>      showToast(`QA label pool increased to 1–${appState.settings.qaLabelMax}.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function handleUploadScreenshots(e) {<br>      const proj = getActiveProject();<br>      const files = Array.from(e.target.files || []);<br>      if (!proj || !files.length) return;<br>      files.forEach(file =&gt; {<br>        const reader = new FileReader();<br>        reader.onload = (ev) =&gt; {<br>          proj.screenshots.push({<br>            id: &#39;scr_&#39; + Date.now() + &#39;_&#39; + Math.random().toString(36).slice(2, 5),<br>            name: file.name,<br>            dataUrl: ev.target.result,<br>            capturedAt: new Date().toISOString(),<br>            source: &#39;Uploaded File&#39;,<br>            isMerged: false<br>          });<br>          scheduleAutosave(&#39;Uploaded screenshot&#39;);<br>          renderApp();<br>        };<br>        reader.readAsDataURL(file);<br>      });<br>    }<br><br>    async function captureBrowserScreen() {<br>      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {<br>        return showToast(&#39;Screen capture API is not supported in this browser context.&#39;, &#39;warning&#39;);<br>      }<br>      try {<br>        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br>        const video = document.createElement(&#39;video&#39;);<br>        video.srcObject = stream;<br>        await video.play();<br><br>        const canvas = document.createElement(&#39;canvas&#39;);<br>        canvas.width = video.videoWidth;<br>        canvas.height = video.videoHeight;<br>        canvas.getContext(&#39;2d&#39;).drawImage(video, 0, 0);<br>        stream.getTracks().forEach(t =&gt; t.stop());<br><br>        const proj = getActiveProject();<br>        proj.screenshots.push({<br>          id: &#39;scr_cap_&#39; + Date.now(),<br>          name: `Screen_Capture_${new Date().toISOString().slice(11, 19).replace(/:/g, &#39;-&#39;)}.png`,<br>          dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>          capturedAt: new Date().toISOString(),<br>          source: &#39;Browser Screen Share&#39;,<br>          isMerged: false<br>        });<br>        activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>        scheduleAutosave(&#39;Captured browser screen&#39;);<br>        showToast(&#39;Screen captured and added to QA Studio.&#39;, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;Screen capture cancelled or permission denied.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    function toggleScreenshotMergeSelect(scrId) {<br>      const sel = appState.ui.selectedScreenshotsForMerge;<br>      const idx = sel.indexOf(scrId);<br>      if (idx &gt;= 0) sel.splice(idx, 1);<br>      else sel.push(scrId);<br>      renderApp();<br>    }<br><br>    function moveScreenshot(idx, dir) {<br>      const proj = getActiveProject();<br>      const target = idx + dir;<br>      if (!proj || target &lt; 0 || target &gt;= proj.screenshots.length) return;<br>      const tmp = proj.screenshots[idx];<br>      proj.screenshots[idx] = proj.screenshots[target];<br>      proj.screenshots[target] = tmp;<br>      scheduleAutosave(&#39;Reordered screenshots&#39;);<br>      renderApp();<br>    }<br><br>    function deleteScreenshot(scrId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.screenshots = proj.screenshots.filter(s =&gt; s.id !== scrId);<br>      appState.ui.selectedScreenshotsForMerge = appState.ui.selectedScreenshotsForMerge.filter(id =&gt; id !== scrId);<br>      scheduleAutosave(&#39;Deleted screenshot&#39;);<br>      renderApp();<br>    }<br><br>    async function mergeSelectedScreenshots(direction = &#39;vertical&#39;) {<br>      const proj = getActiveProject();<br>      const ids = appState.ui.selectedScreenshotsForMerge;<br>      if (!proj || ids.length &lt; 2) {<br>        return showToast(&#39;Select at least 2 screenshots using the checkboxes to merge.&#39;, &#39;warning&#39;);<br>      }<br>      const chosen = ids.map(id =&gt; proj.screenshots.find(s =&gt; s.id === id)).filter(Boolean);<br>      const loadedImgs = await Promise.all(chosen.map(s =&gt; new Promise(res =&gt; {<br>        const img = new Image();<br>        img.onload = () =&gt; res(img);<br>        img.src = s.dataUrl;<br>      })));<br><br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      if (direction === &#39;vertical&#39;) {<br>        canvas.width = Math.max(...loadedImgs.map(i =&gt; i.width));<br>        canvas.height = loadedImgs.reduce((sum, i) =&gt; sum + i.height, 0);<br>      } else {<br>        canvas.width = loadedImgs.reduce((sum, i) =&gt; sum + i.width, 0);<br>        canvas.height = Math.max(...loadedImgs.map(i =&gt; i.height));<br>      }<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      let offset = 0;<br>      loadedImgs.forEach(img =&gt; {<br>        if (direction === &#39;vertical&#39;) {<br>          ctx.drawImage(img, 0, offset);<br>          offset += img.height;<br>        } else {<br>          ctx.drawImage(img, offset, 0);<br>          offset += img.width;<br>        }<br>      });<br><br>      const mergedObj = {<br>        id: &#39;scr_merged_&#39; + Date.now(),<br>        name: `Merged_${direction}_${chosen.length}imgs.png`,<br>        dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>        capturedAt: new Date().toISOString(),<br>        source: `Merged (${direction})`,<br>        isMerged: true<br>      };<br>      proj.screenshots.push(mergedObj);<br>      proj.mergeHistory = proj.mergeHistory || [];<br>      proj.mergeHistory.push({ id: mergedObj.id, sourceIds: [...ids], direction, timestamp: mergedObj.capturedAt });<br>      activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>      scheduleAutosave(&#39;Merged screenshots&#39;);<br>      showToast(`Merged ${chosen.length} screenshots (${direction}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function resetMergeHistory() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.mergeHistory = [];<br>      appState.ui.selectedScreenshotsForMerge = [];<br>      scheduleAutosave(&#39;Reset merge history&#39;);<br>      showToast(&#39;Merge selection &amp; history cleared.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportAnnotatedEvidenceImage() {<br>      const img = document.getElementById(&#39;annotation-base-img&#39;);<br>      const page = getActiveMainPage();<br>      if (!img || !page) return;<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      canvas.width = img.naturalWidth || img.width;<br>      canvas.height = img.naturalHeight || img.height;<br>      const scaleX = canvas.width / img.width;<br>      const scaleY = canvas.height / img.height;<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>      (page.annotations || []).forEach(ann =&gt; {<br>        ctx.strokeStyle = ann.color;<br>        ctx.lineWidth = 3 * scaleX;<br>        if (ann.type === &#39;circle&#39;) {<br>          ctx.beginPath();<br>          ctx.ellipse((ann.x + ann.w / 2) * scaleX, (ann.y + ann.h / 2) * scaleY, Math.abs(ann.w / 2) * scaleX, Math.abs(ann.h / 2) * scaleY, 0, 0, Math.PI * 2);<br>          ctx.stroke();<br>        } else {<br>          ctx.strokeRect(ann.x * scaleX, ann.y * scaleY, ann.w * scaleX, ann.h * scaleY);<br>        }<br>        ctx.fillStyle = ann.color;<br>        ctx.fillRect(ann.x * scaleX, Math.max(0, (ann.y - 22) * scaleY), 110 * scaleX, 22 * scaleY);<br>        ctx.fillStyle = &#39;#ffffff&#39;;<br>        ctx.font = `bold ${Math.round(12 * scaleX)}px sans-serif`;<br>        ctx.fillText(ann.label, (ann.x + 6) * scaleX, Math.max(15 * scaleY, (ann.y - 6) * scaleY));<br>      });<br><br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = canvas.toDataURL(&#39;image/png&#39;);<br>      a.download = `${page.name.replace(/[^a-z0-9]/gi, &#39;_&#39;)}_annotated_evidence.png`;<br>      a.click();<br>      showToast(&#39;Exported annotated evidence PNG.&#39;, &#39;success&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 7 VIEW: TEST CASE MANAGEMENT<br>     ****************************************************************************/<br><br>    /****************************************************************************<br>     * EVIDENCE SCREENSHOTS (opened from Receipt Validation)<br>     * Copy of the QA Screenshot Studio workflow, with its own screenshots &amp; boxes.<br>     * QA-n box  &lt;-&gt;  column Cn.  The text read inside a box fills the field&#39;s<br>     * &quot;Found on Receipt (Editable)&quot; value, same value Re-Run OCR &amp; Auto-Match fills.<br>     ****************************************************************************/<br>    let evActiveShotIdx = 0;<br>    let evFieldMapShowAll = false;<br>    const evReadingIds = new Set();<br><br>    // Main toggle (global setting, so it follows every Main Page): where a box value is written<br>    function evTarget() { return appState.settings.evTarget === &#39;actual&#39; ? &#39;actual&#39; : &#39;expected&#39;; }<br>    function evTargetKey() { return evTarget() === &#39;actual&#39; ? &#39;actualValue&#39; : &#39;expectedValue&#39;; }<br>    function evSourceKey() { return evTarget() === &#39;actual&#39; ? &#39;actualSource&#39; : &#39;expectedSource&#39;; }<br>    function evTargetLabel() { return evTarget() === &#39;actual&#39; ? &#39;Found on Receipt&#39; : &#39;Expected Value&#39;; }<br><br>    function evSetTarget(t) {<br>      appState.settings.evTarget = t === &#39;actual&#39; ? &#39;actual&#39; : &#39;expected&#39;;<br>      scheduleAutosave(&#39;Changed evidence box target&#39;);<br>      showToast(`Box values now go to ${evTargetLabel()} on every Main Page.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function evApplyStored() {<br>      const page = getActiveMainPage();<br>      const list = evAnns(page).filter(a =&gt; String(a.value || &#39;&#39;).trim() !== &#39;&#39;);<br>      if (!list.length) return showToast(&#39;No stored box values on this Main Page yet. Use Read all boxes first.&#39;, &#39;warning&#39;);<br>      list.forEach(a =&gt; evAssign(page, a));<br>      scheduleAutosave(&#39;Applied stored box values&#39;);<br>      showToast(`Applied ${list.length} box value(s) to ${evTargetLabel()}.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function padC(n) { return &#39;C&#39; + String(n).padStart(2, &#39;0&#39;); }<br>    function evShots(page) { page.evidenceShots = page.evidenceShots || []; return page.evidenceShots; }<br>    function evAnns(page) { page.evidenceAnnotations = page.evidenceAnnotations || []; return page.evidenceAnnotations; }<br>    function evVisible(ann, shot) { return !ann.screenshotId || !shot || ann.screenshotId === shot.id; }<br>    function evField(page, n) { return (page.fields || []).find(f =&gt; Number(f.number) === Number(n)) || null; }<br>    function evTag(ann) { return `${ann.label} ▸ ${padC(ann.qaLabel)}`; }<br>    function evRerender() { if (appState.activeModule === &#39;evidence&#39;) renderApp(); }<br><br>    function evNextLabel(page) {<br>      const used = new Set(evAnns(page).map(a =&gt; Number(a.qaLabel)));<br>      const max = appState.settings.qaLabelMax || 200;<br>      for (let i = 1; i &lt;= max; i++) if (!used.has(i)) return i;<br>      return max + 1;<br>    }<br><br>    function evEnsureFields(page, n) {<br>      page.fields = page.fields || [];<br>      while (page.fields.length &lt; n) {<br>        const num = page.fields.length + 1;<br>        page.fields.push({<br>          id: `fld_${num}_${Date.now()}_${Math.random().toString(36).slice(2, 5)}`,<br>          number: num, name: `Custom Field ${num}`, expectedValue: &#39;&#39;, actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;, validationRule: &#39;Exact / Tolerance Match&#39;, ocrEnabled: true,<br>          required: false, tolerance: 0.01, description: `Dynamic Column #${num}`,<br>          pageOverride: false, enabled: true<br>        });<br>      }<br>    }<br><br>    function evLink(page, ann) {<br>      evEnsureFields(page, Number(ann.qaLabel));<br>      const f = evField(page, ann.qaLabel);<br>      if (f) ann.fieldId = f.id;<br>      pushSharedHeadersFrom(page);<br>      return f;<br>    }<br><br>    // Box value -&gt; Expected Value of the matching column<br>    function evAssign(page, ann) {<br>      const f = evLink(page, ann);<br>      if (!f) return;<br>      f[evTargetKey()] = ann.value || &#39;&#39;;<br>      f[evSourceKey()] = ann.id;<br>      f.enabled = true;<br>      ValidationEngine.validateMainPage(page);<br>    }<br><br>    function evAddShot(name, dataUrl, source, merged = false, targetPage = null) {<br>      const page = targetPage || getActiveMainPage();<br>      if (!page) return;<br>      const shot = {<br>        id: &#39;evs_&#39; + Date.now() + &#39;_&#39; + Math.random().toString(36).slice(2, 5),<br>        name, dataUrl, source, isMerged: merged, capturedAt: new Date().toISOString()<br>      };<br>      evShots(page).push(shot);<br>      evActiveShotIdx = page.evidenceShots.length - 1;<br>      page.evidenceShotId = shot.id;<br>      scheduleAutosave(&#39;Added evidence screenshot&#39;);<br>      evRerender();<br>    }<br><br>    function evAddShotFromFile(file, nameOverride) {<br>      const target = getActiveMainPage();<br>      return new Promise(resolve =&gt; {<br>        const reader = new FileReader();<br>        reader.onload = ev =&gt; { evAddShot(nameOverride || file.name, ev.target.result, &#39;Uploaded File&#39;, false, target); resolve(); };<br>        reader.onerror = () =&gt; { showToast(&#39;Unable to read the image file.&#39;, &#39;error&#39;); resolve(); };<br>        reader.readAsDataURL(file);<br>      });<br>    }<br><br>    function evUpload(e) {<br>      Array.from(e.target.files || []).forEach(f =&gt; evAddShotFromFile(f));<br>    }<br><br>    async function evPasteButton() {<br>      try {<br>        if (!navigator.clipboard || !navigator.clipboard.read) return showToast(&#39;Press Ctrl+V on this screen to paste an image.&#39;, &#39;info&#39;);<br>        const items = await navigator.clipboard.read();<br>        for (const item of items) {<br>          const t = item.types.find(x =&gt; x.startsWith(&#39;image/&#39;));<br>          if (t) { const blob = await item.getType(t); await evAddShotFromFile(blob, `pasted_evidence_${Date.now()}.png`); return; }<br>        }<br>        showToast(&#39;No image in clipboard. Copy a screenshot, then press Ctrl+V.&#39;, &#39;warning&#39;);<br>      } catch (e) { showToast(&#39;Press Ctrl+V on this screen to paste your clipboard image.&#39;, &#39;info&#39;); }<br>    }<br><br>    async function evCapture() {<br>      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) return showToast(&#39;Screen capture is not supported here.&#39;, &#39;warning&#39;);<br>      try {<br>        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br>        const video = document.createElement(&#39;video&#39;);<br>        video.srcObject = stream;<br>        await video.play();<br>        const canvas = document.createElement(&#39;canvas&#39;);<br>        canvas.width = video.videoWidth; canvas.height = video.videoHeight;<br>        canvas.getContext(&#39;2d&#39;).drawImage(video, 0, 0);<br>        stream.getTracks().forEach(t =&gt; t.stop());<br>        evAddShot(`Evidence_Capture_${new Date().toISOString().slice(11, 19).replace(/:/g, &#39;-&#39;)}.png`, canvas.toDataURL(&#39;image/png&#39;), &#39;Browser Screen Share&#39;);<br>        showToast(&#39;Screen captured into Evidence Screenshots.&#39;, &#39;success&#39;);<br>      } catch (err) { showToast(&#39;Screen capture cancelled or permission denied.&#39;, &#39;info&#39;); }<br>    }<br><br>    function evSelectShot(idx) {<br>      evActiveShotIdx = idx;<br>      const page = getActiveMainPage();<br>      const shot = evShots(page)[idx];<br>      if (page &amp;&amp; shot) page.evidenceShotId = shot.id;<br>      scheduleAutosave(&#39;Selected evidence screenshot&#39;);<br>      renderApp();<br>    }<br><br>    function evToggleMerge(id) {<br>      const sel = appState.ui.evMergeSel = appState.ui.evMergeSel || [];<br>      const i = sel.indexOf(id);<br>      if (i &gt;= 0) sel.splice(i, 1); else sel.push(id);<br>      renderApp();<br>    }<br><br>    function evMoveShot(idx, dir) {<br>      const shots = evShots(getActiveMainPage());<br>      const t = idx + dir;<br>      if (t &lt; 0 || t &gt;= shots.length) return;<br>      [shots[idx], shots[t]] = [shots[t], shots[idx]];<br>      scheduleAutosave(&#39;Reordered evidence screenshots&#39;);<br>      renderApp();<br>    }<br><br>    function evDeleteShot(id) {<br>      const page = getActiveMainPage();<br>      page.evidenceShots = evShots(page).filter(s =&gt; s.id !== id);<br>      appState.ui.evMergeSel = (appState.ui.evMergeSel || []).filter(x =&gt; x !== id);<br>      scheduleAutosave(&#39;Deleted evidence screenshot&#39;);<br>      renderApp();<br>    }<br><br>    async function evMerge(direction) {<br>      const page = getActiveMainPage();<br>      const ids = appState.ui.evMergeSel || [];<br>      if (ids.length &lt; 2) return showToast(&#39;Tick at least 2 evidence screenshots to merge.&#39;, &#39;warning&#39;);<br>      const chosen = ids.map(id =&gt; evShots(page).find(s =&gt; s.id === id)).filter(Boolean);<br>      const imgs = await Promise.all(chosen.map(sh =&gt; new Promise(res =&gt; { const im = new Image(); im.onload = () =&gt; res(im); im.src = sh.dataUrl; })));<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      if (direction === &#39;vertical&#39;) { canvas.width = Math.max(...imgs.map(i =&gt; i.width)); canvas.height = imgs.reduce((a, i) =&gt; a + i.height, 0); }<br>      else { canvas.width = imgs.reduce((a, i) =&gt; a + i.width, 0); canvas.height = Math.max(...imgs.map(i =&gt; i.height)); }<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      let off = 0;<br>      imgs.forEach(im =&gt; { if (direction === &#39;vertical&#39;) { ctx.drawImage(im, 0, off); off += im.height; } else { ctx.drawImage(im, off, 0); off += im.width; } });<br>      page.evidenceMergeHistory = page.evidenceMergeHistory || [];<br>      page.evidenceMergeHistory.push({ sourceIds: [...ids], direction, timestamp: new Date().toISOString() });<br>      evAddShot(`Evidence_Merged_${direction}_${chosen.length}imgs.png`, canvas.toDataURL(&#39;image/png&#39;), `Merged (${direction})`, true, page);<br>      showToast(`Merged ${chosen.length} evidence screenshots (${direction}).`, &#39;success&#39;);<br>    }<br><br>    function evResetMerge() {<br>      const page = getActiveMainPage();<br>      page.evidenceMergeHistory = [];<br>      appState.ui.evMergeSel = [];<br>      scheduleAutosave(&#39;Reset evidence merge history&#39;);<br>      renderApp();<br>    }<br><br>    function evToggleQuickList() { appState.ui.evQuickListOpen = appState.ui.evQuickListOpen === false; renderApp(); }<br>    function evStepPage(dir) {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.mainPages.length) return;<br>      const idx = proj.mainPages.findIndex(mp =&gt; mp.id === appState.activeMainPageId);<br>      switchActiveMainPage(proj.mainPages[(Math.max(0, idx) + dir + proj.mainPages.length) % proj.mainPages.length].id);<br>    }<br>    function evToggleAutoAssign(c) { appState.settings.evAutoAssign = Boolean(c); scheduleAutosave(&#39;Toggled evidence auto-read&#39;); renderApp(); }<br>    function evToggleShowAll() { evFieldMapShowAll = !evFieldMapShowAll; renderApp(); }<br>    function evStartDraw(n) { appState.ui.evPendingLabel = Number(n); showToast(`Draw a box on the screenshot: it becomes QA-${n} and fills ${evTargetLabel()} of ${padC(n)}. (Esc to cancel)`, &#39;info&#39;); renderApp(); }<br>    function evCancelPending() { appState.ui.evPendingLabel = null; renderApp(); }<br><br>    function evFocus(annId) {<br>      const proj = getActiveProject(); const page = getActiveMainPage();<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      appState.ui.evSelectedAnnId = annId;<br>      const si = ann.screenshotId ? evShots(page).findIndex(s =&gt; s.id === ann.screenshotId) : -1;<br>      if (si &gt;= 0) { evActiveShotIdx = si; page.evidenceShotId = ann.screenshotId; }<br>      renderApp();<br>    }<br><br>    function evNudge(annId, dx, dy) { const a = evAnns(getActiveMainPage()).find(x =&gt; x.id === annId); if (!a) return; a.x = Math.max(0, a.x + dx); a.y = Math.max(0, a.y + dy); scheduleAutosave(&#39;Moved evidence box&#39;); renderApp(); }<br>    function evResize(annId, dw, dh) { const a = evAnns(getActiveMainPage()).find(x =&gt; x.id === annId); if (!a) return; a.w = Math.max(20, a.w + dw); a.h = Math.max(20, a.h + dh); scheduleAutosave(&#39;Resized evidence box&#39;); renderApp(); }<br>    function evUpdateProp(annId, key, val) { const a = evAnns(getActiveMainPage()).find(x =&gt; x.id === annId); if (!a) return; a[key] = val; scheduleAutosave(&#39;Updated evidence box&#39;); }<br>    function evDeleteAnn(annId) {<br>      const page = getActiveMainPage();<br>      (page.fields || []).forEach(f =&gt; { if (f.expectedSource === annId) delete f.expectedSource; if (f.actualSource === annId) delete f.actualSource; });<br>      page.evidenceAnnotations = evAnns(page).filter(a =&gt; a.id !== annId);<br>      scheduleAutosave(&#39;Deleted evidence box&#39;);<br>      renderApp();<br>    }<br><br>    function evSetBoxValue(annId, val) {<br>      const page = getActiveMainPage();<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.value = val;<br>      evAssign(page, ann);<br>      scheduleAutosave(&#39;Edited evidence box value&#39;);<br>      renderApp();<br>    }<br><br>    function evSetFieldValue(fieldId, val) {<br>      const page = getActiveMainPage();<br>      const f = (page.fields || []).find(x =&gt; x.id === fieldId);<br>      if (!f) return;<br>      f[evTargetKey()] = val;<br>      f.enabled = true;<br>      const ann = evAnns(page).find(a =&gt; Number(a.qaLabel) === Number(f.number));<br>      if (ann) { ann.value = val; f[evSourceKey()] = ann.id; }<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Edited box target value from evidence map&#39;);<br>      renderApp();<br>    }<br><br>    function evRelabel(annId, raw) {<br>      const page = getActiveMainPage();<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      const n = Math.floor(Number(raw));<br>      if (!Number.isFinite(n) || n &lt; 1) { renderApp(); return showToast(&#39;QA number must be 1 or higher.&#39;, &#39;warning&#39;); }<br>      if (evAnns(page).some(a =&gt; a.id !== annId &amp;&amp; Number(a.qaLabel) === n)) { renderApp(); return showToast(`QA-${n} (${padC(n)}) is already used on ${page.name}.`, &#39;warning&#39;); }<br>      const oldF = evField(page, ann.qaLabel);<br>      if (oldF &amp;&amp; oldF[evSourceKey()] === ann.id) { oldF[evTargetKey()] = &#39;&#39;; delete oldF[evSourceKey()]; }<br>      if (n &gt; (appState.settings.qaLabelMax || 200)) appState.settings.qaLabelMax = n;<br>      ann.qaLabel = n; ann.label = `QA-${n}`;<br>      evLink(page, ann);<br>      if (ann.value) evAssign(page, ann); else ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Relabelled evidence box&#39;);<br>      renderApp();<br>    }<br><br>    function evCrop(shot, ann) {<br>      return new Promise((resolve, reject) =&gt; {<br>        const img = new Image();<br>        img.onload = () =&gt; {<br>          try {<br>            const nW = img.naturalWidth || img.width, nH = img.naturalHeight || img.height;<br>            const base = document.getElementById(&#39;ev-base-img&#39;);<br>            const refW = ann.refW || (base &amp;&amp; base.clientWidth) || nW;<br>            const refH = ann.refH || (base &amp;&amp; base.clientHeight) || nH;<br>            const kx = nW / refW, ky = nH / refH, pad = 2;<br>            const sx = Math.max(0, Math.floor(ann.x * kx - pad)), sy = Math.max(0, Math.floor(ann.y * ky - pad));<br>            const sw = Math.min(nW - sx, Math.ceil(ann.w * kx + pad * 2)), sh = Math.min(nH - sy, Math.ceil(ann.h * ky + pad * 2));<br>            if (sw &lt; 2 || sh &lt; 2) throw new Error(&#39;Box is outside the screenshot area.&#39;);<br>            const c = document.createElement(&#39;canvas&#39;);<br>            c.width = sw; c.height = sh;<br>            c.getContext(&#39;2d&#39;).drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);<br>            resolve(c.toDataURL(&#39;image/png&#39;));<br>          } catch (err) { reject(err); }<br>        };<br>        img.onerror = () =&gt; reject(new Error(&#39;Could not load the screenshot for OCR.&#39;));<br>        img.src = shot.dataUrl;<br>      });<br>    }<br><br>    async function evReadBox(page, annId, silent = false) {<br>      const ann = evAnns(page).find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      const proj = getActiveProject();<br>      const shot = evShots(page).find(s =&gt; s.id === ann.screenshotId) || evShots(page)[evActiveShotIdx];<br>      if (!shot) { if (!silent) showToast(&#39;No evidence screenshot to read from.&#39;, &#39;warning&#39;); return; }<br>      evReadingIds.add(annId);<br>      evRerender();<br>      try {<br>        const crop = await evCrop(shot, ann);<br>        const pre = await OcrMappingEngine.preprocessImageCanvas(crop, { grayscale: true, contrast: true, scale: 2 });<br>        const out = await OcrMappingEngine.runRealTesseractOCR(pre);<br>        const text = String(out.text || &#39;&#39;).replace(/\s+/g, &#39; &#39;).replace(/^[\s|_~&#39;&quot;`]+|[\s|_~&#39;&quot;`]+$/g, &#39;&#39;).trim();<br>        ann.value = text;<br>        ann.ocrConfidence = out.confidence;<br>        if (text) evAssign(page, ann);<br>        else if (!silent) showToast(`${ann.label}: no text found inside the box.`, &#39;warning&#39;);<br>      } catch (err) {<br>        if (!silent) showToast(`${ann.label} OCR: ${err.message}`, &#39;warning&#39;);<br>      } finally {<br>        evReadingIds.delete(annId);<br>      }<br>      scheduleAutosave(&#39;Read evidence box value&#39;);<br>      evRerender();<br>    }<br><br>    async function evReadAll() {<br>      const page = getActiveMainPage();<br>      const shot = evShots(getActiveMainPage())[evActiveShotIdx];<br>      const list = evAnns(page).filter(a =&gt; evVisible(a, shot));<br>      if (!list.length) return showToast(&#39;Draw at least one box first.&#39;, &#39;warning&#39;);<br>      showToast(`Reading ${list.length} box(es) on ${page.name}...`, &#39;info&#39;);<br>      for (const a of list) await evReadBox(page, a.id, true);<br>      showToast(`Finished reading boxes into ${evTargetLabel()}.`, &#39;success&#39;);<br>    }<br><br>    function evExport() {<br>      const img = document.getElementById(&#39;ev-base-img&#39;);<br>      const page = getActiveMainPage();<br>      if (!img || !page) return;<br>      const shot = evShots(getActiveMainPage())[evActiveShotIdx];<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      canvas.width = img.naturalWidth || img.width; canvas.height = img.naturalHeight || img.height;<br>      const kx = canvas.width / img.width, ky = canvas.height / img.height;<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br>      evAnns(page).filter(a =&gt; evVisible(a, shot)).forEach(ann =&gt; {<br>        ctx.strokeStyle = ann.color; ctx.lineWidth = 3 * kx;<br>        if (ann.type === &#39;circle&#39;) { ctx.beginPath(); ctx.ellipse((ann.x + ann.w / 2) * kx, (ann.y + ann.h / 2) * ky, Math.abs(ann.w / 2) * kx, Math.abs(ann.h / 2) * ky, 0, 0, Math.PI * 2); ctx.stroke(); }<br>        else ctx.strokeRect(ann.x * kx, ann.y * ky, ann.w * kx, ann.h * ky);<br>        ctx.fillStyle = ann.color;<br>        ctx.fillRect(ann.x * kx, Math.max(0, (ann.y - 22) * ky), Math.max(110, evTag(ann).length * 8 + 14) * kx, 22 * ky);<br>        ctx.fillStyle = &#39;#ffffff&#39;;<br>        ctx.font = `bold ${Math.round(12 * kx)}px sans-serif`;<br>        ctx.fillText(evTag(ann), (ann.x + 6) * kx, Math.max(15 * ky, (ann.y - 6) * ky));<br>      });<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = canvas.toDataURL(&#39;image/png&#39;);<br>      a.download = `${page.name.replace(/[^a-z0-9]/gi, &#39;_&#39;)}_evidence_annotated.png`;<br>      a.click();<br>      showToast(&#39;Exported annotated evidence PNG.&#39;, &#39;success&#39;);<br>    }<br><br>    function initEvidenceCanvasEvents() {<br>      const wrapper = document.getElementById(&#39;ev-canvas-wrapper&#39;);<br>      if (!wrapper) return;<br>      let sx = 0, sy = 0, drawing = false;<br>      wrapper.onmousedown = e =&gt; { const r = wrapper.getBoundingClientRect(); sx = e.clientX - r.left; sy = e.clientY - r.top; drawing = true; };<br>      wrapper.onmouseup = e =&gt; {<br>        if (!drawing) return;<br>        drawing = false;<br>        const r = wrapper.getBoundingClientRect();<br>        const ex = e.clientX - r.left, ey = e.clientY - r.top;<br>        const w = Math.abs(ex - sx), h = Math.abs(ey - sy);<br>        if (w &lt; 12 || h &lt; 12) return;<br>        const page = getActiveMainPage(); const proj = getActiveProject();<br>        if (!page) return;<br>        const anns = evAnns(page);<br>        const qaNum = Number(appState.ui.evPendingLabel) || (appState.settings.qaAutoIncrement ? evNextLabel(page) : (appState.ui.evSelectedLabel || 1));<br>        if (anns.some(a =&gt; Number(a.qaLabel) === qaNum)) return showToast(`QA-${qaNum} (${padC(qaNum)}) is already used on ${page.name}. Pick an unused label.`, &#39;warning&#39;);<br>        const base = document.getElementById(&#39;ev-base-img&#39;);<br>        const shot = evShots(page)[evActiveShotIdx];<br>        const ann = {<br>          id: &#39;evann_&#39; + Date.now(), qaLabel: qaNum, type: appState.ui.annotationTool,<br>          x: Math.round(Math.min(sx, ex)), y: Math.round(Math.min(sy, ey)), w: Math.round(w), h: Math.round(h),<br>          color: appState.ui.annotationColor, label: `QA-${qaNum}`, comment: &#39;&#39;, defectId: &#39;&#39;, value: &#39;&#39;,<br>          screenshotId: shot ? shot.id : &#39;&#39;, refW: base ? base.clientWidth : 0, refH: base ? base.clientHeight : 0<br>        };<br>        anns.push(ann);<br>        appState.ui.evSelectedAnnId = ann.id;<br>        appState.ui.evPendingLabel = null;<br>        evLink(page, ann);<br>        if (appState.settings.qaAutoIncrement) appState.ui.evSelectedLabel = evNextLabel(page);<br>        scheduleAutosave(&#39;Added evidence box&#39;);<br>        renderApp();<br>        if (appState.settings.evAutoAssign !== false) setTimeout(() =&gt; evReadBox(page, ann.id, false), 0);<br>      };<br>    }<br><br>    function evPageBar(proj, page) {<br>      const open = appState.ui.evQuickListOpen !== false;<br>      const tExp = evTarget() === &#39;expected&#39;;<br>      const pending = Number(appState.ui.evPendingLabel) || 0;<br>      const nextN = pending || (appState.settings.qaAutoIncrement ? evNextLabel(page) : (appState.ui.evSelectedLabel || 1));<br>      const nf = evField(page, nextN);<br>      const st = page.validationSummary ? page.validationSummary.overallStatus : &#39;PENDING&#39;;<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;navigateTo(&#39;validation&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                &lt;i data-lucide=&quot;arrow-left&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;span&gt;Receipt Validation&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;evStepPage(-1)&quot; class=&quot;px-2.5 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800&quot; title=&quot;Previous Main Page (Alt+←)&quot;&gt;◀&lt;/button&gt;<br>              &lt;select onchange=&quot;switchActiveMainPage(this.value)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 max-w-[260px]&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; `&lt;option value=&quot;${mp.id}&quot; ${mp.id === page.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(mp.name)} (${(mp.evidenceAnnotations || []).length} QA)&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>              &lt;button onclick=&quot;evStepPage(1)&quot; class=&quot;px-2.5 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800&quot; title=&quot;Next Main Page (Alt+→)&quot;&gt;▶&lt;/button&gt;<br>              ${statusBadge(st)}<br>              &lt;span class=&quot;text-[11px] text-slate-500 dark:text-slate-400&quot;&gt;QA-1 = C01, QA-2 = C02 … box value fills &lt;strong&gt;${evTargetLabel()}&lt;/strong&gt;&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;div class=&quot;inline-flex items-center rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden text-xs font-semibold&quot; title=&quot;Main toggle: applies to every Main Page and stays when you switch pages&quot;&gt;<br>                &lt;span class=&quot;px-2.5 py-2 text-slate-400&quot;&gt;Box value →&lt;/span&gt;<br>                &lt;button onclick=&quot;evSetTarget(&#39;expected&#39;)&quot; class=&quot;px-3 py-2 ${tExp ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-50 dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700&#39;}&quot;&gt;Expected Value&lt;/button&gt;<br>                &lt;button onclick=&quot;evSetTarget(&#39;actual&#39;)&quot; class=&quot;px-3 py-2 ${!tExp ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-50 dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700&#39;}&quot;&gt;Found on Receipt&lt;/button&gt;<br>              &lt;/div&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 cursor-pointer&quot; title=&quot;When ON, each drawn box is read with OCR and its text fills the field chosen by the Box value toggle&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; ${appState.settings.evAutoAssign !== false ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;evToggleAutoAssign(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Auto-read box into field&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;button onclick=&quot;evToggleQuickList()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition ${open ? &#39;bg-indigo-600 text-white border-indigo-600&#39; : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700&#39;}&quot;&gt;<br>                &lt;i data-lucide=&quot;list-checks&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;span&gt;Quick List (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2 text-xs px-3 py-2 rounded-xl ${pending ? &#39;bg-amber-500/15 border border-amber-500/40 text-amber-700 dark:text-amber-300&#39; : &#39;bg-slate-50 dark:bg-slate-800/60 text-slate-600 dark:text-slate-300&#39;}&quot;&gt;<br>            &lt;span class=&quot;font-bold&quot;&gt;Next box you draw:&lt;/span&gt;<br>            &lt;span class=&quot;font-mono font-bold&quot;&gt;QA-${nextN} ▸ ${padC(nextN)}${nf ? &#39; · &#39; + escapeHtml(nf.name) : &#39;&#39;}&lt;/span&gt;<br>            ${pending ? `&lt;button onclick=&quot;evCancelPending()&quot; class=&quot;ml-auto px-2 py-0.5 rounded-lg bg-white/70 dark:bg-slate-900/60 text-[11px] font-semibold&quot;&gt;Cancel (Esc)&lt;/button&gt;` : &#39;&lt;span class=&quot;ml-auto text-[11px] text-slate-400&quot;&gt;Alt+←/→ switches page&lt;/span&gt;&#39;}<br>          &lt;/div&gt;<br>          ${open ? renderMainPageQuickListPanel(proj, page, &#39;evToggleQuickList()&#39;, mp =&gt; (mp.evidenceAnnotations || []).length) : &#39;&#39;}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function evAnnCard(page, ann) {<br>      const reading = evReadingIds.has(ann.id);<br>      const f = evField(page, ann.qaLabel);<br>      return `<br>        &lt;div class=&quot;p-3 rounded-xl border ${appState.ui.evSelectedAnnId === ann.id ? &#39;border-brand-500 bg-brand-500/5&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} space-y-2 text-xs&quot;&gt;<br>          &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;button onclick=&quot;evFocus(&#39;${ann.id}&#39;)&quot; class=&quot;font-bold&quot; style=&quot;color:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/button&gt;<br>            &lt;button onclick=&quot;evDeleteAnn(&#39;${ann.id}&#39;)&quot; class=&quot;text-rose-500 hover:underline text-[11px]&quot;&gt;Delete&lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;px-2 py-1 rounded bg-indigo-500/10 text-indigo-500 font-mono text-[10px] font-bold truncate&quot;&gt;▸ ${padC(ann.qaLabel)}${f ? &#39; · &#39; + escapeHtml(f.name) : &#39;&#39;}&lt;/div&gt;<br>          &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.comment || &#39;&#39;)}&quot; onchange=&quot;evUpdateProp(&#39;${ann.id}&#39;, &#39;comment&#39;, this.value)&quot; placeholder=&quot;Evidence comment...&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>          &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>            &lt;span class=&quot;text-[10px] font-bold text-slate-400&quot;&gt;QA #&lt;/span&gt;<br>            &lt;input type=&quot;number&quot; min=&quot;1&quot; value=&quot;${Number(ann.qaLabel)}&quot; onchange=&quot;evRelabel(&#39;${ann.id}&#39;, this.value)&quot; class=&quot;w-16 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; title=&quot;Changing the number moves this box to another column&quot; /&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.defectId || &#39;&#39;)}&quot; onchange=&quot;evUpdateProp(&#39;${ann.id}&#39;, &#39;defectId&#39;, this.value)&quot; placeholder=&quot;Defect ID&quot; class=&quot;flex-1 min-w-0 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.value || &#39;&#39;)}&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} onchange=&quot;evSetBoxValue(&#39;${ann.id}&#39;, this.value)&quot; placeholder=&quot;${reading ? &#39;Reading box...&#39; : &#39;Value read from box&#39;}&quot; class=&quot;flex-1 min-w-0 px-2 py-1 rounded bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono text-[11px]&quot; /&gt;<br>            &lt;button onclick=&quot;evReadBox(getActiveMainPage(), &#39;${ann.id}&#39;)&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-brand-500/10 text-brand-500 text-[10px] font-semibold disabled:opacity-50&quot;&gt;${reading ? &#39;…&#39; : &#39;Read&#39;}&lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex items-center gap-1 pt-1&quot;&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, -10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;←&lt;/button&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, 10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;→&lt;/button&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, 0, -10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↑&lt;/button&gt;<br>            &lt;button onclick=&quot;evNudge(&#39;${ann.id}&#39;, 0, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↓&lt;/button&gt;<br>            &lt;button onclick=&quot;evResize(&#39;${ann.id}&#39;, 15, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;+Size&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br><br>    /****************************************************************************<br>     * EVIDENCE FIELD MAP EXPORT: copy / CSV / Excel (one sheet per Main Page)<br>     * Excel is written by a tiny built-in XLSX writer, so it works offline.<br>     ****************************************************************************/<br>    const EV_EXPORT_HEADERS = [&#39;Col&#39;, &#39;QA Box&#39;, &#39;Field Name&#39;, &#39;Type&#39;, &#39;Expected Value&#39;, &#39;Found on Receipt&#39;, &#39;OCR Confidence %&#39;, &#39;Status&#39;, &#39;Evidence Comment&#39;, &#39;Defect ID&#39;, &#39;Evidence Screenshot&#39;];<br><br>    function evExportRows(page) {<br>      if (!page.validationSummary || !page.fields.some(f =&gt; f.lastValidation)) ValidationEngine.validateMainPage(page);<br>      const byLabel = {};<br>      evAnns(page).forEach(a =&gt; { byLabel[Number(a.qaLabel)] = a; });<br>      const shots = evShots(page);<br>      return (page.fields || [])<br>        .filter(f =&gt; f.number &lt;= 10 || f.enabled || f.expectedValue || f.actualValue || byLabel[f.number])<br>        .map(f =&gt; {<br>          const ann = byLabel[f.number];<br>          const shot = ann ? shots.find(x =&gt; x.id === ann.screenshotId) : null;<br>          return [<br>            padC(f.number),<br>            ann ? ann.label : &#39;&#39;,<br>            f.name || &#39;&#39;,<br>            f.dataType || &#39;&#39;,<br>            f.expectedValue || &#39;&#39;,<br>            f.actualValue || &#39;&#39;,<br>            ann &amp;&amp; ann.ocrConfidence != null ? ann.ocrConfidence : &#39;&#39;,<br>            f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;,<br>            ann ? (ann.comment || &#39;&#39;) : &#39;&#39;,<br>            ann ? (ann.defectId || &#39;&#39;) : &#39;&#39;,<br>            shot ? shot.name : &#39;&#39;<br>          ];<br>        });<br>    }<br><br>    function evExportPages(scope) {<br>      const proj = getActiveProject();<br>      const cur = getActiveMainPage();<br>      return scope === &#39;all&#39; ? (proj.mainPages || []) : (cur ? [cur] : []);<br>    }<br><br>    function evCsvCell(v) {<br>      const t = String(v == null ? &#39;&#39; : v);<br>      return /[&quot;,\r\n]/.test(t) ? &#39;&quot;&#39; + t.replace(/&quot;/g, &#39;&quot;&quot;&#39;) + &#39;&quot;&#39; : t;<br>    }<br>    function evTsvCell(v) {<br>      const t = String(v == null ? &#39;&#39; : v).replace(/[\t\r\n]+/g, &#39; &#39;);<br>      return t;<br>    }<br><br>    function evBuildTable(scope, cell) {<br>      const pages = evExportPages(scope);<br>      const head = [&#39;Main Page&#39;, ...EV_EXPORT_HEADERS];<br>      const lines = [head.map(cell).join(cell === evCsvCell ? &#39;,&#39; : &#39;\t&#39;)];<br>      pages.forEach(p =&gt; {<br>        evExportRows(p).forEach(r =&gt; lines.push([p.name, ...r].map(cell).join(cell === evCsvCell ? &#39;,&#39; : &#39;\t&#39;)));<br>      });<br>      return { text: lines.join(&#39;\r\n&#39;), pages: pages.length, rows: lines.length - 1 };<br>    }<br><br>    async function evCopyText(text) {<br>      try {<br>        if (navigator.clipboard &amp;&amp; navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); return true; }<br>      } catch (e) { /* fall through */ }<br>      try {<br>        const ta = document.createElement(&#39;textarea&#39;);<br>        ta.value = text; ta.style.position = &#39;fixed&#39;; ta.style.opacity = &#39;0&#39;;<br>        document.body.appendChild(ta); ta.select();<br>        const ok = document.execCommand(&#39;copy&#39;);<br>        document.body.removeChild(ta);<br>        return ok;<br>      } catch (e) { return false; }<br>    }<br><br>    async function evCopyMap(scope) {<br>      const t = evBuildTable(scope, evTsvCell);<br>      if (!t.rows) return showToast(&#39;Nothing to copy yet.&#39;, &#39;warning&#39;);<br>      const ok = await evCopyText(t.text);<br>      showToast(ok ? `Copied ${t.rows} row(s) from ${t.pages} page(s). Paste into Excel or Sheets.` : &#39;Copy was blocked by the browser. Use the CSV download instead.&#39;, ok ? &#39;success&#39; : &#39;warning&#39;);<br>    }<br><br>    function evStamp() { return new Date().toISOString().slice(0, 19).replace(/[:T]/g, &#39;-&#39;); }<br><br>    function evDownloadCsv(scope) {<br>      const proj = getActiveProject();<br>      const t = evBuildTable(scope, evCsvCell);<br>      if (!t.rows) return showToast(&#39;Nothing to export yet.&#39;, &#39;warning&#39;);<br>      const name = scope === &#39;all&#39; ? `${proj.name}_evidence_field_map_all_pages` : `${getActiveMainPage().name}_evidence_field_map`;<br>      downloadBlob(&#39; &#39; + t.text, `${name.replace(/[^a-z0-9._-]+/gi, &#39;_&#39;)}_${evStamp()}.csv`, &#39;text/csv;charset=utf-8&#39;);<br>      showToast(`Downloaded CSV with ${t.rows} row(s) from ${t.pages} page(s).`, &#39;success&#39;);<br>    }<br><br>    // ---------- minimal XLSX writer (zip &quot;stored&quot;, inline strings) ----------<br>    const EV_CRC_TABLE = (() =&gt; { const t = new Uint32Array(256); for (let n = 0; n &lt; 256; n++) { let c = n; for (let k = 0; k &lt; 8; k++) c = c &amp; 1 ? 0xEDB88320 ^ (c &gt;&gt;&gt; 1) : c &gt;&gt;&gt; 1; t[n] = c &gt;&gt;&gt; 0; } return t; })();<br>    function evCrc32(bytes) { let c = 0xFFFFFFFF; for (let i = 0; i &lt; bytes.length; i++) c = EV_CRC_TABLE[(c ^ bytes[i]) &amp; 255] ^ (c &gt;&gt;&gt; 8); return (c ^ 0xFFFFFFFF) &gt;&gt;&gt; 0; }<br><br>    function evZip(files) {<br>      const enc = new TextEncoder();<br>      const chunks = [], central = [];<br>      let offset = 0;<br>      const d = new Date();<br>      const dosTime = (d.getHours() &lt;&lt; 11) | (d.getMinutes() &lt;&lt; 5) | (d.getSeconds() &gt;&gt; 1);<br>      const dosDate = ((d.getFullYear() - 1980) &lt;&lt; 9) | ((d.getMonth() + 1) &lt;&lt; 5) | d.getDate();<br>      files.forEach(f =&gt; {<br>        const name = enc.encode(f.name), data = enc.encode(f.content), crc = evCrc32(data);<br>        const lh = new DataView(new ArrayBuffer(30));<br>        lh.setUint32(0, 0x04034b50, true); lh.setUint16(4, 20, true); lh.setUint16(6, 0x0800, true); lh.setUint16(8, 0, true);<br>        lh.setUint16(10, dosTime, true); lh.setUint16(12, dosDate, true); lh.setUint32(14, crc, true);<br>        lh.setUint32(18, data.length, true); lh.setUint32(22, data.length, true); lh.setUint16(26, name.length, true); lh.setUint16(28, 0, true);<br>        chunks.push(new Uint8Array(lh.buffer), name, data);<br>        const ch = new DataView(new ArrayBuffer(46));<br>        ch.setUint32(0, 0x02014b50, true); ch.setUint16(4, 20, true); ch.setUint16(6, 20, true); ch.setUint16(8, 0x0800, true); ch.setUint16(10, 0, true);<br>        ch.setUint16(12, dosTime, true); ch.setUint16(14, dosDate, true); ch.setUint32(16, crc, true);<br>        ch.setUint32(20, data.length, true); ch.setUint32(24, data.length, true); ch.setUint16(28, name.length, true);<br>        ch.setUint32(42, offset, true);<br>        central.push(new Uint8Array(ch.buffer), name);<br>        offset += 30 + name.length + data.length;<br>      });<br>      const cdSize = central.reduce((a, c) =&gt; a + c.length, 0);<br>      const end = new DataView(new ArrayBuffer(22));<br>      end.setUint32(0, 0x06054b50, true); end.setUint16(8, files.length, true); end.setUint16(10, files.length, true);<br>      end.setUint32(12, cdSize, true); end.setUint32(16, offset, true);<br>      const all = [...chunks, ...central, new Uint8Array(end.buffer)];<br>      const out = new Uint8Array(all.reduce((a, c) =&gt; a + c.length, 0));<br>      let p = 0; all.forEach(c =&gt; { out.set(c, p); p += c.length; });<br>      return out;<br>    }<br><br>    function evXml(v) {<br>      return String(v == null ? &#39;&#39; : v).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, &#39;&#39;)<br>        .replace(/&amp;/g, &#39;&amp;amp;&#39;).replace(/&lt;/g, &#39;&amp;lt;&#39;).replace(/&gt;/g, &#39;&amp;gt;&#39;).replace(/&quot;/g, &#39;&amp;quot;&#39;);<br>    }<br>    function evColName(i) { let n = i + 1, s = &#39;&#39;; while (n &gt; 0) { const m = (n - 1) % 26; s = String.fromCharCode(65 + m) + s; n = Math.floor((n - 1) / 26); } return s; }<br><br>    function evSheetXml(headers, rows) {<br>      const widths = headers.map((h, i) =&gt; Math.min(60, Math.max(String(h).length + 2, ...rows.map(r =&gt; String(r[i] == null ? &#39;&#39; : r[i]).length + 2), 8)));<br>      const cell = (v, r, c, style) =&gt; {<br>        const ref = evColName(c) + (r + 1);<br>        if (typeof v === &#39;number&#39; &amp;&amp; Number.isFinite(v)) return `&lt;c r=&quot;${ref}&quot;${style ? ` s=&quot;${style}&quot;` : &#39;&#39;}&gt;&lt;v&gt;${v}&lt;/v&gt;&lt;/c&gt;`;<br>        return `&lt;c r=&quot;${ref}&quot; t=&quot;inlineStr&quot;${style ? ` s=&quot;${style}&quot;` : &#39;&#39;}&gt;&lt;is&gt;&lt;t xml:space=&quot;preserve&quot;&gt;${evXml(v)}&lt;/t&gt;&lt;/is&gt;&lt;/c&gt;`;<br>      };<br>      const all = [headers, ...rows];<br>      const body = all.map((row, r) =&gt; `&lt;row r=&quot;${r + 1}&quot;&gt;${row.map((v, c) =&gt; cell(v, r, c, r === 0 ? 1 : 0)).join(&#39;&#39;)}&lt;/row&gt;`).join(&#39;&#39;);<br>      return `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;worksheet xmlns=&quot;http://schemas.openxmlformats.org/spreadsheetml/2006/main&quot;&gt;&lt;sheetViews&gt;&lt;sheetView workbookViewId=&quot;0&quot;&gt;&lt;pane ySplit=&quot;1&quot; topLeftCell=&quot;A2&quot; activePane=&quot;bottomLeft&quot; state=&quot;frozen&quot;/&gt;&lt;/sheetView&gt;&lt;/sheetViews&gt;&lt;cols&gt;${widths.map((w, i) =&gt; `&lt;col min=&quot;${i + 1}&quot; max=&quot;${i + 1}&quot; width=&quot;${w}&quot; customWidth=&quot;1&quot;/&gt;`).join(&#39;&#39;)}&lt;/cols&gt;&lt;sheetData&gt;${body}&lt;/sheetData&gt;&lt;/worksheet&gt;`;<br>    }<br><br>    function evSheetName(name, used) {<br>      let base = String(name || &#39;Page&#39;).replace(/[\\\/\?\*\[\]:]/g, &#39;-&#39;).replace(/^&#39;+|&#39;+$/g, &#39;&#39;).trim().slice(0, 31) || &#39;Page&#39;;<br>      let out = base, n = 2;<br>      while (used.has(out.toLowerCase())) { const suf = ` (${n++})`; out = base.slice(0, 31 - suf.length) + suf; }<br>      used.add(out.toLowerCase());<br>      return out;<br>    }<br><br>    function evBuildXlsx(sheets) {<br>      const n = sheets.length;<br>      const files = [<br>        { name: &#39;[Content_Types].xml&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;Types xmlns=&quot;http://schemas.openxmlformats.org/package/2006/content-types&quot;&gt;&lt;Default Extension=&quot;rels&quot; ContentType=&quot;application/vnd.openxmlformats-package.relationships+xml&quot;/&gt;&lt;Default Extension=&quot;xml&quot; ContentType=&quot;application/xml&quot;/&gt;&lt;Override PartName=&quot;/xl/workbook.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml&quot;/&gt;&lt;Override PartName=&quot;/xl/styles.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml&quot;/&gt;${sheets.map((_, i) =&gt; `&lt;Override PartName=&quot;/xl/worksheets/sheet${i + 1}.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml&quot;/&gt;`).join(&#39;&#39;)}&lt;/Types&gt;` },<br>        { name: &#39;_rels/.rels&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;&lt;Relationship Id=&quot;rId1&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument&quot; Target=&quot;xl/workbook.xml&quot;/&gt;&lt;/Relationships&gt;` },<br>        { name: &#39;xl/workbook.xml&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;workbook xmlns=&quot;http://schemas.openxmlformats.org/spreadsheetml/2006/main&quot; xmlns:r=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships&quot;&gt;&lt;sheets&gt;${sheets.map((sh, i) =&gt; `&lt;sheet name=&quot;${evXml(sh.name)}&quot; sheetId=&quot;${i + 1}&quot; r:id=&quot;rId${i + 1}&quot;/&gt;`).join(&#39;&#39;)}&lt;/sheets&gt;&lt;/workbook&gt;` },<br>        { name: &#39;xl/_rels/workbook.xml.rels&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;${sheets.map((_, i) =&gt; `&lt;Relationship Id=&quot;rId${i + 1}&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet&quot; Target=&quot;worksheets/sheet${i + 1}.xml&quot;/&gt;`).join(&#39;&#39;)}&lt;Relationship Id=&quot;rId${n + 1}&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles&quot; Target=&quot;styles.xml&quot;/&gt;&lt;/Relationships&gt;` },<br>        { name: &#39;xl/styles.xml&#39;, content: `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;styleSheet xmlns=&quot;http://schemas.openxmlformats.org/spreadsheetml/2006/main&quot;&gt;&lt;fonts count=&quot;2&quot;&gt;&lt;font&gt;&lt;sz val=&quot;11&quot;/&gt;&lt;name val=&quot;Calibri&quot;/&gt;&lt;/font&gt;&lt;font&gt;&lt;b/&gt;&lt;sz val=&quot;11&quot;/&gt;&lt;color rgb=&quot;FFFFFFFF&quot;/&gt;&lt;name val=&quot;Calibri&quot;/&gt;&lt;/font&gt;&lt;/fonts&gt;&lt;fills count=&quot;3&quot;&gt;&lt;fill&gt;&lt;patternFill patternType=&quot;none&quot;/&gt;&lt;/fill&gt;&lt;fill&gt;&lt;patternFill patternType=&quot;gray125&quot;/&gt;&lt;/fill&gt;&lt;fill&gt;&lt;patternFill patternType=&quot;solid&quot;&gt;&lt;fgColor rgb=&quot;FF4F46E5&quot;/&gt;&lt;bgColor indexed=&quot;64&quot;/&gt;&lt;/patternFill&gt;&lt;/fill&gt;&lt;/fills&gt;&lt;borders count=&quot;1&quot;&gt;&lt;border&gt;&lt;left/&gt;&lt;right/&gt;&lt;top/&gt;&lt;bottom/&gt;&lt;diagonal/&gt;&lt;/border&gt;&lt;/borders&gt;&lt;cellStyleXfs count=&quot;1&quot;&gt;&lt;xf numFmtId=&quot;0&quot; fontId=&quot;0&quot; fillId=&quot;0&quot; borderId=&quot;0&quot;/&gt;&lt;/cellStyleXfs&gt;&lt;cellXfs count=&quot;2&quot;&gt;&lt;xf numFmtId=&quot;0&quot; fontId=&quot;0&quot; fillId=&quot;0&quot; borderId=&quot;0&quot; xfId=&quot;0&quot;/&gt;&lt;xf numFmtId=&quot;0&quot; fontId=&quot;1&quot; fillId=&quot;2&quot; borderId=&quot;0&quot; xfId=&quot;0&quot; applyFont=&quot;1&quot; applyFill=&quot;1&quot;/&gt;&lt;/cellXfs&gt;&lt;cellStyles count=&quot;1&quot;&gt;&lt;cellStyle name=&quot;Normal&quot; xfId=&quot;0&quot; builtinId=&quot;0&quot;/&gt;&lt;/cellStyles&gt;&lt;/styleSheet&gt;` },<br>        ...sheets.map((sh, i) =&gt; ({ name: `xl/worksheets/sheet${i + 1}.xml`, content: evSheetXml(sh.headers, sh.rows) }))<br>      ];<br>      return evZip(files);<br>    }<br><br>    function evDownloadXlsx(scope) {<br>      const proj = getActiveProject();<br>      const pages = evExportPages(scope);<br>      if (!pages.length) return showToast(&#39;Nothing to export yet.&#39;, &#39;warning&#39;);<br>      const used = new Set();<br>      const sheets = pages.map(p =&gt; ({ name: evSheetName(p.name, used), headers: EV_EXPORT_HEADERS, rows: evExportRows(p) }));<br>      const bytes = evBuildXlsx(sheets);<br>      const name = scope === &#39;all&#39; ? `${proj.name}_evidence_field_map_all_pages` : `${getActiveMainPage().name}_evidence_field_map`;<br>      downloadBlob(bytes, `${name.replace(/[^a-z0-9._-]+/gi, &#39;_&#39;)}_${evStamp()}.xlsx`, &#39;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;);<br>      showToast(`Downloaded Excel with ${sheets.length} sheet(s), one per Main Page.`, &#39;success&#39;);<br>    }<br><br>    function evFieldMap(page) {<br>      if (!page.validationSummary) ValidationEngine.validateMainPage(page);<br>      const byLabel = {};<br>      evAnns(page).forEach(a =&gt; { byLabel[Number(a.qaLabel)] = a; });<br>      const pending = Number(appState.ui.evPendingLabel) || 0;<br>      const rows = (page.fields || []).filter(f =&gt; evFieldMapShowAll || f.number &lt;= 10 || f.enabled || f.expectedValue || f.actualValue || byLabel[f.number]);<br>      const withBox = rows.filter(f =&gt; byLabel[f.number]);<br>      const filled = withBox.filter(f =&gt; String(f[evTargetKey()] || &#39;&#39;).trim() !== &#39;&#39;).length;<br>      const passed = withBox.filter(f =&gt; f.lastValidation &amp;&amp; f.lastValidation.status === &#39;PASS&#39;).length;<br>      const thr = appState.settings.autoAcceptConfidenceThreshold;<br>      const tExp = evTarget() === &#39;expected&#39;;<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Evidence Box ⇄ Field Map — ${escapeHtml(page.name)}&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;QA-n is column Cn. The value read in a box goes to &lt;strong&gt;${evTargetLabel()}&lt;/strong&gt; (change it with the “Box value →” toggle above; it applies to every Main Page). The other column is read-only here: Found on Receipt is normally filled in Receipt Validation (auto or Re-Run OCR &amp;amp; Auto-Match). Evidence screenshots and boxes belong to this Main Page only.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2 text-xs&quot;&gt;<br>              &lt;span class=&quot;px-2.5 py-1 rounded-full font-bold bg-slate-100 dark:bg-slate-800&quot;&gt;${withBox.length} boxes&lt;/span&gt;<br>              &lt;span class=&quot;px-2.5 py-1 rounded-full font-bold bg-sky-500/15 text-sky-500&quot;&gt;${filled} filled&lt;/span&gt;<br>              &lt;span class=&quot;px-2.5 py-1 rounded-full font-bold ${withBox.length &amp;&amp; passed === withBox.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;${passed} matched on receipt&lt;/span&gt;<br>              &lt;button onclick=&quot;evReadAll()&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;Read all boxes&lt;/button&gt;<br>              &lt;button onclick=&quot;evApplyStored()&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700&quot; title=&quot;Write the values already read from the boxes into the selected target without running OCR again&quot;&gt;Apply values → ${evTargetLabel()}&lt;/button&gt;<br>              &lt;button onclick=&quot;evToggleShowAll()&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;${evFieldMapShowAll ? &#39;Active fields only&#39; : &#39;Show all fields&#39;}&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2 text-xs px-3 py-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>            &lt;span class=&quot;font-bold text-slate-500 mr-1&quot;&gt;Export / Copy&lt;/span&gt;<br>            &lt;button onclick=&quot;evCopyMap(&#39;page&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot; title=&quot;Copy this page&#39;s table (tab-separated) to paste into Excel or Sheets&quot;&gt;Copy this page&lt;/button&gt;<br>            &lt;button onclick=&quot;evCopyMap(&#39;all&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot; title=&quot;Copy all pages in one table with a Main Page column&quot;&gt;Copy all pages (${getActiveProject().mainPages.length})&lt;/button&gt;<br>            &lt;span class=&quot;w-px h-5 bg-slate-300 dark:bg-slate-700 mx-1&quot;&gt;&lt;/span&gt;<br>            &lt;button onclick=&quot;evDownloadCsv(&#39;page&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot;&gt;CSV this page&lt;/button&gt;<br>            &lt;button onclick=&quot;evDownloadCsv(&#39;all&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot; title=&quot;One CSV with a Main Page column&quot;&gt;CSV all pages&lt;/button&gt;<br>            &lt;span class=&quot;w-px h-5 bg-slate-300 dark:bg-slate-700 mx-1&quot;&gt;&lt;/span&gt;<br>            &lt;button onclick=&quot;evDownloadXlsx(&#39;page&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 hover:border-brand-500/50&quot;&gt;Excel this page&lt;/button&gt;<br>            &lt;button onclick=&quot;evDownloadXlsx(&#39;all&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl font-semibold bg-emerald-600 hover:bg-emerald-700 text-white&quot; title=&quot;One .xlsx file, one sheet per Main Page&quot;&gt;Excel all pages (1 sheet per page)&lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;overflow-x-auto max-h-[520px]&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead class=&quot;sticky top-0 bg-white dark:bg-slate-900 z-10&quot;&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2 w-14&quot;&gt;Col&lt;/th&gt;&lt;th class=&quot;pb-2 w-20&quot;&gt;QA Box&lt;/th&gt;&lt;th class=&quot;pb-2&quot;&gt;Field Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2&quot;&gt;${tExp ? &#39;Expected Value (from box, editable)&#39; : &#39;Expected Value&#39;}&lt;/th&gt;&lt;th class=&quot;pb-2&quot;&gt;${tExp ? &#39;Found on Receipt&#39; : &#39;Found on Receipt (from box, editable)&#39;}&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;&lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;&lt;th class=&quot;pb-2 text-right&quot;&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${rows.map(f =&gt; {<br>                  const ann = byLabel[f.number];<br>                  const reading = ann &amp;&amp; evReadingIds.has(ann.id);<br>                  const st = f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;;<br>                  const isSel = ann &amp;&amp; appState.ui.evSelectedAnnId === ann.id;<br>                  const conf = ann &amp;&amp; ann.ocrConfidence != null ? ann.ocrConfidence : null;<br>                  return `<br>                    &lt;tr class=&quot;${isSel ? &#39;bg-brand-500/10&#39; : pending === f.number ? &#39;bg-amber-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/40&#39;}&quot;&gt;<br>                      &lt;td class=&quot;py-2 font-mono font-semibold text-slate-400&quot;&gt;${padC(f.number)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2&quot;&gt;${ann ? `&lt;button onclick=&quot;evFocus(&#39;${ann.id}&#39;)&quot; class=&quot;px-2 py-0.5 rounded text-[11px] font-bold text-white&quot; style=&quot;background:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/button&gt;` : &#39;&lt;span class=&quot;text-slate-300 dark:text-slate-600&quot;&gt;—&lt;/span&gt;&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.name)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;name&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-semibold&quot; /&gt;&lt;/td&gt;<br>                      ${tExp ? `&lt;td class=&quot;py-2 pr-2 font-mono text-emerald-500&quot;&gt;${escapeHtml(f.actualValue || &#39;-&#39;)}&lt;/td&gt;` : `&lt;td class=&quot;py-2 pr-2&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue || &#39;&#39;)}&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} placeholder=&quot;${reading ? &#39;Reading box...&#39; : ann ? &#39;Click Re-read or type&#39; : &#39;Draw a box or type&#39;}&quot; onchange=&quot;evSetFieldValue(&#39;${f.id}&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;&lt;/td&gt;`}<br>                      ${tExp ? `&lt;td class=&quot;py-2 pr-2&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.expectedValue || &#39;&#39;)}&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} placeholder=&quot;${reading ? &#39;Reading box...&#39; : ann ? &#39;Click Re-read or type&#39; : &#39;Draw a box or type&#39;}&quot; onchange=&quot;evSetFieldValue(&#39;${f.id}&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;&lt;/td&gt;` : `&lt;td class=&quot;py-2 pr-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(f.expectedValue || &#39;-&#39;)}&lt;/td&gt;`}<br>                      &lt;td class=&quot;py-2 text-center font-mono text-[11px] ${conf != null &amp;&amp; conf &lt; thr ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;${conf != null ? conf + &#39;%&#39; : &#39;-&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-right whitespace-nowrap&quot;&gt;<br>                        ${ann ? `<br>                          &lt;button onclick=&quot;evReadBox(getActiveMainPage(), &#39;${ann.id}&#39;)&quot; ${reading ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded-lg bg-brand-500/10 text-brand-500 font-semibold disabled:opacity-50&quot;&gt;${reading ? &#39;Reading…&#39; : &#39;Re-read&#39;}&lt;/button&gt;<br>                          &lt;button onclick=&quot;evDeleteAnn(&#39;${ann.id}&#39;)&quot; class=&quot;px-2 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Remove box&lt;/button&gt;<br>                        ` : `<br>                          &lt;button onclick=&quot;evStartDraw(${f.number})&quot; class=&quot;px-2 py-1 rounded-lg ${pending === f.number ? &#39;bg-amber-500 text-slate-950&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;} font-semibold&quot;&gt;${pending === f.number ? &#39;Drawing…&#39; : &#39;Draw box&#39;}&lt;/button&gt;<br>                        `}<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderEvidenceModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No active project.&lt;/div&gt;`;<br>      const shots = evShots(page);<br>      const rememberedIdx = page.evidenceShotId ? shots.findIndex(s =&gt; s.id === page.evidenceShotId) : -1;<br>      evActiveShotIdx = rememberedIdx &gt;= 0 ? rememberedIdx : Math.max(0, shots.length - 1);<br>      const activeShot = shots[evActiveShotIdx] || null;<br>      const anns = evAnns(page);<br>      const mergeSel = appState.ui.evMergeSel = (appState.ui.evMergeSel || []).filter(id =&gt; shots.some(s =&gt; s.id === id));<br>      const nextLabel = appState.settings.qaAutoIncrement ? evNextLabel(page) : (appState.ui.evSelectedLabel || 1);<br>      const used = new Set(anns.map(a =&gt; Number(a.qaLabel)));<br>      const maxLbl = appState.settings.qaLabelMax || 200;<br>      const labelOptions = [];<br>      for (let i = 1; i &lt;= maxLbl; i++) labelOptions.push(`&lt;option value=&quot;${i}&quot; ${i === nextLabel ? &#39;selected&#39; : &#39;&#39;}&gt;QA-${i} ${used.has(i) ? &#39;(Assigned)&#39; : &#39;&#39;}&lt;/option&gt;`);<br><br>      return `<br>        ${evPageBar(proj, page)}<br><br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;image-plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;&lt;span&gt;Upload Evidence Screenshots&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; multiple onchange=&quot;evUpload(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;evPasteButton()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-slate-100 dark:bg-slate-800&quot;&gt;<br>              &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;&lt;span&gt;Paste Image (Ctrl+V)&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;evCapture()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>              &lt;i data-lucide=&quot;monitor-dot&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;&lt;span&gt;Capture Screen (Browser Permission)&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;evMerge(&#39;vertical&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Merge Vertical (${mergeSel.length})&lt;/button&gt;<br>            &lt;button onclick=&quot;evMerge(&#39;horizontal&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Merge Horizontal (${mergeSel.length})&lt;/button&gt;<br>            &lt;button onclick=&quot;evResetMerge()&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold text-slate-500&quot;&gt;Reset Merge History (${(page.evidenceMergeHistory || []).length})&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot; title=&quot;${escapeHtml(page.name)}&quot;&gt;Evidence of this page (${shots.length})&lt;/h3&gt;<br>              &lt;span class=&quot;text-[10px] text-slate-400&quot;&gt;Check to merge&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${shots.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No evidence screenshots for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; yet. Upload, paste (Ctrl+V) or capture one.&lt;/div&gt;` : shots.map((scr, idx) =&gt; `<br>                &lt;div onclick=&quot;evSelectShot(${idx})&quot; class=&quot;p-2.5 rounded-xl border cursor-pointer transition ${idx === evActiveShotIdx ? &#39;border-brand-500 bg-brand-500/10&#39; : &#39;border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between gap-2 mb-1.5&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                    &lt;label class=&quot;inline-flex items-center gap-1.5 text-[11px] font-semibold truncate&quot;&gt;<br>                      &lt;input type=&quot;checkbox&quot; ${mergeSel.includes(scr.id) ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;evToggleMerge(&#39;${scr.id}&#39;)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                      &lt;span class=&quot;truncate&quot;&gt;${escapeHtml(scr.name)}&lt;/span&gt;<br>                    &lt;/label&gt;<br>                    &lt;div class=&quot;flex items-center gap-1 shrink-0&quot;&gt;<br>                      &lt;button onclick=&quot;evMoveShot(${idx}, -1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;↑&lt;/button&gt;<br>                      &lt;button onclick=&quot;evMoveShot(${idx}, 1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;↓&lt;/button&gt;<br>                      &lt;button onclick=&quot;evDeleteShot(&#39;${scr.id}&#39;)&quot; class=&quot;text-rose-500 hover:opacity-80&quot; title=&quot;Delete&quot;&gt;&amp;times;&lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;img src=&quot;${scr.dataUrl}&quot; alt=&quot;${escapeHtml(scr.name)}&quot; class=&quot;w-full h-24 object-cover rounded-lg bg-slate-950&quot; /&gt;<br>                  &lt;div class=&quot;flex items-center justify-between text-[10px] text-slate-400 mt-1&quot;&gt;<br>                    &lt;span&gt;${scr.isMerged ? &#39;Merged Output&#39; : escapeHtml(scr.source)}&lt;/span&gt;<br>                    &lt;a href=&quot;${scr.dataUrl}&quot; download=&quot;${escapeHtml(scr.name)}&quot; onclick=&quot;event.stopPropagation()&quot; class=&quot;text-brand-500 hover:underline&quot;&gt;Download&lt;/a&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 pb-2 border-b border-slate-200 dark:border-slate-800&quot;&gt;<br>              &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;rect&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;rect&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Rectangle&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;circle&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;circle&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Circle&lt;/button&gt;<br>                &lt;input type=&quot;color&quot; value=&quot;${appState.ui.annotationColor}&quot; onchange=&quot;appState.ui.annotationColor = this.value&quot; class=&quot;w-8 h-8 rounded cursor-pointer bg-transparent&quot; title=&quot;Annotation Color&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex items-center gap-2 text-xs&quot;&gt;<br>                &lt;select onchange=&quot;appState.ui.evSelectedLabel = Number(this.value)&quot; class=&quot;px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot;&gt;${labelOptions.join(&#39;&#39;)}&lt;/select&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1 cursor-pointer&quot; title=&quot;Auto-increment to next unused QA label&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${appState.settings.qaAutoIncrement ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.qaAutoIncrement = this.checked; scheduleAutosave(&#39;Toggled QA auto-increment&#39;); renderApp();&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;Auto-Inc&lt;/span&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;relative min-h-[420px] bg-slate-950 rounded-xl overflow-auto flex items-center justify-center p-2 select-none&quot;&gt;<br>              ${activeShot ? `<br>                &lt;div id=&quot;ev-canvas-wrapper&quot; class=&quot;relative inline-block cursor-crosshair&quot;&gt;<br>                  &lt;img id=&quot;ev-base-img&quot; src=&quot;${activeShot.dataUrl}&quot; alt=&quot;Evidence Canvas&quot; class=&quot;max-w-full rounded-lg pointer-events-none&quot; /&gt;<br>                  &lt;svg class=&quot;absolute inset-0 w-full h-full&quot;&gt;<br>                    ${anns.filter(a =&gt; evVisible(a, activeShot)).map(ann =&gt; {<br>                      const isSel = appState.ui.evSelectedAnnId === ann.id;<br>                      const shape = ann.type === &#39;circle&#39;<br>                        ? `&lt;ellipse cx=&quot;${ann.x + ann.w / 2}&quot; cy=&quot;${ann.y + ann.h / 2}&quot; rx=&quot;${Math.abs(ann.w / 2)}&quot; ry=&quot;${Math.abs(ann.h / 2)}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`<br>                        : `&lt;rect x=&quot;${ann.x}&quot; y=&quot;${ann.y}&quot; width=&quot;${ann.w}&quot; height=&quot;${ann.h}&quot; rx=&quot;4&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`;<br>                      return `<br>                        &lt;g onclick=&quot;event.stopPropagation(); appState.ui.evSelectedAnnId = &#39;${ann.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer&quot;&gt;<br>                          ${shape}<br>                          &lt;rect x=&quot;${ann.x}&quot; y=&quot;${Math.max(0, ann.y - 20)}&quot; width=&quot;${Math.max(68, evTag(ann).length * 7 + 12)}&quot; height=&quot;18&quot; rx=&quot;4&quot; fill=&quot;${ann.color}&quot; /&gt;<br>                          &lt;text x=&quot;${ann.x + 6}&quot; y=&quot;${Math.max(13, ann.y - 7)}&quot; font-family=&quot;sans-serif&quot; font-size=&quot;11&quot; font-weight=&quot;bold&quot; fill=&quot;#ffffff&quot;&gt;${escapeHtml(evTag(ann))}&lt;/text&gt;<br>                        &lt;/g&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/svg&gt;<br>                &lt;/div&gt;<br>              ` : `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;Upload, paste or capture an evidence screenshot to draw QA boxes.&lt;/div&gt;`}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center justify-between text-[11px] text-slate-400&quot;&gt;<br>              &lt;span&gt;Click &amp;amp; drag on the image to draw a box for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt;.&lt;/span&gt;<br>              ${activeShot ? `&lt;button onclick=&quot;evExport()&quot; class=&quot;text-brand-500 font-semibold hover:underline&quot;&gt;Export Annotated PNG&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Evidence Boxes (${anns.length})&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${anns.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No evidence boxes on this Main Page yet.&lt;/div&gt;` : anns.map(a =&gt; evAnnCard(page, a)).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        ${evFieldMap(page)}<br>      `;<br>    }<br><br>    let tcSearchQuery = &#39;&#39;;<br>    let tcStatusFilter = &#39;ALL&#39;;<br><br>    function renderTestCasesModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br>      const list = (proj.testCases || []).filter(tc =&gt; {<br>        const matchText = tc.id.toLowerCase().includes(tcSearchQuery.toLowerCase()) || tc.title.toLowerCase().includes(tcSearchQuery.toLowerCase());<br>        const matchStatus = tcStatusFilter === &#39;ALL&#39; || tc.status === tcStatusFilter;<br>        return matchText &amp;&amp; matchStatus;<br>      });<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(tcSearchQuery)}&quot; oninput=&quot;tcSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search test cases...&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;select onchange=&quot;tcStatusFilter = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;ALL&quot; ${tcStatusFilter === &#39;ALL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Statuses&lt;/option&gt;<br>                &lt;option value=&quot;PASS&quot; ${tcStatusFilter === &#39;PASS&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PASS&lt;/option&gt;<br>                &lt;option value=&quot;FAIL&quot; ${tcStatusFilter === &#39;FAIL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;FAIL&lt;/option&gt;<br>                &lt;option value=&quot;PENDING&quot; ${tcStatusFilter === &#39;PENDING&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PENDING&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openTestCaseModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Test Case&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;ID&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Title &amp; Module&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Linked Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Priority&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${list.map(tc =&gt; {<br>                  const mp = proj.mainPages.find(m =&gt; m.id === tc.mainPageId);<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-mono font-bold&quot;&gt;${escapeHtml(tc.id)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 pr-3&quot;&gt;<br>                        &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(tc.title)}&lt;/div&gt;<br>                        &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;${escapeHtml(tc.module)} • Tester: ${escapeHtml(tc.tester)}&lt;/div&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp ? escapeHtml(mp.name) : &#39;-&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 font-medium&quot;&gt;${escapeHtml(tc.priority)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;<br>                        &lt;select onchange=&quot;updateTestCaseStatus(&#39;${tc.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-bold&quot;&gt;<br>                          ${[&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;, &#39;BLOCKED&#39;].map(st =&gt; `&lt;option value=&quot;${st}&quot; ${tc.status === st ? &#39;selected&#39; : &#39;&#39;}&gt;${st}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;openTestCaseModal(&#39;${tc.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 font-semibold mr-1&quot;&gt;Edit&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteTestCase(&#39;${tc.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Delete&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openTestCaseModal(tcId = null) {<br>      const proj = getActiveProject();<br>      const existing = tcId ? proj.testCases.find(t =&gt; t.id === tcId) : null;<br>      const tc = existing || {<br>        id: `TC-${String((proj.testCases?.length || 0) + 1).padStart(3, &#39;0&#39;)}`,<br>        title: &#39;&#39;,<br>        module: &#39;EIS Settlement&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: &#39;&#39;,<br>        expectedResult: &#39;&#39;,<br>        actualResult: &#39;&#39;,<br>        status: &#39;PENDING&#39;,<br>        priority: &#39;High&#39;,<br>        tester: proj.owner || &#39;QA Analyst&#39;,<br>        mainPageId: appState.activeMainPageId || &#39;&#39;<br>      };<br><br>      openModal({<br>        title: existing ? `Edit Test Case (${tc.id})` : &#39;Create Test Case&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Test Case ID&lt;/label&gt;&lt;input id=&quot;tc-id&quot; value=&quot;${escapeHtml(tc.id)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Priority&lt;/label&gt;&lt;select id=&quot;tc-prio&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;${[&#39;Critical&#39;, &#39;High&#39;, &#39;Medium&#39;, &#39;Low&#39;].map(p =&gt; `&lt;option ${tc.priority === p ? &#39;selected&#39; : &#39;&#39;}&gt;${p}&lt;/option&gt;`).join(&#39;&#39;)}&lt;/select&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Title *&lt;/label&gt;&lt;input id=&quot;tc-title&quot; value=&quot;${escapeHtml(tc.title)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Linked Main Page&lt;/label&gt;&lt;select id=&quot;tc-mp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option value=&quot;&quot;&gt;None&lt;/option&gt;${proj.mainPages.map(m =&gt; `&lt;option value=&quot;${m.id}&quot; ${tc.mainPageId === m.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(m.name)}&lt;/option&gt;`).join(&#39;&#39;)}&lt;/select&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Steps&lt;/label&gt;&lt;textarea id=&quot;tc-steps&quot; rows=&quot;3&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot;&gt;${escapeHtml(tc.steps)}&lt;/textarea&gt;&lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Expected Result&lt;/label&gt;&lt;input id=&quot;tc-exp&quot; value=&quot;${escapeHtml(tc.expectedResult)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Actual Result&lt;/label&gt;&lt;input id=&quot;tc-act&quot; value=&quot;${escapeHtml(tc.actualResult)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveTestCaseFromModal(${existing ? `&#39;${existing.id}&#39;` : &#39;null&#39;})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Test Case&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveTestCaseFromModal(existingId) {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;tc-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Test case title is required.&#39;, &#39;warning&#39;);<br><br>      const record = {<br>        id: document.getElementById(&#39;tc-id&#39;).value.trim() || `TC-${Date.now()}`,<br>        title,<br>        module: &#39;EIS Settlement&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: document.getElementById(&#39;tc-steps&#39;).value,<br>        expectedResult: document.getElementById(&#39;tc-exp&#39;).value,<br>        actualResult: document.getElementById(&#39;tc-act&#39;).value,<br>        status: existingId ? (proj.testCases.find(t =&gt; t.id === existingId)?.status || &#39;PENDING&#39;) : &#39;PENDING&#39;,<br>        priority: document.getElementById(&#39;tc-prio&#39;).value,<br>        tester: proj.owner || &#39;QA Analyst&#39;,<br>        executionDate: new Date().toISOString().slice(0, 10),<br>        mainPageId: document.getElementById(&#39;tc-mp&#39;).value<br>      };<br><br>      if (existingId) {<br>        const idx = proj.testCases.findIndex(t =&gt; t.id === existingId);<br>        if (idx &gt;= 0) proj.testCases[idx] = record;<br>      } else {<br>        proj.testCases.unshift(record);<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Saved test case&#39;);<br>      showToast(&#39;Saved test case.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateTestCaseStatus(tcId, status) {<br>      const proj = getActiveProject();<br>      const tc = proj?.testCases.find(t =&gt; t.id === tcId);<br>      if (!tc) return;<br>      tc.status = status;<br>      scheduleAutosave(&#39;Updated test case status&#39;);<br>      renderApp();<br>    }<br><br>    function deleteTestCase(tcId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.testCases = proj.testCases.filter(t =&gt; t.id !== tcId);<br>      scheduleAutosave(&#39;Deleted test case&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 8 VIEW: DEFECT MANAGEMENT<br>     ****************************************************************************/<br>    function renderDefectsModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;QA Defects &amp; Discrepancies (${(proj.defects || []).length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Log EIS receipt calculation errors, CWT mismatches, or UI/OCR issues and copy formatted bug summaries.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openDefectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;bug&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Log New Defect&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            ${(proj.defects || []).length === 0 ? `&lt;div class=&quot;py-8 text-center text-xs text-slate-400&quot;&gt;No defects logged in this project.&lt;/div&gt;` : (proj.defects || []).map(def =&gt; `<br>              &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 bg-slate-50/60 dark:bg-slate-950/40 space-y-2 text-xs&quot;&gt;<br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono font-bold text-rose-500&quot;&gt;${escapeHtml(def.id)}&lt;/span&gt;<br>                    &lt;span class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(def.title)}&lt;/span&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                    &lt;span class=&quot;px-2 py-0.5 rounded bg-slate-200 dark:bg-slate-800 font-semibold&quot;&gt;${escapeHtml(def.severity)}&lt;/span&gt;<br>                    ${statusBadge(def.status)}<br>                    &lt;button onclick=&quot;copyDefectSummary(&#39;${def.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 font-semibold hover:bg-brand-500/20&quot;&gt;Copy Summary&lt;/button&gt;<br>                    &lt;button onclick=&quot;deleteDefect(&#39;${def.id}&#39;)&quot; class=&quot;px-2 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(def.description)}&lt;/p&gt;<br>                &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-2 font-mono text-[11px] bg-white dark:bg-slate-900 p-2.5 rounded-xl border border-slate-200 dark:border-slate-800&quot;&gt;<br>                  &lt;div&gt;&lt;span class=&quot;text-slate-400&quot;&gt;Expected:&lt;/span&gt; ${escapeHtml(def.expectedResult)}&lt;/div&gt;<br>                  &lt;div&gt;&lt;span class=&quot;text-slate-400&quot;&gt;Actual:&lt;/span&gt; &lt;span class=&quot;text-rose-500&quot;&gt;${escapeHtml(def.actualResult)}&lt;/span&gt;&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openDefectModal() {<br>      const proj = getActiveProject();<br>      const nextId = `DEF-${101 + (proj.defects?.length || 0)}`;<br>      openModal({<br>        title: &#39;Log New QA Defect&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-3 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Defect ID&lt;/label&gt;&lt;input id=&quot;def-id&quot; value=&quot;${nextId}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Severity&lt;/label&gt;&lt;select id=&quot;def-sev&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option&gt;Critical&lt;/option&gt;&lt;option selected&gt;High&lt;/option&gt;&lt;option&gt;Medium&lt;/option&gt;&lt;option&gt;Low&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Status&lt;/label&gt;&lt;select id=&quot;def-st&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option selected&gt;Open&lt;/option&gt;&lt;option&gt;In Progress&lt;/option&gt;&lt;option&gt;Fixed&lt;/option&gt;&lt;option&gt;Closed&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Defect Title *&lt;/label&gt;&lt;input id=&quot;def-title&quot; placeholder=&quot;e.g. CWT deduction not subtracted from Net Total&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Description&lt;/label&gt;&lt;textarea id=&quot;def-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;/textarea&gt;&lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Expected Result&lt;/label&gt;&lt;input id=&quot;def-exp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Actual Result&lt;/label&gt;&lt;input id=&quot;def-act&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveDefectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Save Defect&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveDefectFromModal() {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;def-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Defect title is required.&#39;, &#39;warning&#39;);<br><br>      proj.defects.unshift({<br>        id: document.getElementById(&#39;def-id&#39;).value.trim() || `DEF-${Date.now()}`,<br>        title,<br>        description: document.getElementById(&#39;def-desc&#39;).value.trim(),<br>        severity: document.getElementById(&#39;def-sev&#39;).value,<br>        priority: &#39;P1&#39;,<br>        status: document.getElementById(&#39;def-st&#39;).value,<br>        expectedResult: document.getElementById(&#39;def-exp&#39;).value.trim(),<br>        actualResult: document.getElementById(&#39;def-act&#39;).value.trim(),<br>        mainPageId: appState.activeMainPageId,<br>        dateReported: new Date().toISOString().slice(0, 10)<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Logged defect&#39;);<br>      showToast(&#39;Defect logged.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function copyDefectSummary(defId) {<br>      const def = getActiveProject()?.defects.find(d =&gt; d.id === defId);<br>      if (!def) return;<br>      const text = `[${def.id}] ${def.title} (Severity: ${def.severity}, Status: ${def.status})\nExpected: ${def.expectedResult}\nActual: ${def.actualResult}\nDetails: ${def.description}`;<br>      const ta = document.createElement(&#39;textarea&#39;);<br>      ta.value = text;<br>      document.body.appendChild(ta);<br>      ta.select();<br>      try { document.execCommand(&#39;copy&#39;); showToast(&#39;Copied defect summary to clipboard.&#39;, &#39;success&#39;); }<br>      catch (e) { showToast(&#39;Copy failed.&#39;, &#39;error&#39;); }<br>      ta.remove();<br>    }<br><br>    function deleteDefect(defId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.defects = proj.defects.filter(d =&gt; d.id !== defId);<br>      scheduleAutosave(&#39;Deleted defect&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 9 VIEW: TEMPLATES<br>     ****************************************************************************/<br>    function renderTemplatesModule() {<br>      const page = getActiveMainPage();<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Reusable EIS Fee &amp; Column Templates&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Apply a template to &lt;strong&gt;${escapeHtml(page ? page.name : &#39;Active Main Page&#39;)}&lt;/strong&gt; or save your current fee structure as a template.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;saveCurrentPageFeesAsTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              + Save Current Page Fees as Template<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 gap-4&quot;&gt;<br>            ${appState.templates.map(tpl =&gt; `<br>              &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 space-y-3&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                  &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(tpl.name)}&lt;/h4&gt;<br>                  &lt;button onclick=&quot;applyTemplateToActivePage(&#39;${tpl.id}&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                    Apply to ${escapeHtml(page ? page.name.split(&#39;:&#39;)[0] : &#39;Page&#39;)}<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(tpl.description)}&lt;/p&gt;<br>                ${tpl.columns &amp;&amp; tpl.columns.length ? `<br>                  &lt;div class=&quot;text-[11px] text-indigo-500 font-medium&quot;&gt;<br>                    Includes ${tpl.columns.length} saved column names: ${tpl.columns.slice(0, 6).map(c =&gt; escapeHtml(c.name)).join(&#39;, &#39;)}${tpl.columns.length &gt; 6 ? &#39;...&#39; : &#39;&#39;}<br>                  &lt;/div&gt;<br>                ` : &#39;&#39;}<br>                &lt;div class=&quot;text-xs font-mono bg-slate-50 dark:bg-slate-800/60 p-2.5 rounded-xl space-y-1&quot;&gt;<br>                  ${(tpl.fees || []).map(f =&gt; `&lt;div&gt;• ${escapeHtml(f.expectedName)} : &lt;strong&gt;${escapeHtml(f.expectedAmount)}&lt;/strong&gt; [${escapeHtml(f.expectedCode || (f.isCwt ? &#39;CWT&#39; : &#39;FEE&#39;))}]&lt;/div&gt;`).join(&#39;&#39;)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function saveCurrentPageFeesAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.fees.length) return showToast(&#39;Add at least one fee row first.&#39;, &#39;warning&#39;);<br>      const tpl = {<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name: `${page.name} Schema`,<br>        description: `Saved from ${page.name} (${page.fees.length} items)`,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      };<br>      appState.templates.push(tpl);<br>      scheduleAutosave(&#39;Saved template&#39;);<br>      showToast(`Saved template &quot;${tpl.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyTemplateToActivePage(tplId) {<br>      const page = getActiveMainPage();<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br>      if (!page || !tpl) return;<br><br>      if (tpl.columns &amp;&amp; tpl.columns.length) {<br>        tpl.columns.forEach((col, idx) =&gt; {<br>          if (page.fields[idx]) {<br>            page.fields[idx].name = col.name;<br>            page.fields[idx].dataType = col.dataType || page.fields[idx].dataType;<br>            page.fields[idx].required = Boolean(col.required);<br>            page.fields[idx].enabled = true;<br>          }<br>        });<br>      }<br><br>      if (tpl.fees &amp;&amp; tpl.fees.length) {<br>        page.fees = tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_tpl_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;Template&#39;<br>        }));<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Applied template&#39;);<br>      showToast(`Applied &quot;${tpl.name}&quot; to ${page.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 10 VIEW: SETTINGS, DIAGNOSTICS &amp; 12-POINT SELF-TEST SUITE<br>     ****************************************************************************/<br>    let diagnosticTestResults = [];<br><br>    function renderSettingsModule() {<br>      const s = appState.settings;<br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4 text-xs&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Validation &amp; OCR Settings&lt;/h3&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;font-semibold block mb-1&quot;&gt;Numeric Tolerance (±)&lt;/label&gt;<br>              &lt;input type=&quot;number&quot; step=&quot;0.01&quot; value=&quot;${s.numericTolerance}&quot; onchange=&quot;appState.settings.numericTolerance = parseFloat(this.value) || 0.01; scheduleAutosave(&#39;Updated tolerance&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;font-semibold block mb-1&quot;&gt;Auto-Accept OCR Confidence Threshold (%)&lt;/label&gt;<br>              &lt;input type=&quot;number&quot; min=&quot;0&quot; max=&quot;100&quot; value=&quot;${s.autoAcceptConfidenceThreshold}&quot; onchange=&quot;appState.settings.autoAcceptConfidenceThreshold = parseInt(this.value, 10) || 88; scheduleAutosave(&#39;Updated OCR threshold&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;label class=&quot;flex items-center justify-between p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60 cursor-pointer&quot;&gt;<br>              &lt;span class=&quot;font-medium&quot;&gt;Case-Sensitive Fee &amp; Field Names&lt;/span&gt;<br>              &lt;input type=&quot;checkbox&quot; ${s.caseSensitiveNames ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.caseSensitiveNames = this.checked; scheduleAutosave(&#39;Updated case sensitivity&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>            &lt;/label&gt;<br><br>            &lt;label class=&quot;flex items-center justify-between p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60 cursor-pointer&quot;&gt;<br>              &lt;span class=&quot;font-medium&quot;&gt;Normalize Whitespace During Comparison&lt;/span&gt;<br>              &lt;input type=&quot;checkbox&quot; ${s.normalizeWhitespace ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.normalizeWhitespace = this.checked; scheduleAutosave(&#39;Updated whitespace setting&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>            &lt;/label&gt;<br><br>            &lt;div class=&quot;pt-2 border-t border-slate-200 dark:border-slate-800 flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;exportFullWorkspaceBackup()&quot; class=&quot;px-3.5 py-2 rounded-xl font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-slate-200&quot;&gt;Export Full Backup JSON&lt;/button&gt;<br>              &lt;button onclick=&quot;confirmResetSampleData()&quot; class=&quot;px-3.5 py-2 rounded-xl font-semibold text-rose-500 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;Reset to Sample Data&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;12-Point Automated Acceptance &amp; Math Test Suite&lt;/h3&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Verifies CWT math, negative/parenthetical signs, missing-info rules, multi-page isolation, and IndexedDB persistence.&lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;button onclick=&quot;runTwelvePointDiagnostics()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-bold bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm&quot;&gt;<br>                Run All 12 Checks<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;space-y-2 max-h-[460px] overflow-y-auto&quot;&gt;<br>              ${diagnosticTestResults.length === 0 ? `<br>                &lt;div class=&quot;p-8 text-center text-xs text-slate-400 border border-dashed border-slate-200 dark:border-slate-800 rounded-xl&quot;&gt;<br>                  Click &lt;strong&gt;Run All 12 Checks&lt;/strong&gt; to execute automated verification tests on the calculation, validation, and persistence engines.<br>                &lt;/div&gt;<br>              ` : diagnosticTestResults.map((r, i) =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${r.passed ? &#39;border-emerald-500/30 bg-emerald-500/5&#39; : &#39;border-rose-500/30 bg-rose-500/5&#39;} flex items-start justify-between gap-3 text-xs&quot;&gt;<br>                  &lt;div&gt;<br>                    &lt;div class=&quot;font-bold&quot;&gt;#${i + 1}. ${escapeHtml(r.name)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 mt-0.5&quot;&gt;${escapeHtml(r.detail)}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;span class=&quot;px-2 py-0.5 rounded font-bold text-[10px] shrink-0€{r.passed ? &#39;bg-emerald-500/20 text-emerald-500&#39; : &#39;bg-rose-500/20 text-rose-500&#39;}&quot;&gt;${r.passed ? &#39;PASS&#39; : &#39;FAIL&#39;}&lt;/span&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    async function runTwelvePointDiagnostics() {<br>      const results = [];<br><br>      const t1 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;1000&#39;, actualAmount: &#39;1000&#39;, isCwt: false },<br>        { expectedAmount: &#39;250&#39;, actualAmount: &#39;250&#39;, isCwt: false },<br>        { expectedAmount: &#39;-50&#39;, actualAmount: &#39;-50&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;Fee 1 (1000) + Fee 2 (250) with CWT (-50) = Net 1200&#39;, passed: t1.actualGross === 1250 &amp;&amp; t1.actualCwt === 50 &amp;&amp; t1.actualNet === 1200, detail: `Gross=${t1.actualGross}, CWT=${t1.actualCwt}, Net=${t1.actualNet}` });<br><br>      const t2 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;1000&#39;, actualAmount: &#39;1000&#39;, isCwt: false },<br>        { expectedAmount: &#39;250&#39;, actualAmount: &#39;250&#39;, isCwt: false },<br>        { expectedAmount: &#39;(50)&#39;, actualAmount: &#39;(50)&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;Parenthetical CWT (50) deducted cleanly as 50&#39;, passed: t2.actualCwt === 50 &amp;&amp; t2.actualNet === 1200, detail: `CWT=${t2.actualCwt}, Net=${t2.actualNet}` });<br><br>      const t3 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;1200&#39;, actualCode: &#39;NC&#39;, isCwt: false });<br>      results.push({ name: &#39;Fee 1 Mismatch (1000 vs 1200) flags FAIL with +200.00 diff&#39;, passed: t3.status === &#39;FAIL&#39; &amp;&amp; t3.amountComparison.difference === &#39;200.00&#39;, detail: t3.explanation });<br><br>      const t4 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;&#39;, actualCode: &#39;NC&#39;, isCwt: false });<br>      results.push({ name: &#39;Missing Actual Amount evaluates as PENDING (not false PASS)&#39;, passed: t4.status === &#39;PENDING&#39;, detail: `Status=${t4.status}` });<br><br>      const t5 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;1000&#39;, actualCode: &#39;&#39;, isCwt: false });<br>      results.push({ name: &#39;Missing Required Fee Code evaluates as PENDING&#39;, passed: t5.status === &#39;PENDING&#39;, detail: `Status=${t5.status}` });<br><br>      const t6 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;500&#39;, actualAmount: &#39;500&#39;, isCwt: false },<br>        { expectedAmount: &#39;25&#39;, actualAmount: &#39;25&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;CWT excluded from Gross Fees sum&#39;, passed: t6.actualGross === 500 &amp;&amp; t6.actualNet === 475, detail: `Gross=${t6.actualGross}, Net=${t6.actualNet}` });<br><br>      const qp = OcrMappingEngine.parseQuickPasteFees(&#39;Fee 1\n1000\nNC\nCWT\n50&#39;);<br>      results.push({ name: &#39;Quick Paste parser extracts multi-line fee &amp; CWT blocks&#39;, passed: qp.length === 2 &amp;&amp; qp[1].isCwt === true, detail: `Parsed ${qp.length} items` });<br><br>      const proj = getActiveProject();<br>      results.push({ name: &#39;Multi-Main-Page isolation within active project&#39;, passed: proj &amp;&amp; proj.mainPages.length &gt;= 2 &amp;&amp; proj.mainPages[0].id !== proj.mainPages[1].id, detail: `${proj?.mainPages.length || 0} isolated pages` });<br><br>      const savedOk = await PersistenceEngine.saveState(appState);<br>      const loadedState = await PersistenceEngine.loadState();<br>      results.push({ name: &#39;IndexedDB save &amp; reload persistence round-trip&#39;, passed: Boolean(savedOk &amp;&amp; loadedState &amp;&amp; loadedState.projects.length &gt; 0), detail: `Projects persisted: ${loadedState?.projects?.length || 0}` });<br><br>      results.push({ name: &#39;Configurable numbered fields initialized (1-50+)&#39;, passed: Boolean(proj?.mainPages[0]?.fields?.length &gt;= 50), detail: `Field count: ${proj?.mainPages[0]?.fields?.length || 0}` });<br><br>      results.push({ name: &#39;Dynamic QA label pool supports 1–200+ labels&#39;, passed: (appState.settings.qaLabelMax || 200) &gt;= 200, detail: `Max QA label: ${appState.settings.qaLabelMax}` });<br><br>      results.push({ name: &#39;Report export generator function available&#39;, passed: typeof exportReportFile === &#39;function&#39;, detail: &#39;CSV, HTML, DOC, JSON, TXT &amp; Print ready&#39; });<br><br>      diagnosticTestResults = results;<br>      const passCnt = results.filter(r =&gt; r.passed).length;<br>      showToast(`Diagnostics complete: ${passCnt}/${results.length} passed.`, passCnt === results.length ? &#39;success&#39; : &#39;warning&#39;);<br>      renderApp();<br>    }<br><br>    function exportFullWorkspaceBackup() {<br>      const blob = new Blob([JSON.stringify(appState, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `SMART_full_workspace_backup_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full workspace JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function confirmResetSampleData() {<br>      openModal({<br>        title: &#39;Reset Workspace to Sample Seed Data&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;This will replace current workspace projects with fresh sample EIS &amp; QA seed data. Export a JSON backup first if you wish to keep current edits.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;resetToSampleSeedData()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Reset Sample Data&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    async function resetToSampleSeedData() {<br>      appState = createSampleSeedState();<br>      closeModal();<br>      await PersistenceEngine.saveState(appState);<br>      showToast(&#39;Workspace reset to fresh sample data.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 11 VIEW: REPORTS HUB (ALL RESULTS, PROJECTS &amp; QA REPORTS)<br>     * Includes toggle control for embedding/excluding receipt images in HTML &amp; DOC exports.<br>     ****************************************************************************/<br>    let reportScope = &#39;active_page&#39;; // &#39;active_page&#39; | &#39;all_pages&#39; | &#39;all_projects&#39;<br>    let reportIncludeReceipts = true; // Toggle state for embedding receipt images in HTML &amp; Word (.doc) exports<br><br>    function setReportIncludeReceipts(checked) {<br>      reportIncludeReceipts = Boolean(checked);<br>      scheduleAutosave(&#39;Updated report receipt image export preference&#39;);<br>      renderApp();<br>    }<br><br>    function getReportDataset() {<br>      const activeProj = getActiveProject();<br>      const activePage = getActiveMainPage();<br><br>      if (reportScope === &#39;active_page&#39;) {<br>        return {<br>          title: `Main Page Validation &amp; QA Report — ${activePage?.name || &#39;Page&#39;}`,<br>          projects: activeProj ? [{<br>            ...activeProj,<br>            mainPages: activePage ? [activePage] : []<br>          }] : []<br>        };<br>      }<br>      if (reportScope === &#39;all_pages&#39;) {<br>        return {<br>          title: `Full Project EIS &amp; QA Report — ${activeProj?.name || &#39;Project&#39;}`,<br>          projects: activeProj ? [activeProj] : []<br>        };<br>      }<br>      return {<br>        title: `All Projects Master EIS &amp; QA Audit Report (${appState.projects.length} Projects)`,<br>        projects: appState.projects<br>      };<br>    }<br><br><br>    /****************************************************************************<br>     * REPORT SECTION BUILDERS: Side-by-Side Fee/CWT Comparison &amp;<br>     * Expected Row Columns vs Receipt Verification (used by preview + all exports)<br>     ****************************************************************************/<br>    function getReportRows(mp) {<br>      if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>      const feeRows = (mp.fees || []).map(f =&gt; ({ fee: f, v: f.lastValidation || ValidationEngine.validateFeeRow(f) }));<br>      const colRows = (mp.fields || [])<br>        .filter(f =&gt; (f.expectedValue !== &#39;&#39; &amp;&amp; f.expectedValue != null) || (f.actualValue !== &#39;&#39; &amp;&amp; f.actualValue != null))<br>        .map(f =&gt; ({ field: f, v: f.lastValidation || ValidationEngine.validateField(f) }));<br>      const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees || []);<br>      return { feeRows, colRows, fin };<br>    }<br><br>    function fmtSigned(n) {<br>      return `${n &gt; 0 ? &#39;+&#39; : &#39;&#39;}${Number(n).toFixed(2)}`;<br>    }<br><br>    function renderReportSideBySideApp(mp) {<br>      const { feeRows, fin } = getReportRows(mp);<br>      const threshold = appState.settings.autoAcceptConfidenceThreshold;<br>      return `<br>        &lt;div class=&quot;space-y-2&quot;&gt;<br>          &lt;h5 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Side-by-Side EIS Fee &amp;amp; CWT Comparison&lt;/h5&gt;<br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Fee Item&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Receipt Actual (Name / Amt / Code)&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-right&quot;&gt;Diff&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Conf&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody&gt;<br>                ${feeRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-4 text-center text-slate-400&quot;&gt;No fee rows configured on this Main Page.&lt;/td&gt;&lt;/tr&gt;` : feeRows.map(({ fee, v }) =&gt; `<br>                  &lt;tr class=&quot;border-t border-slate-100 dark:border-slate-800/70&quot;&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-semibold&quot;&gt;${escapeHtml(fee.expectedName)} ${v.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-mono text-[11px]&quot;&gt;<br>                      &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-mono text-[11px]&quot;&gt;<br>                      &lt;div&gt;${escapeHtml(fee.actualName || &#39;-&#39;)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.actualAmount || &#39;-&#39;)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.actualCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 text-right font-mono font-bold ${v.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;${escapeHtml(v.amountComparison.difference)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; threshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(v.status)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                  &lt;tr class=&quot;text-[11px] text-slate-500 bg-slate-50/60 dark:bg-slate-950/40&quot;&gt;<br>                    &lt;td colspan=&quot;6&quot; class=&quot;px-2 py-1&quot;&gt;&lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(v.explanation)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-3 gap-2 text-xs pt-1&quot;&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold&quot;&gt;${fin.expectedGross.toFixed(2)} / ${fin.actualGross.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;CWT Deduction (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold text-amber-500&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Net Total (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold text-emerald-500&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)} &lt;span class=&quot;${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;(${fmtSigned(fin.netDifference)})&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;Formula: ${escapeHtml(fin.formulaExplanation)}&lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderReportColumnsApp(mp) {<br>      const { colRows } = getReportRows(mp);<br>      const matched = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>      return `<br>        &lt;div class=&quot;space-y-2&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>            &lt;h5 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h5&gt;<br>            &lt;span class=&quot;px-2.5 py-0.5 rounded-full text-[11px] font-bold ${colRows.length &amp;&amp; matched === colRows.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;${matched} / ${colRows.length} Expected Columns Matched&lt;/span&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Col&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Field Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Expected Row Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Explanation&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${colRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-4 text-center text-slate-400&quot;&gt;No expected row columns pasted or configured for this Main Page.&lt;/td&gt;&lt;/tr&gt;` : colRows.map(({ field, v }) =&gt; `<br>                  &lt;tr&gt;<br>                    &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(field.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(field.name)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(field.expectedValue || &#39;-&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-mono&quot;&gt;${escapeHtml(field.actualValue || &#39;-&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(v.status)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-[11px] text-slate-500&quot;&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderReportSideBySideStandalone(mp) {<br>      const { feeRows, fin } = getReportRows(mp);<br>      return `<br>        &lt;div class=&quot;section-title&quot;&gt;Side-by-Side EIS Fee &amp;amp; CWT Comparison&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th&gt;#&lt;/th&gt;<br>              &lt;th&gt;Fee Item&lt;/th&gt;<br>              &lt;th&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>              &lt;th&gt;Receipt Actual (Name / Amt / Code)&lt;/th&gt;<br>              &lt;th&gt;Diff&lt;/th&gt;<br>              &lt;th&gt;Conf&lt;/th&gt;<br>              &lt;th&gt;Status&lt;/th&gt;<br>              &lt;th&gt;Rule Evaluation&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            ${feeRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;8&quot; class=&quot;muted&quot;&gt;No fee rows configured on this Main Page.&lt;/td&gt;&lt;/tr&gt;` : feeRows.map(({ fee, v }, i) =&gt; `<br>              &lt;tr&gt;<br>                &lt;td&gt;${i + 1}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.expectedName)}${v.isCwt ? &#39; &lt;span class=&quot;badge REVIEW&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.expectedName)} / ${escapeHtml(fee.expectedAmount)} / ${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.actualName || &#39;-&#39;)} / ${escapeHtml(fee.actualAmount || &#39;-&#39;)} / ${escapeHtml(fee.actualCode || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td class=&quot;num&quot;&gt;${escapeHtml(v.amountComparison.difference)}&lt;/td&gt;<br>                &lt;td class=&quot;num&quot;&gt;${fee.ocrConfidence ? escapeHtml(fee.ocrConfidence) + &#39;%&#39; : &#39;Manual&#39;}&lt;/td&gt;<br>                &lt;td&gt;&lt;span class=&quot;badge ${escapeHtml(v.status)}&quot;&gt;${escapeHtml(v.status)}&lt;/span&gt;&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>              &lt;/tr&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>        &lt;div class=&quot;section-title&quot;&gt;CWT &amp;amp; Net Settlement Reconciliation&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Measure&lt;/th&gt;&lt;th&gt;Expected&lt;/th&gt;&lt;th&gt;Receipt&lt;/th&gt;&lt;th&gt;Variance&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>          &lt;tbody&gt;<br>            &lt;tr&gt;&lt;td&gt;Gross Fees (non-CWT)&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.grossDifference)}&lt;/td&gt;&lt;/tr&gt;<br>            &lt;tr&gt;&lt;td&gt;Total CWT Deduction&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.cwtDifference)}&lt;/td&gt;&lt;/tr&gt;<br>            &lt;tr&gt;&lt;td&gt;&lt;strong&gt;Net Total&lt;/strong&gt;&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.netDifference)}&lt;/td&gt;&lt;/tr&gt;<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>        &lt;p class=&quot;muted&quot;&gt;Formula: ${escapeHtml(fin.formulaExplanation)}&lt;/p&gt;<br>      `;<br>    }<br><br>    function renderReportColumnsStandalone(mp) {<br>      const { colRows } = getReportRows(mp);<br>      const matched = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>      return `<br>        &lt;div class=&quot;section-title&quot;&gt;Expected Row Columns vs Receipt Verification — ${matched} / ${colRows.length} Expected Columns Matched&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th&gt;Col&lt;/th&gt;<br>              &lt;th&gt;Field Name&lt;/th&gt;<br>              &lt;th&gt;Expected Row Value&lt;/th&gt;<br>              &lt;th&gt;Found on Receipt&lt;/th&gt;<br>              &lt;th&gt;Status&lt;/th&gt;<br>              &lt;th&gt;Explanation&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            ${colRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;muted&quot;&gt;No expected row columns pasted or configured for this Main Page.&lt;/td&gt;&lt;/tr&gt;` : colRows.map(({ field, v }) =&gt; `<br>              &lt;tr&gt;<br>                &lt;td&gt;C${String(field.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.name)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.expectedValue || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.actualValue || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;&lt;span class=&quot;badge ${escapeHtml(v.status)}&quot;&gt;${escapeHtml(v.status)}&lt;/span&gt;&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>              &lt;/tr&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>      `;<br>    }<br><br>    function renderReportsModule() {<br>      const dataset = getReportDataset();<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br><br>      let totalPages = 0, totalFees = 0, totalPass = 0, totalFail = 0, totalReview = 0, totalPending = 0;<br>      let totalGross = 0, totalCwt = 0, totalNet = 0;<br><br>      dataset.projects.forEach(p =&gt; {<br>        (p.mainPages || []).forEach(mp =&gt; {<br>          totalPages++;<br>          if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>          const s = mp.validationSummary;<br>          totalFees += (mp.fees || []).length;<br>          totalPass += s.counts.pass;<br>          totalFail += s.counts.fail;<br>          totalReview += s.counts.review;<br>          totalPending += s.counts.pending;<br>          totalGross += s.financials.actualGross;<br>          totalCwt += s.financials.actualCwt;<br>          totalNet += s.financials.actualNet;<br>        });<br>      });<br><br>      const allTestCases = dataset.projects.flatMap(p =&gt; (p.testCases || []).map(tc =&gt; ({ ...tc, projectName: p.name })));<br>      const allDefects = dataset.projects.flatMap(p =&gt; (p.defects || []).map(df =&gt; ({ ...df, projectName: p.name })));<br><br>      return `<br>        &lt;!-- Report Scope &amp; Export Controls --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4 no-print&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Unified EIS &amp; QA Reporting Center&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Export all validation results, CWT calculations, test cases, defects, and project summaries.&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;label class=&quot;text-xs font-semibold text-slate-500&quot;&gt;Report Scope:&lt;/label&gt;<br>              &lt;select onchange=&quot;reportScope = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot;&gt;<br>                &lt;option value=&quot;active_page&quot; ${reportScope === &#39;active_page&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;Active Main Page (${escapeHtml(page?.name || &#39;&#39;)})&lt;/option&gt;<br>                &lt;option value=&quot;all_pages&quot; ${reportScope === &#39;all_pages&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Main Pages in Active Project (${escapeHtml(proj?.name || &#39;&#39;)})&lt;/option&gt;<br>                &lt;option value=&quot;all_projects&quot; ${reportScope === &#39;all_projects&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Projects (${appState.projects.length})&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;!-- Toggle for Including/Excluding Receipt Images in HTML &amp; Word (.doc) Exports --&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-2.5 px-3.5 py-2 rounded-xl bg-slate-50 dark:bg-slate-800/80 border border-slate-200 dark:border-slate-700 cursor-pointer select-none text-xs font-semibold&quot;&gt;<br>              &lt;input id=&quot;toggle-include-receipts&quot; type=&quot;checkbox&quot; ${reportIncludeReceipts ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;setReportIncludeReceipts(this.checked)&quot; class=&quot;rounded text-brand-600 focus:ring-brand-500 cursor-pointer&quot; /&gt;<br>              &lt;span&gt;Include receipt images in HTML &amp;amp; Word (.doc) exports&lt;/span&gt;<br>              &lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold ${reportIncludeReceipts ? &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400&#39; : &#39;bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300&#39;}&quot;&gt;${reportIncludeReceipts ? &#39;INCLUDED&#39; : &#39;EXCLUDED&#39;}&lt;/span&gt;<br>            &lt;/label&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;csv&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-spreadsheet&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export CSV&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;html&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-code&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export HTML&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;doc&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-600 hover:bg-indigo-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export Word (.doc)&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;window.print()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-900 text-white dark:bg-slate-700&quot;&gt;<br>                &lt;i data-lucide=&quot;printer&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Print / Save PDF&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;json&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                JSON<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;txt&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                TXT<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Live Printable / Previewable Report Document --&gt;<br>        &lt;div id=&quot;printable-report-area&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-6 space-y-6&quot;&gt;<br>          &lt;div class=&quot;border-b border-slate-200 dark:border-slate-800 pb-4 flex flex-col sm:flex-row sm:items-center justify-between gap-2&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;text-[11px] font-bold uppercase tracking-wider text-brand-500&quot;&gt;SMART EIS &amp; QA VALIDATION STUDIO&lt;/div&gt;<br>              &lt;h2 class=&quot;text-lg font-extrabold mt-0.5&quot;&gt;${escapeHtml(dataset.title)}&lt;/h2&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Generated: ${new Date().toLocaleString()} • Schema v${APP_SCHEMA_VERSION}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;text-xs font-mono text-slate-500&quot;&gt;<br>              Pages: &lt;strong&gt;${totalPages}&lt;/strong&gt; • Fee Rows: &lt;strong&gt;${totalFees}&lt;/strong&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;PASS&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-emerald-500&quot;&gt;${totalPass}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;FAIL&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-rose-500&quot;&gt;${totalFail}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;REVIEW&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-amber-500&quot;&gt;${totalReview}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;PENDING&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-sky-500&quot;&gt;${totalPending}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Gross Actual&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold&quot;&gt;${totalGross.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;CWT Deducted&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold text-amber-500&quot;&gt;-${totalCwt.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Net Actual&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold text-emerald-500&quot;&gt;${totalNet.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${dataset.projects.map(p =&gt; `<br>            &lt;div class=&quot;space-y-4&quot;&gt;<br>              &lt;div class=&quot;bg-slate-100 dark:bg-slate-800/80 px-4 py-2.5 rounded-xl flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                &lt;div&gt;&lt;strong&gt;Project:&lt;/strong&gt; ${escapeHtml(p.name)} &lt;span class=&quot;font-mono text-slate-500&quot;&gt;(${escapeHtml(p.reference)})&lt;/span&gt;&lt;/div&gt;<br>                &lt;div&gt;&lt;strong&gt;Owner:&lt;/strong&gt; ${escapeHtml(p.owner)} • &lt;strong&gt;Status:&lt;/strong&gt; ${escapeHtml(p.status)}&lt;/div&gt;<br>              &lt;/div&gt;<br><br>              ${(p.mainPages || []).map(mp =&gt; {<br>                const fin = mp.validationSummary.financials;<br>                return `<br>                  &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-3&quot;&gt;<br>                    &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                      &lt;div&gt;<br>                        &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(mp.name)}&lt;/h4&gt;<br>                        &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(mp.description)}&lt;/p&gt;<br>                      &lt;/div&gt;<br>                      &lt;div class=&quot;flex items-center gap-3 text-xs&quot;&gt;<br>                        &lt;span class=&quot;font-mono&quot;&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; | CWT: &lt;strong class=&quot;text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; | Net: &lt;strong class=&quot;text-emerald-500&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt;&lt;/span&gt;<br>                        ${statusBadge(mp.validationSummary.overallStatus)}<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br><br>                    ${renderReportSideBySideApp(mp)}<br>                    ${renderReportColumnsApp(mp)}<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          `).join(&#39;&#39;)}<br><br>          &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-2 gap-5 pt-2&quot;&gt;<br>            &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2&quot;&gt;<br>              &lt;h4 class=&quot;font-bold text-xs uppercase tracking-wider text-slate-400&quot;&gt;Test Cases (${allTestCases.length})&lt;/h4&gt;<br>              ${allTestCases.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;No test cases in scope.&lt;/div&gt;` : allTestCases.map(tc =&gt; `<br>                &lt;div class=&quot;flex items-center justify-between text-xs py-1.5 border-b border-slate-100 dark:divide-slate-800&quot;&gt;<br>                  &lt;span class=&quot;truncate pr-2&quot;&gt;&lt;strong class=&quot;font-mono&quot;&gt;${escapeHtml(tc.id)}&lt;/strong&gt;: ${escapeHtml(tc.title)}&lt;/span&gt;<br>                  ${statusBadge(tc.status)}<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2&quot;&gt;<br>              &lt;h4 class=&quot;font-bold text-xs uppercase tracking-wider text-slate-400&quot;&gt;Defects (${allDefects.length})&lt;/h4&gt;<br>              ${allDefects.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;No defects in scope.&lt;/div&gt;` : allDefects.map(df =&gt; `<br>                &lt;div class=&quot;flex items-center justify-between text-xs py-1.5 border-b border-slate-100 dark:divide-slate-800&quot;&gt;<br>                  &lt;span class=&quot;truncate pr-2&quot;&gt;&lt;strong class=&quot;font-mono text-rose-500&quot;&gt;${escapeHtml(df.id)}&lt;/strong&gt;: ${escapeHtml(df.title)}&lt;/span&gt;<br>                  ${statusBadge(df.status)}<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function buildStandaloneHtmlReport(dataset, includeReceipts = true) {<br>      const receiptNotice = includeReceipts<br>        ? &#39;Receipt &amp;amp; evidence images: &lt;strong&gt;Included&lt;/strong&gt;&#39;<br>        : &#39;Receipt &amp;amp; evidence images: &lt;strong&gt;Excluded by user toggle&lt;/strong&gt;&#39;;<br><br>      const pagesHtml = dataset.projects.map(p =&gt; `<br>        &lt;div class=&quot;project-block&quot;&gt;<br>          &lt;h2&gt;Project: ${escapeHtml(p.name)} (${escapeHtml(p.reference)})&lt;/h2&gt;<br>          &lt;p class=&quot;meta&quot;&gt;Owner: ${escapeHtml(p.owner)} | Status: ${escapeHtml(p.status)} | ${receiptNotice}&lt;/p&gt;<br>          ${(p.mainPages || []).map(mp =&gt; {<br>            const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees);<br>            const overall = mp.validationSummary?.overallStatus || &#39;PENDING&#39;;<br>            const receiptPages = (mp.receipt?.pages || []).map(sanitizeImageSrc).filter(Boolean);<br><br>            const receiptSectionHtml = includeReceipts ? `<br>              &lt;div class=&quot;receipt-section&quot;&gt;<br>                &lt;div class=&quot;receipt-title&quot;&gt;Attached Receipt Evidence (${escapeHtml(mp.receipt?.fileName || &#39;Receipt&#39;)} — ${receiptPages.length ? receiptPages.length + &#39; page(s)&#39; : &#39;No image attached&#39;})&lt;/div&gt;<br>                ${receiptPages.length ? receiptPages.map((src, idx) =&gt; `<br>                  &lt;div class=&quot;receipt-img-wrap&quot;&gt;<br>                    &lt;div class=&quot;receipt-page-label&quot;&gt;Page ${idx + 1}&lt;/div&gt;<br>                    &lt;img src=&quot;${src}&quot; alt=&quot;Receipt Page ${idx + 1} for ${escapeHtml(mp.name)}&quot; class=&quot;receipt-img&quot; /&gt;<br>                  &lt;/div&gt;<br>                `).join(&#39;&#39;) : `&lt;p class=&quot;muted&quot;&gt;No receipt image file attached to this Main Page.&lt;/p&gt;`}<br>              &lt;/div&gt;<br>            ` : &#39;&#39;;<br><br>            return `<br>              &lt;div class=&quot;page-block&quot;&gt;<br>                &lt;div class=&quot;page-header&quot;&gt;<br>                  &lt;h3&gt;${escapeHtml(mp.name)}&lt;/h3&gt;<br>                  &lt;span class=&quot;badge ${escapeHtml(overall)}&quot;&gt;${escapeHtml(overall)}&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;desc&quot;&gt;${escapeHtml(mp.description || &#39;&#39;)}&lt;/p&gt;<br>                &lt;p class=&quot;fin&quot;&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; | CWT: &lt;strong&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; | Net Actual: &lt;strong&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt; (Expected Net: ${fin.expectedNet.toFixed(2)})&lt;/p&gt;<br>                ${renderReportSideBySideStandalone(mp)}<br>                ${renderReportColumnsStandalone(mp)}<br>                ${receiptSectionHtml}<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `).join(&#39;&#39;);<br><br>      return `&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;title&gt;${escapeHtml(dataset.title)}&lt;/title&gt;<br>  &lt;style&gt;<br>    body { font-family: Arial, Helvetica, sans-serif; color: #0f172a; background: #ffffff; margin: 24px; line-height: 1.45; }<br>    h1 { margin: 0 0 6px; font-size: 20px; }<br>    h2 { font-size: 16px; margin: 20px 0 6px; color: #1e293b; border-bottom: 2px solid #e2e8f0; padding-bottom: 4px; }<br>    h3 { font-size: 14px; margin: 0; }<br>    .meta, .desc, .muted { font-size: 12px; color: #64748b; margin: 4px 0 10px; }<br>    .fin { font-size: 12px; background: #f8fafc; padding: 8px 10px; border-radius: 6px; border: 1px solid #e2e8f0; }<br>    .page-block { border: 1px solid #cbd5e1; border-radius: 8px; padding: 14px; margin: 14px 0; }<br>    .page-header { display: flex; justify-content: space-between; align-items: center; }<br>    table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 12px; }<br>    th, td { border: 1px solid #cbd5e1; padding: 6px 8px; text-align: left; }<br>    th { background: #f1f5f9; font-weight: bold; }<br>    td.num { text-align: right; font-family: Consolas, monospace; }<br>    .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 10px; font-weight: bold; background: #e2e8f0; color: #1e293b; }<br>    .badge.PASS { background: #dcfce7; color: #166534; }<br>    .badge.FAIL { background: #fee2e2; color: #991b1b; }<br>    .badge.REVIEW { background: #fef3c7; color: #92400e; }<br>    .badge.PENDING { background: #e0f2fe; color: #075985; }<br>    .receipt-section { margin-top: 12px; padding-top: 10px; border-top: 1px dashed #cbd5e1; }<br>    .receipt-title { font-size: 12px; font-weight: bold; margin-bottom: 8px; color: #334155; }<br>    .receipt-img-wrap { margin-bottom: 10px; }<br>    .receipt-page-label { font-size: 11px; color: #64748b; margin-bottom: 4px; }<br>    .receipt-img { max-width: 460px; width: 100%; height: auto; border: 1px solid #cbd5e1; border-radius: 6px; display: block; }<br>    .section-title { font-size: 13px; font-weight: bold; margin: 16px 0 4px; color: #334155; }<br>    td.muted { text-align: center; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;${escapeHtml(dataset.title)}&lt;/h1&gt;<br>  &lt;div class=&quot;meta&quot;&gt;Generated: ${escapeHtml(new Date().toLocaleString())} | ${receiptNotice}&lt;/div&gt;<br>  ${pagesHtml}<br>&lt;/body&gt;<br>&lt;/html&gt;`;<br>    }<br><br>    function exportReportFile(format) {<br>      const dataset = getReportDataset();<br>      const stamp = new Date().toISOString().slice(0, 10);<br>      const includeReceipts = Boolean(reportIncludeReceipts);<br><br>      if (format === &#39;json&#39;) {<br>        const payload = {<br>          title: dataset.title,<br>          exportedAt: new Date().toISOString(),<br>          includeReceiptImages: includeReceipts,<br>          projects: dataset.projects,<br>          reportSections: dataset.projects.flatMap(p =&gt; (p.mainPages || []).map(mp =&gt; {<br>            const { feeRows, colRows, fin } = getReportRows(mp);<br>            return {<br>              project: p.name,<br>              mainPage: mp.name,<br>              sideBySideFeeCwtComparison: feeRows.map(({ fee, v }) =&gt; ({ feeItem: fee.expectedName, isCwt: v.isCwt, expected: { name: fee.expectedName, amount: fee.expectedAmount, code: fee.expectedCode }, receipt: { name: fee.actualName, amount: fee.actualAmount, code: fee.actualCode }, difference: v.amountComparison.difference, confidence: fee.ocrConfidence ?? null, status: v.status, explanation: v.explanation })),<br>              netReconciliation: fin,<br>              expectedRowColumnsVerification: colRows.map(({ field, v }) =&gt; ({ column: &#39;C&#39; + String(field.number).padStart(2, &#39;0&#39;), fieldName: field.name, expectedValue: field.expectedValue, foundOnReceipt: field.actualValue, status: v.status, explanation: v.explanation }))<br>            };<br>          }))<br>        };<br>        downloadBlob(JSON.stringify(payload, null, 2), `SMART_report_${stamp}.json`, &#39;application/json&#39;);<br>      } else if (format === &#39;csv&#39;) {<br>        const rows = [[&#39;Section&#39;, &#39;Project&#39;, &#39;Main Page&#39;, &#39;Fee / Field Name&#39;, &#39;Expected Name&#39;, &#39;Expected Amount&#39;, &#39;Expected Code&#39;, &#39;Receipt Name&#39;, &#39;Receipt Amount&#39;, &#39;Receipt Code&#39;, &#39;Diff&#39;, &#39;Confidence&#39;, &#39;Status&#39;, &#39;Explanation&#39;]];<br>        dataset.projects.forEach(p =&gt; {<br>          (p.mainPages || []).forEach(mp =&gt; {<br>            const { feeRows, colRows } = getReportRows(mp);<br>            feeRows.forEach(({ fee: f, v }) =&gt; {<br>              rows.push([&#39;Fee &amp; CWT Comparison&#39;, p.name, mp.name, f.expectedName, f.expectedName, f.expectedAmount, f.expectedCode, f.actualName, f.actualAmount, f.actualCode, v.amountComparison.difference, f.ocrConfidence ?? &#39;Manual&#39;, v.status, v.explanation]);<br>            });<br>            colRows.forEach(({ field, v }) =&gt; {<br>              rows.push([&#39;Expected Row Column Verification&#39;, p.name, mp.name, `C${String(field.number).padStart(2, &#39;0&#39;)} ${field.name}`, &#39;&#39;, field.expectedValue, &#39;&#39;, &#39;&#39;, field.actualValue, &#39;&#39;, v.difference ?? &#39;&#39;, &#39;&#39;, v.status, v.explanation]);<br>            });<br>          });<br>        });<br>        const csv = rows.map(r =&gt; r.map(c =&gt; `&quot;${String(c ?? &#39;&#39;).replace(/&quot;/g, &#39;&quot;&quot;&#39;)}&quot;`).join(&#39;,&#39;)).join(&#39;\n&#39;);<br>        downloadBlob(csv, `SMART_report_${stamp}.csv`, &#39;text/csv&#39;);<br>      } else if (format === &#39;txt&#39;) {<br>        const lines = [dataset.title, `Generated: ${new Date().toLocaleString()}`, &#39;========================================&#39;];<br>        dataset.projects.forEach(p =&gt; {<br>          lines.push(`\nProject: ${p.name} (${p.reference})`);<br>          (p.mainPages || []).forEach(mp =&gt; {<br>            const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees);<br>            lines.push(`  Main Page: ${mp.name} [${mp.validationSummary?.overallStatus || &#39;PENDING&#39;}] — Gross ${fin.actualGross.toFixed(2)}, CWT -${fin.actualCwt.toFixed(2)}, Net ${fin.actualNet.toFixed(2)}`);<br>            const { feeRows, colRows } = getReportRows(mp);<br>            lines.push(&#39;    [Side-by-Side EIS Fee &amp; CWT Comparison]&#39;);<br>            feeRows.forEach(({ fee: f, v }) =&gt; {<br>              lines.push(`    - ${f.expectedName}${v.isCwt ? &#39; (CWT)&#39; : &#39;&#39;}: Expected ${f.expectedName} / ${f.expectedAmount} / ${f.expectedCode || &#39;-&#39;} | Receipt ${f.actualName || &#39;-&#39;} / ${f.actualAmount || &#39;-&#39;} / ${f.actualCode || &#39;-&#39;} | Diff=${v.amountComparison.difference} | ${v.status}`);<br>              lines.push(`        Rule: ${v.explanation}`);<br>            });<br>            const matchedCols = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>            lines.push(`    [Expected Row Columns vs Receipt Verification: ${matchedCols}/${colRows.length} matched]`);<br>            colRows.forEach(({ field, v }) =&gt; {<br>              lines.push(`    - C${String(field.number).padStart(2, &#39;0&#39;)} ${field.name}: Expected=${field.expectedValue || &#39;-&#39;} | Receipt=${field.actualValue || &#39;-&#39;} | ${v.status}`);<br>            });<br>          });<br>        });<br>        downloadBlob(lines.join(&#39;\n&#39;), `SMART_report_${stamp}.txt`, &#39;text/plain&#39;);<br>      } else if (format === &#39;html&#39;) {<br>        const htmlContent = buildStandaloneHtmlReport(dataset, includeReceipts);<br>        downloadBlob(htmlContent, `SMART_report_${stamp}.html`, &#39;text/html&#39;);<br>      } else if (format === &#39;doc&#39;) {<br>        // Word-compatible HTML document (.doc) honoring receipt image toggle<br>        const docBodyHtml = buildStandaloneHtmlReport(dataset, includeReceipts);<br>        const wordHtml = `&lt;html xmlns:o=&quot;urn:schemas-microsoft-com:office:office&quot; xmlns:w=&quot;urn:schemas-microsoft-com:office:word&quot; xmlns=&quot;http://www.w3.org/TR/REC-html40&quot;&gt;${docBodyHtml.replace(/^[\s\S]*&lt;html[^&gt;]*&gt;|&lt;\/html&gt;\s*$/gi, &#39;&#39;)}&lt;/html&gt;`;<br>        downloadBlob(wordHtml, `SMART_report_${stamp}.doc`, &#39;application/msword&#39;);<br>      }<br><br>      showToast(`Exported ${format.toUpperCase()} report${(format === &#39;html&#39; || format === &#39;doc&#39;) ? (includeReceipts ? &#39; (with receipt images)&#39; : &#39; (receipt images excluded)&#39;) : &#39;&#39;}.`, &#39;success&#39;);<br>    }<br><br>    function downloadBlob(content, filename, mimeType) {<br>      const blob = new Blob([content], { type: mimeType });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = filename;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>    }<br><br>    /****************************************************************************<br>     * GLOBAL KEYBOARD SHORTCUTS &amp; PASTE LISTENER<br>     ****************************************************************************/<br>    document.addEventListener(&#39;keydown&#39;, (e) =&gt; {<br>      if ((e.ctrlKey || e.metaKey) &amp;&amp; e.key.toLowerCase() === &#39;s&#39;) {<br>        e.preventDefault();<br>        manualSaveProject();<br>      }<br>      if (e.key === &#39;Escape&#39;) {<br>        closeModal();<br>        if (appState.ui.evPendingLabel) { appState.ui.evPendingLabel = null; if (appState.activeModule === &#39;evidence&#39;) renderApp(); }<br>      }<br>      if (e.altKey &amp;&amp; (e.key === &#39;ArrowRight&#39; || e.key === &#39;ArrowLeft&#39;) &amp;&amp; appState.activeModule === &#39;evidence&#39;) {<br>        e.preventDefault();<br>        evStepPage(e.key === &#39;ArrowRight&#39; ? 1 : -1);<br>      }<br>    });<br><br>    document.addEventListener(&#39;paste&#39;, async (e) =&gt; {<br>      const activeTag = document.activeElement?.tagName?.toLowerCase();<br>      if (activeTag === &#39;input&#39; || activeTag === &#39;textarea&#39;) return;<br>      const items = e.clipboardData?.items;<br>      if (!items) return;<br>      for (const item of items) {<br>        if (item.type &amp;&amp; item.type.startsWith(&#39;image/&#39;)) {<br>          const blob = item.getAsFile();<br>          if (blob &amp;&amp; appState.activeModule === &#39;evidence&#39;) {<br>            e.preventDefault();<br>            await evAddShotFromFile(blob, `clipboard_evidence_${Date.now()}.png`);<br>          } else if (blob &amp;&amp; appState.activeModule === &#39;validation&#39;) {<br>            e.preventDefault();<br>            const file = new File([blob], `clipboard_receipt_${Date.now()}.png`, { type: item.type });<br>            await processUploadedReceiptFile(file);<br>          }<br>        }<br>      }<br>    });<br><br>    /****************************************************************************<br>     * APPLICATION BOOTSTRAP<br>     ****************************************************************************/<br>    async function bootApplication() {<br>      try {<br>        const rawLoaded = await PersistenceEngine.loadState();<br>        const migrated = PersistenceEngine.migrateState(rawLoaded);<br>        if (migrated &amp;&amp; Array.isArray(migrated.projects) &amp;&amp; migrated.projects.length &gt; 0) {<br>          appState = migrated;<br>        } else {<br>          appState = createSampleSeedState();<br>          await PersistenceEngine.saveState(appState);<br>        }<br><br>        if (!appState.activeProjectId || !appState.projects.some(p =&gt; p.id === appState.activeProjectId)) {<br>          appState.activeProjectId = appState.projects[0]?.id || null;<br>        }<br>        const proj = getActiveProject();<br>        if (proj &amp;&amp; (!appState.activeMainPageId || !proj.mainPages.some(mp =&gt; mp.id === appState.activeMainPageId))) {<br>          appState.activeMainPageId = proj.mainPages[0]?.id || null;<br>        }<br><br>        proj?.mainPages?.forEach(mp =&gt; {<br>          if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        });<br><br>        renderApp();<br>        updateSaveIndicator(&#39;saved&#39;);<br>      } catch (err) {<br>        console.error(&#39;Boot error:&#39;, err);<br>        appState = createSampleSeedState();<br>        renderApp();<br>        showToast(&#39;Loaded fallback seed state due to storage notice: &#39; + err.message, &#39;warning&#39;);<br>      }<br>    }<br><br>    window.addEventListener(&#39;DOMContentLoaded&#39;, bootApplication);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc8dc70f841c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[nexus_eis_qa_validation_studio_v5 -3:35pm-11–19–25]]></title>
            <link>https://medium.com/@barabonajansen/nexus-eis-qa-validation-studio-v5-3-35pm-11-19-25-fbe7e5c8f600?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe7e5c8f600</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 07:35:04 GMT</pubDate>
            <atom:updated>2026-11-19T07:35:04.154Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot; class=&quot;dark&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>  &lt;title&gt;SMART EIS &amp; QA Validation Studio&lt;/title&gt;<br><br>  &lt;!-- Google Fonts: Inter &amp; JetBrains Mono --&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt;<br>  &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&amp;family=JetBrains+Mono:wght@400;500;600&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br><br>  &lt;!-- Tailwind CSS --&gt;<br>  &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    tailwind.config = {<br>      darkMode: &#39;class&#39;,<br>      theme: {<br>        extend: {<br>          fontFamily: {<br>            sans: [&#39;Inter&#39;, &#39;system-ui&#39;, &#39;sans-serif&#39;],<br>            mono: [&#39;JetBrains Mono&#39;, &#39;monospace&#39;]<br>          },<br>          colors: {<br>            brand: {<br>              50: &#39;#eef2ff&#39;,<br>              100: &#39;#e0e7ff&#39;,<br>              400: &#39;#818cf8&#39;,<br>              500: &#39;#6366f1&#39;,<br>              600: &#39;#4f46e5&#39;,<br>              700: &#39;#4338ca&#39;,<br>              900: &#39;#312e81&#39;,<br>              950: &#39;#1e1b4b&#39;<br>            }<br>          }<br>        }<br>      }<br>    };<br>  &lt;/script&gt;<br><br>  &lt;!-- Lucide Icons --&gt;<br>  &lt;script src=&quot;https://unpkg.com/lucide@latest&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Chart.js for Dashboard Analytics --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- PDF.js for Multi-Page PDF Receipt Rendering &amp; Text Extraction --&gt;<br>  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Tesseract.js for Client-Side Local-First OCR --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;style&gt;<br>    * { box-sizing: border-box; }<br>    body { font-family: &#39;Inter&#39;, system-ui, sans-serif; overflow-x: hidden; }<br>    ::-webkit-scrollbar { width: 6px; height: 6px; }<br>    ::-webkit-scrollbar-track { background: transparent; }<br>    ::-webkit-scrollbar-thumb { background: rgba(100, 116, 139, 0.35); border-radius: 9999px; }<br>    ::-webkit-scrollbar-thumb:hover { background: rgba(100, 116, 139, 0.6); }<br><br>    @media print {<br>      body * { visibility: hidden; }<br>      #printable-report-area, #printable-report-area * { visibility: visible; }<br>      #printable-report-area {<br>        position: absolute;<br>        left: 0;<br>        top: 0;<br>        width: 100%;<br>        background: #ffffff !important;<br>        color: #0f172a !important;<br>        padding: 20px;<br>      }<br>      .no-print { display: none !important; }<br>      .page-break { page-break-before: always; }<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100 antialiased selection:bg-brand-500 selection:text-white&quot;&gt;<br><br>  &lt;!-- Main Application Shell --&gt;<br>  &lt;div id=&quot;app-shell&quot; class=&quot;min-h-screen flex flex-col lg:flex-row&quot;&gt;<br><br>    &lt;!-- Mobile Top Header --&gt;<br>    &lt;header class=&quot;lg:hidden flex items-center justify-between px-4 py-3 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 sticky top-0 z-40&quot;&gt;<br>      &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>        &lt;button id=&quot;mobile-menu-btn&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; aria-label=&quot;Toggle Menu&quot;&gt;<br>          &lt;i data-lucide=&quot;menu&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>          &lt;div class=&quot;w-8 h-8 rounded-xl bg-gradient-to-br from-brand-500 to-indigo-600 flex items-center justify-center text-white font-bold shadow-md&quot;&gt;N&lt;/div&gt;<br>          &lt;span class=&quot;font-bold tracking-tight text-sm&quot;&gt;SMART EIS &amp; QA&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>        &lt;span id=&quot;mobile-save-badge&quot; class=&quot;text-xs px-2 py-1 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium&quot;&gt;Saved&lt;/span&gt;<br>        &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Toggle Theme&quot;&gt;<br>          &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/header&gt;<br><br>    &lt;!-- Collapsible Navigation Sidebar --&gt;<br>    &lt;aside id=&quot;sidebar&quot; class=&quot;fixed inset-y-0 left-0 z-50 w-72 lg:w-64 transform -translate-x-full lg:translate-x-0 lg:static transition-all duration-200 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col shrink-0&quot;&gt;<br>      &lt;!-- Brand Header --&gt;<br>      &lt;div class=&quot;p-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 overflow-hidden&quot;&gt;<br>          &lt;div class=&quot;w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500 via-indigo-600 to-violet-600 flex items-center justify-center text-white font-extrabold shadow-lg shrink-0&quot;&gt;<br>            N<br>          &lt;/div&gt;<br>          &lt;div class=&quot;sidebar-label truncate&quot;&gt;<br>            &lt;div class=&quot;font-bold text-sm tracking-tight&quot;&gt;SMART Studio&lt;/div&gt;<br>            &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;EIS Receipt &amp; QA Engine&lt;/div&gt;<br>   &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;Developed By: Jansen B.&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;button onclick=&quot;toggleSidebarCollapse()&quot; class=&quot;hidden lg:flex p-1.5 rounded-lg text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Collapse Sidebar&quot;&gt;<br>          &lt;i data-lucide=&quot;panel-left-close&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;button onclick=&quot;toggleMobileSidebar()&quot; class=&quot;lg:hidden p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- Active Project Quick Switcher --&gt;<br>      &lt;div class=&quot;p-3 border-b border-slate-200 dark:border-slate-800 sidebar-label&quot;&gt;<br>        &lt;label class=&quot;block text-[10px] font-semibold uppercase tracking-wider text-slate-400 mb-1&quot;&gt;Active Project&lt;/label&gt;<br>        &lt;select id=&quot;sidebar-project-select&quot; onchange=&quot;switchActiveProject(this.value)&quot; class=&quot;w-full text-xs font-medium bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-2.5 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- 11 Core Modules Navigation --&gt;<br>      &lt;nav id=&quot;sidebar-nav&quot; class=&quot;flex-1 overflow-y-auto p-2.5 space-y-1&quot;&gt;<br>        &lt;!-- Populated dynamically --&gt;<br>      &lt;/nav&gt;<br><br>      &lt;!-- Footer Status &amp; Privacy Badge --&gt;<br>      &lt;div class=&quot;p-3 border-t border-slate-200 dark:border-slate-800 sidebar-label space-y-2&quot;&gt;<br>        &lt;div class=&quot;flex items-center justify-between text-xs&quot;&gt;<br>          &lt;span class=&quot;text-slate-500 dark:text-slate-400 flex items-center gap-1.5&quot;&gt;<br>            &lt;span class=&quot;w-2 h-2 rounded-full bg-emerald-500 animate-pulse&quot;&gt;&lt;/span&gt;<br>            IndexedDB Local<br>          &lt;/span&gt;<br>          &lt;span id=&quot;sidebar-version-tag&quot; class=&quot;font-mono text-[11px] text-slate-400&quot;&gt;v2.4.0&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-800/70 rounded-xl p-2 flex items-center gap-2&quot;&gt;<br>          &lt;i data-lucide=&quot;shield-check&quot; class=&quot;w-4 h-4 text-emerald-500 shrink-0&quot;&gt;&lt;/i&gt;<br>          &lt;span&gt;Local-first storage. Zero external receipt uploads.&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/aside&gt;<br><br>    &lt;!-- Backdrop for mobile drawer --&gt;<br>    &lt;div id=&quot;mobile-backdrop&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;fixed inset-0 bg-slate-950/60 backdrop-blur-xs z-40 hidden lg:hidden&quot;&gt;&lt;/div&gt;<br><br>    &lt;!-- Main Content Workspace --&gt;<br>    &lt;div class=&quot;flex-1 flex flex-col min-w-0&quot;&gt;<br><br>      &lt;!-- Desktop Top Workspace Bar --&gt;<br>      &lt;header class=&quot;hidden lg:flex items-center justify-between px-6 py-3.5 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 sticky top-0 z-30&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 min-w-0&quot;&gt;<br>          &lt;h1 id=&quot;topbar-title&quot; class=&quot;text-base font-bold tracking-tight truncate&quot;&gt;Dashboard&lt;/h1&gt;<br>          &lt;span id=&quot;topbar-subtitle&quot; class=&quot;text-xs text-slate-500 dark:text-slate-400 hidden xl:inline truncate&quot;&gt;Enterprise EIS Receipt &amp; QA Evidence Overview&lt;/span&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>          &lt;!-- Autosave Status Pill --&gt;<br>          &lt;div id=&quot;save-status-pill&quot; class=&quot;flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20&quot;&gt;<br>            &lt;i data-lucide=&quot;check-circle-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span id=&quot;save-status-text&quot;&gt;All changes saved&lt;/span&gt;<br>          &lt;/div&gt;<br><br>          &lt;!-- Manual Save Button --&gt;<br>          &lt;button onclick=&quot;manualSaveProject()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Save Project Now (Ctrl+S)&quot;&gt;<br>            &lt;i data-lucide=&quot;save&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Save&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Run Validation CTA --&gt;<br>          &lt;button onclick=&quot;runActivePageValidation(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm transition&quot;&gt;<br>            &lt;i data-lucide=&quot;play&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Validate Active Page&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Theme Switcher --&gt;<br>          &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Toggle Dark/Light Theme&quot;&gt;<br>            &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br><br>      &lt;!-- Dynamic Module Viewport --&gt;<br>      &lt;main id=&quot;main-viewport&quot; class=&quot;flex-1 p-4 sm:p-6 max-w-[1600px] w-full mx-auto space-y-6&quot;&gt;<br>        &lt;!-- Active module renders here --&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Toast Notification Container --&gt;<br>  &lt;div id=&quot;toast-container&quot; class=&quot;fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-sm w-full pointer-events-none px-4 sm:px-0&quot;&gt;&lt;/div&gt;<br><br>  &lt;!-- Reusable Modal Container --&gt;<br>  &lt;div id=&quot;modal-overlay&quot; class=&quot;fixed inset-0 z-50 bg-slate-950/70 backdrop-blur-xs hidden items-center justify-center p-4&quot;&gt;<br>    &lt;div id=&quot;modal-box&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] flex flex-col overflow-hidden&quot;&gt;<br>      &lt;div class=&quot;px-5 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;h3 id=&quot;modal-title&quot; class=&quot;font-bold text-base&quot;&gt;Modal Title&lt;/h3&gt;<br>        &lt;button onclick=&quot;closeModal()&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;modal-body&quot; class=&quot;p-5 overflow-y-auto space-y-4 text-sm&quot;&gt;&lt;/div&gt;<br>      &lt;div id=&quot;modal-footer&quot; class=&quot;px-5 py-3.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-end gap-2 bg-slate-50 dark:bg-slate-900/50&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;script&gt;<br>    /****************************************************************************<br>     * SMART EIS &amp; QA VALIDATION STUDIO — MODULAR ARCHITECTURE<br>     * 1. Persistence &amp; Backup Engine (IndexedDB + Versioned Migration)<br>     * 2. Financial Calculator &amp; EIS Fee Validation Engine (Deterministic)<br>     * 3. Intelligent OCR &amp; Smart Field Mapping Engine (PDF.js + Tesseract.js)<br>     * 4. QA Screenshot &amp; Vector Annotation Engine<br>     * 5. Test Case, Defect &amp; Unified Reporting Engine<br>     * 6. Automated 12-Point Acceptance Test Suite<br>     ****************************************************************************/<br><br>    // Configure PDF.js worker with safe error guard<br>    try {<br>      if (window.pdfjsLib) {<br>        pdfjsLib.GlobalWorkerOptions.workerSrc = &#39;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js&#39;;<br>      }<br>    } catch (pdfInitErr) {<br>      console.warn(&#39;PDF.js worker initialization warning:&#39;, pdfInitErr);<br>    }<br><br>    const APP_SCHEMA_VERSION = 3;<br>    const DB_NAME = &#39;SMARTEisQaStudioDB&#39;;<br>    const DB_VERSION = 1;<br>    const STORE_NAME = &#39;workspaceState&#39;;<br><br>    const MODULES = [<br>      { id: &#39;dashboard&#39;, label: &#39;Dashboard&#39;, icon: &#39;layout-dashboard&#39;, subtitle: &#39;Real-time EIS validation metrics &amp; QA progress&#39; },<br>      { id: &#39;projects&#39;, label: &#39;Projects&#39;, icon: &#39;folder-kanban&#39;, subtitle: &#39;Manage isolated audit workspaces, backups &amp; imports&#39; },<br>      { id: &#39;main-pages&#39;, label: &#39;Main Pages&#39;, icon: &#39;file-spreadsheet&#39;, subtitle: &#39;Configure numbered fields (1–50+), per-page dynamic rows &amp; fees&#39; },<br>      { id: &#39;validation&#39;, label: &#39;Receipt Validation&#39;, icon: &#39;split-square-horizontal&#39;, subtitle: &#39;Side-by-side receipt comparison, OCR boxes &amp; mismatch review&#39; },<br>      { id: &#39;ocr-intel&#39;, label: &#39;OCR &amp; Doc Intel&#39;, icon: &#39;scan-text&#39;, subtitle: &#39;Preprocessing pipeline, confidence inspection &amp; block mapping&#39; },<br>      { id: &#39;screenshots&#39;, label: &#39;QA Screenshot Studio&#39;, icon: &#39;camera&#39;, subtitle: &#39;Screen capture, image merging &amp; dynamic QA evidence labels (1–200+)&#39; },<br>      { id: &#39;test-cases&#39;, label: &#39;Test Cases&#39;, icon: &#39;check-square&#39;, subtitle: &#39;QA test execution, preconditions &amp; linked receipt evidence&#39; },<br>      { id: &#39;defects&#39;, label: &#39;Defect Management&#39;, icon: &#39;bug&#39;, subtitle: &#39;Issue tracking, severity triage &amp; copy-ready Jira markup&#39; },<br>      { id: &#39;templates&#39;, label: &#39;Templates&#39;, icon: &#39;copy-plus&#39;, subtitle: &#39;Reusable EIS fee schemas, column mappings &amp; project templates&#39; },<br>      { id: &#39;settings&#39;, label: &#39;Settings &amp; Diagnostics&#39;, icon: &#39;settings&#39;, subtitle: &#39;Validation tolerances, OCR rules &amp; 12-point self-test suite&#39; },<br>      { id: &#39;reports&#39;, label: &#39;Reports&#39;, icon: &#39;file-bar-chart-2&#39;, subtitle: &#39;All results, projects &amp; QA reports (CSV, HTML, PDF, Word/DOC, JSON, TXT)&#39; }<br>    ];<br><br>    // Global Application State<br>    let appState = {<br>      schemaVersion: APP_SCHEMA_VERSION,<br>      theme: &#39;dark&#39;,<br>      sidebarCollapsed: false,<br>      activeModule: &#39;dashboard&#39;,<br>      activeProjectId: null,<br>      activeMainPageId: null,<br>      lastSavedAt: null,<br>      settings: {<br>        numericTolerance: 0.01,<br>        caseSensitiveNames: false,<br>        normalizeWhitespace: true,<br>        autoAcceptConfidenceThreshold: 88,<br>        cwtDeductionMode: &#39;absolute&#39;,<br>        qaLabelMax: 200,<br>        qaAutoIncrement: true<br>      },<br>      templates: [],<br>      projects: [],<br>      ui: {<br>        viewerZoom: 1,<br>        viewerRotation: 0,<br>        showOcrBoxes: true,<br>        selectedComparisonRowId: null,<br>        selectedScreenshotsForMerge: [],<br>        annotationTool: &#39;rect&#39;,<br>        annotationColor: &#39;#ef4444&#39;,<br>        selectedAnnotationId: null,<br>        selectedQaLabel: 1,<br>        mainPageQuickListOpen: false,<br>        selectedMainPageIds: []<br>      }<br>    };<br><br>    let chartInstances = {};<br>    let autosaveTimer = null;<br><br>    /**<br>     * Escapes HTML special characters safely for UI templates and exported HTML/DOC files.<br>     */<br>    function escapeHtml(str) {<br>      if (str === null || str === undefined) return &#39;&#39;;<br>      return String(str)<br>        .replace(/&amp;/g, &#39;&amp;amp;&#39;)<br>        .replace(/&lt;/g, &#39;&amp;lt;&#39;)<br>        .replace(/&gt;/g, &#39;&amp;gt;&#39;)<br>        .replace(/&quot;/g, &#39;&amp;quot;&#39;)<br>        .replace(/&#39;/g, &#39;&amp;#039;&#39;);<br>    }<br><br>    /**<br>     * Sanitizes image URLs or data URIs for safe embedding in HTML and Word (.doc) reports.<br>     */<br>    function sanitizeImageSrc(src) {<br>      if (!src || typeof src !== &#39;string&#39;) return &#39;&#39;;<br>      const trimmed = src.trim();<br>      if (/^data:image\/(png|jpeg|jpg|webp|gif|svg\+xml);/i.test(trimmed)) return trimmed;<br>      if (/^https?:\/\//i.test(trimmed)) return trimmed;<br>      return &#39;&#39;;<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1: PERSISTENCE &amp; BACKUP ENGINE (IndexedDB)<br>     ****************************************************************************/<br>    const PersistenceEngine = {<br>      openDB() {<br>        return new Promise((resolve, reject) =&gt; {<br>          if (!window.indexedDB) {<br>            reject(new Error(&#39;IndexedDB is unavailable in this browser environment.&#39;));<br>            return;<br>          }<br>          const req = indexedDB.open(DB_NAME, DB_VERSION);<br>          req.onupgradeneeded = (e) =&gt; {<br>            const db = e.target.result;<br>            if (!db.objectStoreNames.contains(STORE_NAME)) {<br>              db.createObjectStore(STORE_NAME, { keyPath: &#39;id&#39; });<br>            }<br>          };<br>          req.onsuccess = () =&gt; resolve(req.result);<br>          req.onerror = () =&gt; reject(req.error);<br>        });<br>      },<br><br>      async saveState(stateObj) {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readwrite&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const payload = {<br>            id: &#39;primary_workspace&#39;,<br>            updatedAt: new Date().toISOString(),<br>            data: JSON.parse(JSON.stringify(stateObj))<br>          };<br>          store.put(payload);<br>          return new Promise((resolve, reject) =&gt; {<br>            tx.oncomplete = () =&gt; {<br>              appState.lastSavedAt = payload.updatedAt;<br>              updateSaveIndicator(&#39;saved&#39;);<br>              resolve(true);<br>            };<br>            tx.onerror = () =&gt; reject(tx.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Save Error:&#39;, err);<br>          updateSaveIndicator(&#39;error&#39;);<br>          return false;<br>        }<br>      },<br><br>      async loadState() {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readonly&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const req = store.get(&#39;primary_workspace&#39;);<br>          return new Promise((resolve, reject) =&gt; {<br>            req.onsuccess = () =&gt; resolve(req.result ? req.result.data : null);<br>            req.onerror = () =&gt; reject(req.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Load Error:&#39;, err);<br>          return null;<br>        }<br>      },<br><br>      migrateState(raw) {<br>        if (!raw) return null;<br>        if (!raw.schemaVersion || raw.schemaVersion &lt; APP_SCHEMA_VERSION) {<br>          raw.schemaVersion = APP_SCHEMA_VERSION;<br>          raw.settings = Object.assign({<br>            numericTolerance: 0.01,<br>            caseSensitiveNames: false,<br>            normalizeWhitespace: true,<br>            autoAcceptConfidenceThreshold: 88,<br>            cwtDeductionMode: &#39;absolute&#39;,<br>            qaLabelMax: 200,<br>            qaAutoIncrement: true<br>          }, raw.settings || {});<br>        }<br>        (raw.projects || []).forEach(proj =&gt; {<br>          (proj.mainPages || []).forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>          });<br>        });<br>        return raw;<br>      }<br>    };<br><br>    function scheduleAutosave(reason = &#39;&#39;) {<br>      updateSaveIndicator(&#39;saving&#39;);<br>      if (autosaveTimer) clearTimeout(autosaveTimer);<br>      autosaveTimer = setTimeout(async () =&gt; {<br>        try {<br>          const proj = getActiveProject();<br>          if (proj) proj.lastModified = new Date().toISOString();<br>          await PersistenceEngine.saveState(appState);<br>        } catch (err) {<br>          console.error(&#39;Autosave error:&#39;, err);<br>        }<br>      }, 450);<br>    }<br><br>    async function manualSaveProject() {<br>      try {<br>        const proj = getActiveProject();<br>        if (proj) proj.lastModified = new Date().toISOString();<br>        const saved = await PersistenceEngine.saveState(appState);<br>        if (saved) {<br>          showToast(&#39;Project state persisted to IndexedDB.&#39;, &#39;success&#39;);<br>        } else {<br>          showToast(&#39;Unable to persist project state to IndexedDB.&#39;, &#39;error&#39;);<br>        }<br>      } catch (err) {<br>        showToast(&#39;Save failed: &#39; + err.message, &#39;error&#39;);<br>      }<br>    }<br><br>    function updateSaveIndicator(status) {<br>      const textEl = document.getElementById(&#39;save-status-text&#39;);<br>      const mobileBadge = document.getElementById(&#39;mobile-save-badge&#39;);<br>      if (status === &#39;saving&#39;) {<br>        if (textEl) textEl.textContent = &#39;Saving...&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saving...&#39;;<br>      } else if (status === &#39;saved&#39;) {<br>        const t = new Date().toLocaleTimeString([], { hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39;, second: &#39;2-digit&#39; });<br>        if (textEl) textEl.textContent = `Saved ${t}`;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saved&#39;;<br>      } else {<br>        if (textEl) textEl.textContent = &#39;Save error&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Error&#39;;<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2: FINANCIAL CALCULATOR &amp; EIS FEE VALIDATION ENGINE<br>     ****************************************************************************/<br>    const FinancialCalculator = {<br>      parseAmount(raw) {<br>        if (raw === null || raw === undefined || raw === &#39;&#39;) return null;<br>        if (typeof raw === &#39;number&#39;) return Number.isFinite(raw) ? raw : null;<br>        let str = String(raw).trim();<br>        if (!str) return null;<br><br>        let isNegative = false;<br>        if (/^\(.*\)$/.test(str)) {<br>          isNegative = true;<br>          str = str.replace(/^\(|\)$/g, &#39;&#39;).trim();<br>        }<br>        if (str.startsWith(&#39;-&#39;)) {<br>          isNegative = true;<br>          str = str.slice(1).trim();<br>        }<br>        str = str.replace(/[^0-9.\-]/g, &#39;&#39;);<br>        if (!str || str === &#39;.&#39; || str === &#39;-&#39;) return null;<br>        const val = parseFloat(str);<br>        if (!Number.isFinite(val)) return null;<br>        return isNegative ? -Math.abs(val) : val;<br>      },<br><br>      isCwtEntry(fee) {<br>        if (!fee) return false;<br>        if (fee.isCwt === true) return true;<br>        const code = String(fee.code || fee.actualCode || &#39;&#39;).trim().toUpperCase();<br>        const name = String(fee.name || fee.actualName || &#39;&#39;).trim().toUpperCase();<br>        return code === &#39;CWT&#39; || /\bCWT\b|WITHHOLDING/.test(name);<br>      },<br><br>      calculateTotals(fees = []) {<br>        let expectedGross = 0;<br>        let expectedCwt = 0;<br>        let actualGross = 0;<br>        let actualCwt = 0;<br>        let hasMissingActual = false;<br><br>        fees.forEach(fee =&gt; {<br>          const isCwt = this.isCwtEntry(fee);<br>          const expAmt = this.parseAmount(fee.expectedAmount);<br>          const actAmt = this.parseAmount(fee.actualAmount);<br><br>          if (expAmt !== null) {<br>            if (isCwt) {<br>              expectedCwt += Math.abs(expAmt);<br>            } else {<br>              expectedGross += expAmt;<br>            }<br>          }<br><br>          if (actAmt !== null) {<br>            if (isCwt) {<br>              actualCwt += Math.abs(actAmt);<br>            } else {<br>              actualGross += actAmt;<br>            }<br>          } else {<br>            hasMissingActual = true;<br>          }<br>        });<br><br>        expectedGross = Number(expectedGross.toFixed(2));<br>        expectedCwt = Number(expectedCwt.toFixed(2));<br>        actualGross = Number(actualGross.toFixed(2));<br>        actualCwt = Number(actualCwt.toFixed(2));<br><br>        const expectedNet = Number((expectedGross - expectedCwt).toFixed(2));<br>        const actualNet = Number((actualGross - actualCwt).toFixed(2));<br>        const netDifference = Number((actualNet - expectedNet).toFixed(2));<br>        const grossDifference = Number((actualGross - expectedGross).toFixed(2));<br>        const cwtDifference = Number((actualCwt - expectedCwt).toFixed(2));<br><br>        return {<br>          expectedGross,<br>          expectedCwt,<br>          expectedNet,<br>          actualGross,<br>          actualCwt,<br>          actualNet,<br>          grossDifference,<br>          cwtDifference,<br>          netDifference,<br>          hasMissingActual,<br>          formulaExplanation: `Gross Fees (non-CWT sum) - |CWT Deductions| = Net Total (${actualGross.toFixed(2)} - ${actualCwt.toFixed(2)} = ${actualNet.toFixed(2)})`<br>        };<br>      }<br>    };<br><br>    const ValidationEngine = {<br>      normalizeText(str, settings = appState.settings) {<br>        if (str === null || str === undefined) return &#39;&#39;;<br>        let s = String(str);<br>        if (settings.normalizeWhitespace) s = s.replace(/\s+/g, &#39; &#39;).trim();<br>        if (!settings.caseSensitiveNames) s = s.toLowerCase();<br>        return s;<br>      },<br><br>      validateFeeRow(fee, settings = appState.settings) {<br>        const tolerance = Number(settings.numericTolerance ?? 0.01);<br>        const timestamp = new Date().toISOString();<br>        const isCwt = FinancialCalculator.isCwtEntry(fee);<br><br>        const expName = String(fee.expectedName || &#39;&#39;).trim();<br>        const actName = String(fee.actualName || &#39;&#39;).trim();<br>        const expCode = String(fee.expectedCode || &#39;&#39;).trim();<br>        const actCode = String(fee.actualCode || &#39;&#39;).trim();<br>        const expAmt = FinancialCalculator.parseAmount(fee.expectedAmount);<br>        const actAmt = FinancialCalculator.parseAmount(fee.actualAmount);<br><br>        const nameResult = this.compareTextAttribute(&#39;Fee Name&#39;, expName, actName, true, fee.ocrConfidence, settings);<br><br>        let amtStatus = &#39;PENDING&#39;;<br>        let amtDiff = null;<br>        let amtExplanation = &#39;&#39;;<br>        if (expAmt === null &amp;&amp; actAmt === null) {<br>          amtStatus = &#39;NOT APPLICABLE&#39;;<br>          amtExplanation = &#39;No expected or receipt amount configured.&#39;;<br>        } else if (expAmt === null) {<br>          amtStatus = &#39;REVIEW&#39;;<br>          amtExplanation = `Receipt has ${actAmt.toFixed(2)} but Expected Amount is blank.`;<br>        } else if (actAmt === null) {<br>          amtStatus = &#39;PENDING&#39;;<br>          amtExplanation = `Missing receipt amount for expected ${expAmt.toFixed(2)}.`;<br>        } else {<br>          const cmpExp = isCwt ? Math.abs(expAmt) : expAmt;<br>          const cmpAct = isCwt ? Math.abs(actAmt) : actAmt;<br>          amtDiff = Number((cmpAct - cmpExp).toFixed(2));<br>          if (Math.abs(amtDiff) &lt;= tolerance) {<br>            amtStatus = (fee.ocrConfidence !== null &amp;&amp; fee.ocrConfidence !== undefined &amp;&amp; fee.ocrConfidence &lt; settings.autoAcceptConfidenceThreshold &amp;&amp; !fee.manuallyVerified)<br>              ? &#39;REVIEW&#39;<br>              : &#39;PASS&#39;;<br>            amtExplanation = isCwt<br>              ? `CWT deduction magnitude matches (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`<br>              : `Amount matches within ±${tolerance} tolerance (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`;<br>          } else {<br>            amtStatus = &#39;FAIL&#39;;<br>            amtExplanation = `Amount mismatch: Expected ${cmpExp.toFixed(2)}, Receipt ${cmpAct.toFixed(2)}, Difference ${amtDiff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${amtDiff.toFixed(2)}.`;<br>          }<br>        }<br><br>        const codeResult = this.compareTextAttribute(&#39;Fee Code&#39;, expCode, actCode, true, fee.ocrConfidence, settings, true);<br><br>        const statuses = [nameResult.status, amtStatus, codeResult.status];<br>        let overallStatus = &#39;PASS&#39;;<br>        if (statuses.includes(&#39;FAIL&#39;)) overallStatus = &#39;FAIL&#39;;<br>        else if (statuses.includes(&#39;PENDING&#39;)) overallStatus = &#39;PENDING&#39;;<br>        else if (statuses.includes(&#39;REVIEW&#39;)) overallStatus = &#39;REVIEW&#39;;<br>        else if (statuses.every(s =&gt; s === &#39;NOT APPLICABLE&#39;)) overallStatus = &#39;NOT APPLICABLE&#39;;<br><br>        const explanations = [nameResult.explanation, amtExplanation, codeResult.explanation].filter(Boolean);<br><br>        return {<br>          feeId: fee.id,<br>          isCwt,<br>          nameComparison: nameResult,<br>          amountComparison: {<br>            rule: isCwt ? &#39;CWT Absolute Value Match&#39; : `Numeric Tolerance (±${tolerance})`,<br>            expected: expAmt !== null ? expAmt.toFixed(2) : &#39;&#39;,<br>            actual: actAmt !== null ? actAmt.toFixed(2) : &#39;&#39;,<br>            difference: amtDiff !== null ? amtDiff.toFixed(2) : &#39;N/A&#39;,<br>            status: amtStatus,<br>            explanation: amtExplanation<br>          },<br>          codeComparison: codeResult,<br>          status: overallStatus,<br>          explanation: explanations.join(&#39; | &#39;),<br>          ocrConfidence: fee.ocrConfidence ?? null,<br>          sourceLocation: fee.sourceLocation || &#39;Manual / Unmapped&#39;,<br>          evaluatedAt: timestamp<br>        };<br>      },<br><br>      compareTextAttribute(label, expected, actual, required, confidence, settings, exactCode = false) {<br>        if (!expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual: &#39;&#39;,<br>            difference: &#39;0&#39;,<br>            status: required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            explanation: required ? `${label} is missing on both Expected and Receipt.` : `${label} not configured.`<br>          };<br>        }<br>        if (!expected &amp;&amp; actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual,<br>            difference: &#39;Unconfigured expected&#39;,<br>            status: &#39;REVIEW&#39;,<br>            explanation: `${label} &quot;${actual}&quot; found on receipt, but expected value is empty.`<br>          };<br>        }<br>        if (expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual: &#39;&#39;,<br>            difference: &#39;Missing on receipt&#39;,<br>            status: &#39;PENDING&#39;,<br>            explanation: `Required ${label} &quot;${expected}&quot; is missing from receipt extraction.`<br>          };<br>        }<br><br>        const normExp = exactCode ? expected.trim().toUpperCase() : this.normalizeText(expected, settings);<br>        const normAct = exactCode ? actual.trim().toUpperCase() : this.normalizeText(actual, settings);<br><br>        if (normExp === normAct) {<br>          const lowConf = confidence !== null &amp;&amp; confidence !== undefined &amp;&amp; confidence &lt; settings.autoAcceptConfidenceThreshold;<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual,<br>            difference: &#39;0&#39;,<br>            status: lowConf ? &#39;REVIEW&#39; : &#39;PASS&#39;,<br>            explanation: lowConf ? `${label} matched (&quot;${actual}&quot;), flagged REVIEW due to ${confidence}% OCR confidence.` : `${label} matched (&quot;${actual}&quot;).`<br>          };<br>        }<br><br>        return {<br>          rule: `${label} Match`,<br>          expected,<br>          actual,<br>          difference: `&quot;${expected}&quot; ≠ &quot;${actual}&quot;`,<br>          status: &#39;FAIL&#39;,<br>          explanation: `${label} mismatch: Expected &quot;${expected}&quot;, Receipt &quot;${actual}&quot;.`<br>        };<br>      },<br><br>      validateField(field, settings = appState.settings) {<br>        if (!field.enabled &amp;&amp; !field.expectedValue &amp;&amp; !field.actualValue) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: &#39;Field disabled / unused.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        const exp = String(field.expectedValue ?? &#39;&#39;).trim();<br>        const act = String(field.actualValue ?? &#39;&#39;).trim();<br><br>        if (!exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: field.required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: field.required ? &#39;Required field has no expected or actual value.&#39; : &#39;Optional field blank.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;PENDING&#39;,<br>            difference: &#39;Missing actual&#39;,<br>            explanation: `Expected &quot;${exp}&quot;, awaiting receipt/system value.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (!exp &amp;&amp; act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;REVIEW&#39;,<br>            difference: &#39;Missing expected&#39;,<br>            explanation: `Actual &quot;${act}&quot; present, but Expected value is blank.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        if (field.dataType === &#39;Currency&#39; || field.dataType === &#39;Number&#39; || field.dataType === &#39;Percentage&#39;) {<br>          const nExp = FinancialCalculator.parseAmount(exp);<br>          const nAct = FinancialCalculator.parseAmount(act);<br>          const tol = Number(field.tolerance ?? settings.numericTolerance ?? 0.01);<br>          if (nExp !== null &amp;&amp; nAct !== null) {<br>            const diff = Number((nAct - nExp).toFixed(4));<br>            const pass = Math.abs(diff) &lt;= tol;<br>            return {<br>              fieldId: field.id,<br>              status: pass ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>              difference: diff === 0 ? &#39;0.00&#39; : `${diff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${diff.toFixed(2)}`,<br>              explanation: pass ? `Numeric match within ±${tol}.` : `Expected ${nExp}, found ${nAct} (Diff: ${diff}).`,<br>              evaluatedAt: new Date().toISOString()<br>            };<br>          }<br>        }<br><br>        const normExp = this.normalizeText(exp, settings);<br>        const normAct = this.normalizeText(act, settings);<br>        const match = normExp === normAct;<br>        return {<br>          fieldId: field.id,<br>          status: match ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>          difference: match ? &#39;0&#39; : `&quot;${exp}&quot; ≠ &quot;${act}&quot;`,<br>          explanation: match ? &#39;Value matched.&#39; : `Expected &quot;${exp}&quot;, got &quot;${act}&quot;.`,<br>          evaluatedAt: new Date().toISOString()<br>        };<br>      },<br><br>      validateMainPage(mainPage, recordHistory = false) {<br>        if (!mainPage) return null;<br>        const feeResults = (mainPage.fees || []).map(f =&gt; {<br>          const res = this.validateFeeRow(f);<br>          f.lastValidation = res;<br>          return res;<br>        });<br><br>        const fieldResults = (mainPage.fields || []).map(fld =&gt; {<br>          const res = this.validateField(fld);<br>          fld.lastValidation = res;<br>          return res;<br>        });<br><br>        const financials = FinancialCalculator.calculateTotals(mainPage.fees || []);<br><br>        const activeStatuses = [<br>          ...feeResults.map(r =&gt; r.status),<br>          ...fieldResults.filter(r =&gt; r.status !== &#39;NOT APPLICABLE&#39;).map(r =&gt; r.status)<br>        ];<br><br>        let overallStatus = &#39;PENDING&#39;;<br>        if (activeStatuses.length === 0) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;FAIL&#39;)) {<br>          overallStatus = &#39;FAIL&#39;;<br>        } else if (activeStatuses.includes(&#39;PENDING&#39;)) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;REVIEW&#39;)) {<br>          overallStatus = &#39;REVIEW&#39;;<br>        } else {<br>          overallStatus = &#39;PASS&#39;;<br>        }<br><br>        const summary = {<br>          overallStatus,<br>          feeResults,<br>          fieldResults,<br>          financials,<br>          counts: {<br>            pass: activeStatuses.filter(s =&gt; s === &#39;PASS&#39;).length,<br>            fail: activeStatuses.filter(s =&gt; s === &#39;FAIL&#39;).length,<br>            review: activeStatuses.filter(s =&gt; s === &#39;REVIEW&#39;).length,<br>            pending: activeStatuses.filter(s =&gt; s === &#39;PENDING&#39;).length<br>          },<br>          validatedAt: new Date().toISOString()<br>        };<br><br>        mainPage.validationSummary = summary;<br><br>        if (recordHistory) {<br>          mainPage.validationHistory = mainPage.validationHistory || [];<br>          mainPage.validationHistory.unshift({<br>            id: &#39;vh_&#39; + Date.now(),<br>            timestamp: summary.validatedAt,<br>            overallStatus: summary.overallStatus,<br>            counts: { ...summary.counts },<br>            netTotal: financials.actualNet<br>          });<br>          if (mainPage.validationHistory.length &gt; 25) mainPage.validationHistory.pop();<br>        }<br><br>        return summary;<br>      }<br>    };<br><br>    /****************************************************************************<br>     * MODULE 3: INTELLIGENT OCR, ROW PARSER &amp; SMART FIELD MAPPING ENGINE<br>     ****************************************************************************/<br>    const RowToFieldsEngine = {<br>      parseSpreadsheetRow(rawText, hasHeaderRow = false) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br>        if (!lines.length) return { headers: [], values: [], delimiter: &#39;None&#39; };<br><br>        const detectDelimiter = (line) =&gt; {<br>          if (line.includes(&#39;\t&#39;)) return &#39;\t&#39;;<br>          if (line.includes(&#39;|&#39;)) return &#39;|&#39;;<br>          if (line.includes(&#39;,&#39;)) return &#39;,&#39;;<br>          return &#39;\t&#39;;<br>        };<br><br>        const splitLine = (line, delim) =&gt; {<br>          if (delim === &#39;,&#39;) {<br>            const matches = line.match(/(&quot;.*?&quot;|[^&quot;,]+)(?=\s*,|\s*$)/g);<br>            return matches ? matches.map(c =&gt; c.replace(/^&quot;|&quot;$/g, &#39;&#39;).trim()) : line.split(&#39;,&#39;).map(c =&gt; c.trim());<br>          }<br>          return line.split(delim).map(c =&gt; c.trim());<br>        };<br><br>        const delim = detectDelimiter(lines[0]);<br>        const delimLabel = delim === &#39;\t&#39; ? &#39;Tab (Excel/Sheets)&#39; : delim === &#39;|&#39; ? &#39;Pipe (|)&#39; : &#39;CSV (,)&#39;;<br><br>        if (hasHeaderRow &amp;&amp; lines.length &gt;= 2) {<br>          return {<br>            headers: splitLine(lines[0], delim),<br>            values: splitLine(lines[1], delim),<br>            delimiter: delimLabel<br>          };<br>        }<br><br>        return {<br>          headers: [],<br>          values: splitLine(lines[0], delim),<br>          delimiter: delimLabel<br>        };<br>      },<br><br>      inferDataType(val) {<br>        const s = String(val || &#39;&#39;).trim();<br>        if (!s) return &#39;Dynamic&#39;;<br>        if (/^\d{4}-\d{2}-\d{2}$/.test(s) || /^\d{1,2}\/\d{1,2}\/\d{2,4}$/.test(s)) return &#39;Date&#39;;<br>        if (/^[$₱€£]?\s*\(?-?\d{1,3}(,\d{3})*(\.\d+)?\)?$/.test(s)) return &#39;Currency&#39;;<br>        if (/^[A-Z]{2,5}$/.test(s)) return &#39;Code&#39;;<br>        return &#39;Dynamic&#39;;<br>      },<br><br>      autoMatchReceiptAgainstExpectedFields(mainPage) {<br>        if (!mainPage || !mainPage.receipt || !mainPage.receipt.ocrRawText) {<br>          return { matched: 0, total: 0 };<br>        }<br>        const rawText = mainPage.receipt.ocrRawText;<br>        const normReceipt = rawText.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>        const compactReceipt = rawText.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br>        const lines = rawText.split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br><br>        let matched = 0;<br>        let total = 0;<br><br>        (mainPage.fields || []).forEach(f =&gt; {<br>          const exp = String(f.expectedValue || &#39;&#39;).trim();<br>          if (!exp) return;<br>          total++;<br><br>          const normExp = exp.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>          const compactExp = exp.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br><br>          if (normReceipt.includes(normExp) || (compactExp.length &gt;= 2 &amp;&amp; compactReceipt.includes(compactExp))) {<br>            f.actualValue = exp;<br>            f.enabled = true;<br>            matched++;<br>            return;<br>          }<br><br>          const labelNorm = f.name.toLowerCase();<br>          const labelLine = lines.find(l =&gt; l.toLowerCase().includes(labelNorm));<br>          if (labelLine) {<br>            const afterColon = labelLine.split(/[:\-]/).slice(1).join(&#39;:&#39;).trim();<br>            if (afterColon) {<br>              f.actualValue = afterColon;<br>              f.enabled = true;<br>            }<br>          }<br>        });<br><br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { matched, total };<br>      }<br>    };<br><br>    const OcrMappingEngine = {<br>      parseQuickPasteFees(rawText) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br><br>        const parsed = [];<br>        let i = 0;<br><br>        while (i &lt; lines.length) {<br>          const line = lines[i];<br><br>          if (line.includes(&#39;|&#39;) || line.includes(&#39;\t&#39;)) {<br>            const parts = line.split(/\||\t/).map(p =&gt; p.trim()).filter(Boolean);<br>            const name = parts[0] || `Fee ${parsed.length + 1}`;<br>            const amount = parts[1] || &#39;0&#39;;<br>            const isCwt = /\bcwt\b|withholding/i.test(name) || (parts[2] &amp;&amp; parts[2].toUpperCase() === &#39;CWT&#39;);<br>            const code = parts[2] || (isCwt ? &#39;CWT&#39; : &#39;&#39;);<br>            parsed.push({ name, amount, code, isCwt });<br>            i += 1;<br>            continue;<br>          }<br><br>          const name = line;<br>          const amount = lines[i + 1] !== undefined ? lines[i + 1] : &#39;&#39;;<br>          const isCwtName = /\bcwt\b|withholding/i.test(name);<br>          const possibleCode = lines[i + 2];<br><br>          const looksLikeCode = possibleCode !== undefined &amp;&amp;<br>            /^[A-Za-z0-9_-]{1,12}$/.test(possibleCode) &amp;&amp;<br>            !/^\d+(\.\d+)?$/.test(possibleCode);<br><br>          if (looksLikeCode) {<br>            const isCwt = isCwtName || possibleCode.toUpperCase() === &#39;CWT&#39;;<br>            parsed.push({ name, amount, code: possibleCode.toUpperCase(), isCwt });<br>            i += 3;<br>          } else {<br>            parsed.push({<br>              name,<br>              amount,<br>              code: isCwtName ? &#39;CWT&#39; : &#39;&#39;,<br>              isCwt: isCwtName<br>            });<br>            i += 2;<br>          }<br>        }<br><br>        return parsed;<br>      },<br><br>      parseReceiptTextToBlocks(rawText, pageNum = 1, baseConfidence = 92) {<br>        const lines = String(rawText || &#39;&#39;).split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br>        const blocks = [];<br><br>        lines.forEach((line, idx) =&gt; {<br>          const yPct = Math.min(92, 8 + idx * 7);<br>          const pipeOrCol = line.split(/\||\t|\s{2,}/).map(s =&gt; s.trim()).filter(Boolean);<br>          if (pipeOrCol.length &gt;= 2) {<br>            const name = pipeOrCol[0];<br>            const amtMatch = pipeOrCol.find(p =&gt; /^\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?$/.test(p)) || pipeOrCol[1];<br>            const codeMatch = pipeOrCol.find(p =&gt; /^[A-Z0-9]{2,8}$/.test(p) &amp;&amp; p !== amtMatch) || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;);<br>            blocks.push({<br>              id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>              page: pageNum,<br>              rawLine: line,<br>              detectedName: name,<br>              detectedAmount: amtMatch,<br>              detectedCode: codeMatch,<br>              confidence: baseConfidence,<br>              bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>              mappedToFeeId: null,<br>              status: &#39;UNMAPPED&#39;<br>            });<br>          } else {<br>            const regex = /^(.+?)\s+(\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?)(?:\s+([A-Za-z0-9_-]{2,10}))?$/;<br>            const m = line.match(regex);<br>            if (m) {<br>              const name = m[1].trim();<br>              const amt = m[2].trim();<br>              const code = (m[4] || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;)).toUpperCase();<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: name,<br>                detectedAmount: amt,<br>                detectedCode: code,<br>                confidence: baseConfidence,<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;UNMAPPED&#39;<br>              });<br>            } else {<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: line,<br>                detectedAmount: &#39;&#39;,<br>                detectedCode: &#39;&#39;,<br>                confidence: Math.max(65, baseConfidence - 10),<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;TEXT_ONLY&#39;<br>              });<br>            }<br>          }<br>        });<br><br>        return blocks;<br>      },<br><br>      autoMapBlocksToMainPage(mainPage) {<br>        if (!mainPage || !mainPage.receipt) return { autoAccepted: 0, reviewNeeded: 0 };<br>        const blocks = (mainPage.receipt.ocrBlocks || []).filter(b =&gt; b.detectedAmount !== &#39;&#39;);<br>        const fees = mainPage.fees || [];<br>        let autoAccepted = 0;<br>        let reviewNeeded = 0;<br><br>        const usedBlockIds = new Set();<br><br>        fees.forEach((fee, feeIdx) =&gt; {<br>          const expNameNorm = ValidationEngine.normalizeText(fee.expectedName);<br>          const expCodeNorm = String(fee.expectedCode || &#39;&#39;).trim().toUpperCase();<br><br>          let bestBlock = null;<br>          let bestScore = 0;<br><br>          blocks.forEach(blk =&gt; {<br>            if (usedBlockIds.has(blk.id)) return;<br>            let score = 0;<br>            const blkNameNorm = ValidationEngine.normalizeText(blk.detectedName);<br>            const blkCodeNorm = String(blk.detectedCode || &#39;&#39;).trim().toUpperCase();<br><br>            if (expNameNorm &amp;&amp; blkNameNorm === expNameNorm) score += 50;<br>            else if (expNameNorm &amp;&amp; (blkNameNorm.includes(expNameNorm) || expNameNorm.includes(blkNameNorm))) score += 30;<br><br>            if (expCodeNorm &amp;&amp; blkCodeNorm === expCodeNorm) score += 40;<br>            if (blocks.indexOf(blk) === feeIdx) score += 15;<br><br>            if (score &gt; bestScore) {<br>              bestScore = score;<br>              bestBlock = blk;<br>            }<br>          });<br><br>          if (bestBlock &amp;&amp; bestScore &gt;= 30) {<br>            usedBlockIds.add(bestBlock.id);<br>            fee.actualName = bestBlock.detectedName;<br>            fee.actualAmount = bestBlock.detectedAmount;<br>            fee.actualCode = bestBlock.detectedCode || fee.actualCode;<br>            fee.ocrConfidence = bestBlock.confidence;<br>            fee.sourceLocation = `Page ${bestBlock.page} (Y:${Math.round(bestBlock.bbox.y)}%)`;<br>            bestBlock.mappedToFeeId = fee.id;<br><br>            if (bestScore &gt;= 65 &amp;&amp; bestBlock.confidence &gt;= appState.settings.autoAcceptConfidenceThreshold) {<br>              bestBlock.status = &#39;AUTO_ACCEPTED&#39;;<br>              autoAccepted++;<br>            } else {<br>              bestBlock.status = &#39;REVIEW&#39;;<br>              reviewNeeded++;<br>            }<br>          }<br>        });<br><br>        RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(mainPage);<br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { autoAccepted, reviewNeeded };<br>      },<br><br>      async preprocessImageCanvas(imageDataUrl, opts = {}) {<br>        return new Promise((resolve) =&gt; {<br>          const img = new Image();<br>          img.onload = () =&gt; {<br>            try {<br>              const scale = opts.scale || 1.5;<br>              const canvas = document.createElement(&#39;canvas&#39;);<br>              canvas.width = Math.max(1, Math.round((img.naturalWidth || img.width || 400) * scale));<br>              canvas.height = Math.max(1, Math.round((img.naturalHeight || img.height || 400) * scale));<br>              const ctx = canvas.getContext(&#39;2d&#39;);<br>              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>              if (opts.grayscale || opts.contrast || opts.sharpen) {<br>                const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);<br>                const d = imgData.data;<br>                const contrastFactor = opts.contrast ? 1.35 : 1.0;<br>                for (let i = 0; i &lt; d.length; i += 4) {<br>                  let r = d[i], g = d[i + 1], b = d[i + 2];<br>                  if (opts.grayscale) {<br>                    const gray = 0.299 * r + 0.587 * g + 0.114 * b;<br>                    r = g = b = gray;<br>                  }<br>                  if (opts.contrast) {<br>                    r = Math.min(255, Math.max(0, (r - 128) * contrastFactor + 128));<br>                    g = Math.min(255, Math.max(0, (g - 128) * contrastFactor + 128));<br>                    b = Math.min(255, Math.max(0, (b - 128) * contrastFactor + 128));<br>                  }<br>                  d[i] = r; d[i + 1] = g; d[i + 2] = b;<br>                }<br>                ctx.putImageData(imgData, 0, 0);<br>              }<br>              resolve(canvas.toDataURL(&#39;image/png&#39;));<br>            } catch (canvasErr) {<br>              console.warn(&#39;Preprocessing canvas fallback:&#39;, canvasErr);<br>              resolve(imageDataUrl);<br>            }<br>          };<br>          img.onerror = () =&gt; resolve(imageDataUrl);<br>          img.src = imageDataUrl;<br>        });<br>      },<br><br>      async runRealTesseractOCR(imageDataUrl, onProgress) {<br>        if (!window.Tesseract) {<br>          throw new Error(&#39;Tesseract.js library is unavailable offline.&#39;);<br>        }<br>        const worker = await Tesseract.createWorker(&#39;eng&#39;, 1, {<br>          logger: m =&gt; {<br>            if (onProgress &amp;&amp; m.status === &#39;recognizing text&#39;) {<br>              onProgress(Math.round((m.progress || 0) * 100));<br>            }<br>          }<br>        });<br>        try {<br>          const ret = await worker.recognize(imageDataUrl);<br>          return {<br>            text: ret.data.text || &#39;&#39;,<br>            confidence: Math.round(ret.data.confidence || 85)<br>          };<br>        } finally {<br>          await worker.terminate();<br>        }<br>      }<br>    };<br><br>    /****************************************************************************<br>     * SAMPLE DATA &amp; SVG RECEIPT GENERATOR (100% SELF-CONTAINED)<br>     ****************************************************************************/<br>    function generateSyntheticReceiptSvgDataUrl({ title, invoiceNo, date, lines, footer }) {<br>      const lineRows = lines.map((l, idx) =&gt; {<br>        const y = 135 + idx * 32;<br>        return `<br>          &lt;text x=&quot;28&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; fill=&quot;#1e293b&quot;&gt;${escapeHtml(l.label)}&lt;/text&gt;<br>          &lt;text x=&quot;315&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(l.amount)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;13&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#4f46e5&quot;&gt;${escapeHtml(l.code)}&lt;/text&gt;<br>        `;<br>      }).join(&#39;&#39;);<br><br>      const svg = `<br>        &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;400&quot; height=&quot;420&quot; viewBox=&quot;0 0 400 420&quot;&gt;<br>          &lt;rect width=&quot;400&quot; height=&quot;420&quot; fill=&quot;#ffffff&quot; rx=&quot;8&quot;/&gt;<br>          &lt;rect x=&quot;12&quot; y=&quot;12&quot; width=&quot;376&quot; height=&quot;396&quot; fill=&quot;none&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1.5&quot; stroke-dasharray=&quot;4 3&quot; rx=&quot;6&quot;/&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;45&quot; font-family=&quot;sans-serif&quot; font-size=&quot;16&quot; font-weight=&quot;800&quot; text-anchor=&quot;middle&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(title)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;66&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;middle&quot; fill=&quot;#64748b&quot;&gt;OFFICIAL EIS ELECTRONIC RECEIPT&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;80&quot; x2=&quot;376&quot; y2=&quot;80&quot; stroke=&quot;#94a3b8&quot; stroke-width=&quot;1&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; fill=&quot;#334155&quot;&gt;REF: ${escapeHtml(invoiceNo)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;end&quot; fill=&quot;#334155&quot;&gt;${escapeHtml(date)}&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;112&quot; x2=&quot;376&quot; y2=&quot;112&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1&quot;/&gt;<br>          ${lineRows}<br>          &lt;line x1=&quot;24&quot; y1=&quot;315&quot; x2=&quot;376&quot; y2=&quot;315&quot; stroke=&quot;#0f172a&quot; stroke-width=&quot;1.5&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(footer.label)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;15&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#059669&quot;&gt;${escapeHtml(footer.value)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;385&quot; font-family=&quot;monospace&quot; font-size=&quot;10&quot; text-anchor=&quot;middle&quot; fill=&quot;#94a3b8&quot;&gt;EIS-AUTH-HASH: 9F82-77C1-SMART-QA&lt;/text&gt;<br>        &lt;/svg&gt;<br>      `;<br>      return &#39;data:image/svg+xml;charset=utf-8,&#39; + encodeURIComponent(svg);<br>    }<br><br>    function createDefaultFields(count = 50) {<br>      const presets = [<br>        { name: &#39;Invoice / Receipt Number&#39;, type: &#39;Reference&#39;, req: true },<br>        { name: &#39;Transaction Date&#39;, type: &#39;Date&#39;, req: true },<br>        { name: &#39;Merchant / Taxpayer TIN&#39;, type: &#39;Reference&#39;, req: false },<br>        { name: &#39;Currency Code&#39;, type: &#39;Code&#39;, req: true },<br>        { name: &#39;Gross Settlement Total&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;CWT Withholding Amount&#39;, type: &#39;Currency&#39;, req: false },<br>        { name: &#39;Net Payable Amount&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;EIS Acknowledgement ID&#39;, type: &#39;Reference&#39;, req: false }<br>      ];<br>      const list = [];<br>      for (let i = 1; i &lt;= count; i++) {<br>        const p = presets[i - 1];<br>        list.push({<br>          id: `fld_${i}_${Math.random().toString(36).slice(2, 6)}`,<br>          number: i,<br>          name: p ? p.name : `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: p ? p.type : &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: p ? p.req : false,<br>          tolerance: 0.01,<br>          description: p ? `Standard EIS ${p.name}` : `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: i &lt;= 8<br>        });<br>      }<br>      return list;<br>    }<br><br>    function createSampleSeedState() {<br>      const now = new Date().toISOString();<br><br>      // Page 1: PASS (Fee 1 = 1000/NC, Fee 2 = 250/IC, CWT = -50 -&gt; Gross 1250, CWT 50, Net 1200)<br>      const p1ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;MANILA LOGISTICS &amp; FREIGHT CORP.&#39;,<br>        invoiceNo: &#39;EIS-2026-1001&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Fee 1 Charge&#39;, amount: &#39;1,000.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Fee 2 Charge&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;-50.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,200.00&#39; }<br>      });<br><br>      const p1RawText = `Fee 1 Charge | 1000.00 | NC\nFee 2 Charge | 250.00 | IC\nCWT | -50.00 | CWT`;<br>      const page1 = {<br>        id: &#39;mp_manila_01&#39;,<br>        name: &#39;MP-01: Manila HQ Settlement&#39;,<br>        description: &#39;Standard two-fee transaction with negative CWT notation (-50).&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;EIS-2026-1001\t2026-11-19\t004-892-110-000\tPHP\t1250.00\t50.00\t1200.00&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_01&#39;,<br>          fileName: &#39;manila_eis_receipt_1001.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p1ReceiptImg],<br>          ocrRawText: p1RawText,<br>          ocrConfidence: 96,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p1RawText, 1, 96),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_1a&#39;, expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1 Charge&#39;, actualAmount: &#39;1000.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 97, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_1b&#39;, expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 2 Charge&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 95, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_1c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;-50&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;-50.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 96, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_1&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#10b981&#39;, label: &#39;QA-1: Fee 1 Verified&#39;, comment: &#39;Matches 1000.00 NC&#39;, fieldRef: &#39;Fee 1 Charge&#39;, testCaseId: &#39;TC-001&#39;, defectId: &#39;&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page1.fields[0].expectedValue = &#39;EIS-2026-1001&#39;; page1.fields[0].actualValue = &#39;EIS-2026-1001&#39;;<br>      page1.fields[1].expectedValue = &#39;2026-11-19&#39;; page1.fields[1].actualValue = &#39;2026-11-19&#39;;<br>      page1.fields[2].expectedValue = &#39;004-892-110-000&#39;; page1.fields[2].actualValue = &#39;004-892-110-000&#39;;<br>      page1.fields[3].expectedValue = &#39;PHP&#39;; page1.fields[3].actualValue = &#39;PHP&#39;;<br>      page1.fields[4].expectedValue = &#39;1250.00&#39;; page1.fields[4].actualValue = &#39;1250.00&#39;;<br>      page1.fields[5].expectedValue = &#39;50.00&#39;; page1.fields[5].actualValue = &#39;50.00&#39;;<br>      page1.fields[6].expectedValue = &#39;1200.00&#39;; page1.fields[6].actualValue = &#39;1200.00&#39;;<br><br>      // Page 2: FAIL (Fee 1 Expected 1000 vs Receipt 1200 -&gt; Diff +200, CWT = (50))<br>      const p2ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;CEBU PORT TERMINAL SERVICES&#39;,<br>        invoiceNo: &#39;EIS-2026-2044&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Terminal Handling&#39;, amount: &#39;1,200.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Documentation Fee&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;(50.00)&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,400.00&#39; }<br>      });<br>      const p2RawText = `Terminal Handling | 1200.00 | NC\nDocumentation Fee | 250.00 | IC\nCWT | (50.00) | CWT`;<br>      const page2 = {<br>        id: &#39;mp_cebu_02&#39;,<br>        name: &#39;MP-02: Cebu Hub Clearance&#39;,<br>        description: &#39;Demonstrates Fee 1 amount mismatch (Expected 1000 vs Receipt 1200) &amp; parenthetical CWT (50).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_02&#39;,<br>          fileName: &#39;cebu_eis_receipt_2044.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p2ReceiptImg],<br>          ocrRawText: p2RawText,<br>          ocrConfidence: 93,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p2RawText, 1, 93),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_2a&#39;, expectedName: &#39;Terminal Handling&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Terminal Handling&#39;, actualAmount: &#39;1200.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 94, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_2b&#39;, expectedName: &#39;Documentation Fee&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Documentation Fee&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 93, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_2c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;(50)&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;(50.00)&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 92, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_2&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#ef4444&#39;, label: &#39;QA-1: Overcharge +200&#39;, comment: &#39;Expected 1000.00, Receipt shows 1200.00&#39;, fieldRef: &#39;Terminal Handling&#39;, testCaseId: &#39;TC-002&#39;, defectId: &#39;DEF-101&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page2.fields[0].expectedValue = &#39;EIS-2026-2044&#39;; page2.fields[0].actualValue = &#39;EIS-2026-2044&#39;;<br>      page2.fields[3].expectedValue = &#39;PHP&#39;; page2.fields[3].actualValue = &#39;PHP&#39;;<br><br>      // Page 3: PENDING (Missing Fee Code on Inspection Fee -&gt; verifies missing info never auto-passes)<br>      const p3ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;DAVAO AGRI-EXPORT GATEWAY&#39;,<br>        invoiceNo: &#39;EIS-2026-3099&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Export Inspection&#39;, amount: &#39;800.00&#39;, code: &#39;&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;40.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 760.00&#39; }<br>      });<br>      const p3RawText = `Export Inspection | 800.00\nCWT | 40.00 | CWT`;<br>      const page3 = {<br>        id: &#39;mp_davao_03&#39;,<br>        name: &#39;MP-03: Davao Branch Export&#39;,<br>        description: &#39;Demonstrates missing required fee code evaluation (PENDING rather than false PASS).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_03&#39;,<br>          fileName: &#39;davao_eis_receipt_3099.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p3ReceiptImg],<br>          ocrRawText: p3RawText,<br>          ocrConfidence: 89,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p3RawText, 1, 89),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_3a&#39;, expectedName: &#39;Export Inspection&#39;, expectedAmount: &#39;800&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Export Inspection&#39;, actualAmount: &#39;800.00&#39;, actualCode: &#39;&#39;, isCwt: false, ocrConfidence: 89, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_3b&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;40&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;40.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 91, sourceLocation: &#39;Page 1 Row 2&#39; }<br>        ],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      page3.fields[0].expectedValue = &#39;EIS-2026-3099&#39;; page3.fields[0].actualValue = &#39;EIS-2026-3099&#39;;<br><br>      [page1, page2, page3].forEach(p =&gt; ValidationEngine.validateMainPage(p, true));<br><br>      const sampleProject = {<br>        id: &#39;proj_eis_2026_q4&#39;,<br>        name: &#39;EIS Q4 Release — Core Settlement &amp; CWT Audit&#39;,<br>        reference: &#39;PRJ-EIS-2026-04&#39;,<br>        description: &#39;End-to-end EIS electronic receipt validation, CWT deduction accuracy, and QA screenshot evidence suite.&#39;,<br>        owner: &#39;Jansen B. (Lead QA Analyst)&#39;,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [page1, page2, page3],<br>        screenshots: [<br>          {<br>            id: &#39;scr_01&#39;,<br>            name: &#39;EIS_Portal_Manila_Settlement.svg&#39;,<br>            dataUrl: p1ReceiptImg,<br>            capturedAt: now,<br>            source: &#39;Sample Evidence&#39;,<br>            isMerged: false<br>          }<br>        ],<br>        mergeHistory: [],<br>        testCases: [<br>          {<br>            id: &#39;TC-001&#39;,<br>            title: &#39;Verify Standard 2-Fee Gross &amp; Negative CWT (-50) Net Settlement&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Manila HQ Settlement Main Page configured with Fee 1 (1000/NC), Fee 2 (250/IC), CWT (-50).&#39;,<br>            steps: &#39;1. Upload official EIS receipt.\n2. Run OCR extraction &amp; auto-mapping.\n3. Verify Gross = 1250.00, CWT = 50.00, Net = 1200.00.&#39;,<br>            expectedResult: &#39;All fee names, amounts, and codes PASS; Net Total equals 1200.00.&#39;,<br>            actualResult: &#39;Gross 1250.00 - CWT 50.00 = Net 1200.00. Status: PASS.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_manila_01&#39;,<br>            linkedDefectId: &#39;&#39;<br>          },<br>          {<br>            id: &#39;TC-002&#39;,<br>            title: &#39;Detect Fee 1 Overcharge Mismatch &amp; Parenthetical CWT (50)&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Cebu Hub Main Page expects Terminal Handling = 1000.00 NC.&#39;,<br>            steps: &#39;1. Attach Cebu receipt showing 1200.00 NC.\n2. Execute validation engine.&#39;,<br>            expectedResult: &#39;System flags FAIL with +200.00 difference while deducting 50.00 for (50) CWT.&#39;,<br>            actualResult: &#39;Flagged FAIL (+200.00 variance). Defect DEF-101 logged.&#39;,<br>            status: &#39;FAIL&#39;,<br>            priority: &#39;Critical&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            linkedDefectId: &#39;DEF-101&#39;<br>          },<br>          {<br>            id: &#39;TC-003&#39;,<br>            title: &#39;Verify Missing Fee Code Triggers PENDING Instead of False PASS&#39;,<br>            module: &#39;Validation Rules&#39;,<br>            preconditions: &#39;Davao Branch receipt omits IC fee code on Export Inspection.&#39;,<br>            steps: &#39;1. Validate Davao Branch Main Page.&#39;,<br>            expectedResult: &#39;Status evaluates to PENDING until code is verified.&#39;,<br>            actualResult: &#39;Evaluated as PENDING as expected.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;Jansen B.&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_davao_03&#39;,<br>            linkedDefectId: &#39;&#39;<br>          }<br>        ],<br>        defects: [<br>          {<br>            id: &#39;DEF-101&#39;,<br>            title: &#39;Terminal Handling Fee billed at 1,200.00 instead of contracted 1,000.00 (+200.00 variance)&#39;,<br>            description: &#39;EIS receipt #EIS-2026-2044 reflects 1,200.00 NC for Terminal Handling, exceeding Main Page expected tariff by 200.00.&#39;,<br>            stepsToReproduce: &#39;1. Open MP-02: Cebu Hub Clearance.\n2. Compare Fee 1 expected (1000.00 NC) against uploaded receipt.\n3. Observe +200.00 variance.&#39;,<br>            expectedResult: &#39;Terminal Handling = 1,000.00 NC; Net Payable = 1,200.00&#39;,<br>            actualResult: &#39;Terminal Handling = 1,200.00 NC; Net Payable = 1,400.00&#39;,<br>            severity: &#39;High&#39;,<br>            priority: &#39;P1&#39;,<br>            status: &#39;Open&#39;,<br>            environment: &#39;EIS Staging v4.12&#39;,<br>            linkedTestCaseId: &#39;TC-002&#39;,<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            annotationRef: &#39;QA-1: Overcharge +200&#39;,<br>            dateReported: now.slice(0, 10),<br>            assignee: &#39;M. Santos (Billing Dev)&#39;<br>          }<br>        ],<br>        activityLog: [<br>          { timestamp: now, action: &#39;Initialized Workspace&#39;, detail: &#39;Loaded sample project PRJ-EIS-2026-04 with 3 isolated Main Pages.&#39; }<br>        ]<br>      };<br><br>      const defaultTemplates = [<br>        {<br>          id: &#39;tpl_standard_cwt&#39;,<br>          name: &#39;Standard 2-Fee + CWT Settlement&#39;,<br>          description: &#39;Includes Fee 1 (NC), Fee 2 (IC), and CWT deduction rule.&#39;,<br>          fees: [<br>            { expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, isCwt: false },<br>            { expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;50&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        },<br>        {<br>          id: &#39;tpl_brokerage_3fee&#39;,<br>          name: &#39;Customs Brokerage 3-Fee + 2% CWT&#39;,<br>          description: &#39;Brokerage, Arrastre, Wharfage, and Withholding Tax.&#39;,<br>          fees: [<br>            { expectedName: &#39;Brokerage Fee&#39;, expectedAmount: &#39;2500&#39;, expectedCode: &#39;BRK&#39;, isCwt: false },<br>            { expectedName: &#39;Arrastre Charge&#39;, expectedAmount: &#39;850&#39;, expectedCode: &#39;ARR&#39;, isCwt: false },<br>            { expectedName: &#39;Wharfage Fee&#39;, expectedAmount: &#39;400&#39;, expectedCode: &#39;WHF&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;75&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        }<br>      ];<br><br>      return {<br>        schemaVersion: APP_SCHEMA_VERSION,<br>        theme: &#39;dark&#39;,<br>        sidebarCollapsed: false,<br>        activeModule: &#39;dashboard&#39;,<br>        activeProjectId: sampleProject.id,<br>        activeMainPageId: page1.id,<br>        lastSavedAt: now,<br>        settings: {<br>          numericTolerance: 0.01,<br>          caseSensitiveNames: false,<br>          normalizeWhitespace: true,<br>          autoAcceptConfidenceThreshold: 88,<br>          cwtDeductionMode: &#39;absolute&#39;,<br>          qaLabelMax: 200,<br>          qaAutoIncrement: true<br>        },<br>        templates: defaultTemplates,<br>        projects: [sampleProject],<br>        ui: {<br>          viewerZoom: 1,<br>          viewerRotation: 0,<br>          showOcrBoxes: true,<br>          selectedComparisonRowId: null,<br>          selectedScreenshotsForMerge: [],<br>          annotationTool: &#39;rect&#39;,<br>          annotationColor: &#39;#ef4444&#39;,<br>          selectedAnnotationId: null,<br>          selectedQaLabel: 1,<br>          mainPageQuickListOpen: false,<br>          selectedMainPageIds: []<br>        }<br>      };<br>    }<br><br>    /****************************************************************************<br>     * STATE HELPERS &amp; NAVIGATION<br>     ****************************************************************************/<br>    function getActiveProject() {<br>      return appState.projects.find(p =&gt; p.id === appState.activeProjectId) || appState.projects[0] || null;<br>    }<br><br>    function getActiveMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.mainPages || proj.mainPages.length === 0) return null;<br>      return proj.mainPages.find(mp =&gt; mp.id === appState.activeMainPageId) || proj.mainPages[0];<br>    }<br><br>    function logActivity(action, detail) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.activityLog = proj.activityLog || [];<br>      proj.activityLog.unshift({ timestamp: new Date().toISOString(), action, detail });<br>      if (proj.activityLog.length &gt; 40) proj.activityLog.pop();<br>    }<br><br>    function navigateTo(moduleId) {<br>      appState.activeModule = moduleId;<br>      closeMobileSidebar();<br>      renderApp();<br>    }<br><br>    function switchActiveProject(projectId) {<br>      appState.activeProjectId = projectId;<br>      const proj = getActiveProject();<br>      appState.activeMainPageId = proj &amp;&amp; proj.mainPages[0] ? proj.mainPages[0].id : null;<br>      scheduleAutosave(&#39;Switched active project&#39;);<br>      renderApp();<br>    }<br><br>    function switchActiveMainPage(pageId) {<br>      appState.activeMainPageId = pageId;<br>      appState.ui.selectedComparisonRowId = null;<br>      appState.ui.selectedAnnotationId = null;<br>      scheduleAutosave(&#39;Switched Main Page&#39;);<br>      renderApp();<br>    }<br><br>    function toggleTheme() {<br>      appState.theme = appState.theme === &#39;dark&#39; ? &#39;light&#39; : &#39;dark&#39;;<br>      applyTheme();<br>      scheduleAutosave(&#39;Theme changed&#39;);<br>    }<br><br>    function applyTheme() {<br>      const html = document.documentElement;<br>      if (appState.theme === &#39;dark&#39;) html.classList.add(&#39;dark&#39;);<br>      else html.classList.remove(&#39;dark&#39;);<br>    }<br><br>    function toggleSidebarCollapse() {<br>      appState.sidebarCollapsed = !appState.sidebarCollapsed;<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const labels = document.querySelectorAll(&#39;.sidebar-label&#39;);<br>      if (appState.sidebarCollapsed) {<br>        sidebar.classList.remove(&#39;lg:w-64&#39;);<br>        sidebar.classList.add(&#39;lg:w-20&#39;);<br>        labels.forEach(el =&gt; el.classList.add(&#39;lg:hidden&#39;));<br>      } else {<br>        sidebar.classList.remove(&#39;lg:w-20&#39;);<br>        sidebar.classList.add(&#39;lg:w-64&#39;);<br>        labels.forEach(el =&gt; el.classList.remove(&#39;lg:hidden&#39;));<br>      }<br>    }<br><br>    function toggleMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      const isOpen = !sidebar.classList.contains(&#39;-translate-x-full&#39;);<br>      if (isOpen) {<br>        closeMobileSidebar();<br>      } else {<br>        sidebar.classList.remove(&#39;-translate-x-full&#39;);<br>        backdrop.classList.remove(&#39;hidden&#39;);<br>      }<br>    }<br><br>    function closeMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      if (sidebar) sidebar.classList.add(&#39;-translate-x-full&#39;);<br>      if (backdrop) backdrop.classList.add(&#39;hidden&#39;);<br>    }<br><br>    function showToast(message, type = &#39;info&#39;) {<br>      const container = document.getElementById(&#39;toast-container&#39;);<br>      if (!container) return;<br>      const colors = {<br>        success: &#39;bg-emerald-600 text-white border-emerald-500&#39;,<br>        error: &#39;bg-rose-600 text-white border-rose-500&#39;,<br>        warning: &#39;bg-amber-500 text-slate-950 border-amber-400&#39;,<br>        info: &#39;bg-slate-800 text-white border-slate-700&#39;<br>      };<br>      const el = document.createElement(&#39;div&#39;);<br>      el.className = `pointer-events-auto px-4 py-3 rounded-xl shadow-xl border text-xs font-medium flex items-center justify-between gap-3 transition-all ${colors[type] || colors.info}`;<br>      el.innerHTML = `&lt;span&gt;${escapeHtml(message)}&lt;/span&gt;&lt;button onclick=&quot;this.parentElement.remove()&quot; class=&quot;opacity-75 hover:opacity-100&quot;&gt;&amp;times;&lt;/button&gt;`;<br>      container.appendChild(el);<br>      setTimeout(() =&gt; { if (el.parentElement) el.remove(); }, 4200);<br>    }<br><br>    function openModal({ title, bodyHtml, footerHtml = &#39;&#39; }) {<br>      document.getElementById(&#39;modal-title&#39;).textContent = title;<br>      document.getElementById(&#39;modal-body&#39;).innerHTML = bodyHtml;<br>      document.getElementById(&#39;modal-footer&#39;).innerHTML = footerHtml;<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.remove(&#39;hidden&#39;);<br>      overlay.classList.add(&#39;flex&#39;);<br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    function closeModal() {<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.add(&#39;hidden&#39;);<br>      overlay.classList.remove(&#39;flex&#39;);<br>    }<br><br>    function statusBadge(status) {<br>      const s = String(status || &#39;PENDING&#39;).toUpperCase();<br>      const styles = {<br>        PASS: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;,<br>        FAIL: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        REVIEW: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        PENDING: &#39;bg-sky-500/15 text-sky-600 dark:text-sky-400 border-sky-500/30&#39;,<br>        &#39;NOT APPLICABLE&#39;: &#39;bg-slate-500/15 text-slate-500 dark:text-slate-400 border-slate-500/30&#39;,<br>        OPEN: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        &#39;IN PROGRESS&#39;: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        FIXED: &#39;bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border-indigo-500/30&#39;,<br>        RETEST: &#39;bg-purple-500/15 text-purple-600 dark:text-purple-400 border-purple-500/30&#39;,<br>        CLOSED: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;<br>      };<br>      return `&lt;span class=&quot;inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide border ${styles[s] || styles.PENDING}&quot;&gt;${escapeHtml(s)}&lt;/span&gt;`;<br>    }<br><br>    function runActivePageValidation(notify = false) {<br>      const mp = getActiveMainPage();<br>      if (!mp) return showToast(&#39;No active Main Page selected.&#39;, &#39;warning&#39;);<br>      const res = ValidationEngine.validateMainPage(mp, true);<br>      logActivity(&#39;Validated Main Page&#39;, `${mp.name} → ${res.overallStatus}`);<br>      scheduleAutosave(&#39;Validated Main Page&#39;);<br>      if (notify) showToast(`${mp.name}: ${res.overallStatus} (${res.counts.pass} Pass, ${res.counts.fail} Fail, ${res.counts.review} Review, ${res.counts.pending} Pending)`, res.overallStatus === &#39;PASS&#39; ? &#39;success&#39; : res.overallStatus === &#39;FAIL&#39; ? &#39;error&#39; : &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * SHELL &amp; NAVIGATION RENDERER<br>     ****************************************************************************/<br>    function renderShellChrome() {<br>      const projSelect = document.getElementById(&#39;sidebar-project-select&#39;);<br>      if (projSelect) {<br>        projSelect.innerHTML = appState.projects.map(p =&gt;<br>          `&lt;option value=&quot;${escapeHtml(p.id)}&quot; ${p.id === appState.activeProjectId ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(p.name)} ${p.archived ? &#39;(Archived)&#39; : &#39;&#39;}&lt;/option&gt;`<br>        ).join(&#39;&#39;);<br>      }<br><br>      const nav = document.getElementById(&#39;sidebar-nav&#39;);<br>      if (nav) {<br>        nav.innerHTML = MODULES.map(m =&gt; {<br>          const active = appState.activeModule === m.id;<br>          return `<br>            &lt;button onclick=&quot;navigateTo(&#39;${m.id}&#39;)&quot; class=&quot;w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-xs font-semibold transition ${<br>              active<br>                ? &#39;bg-brand-600 text-white shadow-sm&#39;<br>                : &#39;text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800/80&#39;<br>            }&quot;&gt;<br>              &lt;i data-lucide=&quot;${m.icon}&quot; class=&quot;w-4 h-4 shrink-0&quot;&gt;&lt;/i&gt;<br>              &lt;span class=&quot;sidebar-label truncate&quot;&gt;${escapeHtml(m.label)}&lt;/span&gt;<br>            &lt;/button&gt;<br>          `;<br>        }).join(&#39;&#39;);<br>      }<br><br>      const activeMod = MODULES.find(m =&gt; m.id === appState.activeModule) || MODULES[0];<br>      const topTitle = document.getElementById(&#39;topbar-title&#39;);<br>      const topSub = document.getElementById(&#39;topbar-subtitle&#39;);<br>      if (topTitle) topTitle.textContent = activeMod.label;<br>      if (topSub) topSub.textContent = activeMod.subtitle;<br>    }<br><br>    function renderApp() {<br>      applyTheme();<br>      renderShellChrome();<br>      const viewport = document.getElementById(&#39;main-viewport&#39;);<br>      if (!viewport) return;<br><br>      Object.values(chartInstances).forEach(c =&gt; { try { c.destroy(); } catch (e) {} });<br>      chartInstances = {};<br><br>      switch (appState.activeModule) {<br>        case &#39;dashboard&#39;: viewport.innerHTML = renderDashboardModule(); initDashboardCharts(); break;<br>        case &#39;projects&#39;: viewport.innerHTML = renderProjectsModule(); break;<br>        case &#39;main-pages&#39;: viewport.innerHTML = renderMainPagesModule(); break;<br>        case &#39;validation&#39;: viewport.innerHTML = renderValidationWorkspaceModule(); break;<br>        case &#39;ocr-intel&#39;: viewport.innerHTML = renderOcrIntelligenceModule(); break;<br>        case &#39;screenshots&#39;: viewport.innerHTML = renderScreenshotStudioModule(); initAnnotationCanvasEvents(); break;<br>        case &#39;test-cases&#39;: viewport.innerHTML = renderTestCasesModule(); break;<br>        case &#39;defects&#39;: viewport.innerHTML = renderDefectsModule(); break;<br>        case &#39;reports&#39;: viewport.innerHTML = renderReportsModule(); break;<br>        case &#39;templates&#39;: viewport.innerHTML = renderTemplatesModule(); break;<br>        case &#39;settings&#39;: viewport.innerHTML = renderSettingsModule(); break;<br>        default: viewport.innerHTML = renderDashboardModule();<br>      }<br><br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1 VIEW: DASHBOARD<br>     ****************************************************************************/<br>    function renderDashboardModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return `&lt;div class=&quot;p-8 text-center&quot;&gt;No project found. Create one in Projects.&lt;/div&gt;`;<br><br>      const totalProjects = appState.projects.length;<br>      const totalMainPages = proj.mainPages.length;<br>      const totalReceipts = proj.mainPages.filter(mp =&gt; mp.receipt).length;<br>      const totalScreenshots = (proj.screenshots || []).length;<br><br>      let passCount = 0, failCount = 0, reviewCount = 0, pendingCount = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        const c = mp.validationSummary.counts;<br>        passCount += c.pass;<br>        failCount += c.fail;<br>        reviewCount += c.review;<br>        pendingCount += c.pending;<br>      });<br>      const totalChecks = passCount + failCount + reviewCount + pendingCount;<br><br>      const totalTC = (proj.testCases || []).length;<br>      const passedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>      const failedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>      const openDefects = (proj.defects || []).filter(d =&gt; d.status !== &#39;Closed&#39; &amp;&amp; d.status !== &#39;Rejected&#39;).length;<br><br>      return `<br>        &lt;div class=&quot;bg-gradient-to-r from-brand-600 via-indigo-600 to-violet-700 rounded-2xl p-6 text-white shadow-lg flex flex-col lg:flex-row lg:items-center justify-between gap-4&quot;&gt;<br>          &lt;div class=&quot;space-y-1&quot;&gt;<br>            &lt;div class=&quot;inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-white/15 text-xs font-semibold&quot;&gt;<br>              &lt;span&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>              &lt;span&gt;•&lt;/span&gt;<br>              &lt;span&gt;${escapeHtml(proj.status)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;h2 class=&quot;text-xl sm:text-2xl font-extrabold tracking-tight&quot;&gt;${escapeHtml(proj.name)}&lt;/h2&gt;<br>            &lt;p class=&quot;text-xs sm:text-sm text-indigo-100 max-w-2xl&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap gap-2.5 shrink-0&quot;&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;validation&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white text-brand-700 font-bold text-xs shadow hover:bg-indigo-50 transition&quot;&gt;<br>              Open Side-by-Side Validator<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white/15 hover:bg-white/25 text-white font-semibold text-xs border border-white/20 transition&quot;&gt;<br>              Configure Main Pages (${totalMainPages})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3.5&quot;&gt;<br>          ${renderKpiCard(&#39;Projects&#39;, totalProjects, &#39;folder-kanban&#39;, &#39;text-brand-500&#39;)}<br>          ${renderKpiCard(&#39;Main Pages&#39;, totalMainPages, &#39;file-spreadsheet&#39;, &#39;text-indigo-500&#39;)}<br>          ${renderKpiCard(&#39;Receipts Attached&#39;, totalReceipts, &#39;receipt&#39;, &#39;text-emerald-500&#39;)}<br>          ${renderKpiCard(&#39;QA Screenshots&#39;, totalScreenshots, &#39;camera&#39;, &#39;text-violet-500&#39;)}<br>          ${renderKpiCard(&#39;Test Cases Passed&#39;, `${passedTC}/${totalTC}`, &#39;check-square&#39;, &#39;text-sky-500&#39;)}<br>          ${renderKpiCard(&#39;Open Defects&#39;, openDefects, &#39;bug&#39;, &#39;text-rose-500&#39;)}<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 lg:grid-cols-5 gap-3.5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;Total Checks&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold mt-1&quot;&gt;${totalChecks}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-emerald-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-emerald-600 dark:text-emerald-400 font-semibold&quot;&gt;PASS&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-emerald-600 dark:text-emerald-400 mt-1&quot;&gt;${passCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-rose-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-rose-600 dark:text-rose-400 font-semibold&quot;&gt;FAIL&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-rose-600 dark:text-rose-400 mt-1&quot;&gt;${failCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-amber-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-amber-600 dark:text-amber-400 font-semibold&quot;&gt;REVIEW&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-amber-600 dark:text-amber-400 mt-1&quot;&gt;${reviewCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-sky-500/30 rounded-2xl p-4 col-span-2 lg:col-span-1&quot;&gt;<br>            &lt;div class=&quot;text-xs text-sky-600 dark:text-sky-400 font-semibold&quot;&gt;PENDING&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-sky-600 dark:text-sky-400 mt-1&quot;&gt;${pendingCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Validation Status Distribution&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-validation-dist&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Main Page Net Totals (Expected vs Actual)&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-page-financials&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;QA Execution &amp; Defects&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-qa-health&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 overflow-x-auto&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between mb-4&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Main Pages Validation Matrix&lt;/h3&gt;<br>              &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;text-xs font-semibold text-brand-500 hover:underline&quot;&gt;+ Add Main Page&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Gross&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;CWT&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Net Actual&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; {<br>                  const fin = mp.validationSummary.financials;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-semibold&quot;&gt;${escapeHtml(mp.name)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;&lt;span class=&quot;text-amber-500&quot;&gt;None&lt;/span&gt;&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono font-bold&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(mp.validationSummary.overallStatus)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right&quot;&gt;<br>                        &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;); navigateTo(&#39;validation&#39;);&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 hover:bg-brand-500/20 font-semibold&quot;&gt;Inspect&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-4&quot;&gt;Recent Audit Activity&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-3 max-h-72 overflow-y-auto pr-1&quot;&gt;<br>              ${(proj.activityLog || []).slice(0, 12).map(item =&gt; `<br>                &lt;div class=&quot;flex items-start gap-2.5 text-xs border-b border-slate-100 dark:border-slate-800/60 pb-2.5&quot;&gt;<br>                  &lt;span class=&quot;w-2 h-2 rounded-full bg-brand-500 mt-1.5 shrink-0&quot;&gt;&lt;/span&gt;<br>                  &lt;div class=&quot;min-w-0 flex-1&quot;&gt;<br>                    &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(item.action)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 truncate&quot;&gt;${escapeHtml(item.detail)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-[10px] text-slate-400 mt-0.5&quot;&gt;${new Date(item.timestamp).toLocaleString()}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderKpiCard(label, value, icon, colorClass) {<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex items-center justify-between&quot;&gt;<br>          &lt;div&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;${escapeHtml(label)}&lt;/div&gt;<br>            &lt;div class=&quot;text-xl font-extrabold mt-1&quot;&gt;${escapeHtml(value)}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;w-10 h-10 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center ${colorClass}&quot;&gt;<br>            &lt;i data-lucide=&quot;${icon}&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initDashboardCharts() {<br>      const proj = getActiveProject();<br>      if (!proj || !window.Chart) return;<br><br>      let pass = 0, fail = 0, review = 0, pending = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        pass += mp.validationSummary.counts.pass;<br>        fail += mp.validationSummary.counts.fail;<br>        review += mp.validationSummary.counts.review;<br>        pending += mp.validationSummary.counts.pending;<br>      });<br><br>      const ctx1 = document.getElementById(&#39;chart-validation-dist&#39;);<br>      if (ctx1) {<br>        chartInstances.dist = new Chart(ctx1, {<br>          type: &#39;doughnut&#39;,<br>          data: {<br>            labels: [&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;],<br>            datasets: [{<br>              data: [pass, fail, review, pending],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f59e0b&#39;, &#39;#0ea5e9&#39;],<br>              borderWidth: 0<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: &#39;bottom&#39;, labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx2 = document.getElementById(&#39;chart-page-financials&#39;);<br>      if (ctx2) {<br>        chartInstances.fin = new Chart(ctx2, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: proj.mainPages.map(p =&gt; p.name.split(&#39;:&#39;)[0]),<br>            datasets: [<br>              { label: &#39;Expected Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.expectedNet), backgroundColor: &#39;#6366f1&#39;, borderRadius: 6 },<br>              { label: &#39;Actual Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.actualNet), backgroundColor: &#39;#10b981&#39;, borderRadius: 6 }<br>            ]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39; } } }, plugins: { legend: { labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx3 = document.getElementById(&#39;chart-qa-health&#39;);<br>      if (ctx3) {<br>        const tcPass = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>        const tcFail = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>        const defOpen = (proj.defects || []).filter(d =&gt; d.status === &#39;Open&#39;).length;<br>        const defClosed = (proj.defects || []).filter(d =&gt; d.status === &#39;Closed&#39;).length;<br>        chartInstances.qa = new Chart(ctx3, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: [&#39;TC Pass&#39;, &#39;TC Fail&#39;, &#39;Open Defects&#39;, &#39;Closed Defects&#39;],<br>            datasets: [{<br>              label: &#39;Count&#39;,<br>              data: [tcPass, tcFail, defOpen, defClosed],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f97316&#39;, &#39;#64748b&#39;],<br>              borderRadius: 6<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39;, stepSize: 1 } } } }<br>        });<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2 VIEW: PROJECT MANAGEMENT<br>     ****************************************************************************/<br>    let projectSearchQuery = &#39;&#39;;<br><br>    function renderProjectsModule() {<br>      const filtered = appState.projects.filter(p =&gt;<br>        p.name.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.reference.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.owner.toLowerCase().includes(projectSearchQuery.toLowerCase())<br>      );<br><br>      return `<br>        &lt;div class=&quot;flex flex-col sm:flex-row sm:items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;relative flex-1 max-w-md&quot;&gt;<br>            &lt;i data-lucide=&quot;search&quot; class=&quot;w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(projectSearchQuery)}&quot; oninput=&quot;projectSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search projects by name, reference, or owner...&quot; class=&quot;w-full pl-10 pr-4 py-2.5 rounded-xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-xl text-xs font-semibold bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Import Project JSON&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.json&quot; onchange=&quot;importProjectJson(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;openCreateProjectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Project&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5&quot;&gt;<br>          ${filtered.map(proj =&gt; {<br>            const isActive = proj.id === appState.activeProjectId;<br>            return `<br>              &lt;div class=&quot;bg-white dark:bg-slate-900 border ${isActive ? &#39;border-brand-500 ring-2 ring-brand-500/20&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 flex flex-col justify-between gap-4&quot;&gt;<br>                &lt;div class=&quot;space-y-2.5&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] px-2.5 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>                    &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                      ${isActive ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-brand-500/15 text-brand-500&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      ${proj.archived ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/15 text-amber-500&quot;&gt;ARCHIVED&lt;/span&gt;&#39; : &#39;&#39;}<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;h3 class=&quot;font-bold text-base leading-snug&quot;&gt;${escapeHtml(proj.name)}&lt;/h3&gt;<br>                  &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400 line-clamp-2&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>                  &lt;div class=&quot;grid grid-cols-3 gap-2 pt-2 text-center&quot;&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${proj.mainPages.length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Main Pages&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.testCases || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Test Cases&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.defects || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Defects&lt;/div&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;text-[11px] text-slate-400 pt-1&quot;&gt;<br>                    Owner: &lt;span class=&quot;text-slate-600 dark:text-slate-300 font-medium&quot;&gt;${escapeHtml(proj.owner)}&lt;/span&gt; • Updated ${new Date(proj.lastModified).toLocaleDateString()}<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;pt-3 border-t border-slate-100 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;button onclick=&quot;switchActiveProject(&#39;${proj.id}&#39;); navigateTo(&#39;dashboard&#39;);&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                    Open Workspace<br>                  &lt;/button&gt;<br>                  &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                    &lt;button onclick=&quot;openRenameProjectModal(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Rename Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;pencil&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;duplicateProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Duplicate Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;exportProjectJson(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Export Project JSON&quot;&gt;<br>                      &lt;i data-lucide=&quot;download&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;toggleArchiveProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Archive / Unarchive&quot;&gt;<br>                      &lt;i data-lucide=&quot;archive&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;confirmDeleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-rose-500/10 text-rose-500&quot; title=&quot;Delete Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openCreateProjectModal() {<br>      openModal({<br>        title: &#39;Create New EIS &amp; QA Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name *&lt;/label&gt;<br>              &lt;input id=&quot;new-proj-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Phase 2 — Regional Port Audit&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Reference&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-ref&quot; type=&quot;text&quot; value=&quot;PRJ-EIS-${Math.floor(1000 + Math.random() * 9000)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Owner / QA Lead&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-owner&quot; type=&quot;text&quot; value=&quot;QA Analyst&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Fee Template (Optional)&lt;/label&gt;<br>              &lt;select id=&quot;new-proj-template&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;&quot;&gt;Blank Main Page (No pre-configured fees)&lt;/option&gt;<br>                ${appState.templates.map(t =&gt; `&lt;option value=&quot;${t.id}&quot;&gt;${escapeHtml(t.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;new-proj-desc&quot; rows=&quot;2&quot; placeholder=&quot;Scope of receipt validation and QA evidence...&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;createNewProjectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;Create Project&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function createNewProjectFromModal() {<br>      const name = document.getElementById(&#39;new-proj-name&#39;).value.trim();<br>      if (!name) return showToast(&#39;Project name is required.&#39;, &#39;warning&#39;);<br>      const ref = document.getElementById(&#39;new-proj-ref&#39;).value.trim() || `PRJ-${Date.now()}`;<br>      const owner = document.getElementById(&#39;new-proj-owner&#39;).value.trim() || &#39;QA Tester&#39;;<br>      const desc = document.getElementById(&#39;new-proj-desc&#39;).value.trim();<br>      const tplId = document.getElementById(&#39;new-proj-template&#39;).value;<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br><br>      const now = new Date().toISOString();<br>      const firstPage = {<br>        id: &#39;mp_&#39; + Date.now(),<br>        name: &#39;MP-01: Primary Receipt Page&#39;,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: tpl ? tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;&#39;<br>        })) : [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(firstPage);<br><br>      const proj = {<br>        id: &#39;proj_&#39; + Date.now(),<br>        name,<br>        reference: ref,<br>        description: desc || &#39;EIS Receipt Validation &amp; QA Evidence Workspace&#39;,<br>        owner,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [firstPage],<br>        screenshots: [],<br>        mergeHistory: [],<br>        testCases: [],<br>        defects: [],<br>        activityLog: [{ timestamp: now, action: &#39;Project Created&#39;, detail: `Created ${name}` }]<br>      };<br><br>      appState.projects.unshift(proj);<br>      appState.activeProjectId = proj.id;<br>      appState.activeMainPageId = firstPage.id;<br>      closeModal();<br>      scheduleAutosave(&#39;Created project&#39;);<br>      showToast(`Created project &quot;${name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function openRenameProjectModal(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      openModal({<br>        title: &#39;Rename Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name&lt;/label&gt;<br>              &lt;input id=&quot;rename-proj-input&quot; type=&quot;text&quot; value=&quot;${escapeHtml(proj.name)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;rename-proj-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;${escapeHtml(proj.description)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveProjectRename(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Changes&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveProjectRename(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      const val = document.getElementById(&#39;rename-proj-input&#39;).value.trim();<br>      if (!val) return showToast(&#39;Project name cannot be empty.&#39;, &#39;warning&#39;);<br>      proj.name = val;<br>      proj.description = document.getElementById(&#39;rename-proj-desc&#39;).value.trim();<br>      closeModal();<br>      scheduleAutosave(&#39;Renamed project&#39;);<br>      showToast(&#39;Project updated.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateProject(projId) {<br>      const orig = appState.projects.find(p =&gt; p.id === projId);<br>      if (!orig) return;<br>      const copy = JSON.parse(JSON.stringify(orig));<br>      copy.id = &#39;proj_&#39; + Date.now();<br>      copy.name = orig.name + &#39; (Copy)&#39;;<br>      copy.reference = orig.reference + &#39;-COPY&#39;;<br>      copy.createdAt = new Date().toISOString();<br>      copy.lastModified = copy.createdAt;<br>      appState.projects.unshift(copy);<br>      scheduleAutosave(&#39;Duplicated project&#39;);<br>      showToast(`Duplicated &quot;${orig.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function toggleArchiveProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      proj.archived = !proj.archived;<br>      proj.status = proj.archived ? &#39;Archived&#39; : &#39;Active&#39;;<br>      scheduleAutosave(&#39;Toggled archive&#39;);<br>      showToast(proj.archived ? &#39;Project archived.&#39; : &#39;Project restored.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function confirmDeleteProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      if (appState.projects.length &lt;= 1) {<br>        return showToast(&#39;Cannot delete the only remaining project.&#39;, &#39;warning&#39;);<br>      }<br>      openModal({<br>        title: &#39;Confirm Project Deletion&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to permanently delete &lt;strong&gt;${escapeHtml(proj.name)}&lt;/strong&gt; (${proj.mainPages.length} Main Pages, receipts, and QA evidence)? This action cannot be undone unless you have exported a JSON backup.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;deleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete Permanently&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function deleteProject(projId) {<br>      appState.projects = appState.projects.filter(p =&gt; p.id !== projId);<br>      if (appState.activeProjectId === projId) {<br>        appState.activeProjectId = appState.projects[0].id;<br>        appState.activeMainPageId = appState.projects[0].mainPages[0]?.id || null;<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted project&#39;);<br>      showToast(&#39;Project deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportProjectJson(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId) || getActiveProject();<br>      if (!proj) return;<br>      const exportObj = {<br>        SMARTExportVersion: APP_SCHEMA_VERSION,<br>        exportedAt: new Date().toISOString(),<br>        project: proj<br>      };<br>      const blob = new Blob([JSON.stringify(exportObj, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `${proj.reference || &#39;SMART_project&#39;}_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full project JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function importProjectJson(event) {<br>      const file = event.target.files[0];<br>      if (!file) return;<br>      const reader = new FileReader();<br>      reader.onload = (e) =&gt; {<br>        try {<br>          const parsed = JSON.parse(e.target.result);<br>          const importedProj = parsed.project || parsed;<br>          if (!importedProj || !importedProj.name || !Array.isArray(importedProj.mainPages)) {<br>            throw new Error(&#39;Invalid SMART project JSON schema.&#39;);<br>          }<br>          importedProj.id = &#39;proj_&#39; + Date.now();<br>          importedProj.lastModified = new Date().toISOString();<br>          importedProj.mainPages.forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>            ValidationEngine.validateMainPage(mp);<br>          });<br>          appState.projects.unshift(importedProj);<br>          appState.activeProjectId = importedProj.id;<br>          appState.activeMainPageId = importedProj.mainPages[0]?.id || null;<br>          scheduleAutosave(&#39;Imported project JSON&#39;);<br>          showToast(`Imported &quot;${importedProj.name}&quot; successfully!`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;Import failed: &#39; + err.message, &#39;error&#39;);<br>        }<br>      };<br>      reader.readAsText(file);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 3 VIEW: MAIN PAGE MANAGEMENT (1-50+ Fields, Per-Page Dynamic Row &amp; Fees)<br>     ****************************************************************************/<br>    let fieldSearchQuery = &#39;&#39;;<br>    let showAll50Fields = false;<br>    let mainPageQuickListSearch = &#39;&#39;;<br><br>    function renderMainPagesModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page found.&lt;/div&gt;`;<br><br>      const fin = page.validationSummary ? page.validationSummary.financials : FinancialCalculator.calculateTotals(page.fees);<br>      const visibleFields = page.fields.filter(f =&gt; {<br>        if (!showAll50Fields &amp;&amp; !f.enabled &amp;&amp; f.number &gt; 10) return false;<br>        if (!fieldSearchQuery) return true;<br>        const q = fieldSearchQuery.toLowerCase();<br>        return String(f.number).includes(q) || f.name.toLowerCase().includes(q) || String(f.expectedValue).toLowerCase().includes(q) || String(f.actualValue).toLowerCase().includes(q);<br>      });<br><br>      const isRowPasteEnabled = page.rowPasteEnabled !== false;<br>      const pageRowInput = page.rowPasteInput || &#39;&#39;;<br>      const pageRowHasHeaders = Boolean(page.rowPasteHasHeaders);<br>      const parsedPreview = RowToFieldsEngine.parseSpreadsheetRow(pageRowInput, pageRowHasHeaders);<br><br>      return `<br>        &lt;!-- Main Page Selector Tabs --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2 overflow-x-auto pb-1 max-w-full&quot;&gt;<br>              ${proj.mainPages.map(mp =&gt; {<br>                const active = mp.id === page.id;<br>                const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>                return `<br>                  &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold border transition flex items-center gap-2 shrink-0 ${<br>                    active<br>                      ? &#39;bg-brand-600 text-white border-brand-600 shadow-sm&#39;<br>                      : &#39;bg-slate-50 dark:bg-slate-800/70 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>                  }&quot;&gt;<br>                    &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                    &lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold ${active ? &#39;bg-white/20 text-white&#39; : &#39;bg-slate-200 dark:bg-slate-700&#39;}&quot;&gt;${st}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center gap-2 shrink-0&quot;&gt;<br>              &lt;button onclick=&quot;addNewMainPage()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;New Main Page&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;toggleMainPageQuickList()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition ${<br>                appState.ui.mainPageQuickListOpen<br>                  ? &#39;bg-indigo-600 text-white border-indigo-600 shadow-sm&#39;<br>                  : &#39;bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>              }&quot; title=&quot;View all Main Page tabs in a quick list with Select All &amp; Delete All&quot;&gt;<br>                &lt;i data-lucide=&quot;list-checks&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick List (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;duplicateActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Duplicate Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>              ${proj.mainPages.length &gt; 1 ? `<br>                &lt;button onclick=&quot;deleteActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-rose-500/30 text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete Main Page&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${appState.ui.mainPageQuickListOpen ? renderMainPageQuickListPanel(proj, page) : &#39;&#39;}<br><br>          &lt;!-- Isolated Main Page Metadata --&gt;<br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-3 gap-3 pt-2 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Main Page Name (Isolated Record)&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.name)}&quot; onchange=&quot;updateMainPageMeta(&#39;name&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;md:col-span-2&quot;&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Page Scenario Description&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.description)}&quot; onchange=&quot;updateMainPageMeta(&#39;description&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- 1-Row Spreadsheet-to-Columns Expected Output Paste Studio (Per-Page Dynamic Config) --&gt;<br>        &lt;div class=&quot;bg-gradient-to-br from-brand-500/5 via-white to-indigo-500/5 dark:from-brand-950/30 dark:via-slate-900 dark:to-indigo-950/20 border ${isRowPasteEnabled ? &#39;border-brand-500/30&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 space-y-4 shadow-sm transition&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-start justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap mb-1&quot;&gt;<br>                &lt;span class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-brand-600/15 text-brand-600 dark:text-brand-400&quot;&gt;<br>                  &lt;i data-lucide=&quot;table-2&quot; class=&quot;w-3 h-3&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;Per-Page Dynamic Row Mapper • ${escapeHtml(page.name)}&lt;/span&gt;<br>                &lt;/span&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[11px] font-semibold border cursor-pointer ${isRowPasteEnabled ? &#39;bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${isRowPasteEnabled ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteConfig(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;${isRowPasteEnabled ? &#39;Enabled for this page&#39; : &#39;Not Applicable for this page&#39;}&lt;/span&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Paste Expected Receipt Row (Excel / Sheets / CSV / Pipe)&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;${isRowPasteEnabled<br>                ? &#39;Independent dynamic configuration for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Custom column names are preserved by default; header-based renaming is opt-in.&#39;<br>                : &#39;Row-paste mapping is marked &lt;strong&gt;Not Applicable&lt;/strong&gt; for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Toggle above if this page uses spreadsheet row expectations.&#39;}&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            ${isRowPasteEnabled ? `<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap&quot;&gt;<br>                &lt;button onclick=&quot;saveFieldSchemaAsTemplate()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:border-brand-500/50&quot;&gt;<br>                  Save Column Names as Template<br>                &lt;/button&gt;<br>                &lt;button onclick=&quot;clearExpectedRowValues()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold text-rose-600 dark:text-rose-400 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;<br>                  Clear This Page&#39;s Row<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          ${isRowPasteEnabled ? `<br>            &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-4&quot;&gt;<br>              &lt;div class=&quot;lg:col-span-6 space-y-2.5&quot;&gt;<br>                &lt;textarea id=&quot;row-to-fields-textarea&quot; rows=&quot;3&quot; oninput=&quot;updatePageRowPasteInput(this.value)&quot; placeholder=&quot;Paste 1 dynamic row for ${escapeHtml(page.name)} (Tab-separated, CSV, or Pipe):&amp;#10;INV-2026-88410 2026-11-15 004-892-110-000 APEX GLOBAL PHP 1250.00 50.00 1200.00&quot; class=&quot;w-full p-3 rounded-xl bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-700 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;${escapeHtml(pageRowInput)}&lt;/textarea&gt;<br><br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${pageRowHasHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;First pasted row contains column headers&lt;/span&gt;<br>                  &lt;/label&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${page.autoRenameFieldsFromHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleAutoRenameFieldsFromHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;Allow pasted headers to rename my fields&lt;/span&gt;<br>                  &lt;/label&gt;<br><br>                  &lt;button onclick=&quot;applyPastedRowToMainPageFields()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>                    &lt;i data-lucide=&quot;arrow-down-to-line&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;span&gt;Apply Dynamic Row to ${escapeHtml(page.name.split(&#39;:&#39;)[0])}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br><br>              &lt;!-- Live Column -&gt; Field Preview --&gt;<br>              &lt;div class=&quot;lg:col-span-6 bg-white/80 dark:bg-slate-950/70 border border-slate-200 dark:border-slate-800 rounded-xl p-3 flex flex-col justify-between&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between mb-2&quot;&gt;<br>                  &lt;span class=&quot;text-[11px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Live Dynamic Mapping Preview (${parsedPreview.values.length} cols • ${parsedPreview.delimiter})&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div id=&quot;row-paste-preview-grid&quot; class=&quot;flex flex-wrap gap-1.5 max-h-28 overflow-y-auto&quot;&gt;<br>                  ${renderRowPastePreviewChips(page, parsedPreview)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          ` : &#39;&#39;}<br>        &lt;/div&gt;<br><br>        &lt;!-- EIS Fee &amp; CWT Configuration Engine --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;EIS Fee &amp; CWT Line-Item Configuration&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Independent Fee Name, Amount &amp; Code per row. CWT deducts absolute magnitude without double-counting in Gross Fees.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;openQuickPasteFeeModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/20&quot;&gt;<br>                &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick Paste Fees&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(false)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add Fee&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30 hover:bg-amber-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;minus-circle&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add CWT&lt;/span&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-10&quot;&gt;#&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Fee Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Amount&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Amt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${page.fees.length === 0 ? `<br>                  &lt;tr&gt;&lt;td colspan=&quot;10&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No fees configured yet. Click &lt;strong&gt;Add Fee&lt;/strong&gt; or &lt;strong&gt;Quick Paste Fees&lt;/strong&gt;.&lt;/td&gt;&lt;/tr&gt;<br>                ` : page.fees.map((fee, idx) =&gt; {<br>                  const isCwt = FinancialCalculator.isCwtEntry(fee);<br>                  const st = fee.lastValidation ? fee.lastValidation.status : &#39;PENDING&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-slate-400&quot;&gt;${idx + 1}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;button onclick=&quot;toggleFeeCwtFlag(&#39;${fee.id}&#39;)&quot; class=&quot;px-2 py-0.5 rounded text-[10px] font-bold border ${isCwt ? &#39;bg-amber-500/15 text-amber-500 border-amber-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-200 dark:border-slate-700&#39;}&quot; title=&quot;Click to toggle Fee vs CWT Deduction&quot;&gt;<br>                          ${isCwt ? &#39;CWT (-)&#39; : &#39;FEE (+)&#39;}<br>                        &lt;/button&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedName&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-medium&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedAmount&#39;, this.value)&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedCode&#39;, this.value)&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; placeholder=&quot;OCR / Receipt&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; placeholder=&quot;0.00&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; placeholder=&quot;Code&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, -1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;&lt;i data-lucide=&quot;arrow-up&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, 1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;&lt;i data-lucide=&quot;arrow-down&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;duplicateFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Duplicate&quot;&gt;&lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;removeFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-rose-500 hover:bg-rose-500/10 rounded&quot; title=&quot;Remove&quot;&gt;&lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Gross Fees (Expected / Actual)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)} / &lt;span class=&quot;text-brand-500&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/span&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Total CWT Deduction (|CWT|)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Total (Gross - CWT)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-emerald-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Variance&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm ${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;} mt-0.5&quot;&gt;${fin.netDifference &gt; 0 ? &#39;+&#39; : &#39;&#39;}${fin.netDifference.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Configurable Columns / Numbered Main Page Fields (1-50+) --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Configurable Column Fields (1–${page.fields.length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Edit professional field names directly. Names are saved per Main Page and stay unchanged when you paste rows unless header-based renaming is enabled above.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fieldSearchQuery)}&quot; oninput=&quot;fieldSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search fields...&quot; class=&quot;px-3 py-1.5 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;button onclick=&quot;showAll50Fields = !showAll50Fields; renderApp();&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;<br>                ${showAll50Fields ? &#39;Show Active / First 10&#39; : `Show All ${page.fields.length} Fields`}<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addMoreNumberedFields(10)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                + Add 10 More Fields<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto max-h-[420px]&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead class=&quot;sticky top-0 bg-white dark:bg-slate-900 z-10&quot;&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-14&quot;&gt;Col #&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Configurable Field / Column Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Req&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${visibleFields.map(f =&gt; {<br>                  const st = f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2 font-mono font-semibold text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.name)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;name&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-semibold&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;select onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;dataType&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700&quot;&gt;<br>                          ${[&#39;Dynamic&#39;, &#39;Text&#39;, &#39;Number&#39;, &#39;Currency&#39;, &#39;Date&#39;, &#39;Percentage&#39;, &#39;Code&#39;, &#39;Reference&#39;, &#39;Boolean&#39;].map(t =&gt; `&lt;option value=&quot;${t}&quot; ${f.dataType === t ? &#39;selected&#39; : &#39;&#39;}&gt;${t}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.expectedValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;expectedValue&#39;, this.value)&quot; placeholder=&quot;Expected&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; placeholder=&quot;Receipt value&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${f.required ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;required&#39;, this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderRowPastePreviewChips(page, parsed) {<br>      if (!parsed.values.length) {<br>        return `&lt;span class=&quot;text-xs text-slate-400 italic&quot;&gt;Paste a row on the left to preview how each column maps into C01, C02, C03...&lt;/span&gt;`;<br>      }<br>      return parsed.values.map((val, idx) =&gt; {<br>        const colNum = idx + 1;<br>        const existingField = page.fields[idx];<br>        const colName = parsed.headers[idx] || (existingField ? existingField.name : `Custom Field ${colNum}`);<br>        return `<br>          &lt;div class=&quot;px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot;&gt;<br>            &lt;div class=&quot;text-[10px] font-bold text-brand-500&quot;&gt;C${String(colNum).padStart(2, &#39;0&#39;)}: ${escapeHtml(colName)}&lt;/div&gt;<br>            &lt;div class=&quot;font-mono font-semibold truncate max-w-[160px]&quot;&gt;${escapeHtml(val || &#39;(blank)&#39;)}&lt;/div&gt;<br>          &lt;/div&gt;<br>        `;<br>      }).join(&#39;&#39;);<br>    }<br><br>    function updateRowPastePreviewOnly() {<br>      const page = getActiveMainPage();<br>      const grid = document.getElementById(&#39;row-paste-preview-grid&#39;);<br>      if (!page || !grid) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      grid.innerHTML = renderRowPastePreviewChips(page, parsed);<br>    }<br><br>    function togglePageRowPasteConfig(enabled) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteEnabled = Boolean(enabled);<br>      scheduleAutosave(`Updated row mapper config on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function updatePageRowPasteInput(val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteInput = val;<br>      updateRowPastePreviewOnly();<br>      scheduleAutosave(`Updated dynamic row input on ${page.name}`);<br>    }<br><br>    function togglePageRowPasteHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteHasHeaders = Boolean(checked);<br>      scheduleAutosave(`Toggled row headers on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function toggleAutoRenameFieldsFromHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.autoRenameFieldsFromHeaders = Boolean(checked);<br>      scheduleAutosave(&#39;Updated column header rename preference on &#39; + page.name);<br>      showToast(checked<br>        ? &#39;Pasted headers can now rename fields on this page.&#39;<br>        : &#39;Custom field names are protected from pasted headers.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyPastedRowToMainPageFields() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      if (!parsed.values.length) {<br>        return showToast(&#39;Paste at least 1 row of values first.&#39;, &#39;warning&#39;);<br>      }<br><br>      while (page.fields.length &lt; parsed.values.length) {<br>        const num = page.fields.length + 1;<br>        page.fields.push({<br>          id: `fld_${num}_${Date.now()}_${num}`,<br>          number: num,<br>          name: `Custom Field ${num}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: true,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${num}`,<br>          pageOverride: true,<br>          enabled: true<br>        });<br>      }<br><br>      parsed.values.forEach((val, idx) =&gt; {<br>        const fld = page.fields[idx];<br>        if (parsed.headers[idx] &amp;&amp; page.autoRenameFieldsFromHeaders === true) {<br>          fld.name = parsed.headers[idx];<br>        }<br>        fld.expectedValue = val;<br>        fld.enabled = true;<br>        fld.pageOverride = true;<br>        if (val !== &#39;&#39;) {<br>          fld.required = true;<br>          fld.dataType = &#39;Dynamic&#39;;<br>        }<br>      });<br><br>      let matchInfo = &#39;&#39;;<br>      if (page.receipt &amp;&amp; page.receipt.ocrRawText) {<br>        const m = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>        matchInfo = ` • Auto-matched ${m.matched}/${m.total} against attached receipt`;<br>      } else {<br>        ValidationEngine.validateMainPage(page);<br>      }<br><br>      logActivity(&#39;Pasted Dynamic Row&#39;, `Applied ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`);<br>      scheduleAutosave(&#39;Applied dynamic expected row&#39;);<br>      showToast(`Mapped ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function clearExpectedRowValues() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fields.forEach(f =&gt; {<br>        f.expectedValue = &#39;&#39;;<br>        f.actualValue = &#39;&#39;;<br>        if (f.number &gt; 10) f.enabled = false;<br>      });<br>      page.rowPasteInput = &#39;&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Cleared expected row values&#39;);<br>      showToast(&#39;Cleared expected &amp; actual field values on &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function saveFieldSchemaAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const activeCols = page.fields.filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10);<br>      openModal({<br>        title: &#39;Save Configurable Column Names as Reusable Template&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Save your current &lt;strong&gt;${activeCols.length} configurable column headers&lt;/strong&gt; (plus any fee rows) so you can apply this exact column layout to future Main Pages with one click.&lt;/p&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Template Name&lt;/label&gt;<br>              &lt;input id=&quot;col-schema-tpl-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Standard 8-Column Export Layout&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmSaveFieldSchemaTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Schema Template&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmSaveFieldSchemaTemplate() {<br>      const page = getActiveMainPage();<br>      const name = document.getElementById(&#39;col-schema-tpl-name&#39;).value.trim();<br>      if (!page || !name) return showToast(&#39;Enter a template name.&#39;, &#39;warning&#39;);<br><br>      const activeCols = page.fields<br>        .filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10)<br>        .map(f =&gt; ({ number: f.number, name: f.name, dataType: f.dataType, required: f.required }));<br><br>      appState.templates.push({<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name,<br>        description: `${activeCols.length} configured columns + ${page.fees.length} fee rows`,<br>        columns: activeCols,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Saved column schema template&#39;);<br>      showToast(`Saved template &quot;${name}&quot;`, &#39;success&#39;);<br>    }<br><br>    function renderMainPageQuickListPanel(proj, activePage) {<br>      const selectedIds = new Set((appState.ui.selectedMainPageIds || []).filter(id =&gt; proj.mainPages.some(mp =&gt; mp.id === id)));<br>      const q = (mainPageQuickListSearch || &#39;&#39;).trim().toLowerCase();<br>      const filteredPages = proj.mainPages.filter(mp =&gt;<br>        !q ||<br>        mp.name.toLowerCase().includes(q) ||<br>        (mp.description || &#39;&#39;).toLowerCase().includes(q)<br>      );<br>      const allFilteredSelected = filteredPages.length &gt; 0 &amp;&amp; filteredPages.every(mp =&gt; selectedIds.has(mp.id));<br><br>      return `<br>        &lt;div class=&quot;rounded-xl border border-indigo-500/30 bg-slate-50/90 dark:bg-slate-950/80 p-3.5 space-y-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>              &lt;span class=&quot;text-xs font-bold text-indigo-600 dark:text-indigo-400 flex items-center gap-1.5&quot;&gt;<br>                &lt;i data-lucide=&quot;layers&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;All Main Page Tabs (${proj.mainPages.length})&lt;/span&gt;<br>              &lt;/span&gt;<br>              &lt;span class=&quot;text-[11px] px-2 py-0.5 rounded-full bg-slate-200 dark:bg-slate-800 font-semibold&quot;&gt;<br>                ${selectedIds.size} selected<br>              &lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;div class=&quot;relative&quot;&gt;<br>                &lt;i data-lucide=&quot;search&quot; class=&quot;w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(mainPageQuickListSearch)}&quot; oninput=&quot;mainPageQuickListSearch = this.value; renderApp();&quot; placeholder=&quot;Filter tabs...&quot; class=&quot;pl-8 pr-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-xs w-44 focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;button onclick=&quot;selectAllMainPagesInQuickList()&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:border-brand-500/50&quot;&gt;<br>                ${allFilteredSelected ? &#39;Deselect All&#39; : &#39;Select All&#39;}<br>              &lt;/button&gt;<br><br>              ${selectedIds.size &gt; 0 ? `<br>                &lt;button onclick=&quot;deleteSelectedMainPages()&quot; class=&quot;inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white shadow-xs&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;${selectedIds.size === proj.mainPages.length ? &#39;Delete All (&#39; + selectedIds.size + &#39;)&#39; : &#39;Delete Selected (&#39; + selectedIds.size + &#39;)&#39;}&lt;/span&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br><br>              &lt;button onclick=&quot;confirmDeleteAllMainPages()&quot; class=&quot;inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-rose-500/40 text-rose-600 dark:text-rose-400 hover:bg-rose-500/10&quot; title=&quot;Delete all tabs and reset to a single clean Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;trash&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Delete All&lt;/span&gt;<br>              &lt;/button&gt;<br><br>              &lt;button onclick=&quot;toggleMainPageQuickList()&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-800&quot; title=&quot;Close Quick List&quot;&gt;<br>                &lt;i data-lucide=&quot;x&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;max-h-60 overflow-y-auto divide-y divide-slate-200/70 dark:divide-slate-800 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900&quot;&gt;<br>            ${filteredPages.length === 0 ? `<br>              &lt;div class=&quot;py-6 text-center text-xs text-slate-400&quot;&gt;No tabs match &quot;${escapeHtml(mainPageQuickListSearch)}&quot;.&lt;/div&gt;<br>            ` : filteredPages.map((mp) =&gt; {<br>              const isCurrent = mp.id === activePage.id;<br>              const isChecked = selectedIds.has(mp.id);<br>              const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>              const realIndex = proj.mainPages.findIndex(item =&gt; item.id === mp.id) + 1;<br>              return `<br>                &lt;div class=&quot;flex items-center justify-between gap-3 px-3 py-2 text-xs transition ${isCurrent ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                  &lt;div class=&quot;flex items-center gap-2.5 min-w-0 flex-1&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleMainPageQuickSelect(&#39;${mp.id}&#39;)&quot; class=&quot;rounded text-brand-600 cursor-pointer shrink-0&quot; /&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] text-slate-400 shrink-0&quot;&gt;#${realIndex}&lt;/span&gt;<br>                    &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;text-left min-w-0 flex-1 group&quot;&gt;<br>                      &lt;div class=&quot;font-semibold truncate group-hover:text-brand-500 transition flex items-center gap-2&quot;&gt;<br>                        &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                        ${isCurrent ? &#39;&lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold bg-brand-600 text-white&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      &lt;/div&gt;<br>                      &lt;div class=&quot;text-[11px] text-slate-400 truncate&quot;&gt;<br>                        ${mp.fees.length} fees • ${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;No receipt&#39;} ${mp.description ? &#39;• &#39; + escapeHtml(mp.description) : &#39;&#39;}<br>                      &lt;/div&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br><br>                  &lt;div class=&quot;flex items-center gap-2 shrink-0&quot;&gt;<br>                    ${statusBadge(st)}<br>                    &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-brand-600 hover:text-white transition&quot;&gt;<br>                      Open<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;deleteSingleMainPageFromList(&#39;${mp.id}&#39;)&quot; class=&quot;p-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete this tab&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            }).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function toggleMainPageQuickList() {<br>      appState.ui.mainPageQuickListOpen = !appState.ui.mainPageQuickListOpen;<br>      renderApp();<br>    }<br><br>    function toggleMainPageQuickSelect(pageId) {<br>      appState.ui.selectedMainPageIds = appState.ui.selectedMainPageIds || [];<br>      const idx = appState.ui.selectedMainPageIds.indexOf(pageId);<br>      if (idx &gt;= 0) appState.ui.selectedMainPageIds.splice(idx, 1);<br>      else appState.ui.selectedMainPageIds.push(pageId);<br>      renderApp();<br>    }<br><br>    function selectAllMainPagesInQuickList() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const q = (mainPageQuickListSearch || &#39;&#39;).trim().toLowerCase();<br>      const targetIds = proj.mainPages<br>        .filter(mp =&gt; !q || mp.name.toLowerCase().includes(q) || (mp.description || &#39;&#39;).toLowerCase().includes(q))<br>        .map(mp =&gt; mp.id);<br><br>      const currentSet = new Set(appState.ui.selectedMainPageIds || []);<br>      const allSelected = targetIds.length &gt; 0 &amp;&amp; targetIds.every(id =&gt; currentSet.has(id));<br>      if (allSelected) {<br>        targetIds.forEach(id =&gt; currentSet.delete(id));<br>      } else {<br>        targetIds.forEach(id =&gt; currentSet.add(id));<br>      }<br>      appState.ui.selectedMainPageIds = Array.from(currentSet);<br>      renderApp();<br>    }<br><br>    function createFreshDefaultMainPage(index = 1) {<br>      const fresh = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + index,<br>        name: `MP-0${index}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(fresh);<br>      return fresh;<br>    }<br><br>    function deleteSingleMainPageFromList(pageId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const target = proj.mainPages.find(mp =&gt; mp.id === pageId);<br>      if (!target) return;<br><br>      if (proj.mainPages.length &lt;= 1) {<br>        openModal({<br>          title: &#39;Reset Last Main Page&#39;,<br>          bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;&lt;strong&gt;${escapeHtml(target.name)}&lt;/strong&gt; is the only remaining tab. Deleting it will replace it with a clean blank &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;. Continue?&lt;/p&gt;`,<br>          footerHtml: `<br>            &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>            &lt;button onclick=&quot;executeBulkDeleteMainPages([&#39;${pageId}&#39;])&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Reset Tab&lt;/button&gt;<br>          `<br>        });<br>        return;<br>      }<br><br>      proj.mainPages = proj.mainPages.filter(mp =&gt; mp.id !== pageId);<br>      appState.ui.selectedMainPageIds = (appState.ui.selectedMainPageIds || []).filter(id =&gt; id !== pageId);<br>      if (appState.activeMainPageId === pageId) {<br>        appState.activeMainPageId = proj.mainPages[0].id;<br>      }<br>      logActivity(&#39;Deleted Main Page&#39;, target.name);<br>      scheduleAutosave(&#39;Deleted Main Page from Quick List&#39;);<br>      showToast(`Deleted &quot;${target.name}&quot;`, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function deleteSelectedMainPages() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const toDelete = (appState.ui.selectedMainPageIds || []).filter(id =&gt; proj.mainPages.some(mp =&gt; mp.id === id));<br>      if (!toDelete.length) return showToast(&#39;Select at least one tab first.&#39;, &#39;warning&#39;);<br><br>      const deletingAll = toDelete.length &gt;= proj.mainPages.length;<br>      openModal({<br>        title: deletingAll ? &#39;Delete All Main Page Tabs&#39; : `Delete ${toDelete.length} Selected Tab(s)`,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;${<br>          deletingAll<br>            ? `Delete all &lt;strong&gt;${proj.mainPages.length}&lt;/strong&gt; Main Page tabs and start fresh with a clean &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;?`<br>            : `Permanently delete &lt;strong&gt;${toDelete.length}&lt;/strong&gt; selected Main Page tab(s) along with their attached receipts and fee rules?`<br>        }&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;executeBulkDeleteMainPages(${escapeHtml(JSON.stringify(toDelete))})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Confirm Delete&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteAllMainPages() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const allIds = proj.mainPages.map(mp =&gt; mp.id);<br>      openModal({<br>        title: &#39;Delete All Main Page Tabs&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to delete all &lt;strong&gt;${allIds.length}&lt;/strong&gt; Main Page tab(s) and reset to a single clean &lt;strong&gt;MP-01: New Receipt Page&lt;/strong&gt;?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;executeBulkDeleteMainPages(${escapeHtml(JSON.stringify(allIds))})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete All Tabs&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function executeBulkDeleteMainPages(idsToDelete) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const removeSet = new Set(idsToDelete || []);<br>      const removedCount = proj.mainPages.filter(mp =&gt; removeSet.has(mp.id)).length;<br>      proj.mainPages = proj.mainPages.filter(mp =&gt; !removeSet.has(mp.id));<br><br>      if (proj.mainPages.length === 0) {<br>        proj.mainPages.push(createFreshDefaultMainPage(1));<br>      }<br><br>      if (!proj.mainPages.some(mp =&gt; mp.id === appState.activeMainPageId)) {<br>        appState.activeMainPageId = proj.mainPages[0].id;<br>      }<br><br>      appState.ui.selectedMainPageIds = [];<br>      closeModal();<br>      logActivity(&#39;Bulk Deleted Main Pages&#39;, `Removed ${removedCount} tab(s)`);<br>      scheduleAutosave(&#39;Bulk deleted Main Pages&#39;);<br>      showToast(`Deleted ${removedCount} Main Page tab(s).`, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function addNewMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const idx = proj.mainPages.length + 1;<br>      const newPage = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + idx,<br>        name: `MP-0${idx}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(newPage);<br>      proj.mainPages.push(newPage);<br>      appState.activeMainPageId = newPage.id;<br>      logActivity(&#39;Added Main Page&#39;, newPage.name);<br>      scheduleAutosave(&#39;Added Main Page&#39;);<br>      showToast(`Created ${newPage.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      const copy = JSON.parse(JSON.stringify(page));<br>      copy.id = &#39;mp_&#39; + Date.now();<br>      copy.name = page.name + &#39; (Copy)&#39;;<br>      proj.mainPages.push(copy);<br>      appState.activeMainPageId = copy.id;<br>      scheduleAutosave(&#39;Duplicated Main Page&#39;);<br>      showToast(`Duplicated &quot;${page.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function deleteActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page || proj.mainPages.length &lt;= 1) return;<br>      openModal({<br>        title: &#39;Delete Main Page&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Delete &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; and its attached receipt &amp; fee rules?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmDeleteMainPage(&#39;${page.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Delete Page&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteMainPage(pageId) {<br>      const proj = getActiveProject();<br>      proj.mainPages = proj.mainPages.filter(p =&gt; p.id !== pageId);<br>      appState.activeMainPageId = proj.mainPages[0].id;<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted Main Page&#39;);<br>      showToast(&#39;Main Page deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function updateMainPageMeta(key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page[key] = val;<br>      scheduleAutosave(&#39;Updated Main Page metadata&#39;);<br>      renderApp();<br>    }<br><br>    function addFeeRow(isCwt = false) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const idx = page.fees.length + 1;<br>      page.fees.push({<br>        id: &#39;fee_&#39; + Date.now() + &#39;_&#39; + idx,<br>        expectedName: isCwt ? &#39;CWT&#39; : `Fee ${idx} Charge`,<br>        expectedAmount: isCwt ? &#39;50&#39; : &#39;100&#39;,<br>        expectedCode: isCwt ? &#39;CWT&#39; : &#39;NC&#39;,<br>        actualName: &#39;&#39;,<br>        actualAmount: &#39;&#39;,<br>        actualCode: &#39;&#39;,<br>        isCwt,<br>        ocrConfidence: null,<br>        sourceLocation: &#39;&#39;<br>      });<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Added fee row&#39;);<br>      renderApp();<br>    }<br><br>    function updateFeeField(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const fee = page.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee[key] = val;<br>      if (key === &#39;expectedCode&#39; &amp;&amp; val.trim().toUpperCase() === &#39;CWT&#39;) fee.isCwt = true;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated fee&#39;);<br>      renderApp();<br>    }<br><br>    function toggleFeeCwtFlag(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee.isCwt = !FinancialCalculator.isCwtEntry(fee);<br>      if (fee.isCwt &amp;&amp; !fee.expectedCode) fee.expectedCode = &#39;CWT&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Toggled CWT flag&#39;);<br>      renderApp();<br>    }<br><br>    function moveFeeRow(idx, dir) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const target = idx + dir;<br>      if (target &lt; 0 || target &gt;= page.fees.length) return;<br>      const temp = page.fees[idx];<br>      page.fees[idx] = page.fees[target];<br>      page.fees[target] = temp;<br>      scheduleAutosave(&#39;Reordered fees&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const copy = JSON.parse(JSON.stringify(fee));<br>      copy.id = &#39;fee_&#39; + Date.now();<br>      page.fees.push(copy);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Duplicated fee&#39;);<br>      renderApp();<br>    }<br><br>    function removeFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fees = page.fees.filter(f =&gt; f.id !== feeId);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Removed fee&#39;);<br>      renderApp();<br>    }<br><br>    function openQuickPasteFeeModal() {<br>      openModal({<br>        title: &#39;Quick Paste EIS Fees &amp; CWT&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Paste multi-line blocks (Name / Amount / Code) or pipe-delimited rows. CWT entries are automatically recognized.&lt;/p&gt;<br>            &lt;textarea id=&quot;quick-paste-fee-input&quot; rows=&quot;9&quot; placeholder=&quot;Fee 1 Charge&amp;#10;1000&amp;#10;NC&amp;#10;Fee 2 Charge&amp;#10;250&amp;#10;IC&amp;#10;CWT&amp;#10;50&quot; class=&quot;w-full p-3 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;div class=&quot;flex items-center gap-4 text-xs&quot;&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;expected&quot; checked /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Expected&lt;/strong&gt; Main Page Fees&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;actual&quot; /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Actual / Receipt&lt;/strong&gt; Values&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;applyQuickPasteFees()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Parse &amp; Apply Fees&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function applyQuickPasteFees() {<br>      const page = getActiveMainPage();<br>      const raw = document.getElementById(&#39;quick-paste-fee-input&#39;).value;<br>      const target = document.querySelector(&#39;input[name=&quot;qp-target&quot;]:checked&#39;)?.value || &#39;expected&#39;;<br>      const parsed = OcrMappingEngine.parseQuickPasteFees(raw);<br>      if (!parsed.length) return showToast(&#39;No valid fee rows detected.&#39;, &#39;warning&#39;);<br><br>      if (target === &#39;expected&#39;) {<br>        parsed.forEach((p, idx) =&gt; {<br>          page.fees.push({<br>            id: `fee_qp_${Date.now()}_${idx}`,<br>            expectedName: p.name,<br>            expectedAmount: p.amount,<br>            expectedCode: p.code,<br>            actualName: &#39;&#39;,<br>            actualAmount: &#39;&#39;,<br>            actualCode: &#39;&#39;,<br>            isCwt: p.isCwt,<br>            ocrConfidence: null,<br>            sourceLocation: &#39;Quick Paste&#39;<br>          });<br>        });<br>      } else {<br>        parsed.forEach((p, idx) =&gt; {<br>          if (page.fees[idx]) {<br>            page.fees[idx].actualName = p.name;<br>            page.fees[idx].actualAmount = p.amount;<br>            page.fees[idx].actualCode = p.code;<br>            page.fees[idx].sourceLocation = &#39;Quick Paste Receipt&#39;;<br>          } else {<br>            page.fees.push({<br>              id: `fee_qp_${Date.now()}_${idx}`,<br>              expectedName: p.name,<br>              expectedAmount: &#39;&#39;,<br>              expectedCode: p.code,<br>              actualName: p.name,<br>              actualAmount: p.amount,<br>              actualCode: p.code,<br>              isCwt: p.isCwt,<br>              ocrConfidence: 100,<br>              sourceLocation: &#39;Quick Paste Receipt&#39;<br>            });<br>          }<br>        });<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      closeModal();<br>      scheduleAutosave(&#39;Quick pasted fees&#39;);<br>      showToast(`Imported ${parsed.length} fee entries.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateNumberedField(fieldId, key, val) {<br>      const page = getActiveMainPage();<br>      const fld = page?.fields.find(f =&gt; f.id === fieldId);<br>      if (!fld) return;<br>      fld[key] = val;<br>      if (key === &#39;expectedValue&#39; || key === &#39;actualValue&#39;) fld.enabled = true;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated numbered field&#39;);<br>      renderApp();<br>    }<br><br>    function addMoreNumberedFields(count = 10) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const start = page.fields.length + 1;<br>      for (let i = start; i &lt; start + count; i++) {<br>        page.fields.push({<br>          id: `fld_${i}_${Date.now()}`,<br>          number: i,<br>          name: `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: false,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: true<br>        });<br>      }<br>      showAll50Fields = true;<br>      scheduleAutosave(&#39;Added numbered fields&#39;);<br>      showToast(`Added ${count} fields (Total: ${page.fields.length}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 4 VIEW: SIDE-BY-SIDE RECEIPT VALIDATION WORKSPACE<br>     ****************************************************************************/<br>    function renderValidationWorkspaceModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      if (!page.validationSummary) ValidationEngine.validateMainPage(page);<br>      const summary = page.validationSummary;<br>      const fin = summary.financials;<br>      const rec = page.receipt;<br>      const currentImg = rec &amp;&amp; rec.pages &amp;&amp; rec.pages[rec.currentPage - 1] ? rec.pages[rec.currentPage - 1] : null;<br>      const selectedRowId = appState.ui.selectedComparisonRowId;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[10px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Active Main Page (Isolated)&lt;/label&gt;<br>              &lt;select onchange=&quot;switchActiveMainPage(this.value)&quot; class=&quot;mt-0.5 text-xs font-bold bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-1.5&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; `&lt;option value=&quot;${mp.id}&quot; ${mp.id === page.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(mp.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;pt-3&quot;&gt;${statusBadge(summary.overallStatus)}&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;${rec ? &#39;Replace Receipt&#39; : &#39;Upload Receipt (PNG/JPG/WEBP/PDF)&#39;}&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.png,.jpg,.jpeg,.webp,.pdf,image/*,application/pdf&quot; onchange=&quot;handleReceiptUpload(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;pasteReceiptFromClipboardButton()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700&quot; title=&quot;Or press Ctrl+V / Cmd+V anywhere on this screen&quot;&gt;<br>              &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Paste Image (Ctrl+V)&lt;/span&gt;<br>            &lt;/button&gt;<br>            ${rec ? `<br>              &lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;scan-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Re-Run OCR &amp; Auto-Match&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;removeReceiptAttachment()&quot; class=&quot;p-2 rounded-xl text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Remove Receipt Attachment&quot;&gt;<br>                &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl flex flex-col overflow-hidden&quot;&gt;<br>            &lt;div class=&quot;px-4 py-3 border-b border-slate-200 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div class=&quot;text-xs font-bold flex items-center gap-2&quot;&gt;<br>                &lt;i data-lucide=&quot;file-check-2&quot; class=&quot;w-4 h-4 text-brand-500&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Original Receipt (${escapeHtml(page.name)})&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(-0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom Out&quot;&gt;&lt;i data-lucide=&quot;zoom-out&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;span class=&quot;text-[11px] font-mono px-1&quot;&gt;${Math.round(appState.ui.viewerZoom * 100)}%&lt;/span&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom In&quot;&gt;&lt;i data-lucide=&quot;zoom-in&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;rotateViewer()&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Rotate 90°&quot;&gt;&lt;i data-lucide=&quot;rotate-cw&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.showOcrBoxes = !appState.ui.showOcrBoxes; renderApp();&quot; class=&quot;px-2 py-1 rounded-lg text-[10px] font-bold border ${appState.ui.showOcrBoxes ? &#39;bg-brand-500/15 text-brand-500 border-brand-500/30&#39; : &#39;border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  OCR Boxes<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div ondragover=&quot;event.preventDefault()&quot; ondrop=&quot;handleReceiptDrop(event)&quot; class=&quot;relative flex-1 min-h-[420px] max-h-[600px] overflow-auto bg-slate-100 dark:bg-slate-950 flex items-center justify-center p-4&quot;&gt;<br>              ${currentImg ? `<br>                &lt;div class=&quot;relative inline-block transition-transform duration-150&quot; style=&quot;transform: scale(${appState.ui.viewerZoom}) rotate(${appState.ui.viewerRotation}deg);&quot;&gt;<br>                  &lt;img src=&quot;${currentImg}&quot; alt=&quot;Original Receipt&quot; class=&quot;max-w-full rounded-lg shadow-lg border border-slate-300 dark:border-slate-700&quot; /&gt;<br>                  ${appState.ui.showOcrBoxes ? (rec.ocrBlocks || []).filter(b =&gt; b.page === rec.currentPage).map(blk =&gt; {<br>                    const isHighlighted = selectedRowId &amp;&amp; blk.mappedToFeeId === selectedRowId;<br>                    return `<br>                      &lt;div onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${blk.mappedToFeeId || &#39;&#39;}&#39;; renderApp();&quot;<br>                           style=&quot;left:${blk.bbox.x}%; top:${blk.bbox.y}%; width:${blk.bbox.w}%; height:${blk.bbox.h}%;&quot;<br>                           title=&quot;${escapeHtml(blk.rawLine)} (${blk.confidence}% conf)&quot;<br>                           class=&quot;absolute cursor-pointer rounded border-2 transition ${<br>                             isHighlighted<br>                               ? &#39;border-rose-500 bg-rose-500/25 ring-2 ring-rose-400&#39;<br>                               : &#39;border-brand-500/70 bg-brand-500/10 hover:bg-brand-500/25&#39;<br>                           }&quot;&gt;<br>                      &lt;/div&gt;<br>                    `;<br>                  }).join(&#39;&#39;) : &#39;&#39;}<br>                &lt;/div&gt;<br>              ` : `<br>                &lt;div class=&quot;text-center max-w-xs space-y-2 p-6 border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-2xl&quot;&gt;<br>                  &lt;i data-lucide=&quot;file-up&quot; class=&quot;w-8 h-8 text-slate-400 mx-auto&quot;&gt;&lt;/i&gt;<br>                  &lt;div class=&quot;text-xs font-bold&quot;&gt;No Receipt Attached to ${escapeHtml(page.name)}&lt;/div&gt;<br>                  &lt;p class=&quot;text-[11px] text-slate-500&quot;&gt;Drag &amp; drop a PNG, JPG, WEBP, or multi-page PDF receipt here, or press &lt;strong&gt;Ctrl+V&lt;/strong&gt; to paste a receipt screenshot.&lt;/p&gt;<br>                &lt;/div&gt;<br>              `}<br>            &lt;/div&gt;<br><br>            ${rec ? `<br>              &lt;div class=&quot;px-4 py-2.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between text-xs bg-slate-50 dark:bg-slate-900&quot;&gt;<br>                &lt;span class=&quot;truncate text-slate-500&quot;&gt;${escapeHtml(rec.fileName)} • Conf: &lt;strong&gt;${rec.ocrConfidence}%&lt;/strong&gt;&lt;/span&gt;<br>                &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(-1)&quot; ${rec.currentPage &lt;= 1 ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;lt;&lt;/button&gt;<br>                  &lt;span class=&quot;font-mono&quot;&gt;Page ${rec.currentPage}/${rec.totalPages}&lt;/span&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(1)&quot; ${rec.currentPage &gt;= rec.totalPages ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;xl:col-span-7 space-y-5&quot;&gt;<br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Side-by-Side EIS Fee &amp; CWT Comparison&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] text-slate-400&quot;&gt;Click any row to highlight OCR location&lt;/span&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                  &lt;thead&gt;<br>                    &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Fee Item&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Receipt Actual (Editable)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-right&quot;&gt;Diff&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                    &lt;/tr&gt;<br>                  &lt;/thead&gt;<br>                  &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                    ${page.fees.map(fee =&gt; {<br>                      const val = fee.lastValidation || ValidationEngine.validateFeeRow(fee);<br>                      const isSel = selectedRowId === fee.id;<br>                      return `<br>                        &lt;tr onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${fee.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer transition ${isSel ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/40&#39;}&quot;&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-semibold&quot;&gt;<br>                            ${escapeHtml(fee.expectedName)}<br>                            ${val.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 py-0.2 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-mono text-[11px]&quot;&gt;<br>                            &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                            &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 space-y-1&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                            &lt;div class=&quot;flex gap-1&quot;&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; class=&quot;w-24 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; class=&quot;w-16 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase text-[11px]&quot; /&gt;<br>                            &lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-right font-mono font-bold ${val.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;<br>                            ${escapeHtml(val.amountComparison.difference)}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;<br>                            ${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(val.status)}&lt;/td&gt;<br>                        &lt;/tr&gt;<br>                        &lt;tr class=&quot;bg-slate-50/60 dark:bg-slate-950/40 text-[11px] text-slate-500&quot;&gt;<br>                          &lt;td colspan=&quot;6&quot; class=&quot;px-3 py-1.5&quot;&gt;<br>                            &lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(val.explanation)}<br>                          &lt;/td&gt;<br>                        &lt;/tr&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/tbody&gt;<br>                &lt;/table&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;!-- Pasted Dynamic Column Fields Verification --&gt;<br>            ${(() =&gt; {<br>              const configuredCols = page.fields.filter(f =&gt; f.expectedValue !== &#39;&#39; || f.actualValue !== &#39;&#39;);<br>              if (!configuredCols.length) return &#39;&#39;;<br>              const matchedCols = configuredCols.filter(f =&gt; f.lastValidation &amp;&amp; f.lastValidation.status === &#39;PASS&#39;).length;<br>              return `<br>                &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>                  &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h3&gt;<br>                      &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Auto-searches uploaded/pasted receipt text for every expected column value.&lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                      &lt;span class=&quot;px-2.5 py-1 rounded-full text-xs font-bold ${matchedCols === configuredCols.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;<br>                        ${matchedCols} / ${configuredCols.length} Expected Columns Matched<br>                      &lt;/span&gt;<br>                      &lt;button onclick=&quot;reMatchExpectedColumnsNow()&quot; class=&quot;px-2.5 py-1 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                        Re-Scan Receipt<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                    &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                      &lt;thead&gt;<br>                        &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Col&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Configurable Field Name&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Expected Row Value&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Found on Receipt (Editable)&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                        &lt;/tr&gt;<br>                      &lt;/thead&gt;<br>                      &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                        ${configuredCols.map(f =&gt; {<br>                          const st = f.lastValidation ? f.lastValidation.status : &#39;PENDING&#39;;<br>                          return `<br>                            &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(f.name)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(f.expectedValue)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;/td&gt;<br>                              &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                            &lt;/tr&gt;<br>                          `;<br>                        }).join(&#39;&#39;)}<br>                      &lt;/tbody&gt;<br>                    &lt;/table&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            })()}<br><br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;CWT &amp; Net Settlement Reconciliation&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] font-mono text-slate-400&quot;&gt;Deterministic Engine&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs&quot;&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Expected Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-indigo-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Actual Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-emerald-500 mt-0.5&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;<br>                Formula: ${escapeHtml(fin.formulaExplanation)}<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function correctReceiptFeeValue(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const oldVal = fee[key];<br>      fee[key] = val;<br>      fee.manuallyVerified = true;<br>      fee.ocrConfidence = 100;<br>      logActivity(&#39;Manual OCR Correction&#39;, `${page.name}: ${fee.expectedName} (${key}: &quot;${oldVal}&quot; → &quot;${val}&quot;)`);<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manual receipt value correction&#39;);<br>      showToast(&#39;Updated receipt value &amp; recalculated validation.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function adjustViewerZoom(delta) {<br>      appState.ui.viewerZoom = Math.min(2.5, Math.max(0.5, Number((appState.ui.viewerZoom + delta).toFixed(2))));<br>      renderApp();<br>    }<br><br>    function rotateViewer() {<br>      appState.ui.viewerRotation = (appState.ui.viewerRotation + 90) % 360;<br>      renderApp();<br>    }<br><br>    function changeReceiptPage(delta) {<br>      const rec = getActiveMainPage()?.receipt;<br>      if (!rec) return;<br>      const next = rec.currentPage + delta;<br>      if (next &gt;= 1 &amp;&amp; next &lt;= rec.totalPages) {<br>        rec.currentPage = next;<br>        renderApp();<br>      }<br>    }<br><br>    function removeReceiptAttachment() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.receipt = null;<br>      scheduleAutosave(&#39;Removed receipt attachment&#39;);<br>      showToast(&#39;Receipt removed from &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function handleReceiptDrop(e) {<br>      e.preventDefault();<br>      const file = e.dataTransfer?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    function handleReceiptUpload(e) {<br>      const file = e.target?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    async function processUploadedReceiptFile(file) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br><br>      const allowed = [&#39;image/png&#39;, &#39;image/jpeg&#39;, &#39;image/webp&#39;, &#39;image/svg+xml&#39;, &#39;application/pdf&#39;];<br>      if (!allowed.includes(file.type) &amp;&amp; !/\.(png|jpg|jpeg|webp|pdf)$/i.test(file.name)) {<br>        return showToast(&#39;Unsupported file type. Upload PNG, JPG, WEBP, or PDF.&#39;, &#39;error&#39;);<br>      }<br><br>      showToast(`Processing &quot;${file.name}&quot; for ${page.name}...`, &#39;info&#39;);<br>      const now = new Date().toISOString();<br><br>      if (file.type === &#39;application/pdf&#39; || /\.pdf$/i.test(file.name)) {<br>        try {<br>          if (!window.pdfjsLib) {<br>            throw new Error(&#39;PDF.js is unavailable in this environment.&#39;);<br>          }<br>          const arrayBuf = await file.arrayBuffer();<br>          const pdf = await pdfjsLib.getDocument({ data: arrayBuf }).promise;<br>          const pageImages = [];<br>          let combinedText = &#39;&#39;;<br><br>          for (let pNum = 1; pNum &lt;= pdf.numPages; pNum++) {<br>            const pdfPage = await pdf.getPage(pNum);<br>            const viewport = pdfPage.getViewport({ scale: 1.5 });<br>            const canvas = document.createElement(&#39;canvas&#39;);<br>            canvas.width = viewport.width;<br>            canvas.height = viewport.height;<br>            const ctx = canvas.getContext(&#39;2d&#39;);<br>            await pdfPage.render({ canvasContext: ctx, viewport }).promise;<br>            pageImages.push(canvas.toDataURL(&#39;image/png&#39;));<br><br>            const txtContent = await pdfPage.getTextContent();<br>            const pageText = txtContent.items.map(it =&gt; it.str).join(&#39; &#39;);<br>            combinedText += pageText + &#39;\n&#39;;<br>          }<br><br>          const blocks = OcrMappingEngine.parseReceiptTextToBlocks(combinedText, 1, 94);<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: &#39;application/pdf&#39;,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: pdf.numPages,<br>            pages: pageImages,<br>            ocrRawText: combinedText.trim(),<br>            ocrConfidence: 94,<br>            ocrBlocks: blocks,<br>            history: [{ action: `Uploaded ${pdf.numPages}-page PDF &amp; Extracted Text`, timestamp: now }]<br>          };<br><br>          const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>          logActivity(&#39;Uploaded PDF Receipt&#39;, `${file.name} (${pdf.numPages} pages) → ${page.name}`);<br>          scheduleAutosave(&#39;Uploaded PDF receipt&#39;);<br>          showToast(`PDF loaded (${pdf.numPages} pages). Auto-mapped ${mapRes.autoAccepted} items.`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;PDF parsing error: &#39; + err.message, &#39;error&#39;);<br>        }<br>      } else {<br>        const reader = new FileReader();<br>        reader.onload = async (ev) =&gt; {<br>          const dataUrl = ev.target.result;<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: file.type,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: 1,<br>            pages: [dataUrl],<br>            ocrRawText: &#39;&#39;,<br>            ocrConfidence: 0,<br>            ocrBlocks: [],<br>            history: [{ action: &#39;Uploaded Image Receipt&#39;, timestamp: now }]<br>          };<br>          scheduleAutosave(&#39;Uploaded receipt image&#39;);<br>          renderApp();<br>          await runOcrOnActiveReceipt();<br>        };<br>        reader.onerror = () =&gt; {<br>          showToast(&#39;Unable to read the selected image file.&#39;, &#39;error&#39;);<br>        };<br>        reader.readAsDataURL(file);<br>      }<br>    }<br><br>    async function runOcrOnActiveReceipt() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Attach a receipt first.&#39;, &#39;warning&#39;);<br><br>      const rec = page.receipt;<br>      const imgUrl = rec.pages[rec.currentPage - 1];<br>      if (!imgUrl) return;<br><br>      showToast(&#39;Running local OCR preprocessing &amp; extraction...&#39;, &#39;info&#39;);<br>      try {<br>        const preprocessed = await OcrMappingEngine.preprocessImageCanvas(imgUrl, { grayscale: true, contrast: true, scale: 1.5 });<br>        const ocrOut = await OcrMappingEngine.runRealTesseractOCR(preprocessed);<br>        rec.ocrRawText = ocrOut.text;<br>        rec.ocrConfidence = ocrOut.confidence;<br>        rec.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(ocrOut.text, rec.currentPage, ocrOut.confidence);<br>        rec.history.unshift({ action: `OCR Re-run (${ocrOut.confidence}% confidence)`, timestamp: new Date().toISOString() });<br><br>        const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>        scheduleAutosave(&#39;Completed OCR extraction&#39;);<br>        showToast(`OCR complete (${ocrOut.confidence}% conf). Auto-mapped: ${mapRes.autoAccepted}, Review: ${mapRes.reviewNeeded}`, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;OCR notice: &#39; + err.message + &#39;. You can also enter/edit extracted text in OCR &amp; Doc Intel.&#39;, &#39;warning&#39;);<br>      }<br>    }<br><br>    function reMatchExpectedColumnsNow() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Upload or paste a receipt first.&#39;, &#39;warning&#39;);<br>      const res = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>      scheduleAutosave(&#39;Re-matched expected columns against receipt&#39;);<br>      showToast(`Matched ${res.matched} of ${res.total} expected columns against receipt.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    async function pasteReceiptFromClipboardButton() {<br>      try {<br>        if (!navigator.clipboard || !navigator.clipboard.read) {<br>          return showToast(&#39;Press Ctrl+V (or Cmd+V) directly on the page to paste your receipt screenshot.&#39;, &#39;info&#39;);<br>        }<br>        const items = await navigator.clipboard.read();<br>        for (const item of items) {<br>          const imgType = item.types.find(t =&gt; t.startsWith(&#39;image/&#39;));<br>          if (imgType) {<br>            const blob = await item.getType(imgType);<br>            const file = new File([blob], `pasted_receipt_${Date.now()}.png`, { type: imgType });<br>            await processUploadedReceiptFile(file);<br>            return;<br>          }<br>        }<br>        showToast(&#39;No image found in clipboard. Copy a receipt screenshot first, then press Ctrl+V.&#39;, &#39;warning&#39;);<br>      } catch (e) {<br>        showToast(&#39;Press Ctrl+V (or Cmd+V) anywhere in Receipt Validation to paste your clipboard image.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 5 VIEW: OCR &amp; DOCUMENT INTELLIGENCE<br>     ****************************************************************************/<br>    function renderOcrIntelligenceModule() {<br>      const page = getActiveMainPage();<br>      const rec = page?.receipt;<br>      if (!page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;OCR Preprocessing &amp; Raw Text Editor&lt;/h3&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Edit or paste raw receipt OCR text for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; to re-parse blocks and test smart field mapping.&lt;/p&gt;<br><br>            &lt;div class=&quot;grid grid-cols-2 gap-2 text-xs&quot;&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Grayscale Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Contrast Enhancement (1.35x)&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;1.5x Resolution Upscale&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;CWT Sign Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Extracted / Manual Receipt Text&lt;/label&gt;<br>              &lt;textarea id=&quot;ocr-manual-raw-text&quot; rows=&quot;10&quot; placeholder=&quot;Fee 1 Charge | 1000.00 | NC&amp;#10;Fee 2 Charge | 250.00 | IC&amp;#10;CWT | -50.00 | CWT&quot; class=&quot;w-full p-3 rounded-xl bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono text-xs&quot;&gt;${escapeHtml(rec ? rec.ocrRawText : &#39;&#39;)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;applyManualOcrTextAndMap()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                Parse Text &amp; Auto-Map to Main Page<br>              &lt;/button&gt;<br>              ${rec ? `&lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Re-Run Image OCR&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Detected Document Structure &amp; Smart Mapping&lt;/h3&gt;<br>              &lt;span class=&quot;text-xs text-slate-400&quot;&gt;Auto-Accept Threshold: ≥${appState.settings.autoAcceptConfidenceThreshold}%&lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>              &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                &lt;thead&gt;<br>                  &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Page&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Detected Label&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Amount&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Code&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Mapped Main Page Fee&lt;/th&gt;<br>                  &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                  ${!rec || !(rec.ocrBlocks || []).length ? `<br>                    &lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No OCR blocks detected yet. Upload a receipt or parse raw text on the left.&lt;/td&gt;&lt;/tr&gt;<br>                  ` : rec.ocrBlocks.map(blk =&gt; `<br>                    &lt;tr&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;P${blk.page}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-medium&quot;&gt;${escapeHtml(blk.detectedName)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;${escapeHtml(blk.detectedAmount || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-indigo-500&quot;&gt;${escapeHtml(blk.detectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center font-mono ${blk.confidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-emerald-500&#39;}&quot;&gt;${blk.confidence}%&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;select onchange=&quot;manuallyMapOcrBlock(&#39;${blk.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                          &lt;option value=&quot;&quot;&gt;-- Unmapped --&lt;/option&gt;<br>                          ${page.fees.map(f =&gt; `&lt;option value=&quot;${f.id}&quot; ${blk.mappedToFeeId === f.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(f.expectedName)} (${escapeHtml(f.expectedCode)})&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `).join(&#39;&#39;)}<br>                &lt;/tbody&gt;<br>              &lt;/table&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function applyManualOcrTextAndMap() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const rawText = document.getElementById(&#39;ocr-manual-raw-text&#39;).value;<br>      const now = new Date().toISOString();<br>      if (!page.receipt) {<br>        page.receipt = {<br>          id: &#39;rec_manual_&#39; + Date.now(),<br>          fileName: &#39;manual_ocr_transcript.txt&#39;,<br>          mimeType: &#39;text/plain&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [],<br>          ocrRawText: rawText,<br>          ocrConfidence: 95,<br>          ocrBlocks: [],<br>          history: []<br>        };<br>      }<br>      page.receipt.ocrRawText = rawText;<br>      page.receipt.ocrConfidence = 95;<br>      page.receipt.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(rawText, page.receipt.currentPage || 1, 95);<br>      page.receipt.history.unshift({ action: &#39;Manual Text Parsed &amp; Mapped&#39;, timestamp: now });<br><br>      const res = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>      scheduleAutosave(&#39;Mapped manual OCR text&#39;);<br>      showToast(`Parsed ${page.receipt.ocrBlocks.length} blocks. Auto-mapped: ${res.autoAccepted}, Review: ${res.reviewNeeded}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function manuallyMapOcrBlock(blockId, feeId) {<br>      const page = getActiveMainPage();<br>      const blk = page?.receipt?.ocrBlocks.find(b =&gt; b.id === blockId);<br>      if (!blk) return;<br>      blk.mappedToFeeId = feeId || null;<br>      if (feeId) {<br>        const fee = page.fees.find(f =&gt; f.id === feeId);<br>        if (fee) {<br>          fee.actualName = blk.detectedName;<br>          fee.actualAmount = blk.detectedAmount;<br>          fee.actualCode = blk.detectedCode || fee.actualCode;<br>          fee.ocrConfidence = blk.confidence;<br>          fee.sourceLocation = `Page ${blk.page} (Manual Map)`;<br>        }<br>      }<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manually mapped OCR block&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 6 VIEW: QA SCREENSHOT STUDIO &amp; EVIDENCE ANNOTATIONS (1-200+)<br>     ****************************************************************************/<br>    let activeStudioScreenshotIdx = 0;<br><br>    function getNextAvailableQaLabel(page) {<br>      const used = new Set((page?.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      const max = appState.settings.qaLabelMax || 200;<br>      for (let i = 1; i &lt;= max; i++) {<br>        if (!used.has(i)) return i;<br>      }<br>      return max + 1;<br>    }<br><br>    function renderScreenshotStudioModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No active project.&lt;/div&gt;`;<br><br>      const screenshots = proj.screenshots || [];<br>      if (activeStudioScreenshotIdx &gt;= screenshots.length) activeStudioScreenshotIdx = Math.max(0, screenshots.length - 1);<br>      const activeShot = screenshots[activeStudioScreenshotIdx] || null;<br>      const nextLabel = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br><br>      const labelOptions = [];<br>      const maxLbl = appState.settings.qaLabelMax || 200;<br>      const usedLabels = new Set((page.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      for (let i = 1; i &lt;= maxLbl; i++) {<br>        labelOptions.push(`&lt;option value=&quot;${i}&quot; ${i === nextLabel ? &#39;selected&#39; : &#39;&#39;}&gt;QA-${i} ${usedLabels.has(i) ? &#39;(Assigned)&#39; : &#39;&#39;}&lt;/option&gt;`);<br>      }<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;image-plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Upload Screenshots&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; multiple onchange=&quot;handleUploadScreenshots(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;captureBrowserScreen()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>              &lt;i data-lucide=&quot;monitor-dot&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Capture Screen (Browser Permission)&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;vertical&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Vertical (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;horizontal&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Horizontal (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;resetMergeHistory()&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Reset Merge History (${(proj.mergeHistory || []).length})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Captures (${screenshots.length})&lt;/h3&gt;<br>              &lt;span class=&quot;text-[10px] text-slate-400&quot;&gt;Check to merge&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${screenshots.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No screenshots yet.&lt;/div&gt;` : screenshots.map((scr, idx) =&gt; {<br>                const isChecked = appState.ui.selectedScreenshotsForMerge.includes(scr.id);<br>                const isActive = idx === activeStudioScreenshotIdx;<br>                return `<br>                  &lt;div onclick=&quot;activeStudioScreenshotIdx = ${idx}; renderApp();&quot; class=&quot;p-2.5 rounded-xl border cursor-pointer transition ${isActive ? &#39;border-brand-500 bg-brand-500/10&#39; : &#39;border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                    &lt;div class=&quot;flex items-center justify-between gap-2 mb-1.5&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                      &lt;label class=&quot;inline-flex items-center gap-1.5 text-[11px] font-semibold truncate&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleScreenshotMergeSelect(&#39;${scr.id}&#39;)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                        &lt;span class=&quot;truncate&quot;&gt;${escapeHtml(scr.name)}&lt;/span&gt;<br>                      &lt;/label&gt;<br>                      &lt;div class=&quot;flex items-center gap-1 shrink-0&quot;&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, -1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;↑&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, 1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;↓&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteScreenshot(&#39;${scr.id}&#39;)&quot; class=&quot;text-rose-500 hover:opacity-80&quot; title=&quot;Delete&quot;&gt;&amp;times;&lt;/button&gt;<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;img src=&quot;${scr.dataUrl}&quot; alt=&quot;${escapeHtml(scr.name)}&quot; class=&quot;w-full h-24 object-cover rounded-lg bg-slate-950&quot; /&gt;<br>                    &lt;div class=&quot;flex items-center justify-between text-[10px] text-slate-400 mt-1&quot;&gt;<br>                      &lt;span&gt;${scr.isMerged ? &#39;Merged Output&#39; : escapeHtml(scr.source)}&lt;/span&gt;<br>                      &lt;a href=&quot;${scr.dataUrl}&quot; download=&quot;${escapeHtml(scr.name)}.png&quot; onclick=&quot;event.stopPropagation()&quot; class=&quot;text-brand-500 hover:underline&quot;&gt;Download&lt;/a&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 pb-2 border-b border-slate-200 dark:border-slate-800&quot;&gt;<br>              &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;rect&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;rect&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Rectangle&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;circle&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;circle&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Circle&lt;/button&gt;<br>                &lt;input type=&quot;color&quot; value=&quot;${appState.ui.annotationColor}&quot; onchange=&quot;appState.ui.annotationColor = this.value&quot; class=&quot;w-8 h-8 rounded cursor-pointer bg-transparent&quot; title=&quot;Annotation Color&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;flex items-center gap-2 text-xs&quot;&gt;<br>                &lt;select onchange=&quot;appState.ui.selectedQaLabel = Number(this.value)&quot; class=&quot;px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot;&gt;<br>                  ${labelOptions.join(&#39;&#39;)}<br>                &lt;/select&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1 cursor-pointer&quot; title=&quot;Auto-increment to next unused QA label&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${appState.settings.qaAutoIncrement ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.qaAutoIncrement = this.checked; scheduleAutosave(&#39;Toggled QA auto-increment&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;Auto-Inc&lt;/span&gt;<br>                &lt;/label&gt;<br>                &lt;button onclick=&quot;increaseQaLabelLimit()&quot; class=&quot;px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[11px]&quot; title=&quot;Increase Max QA Labels&quot;&gt;+50&lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div id=&quot;annotation-stage&quot; class=&quot;relative min-h-[420px] bg-slate-950 rounded-xl overflow-auto flex items-center justify-center p-2 select-none&quot;&gt;<br>              ${activeShot ? `<br>                &lt;div id=&quot;annotation-canvas-wrapper&quot; class=&quot;relative inline-block cursor-crosshair&quot;&gt;<br>                  &lt;img id=&quot;annotation-base-img&quot; src=&quot;${activeShot.dataUrl}&quot; alt=&quot;Evidence Canvas&quot; class=&quot;max-w-full rounded-lg pointer-events-none&quot; /&gt;<br>                  &lt;svg id=&quot;annotation-svg-overlay&quot; class=&quot;absolute inset-0 w-full h-full&quot;&gt;<br>                    ${(page.annotations || []).map(ann =&gt; {<br>                      const isSel = appState.ui.selectedAnnotationId === ann.id;<br>                      const shape = ann.type === &#39;circle&#39;<br>                        ? `&lt;ellipse cx=&quot;${ann.x + ann.w / 2}&quot; cy=&quot;${ann.y + ann.h / 2}&quot; rx=&quot;${Math.abs(ann.w / 2)}&quot; ry=&quot;${Math.abs(ann.h / 2)}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`<br>                        : `&lt;rect x=&quot;${ann.x}&quot; y=&quot;${ann.y}&quot; width=&quot;${ann.w}&quot; height=&quot;${ann.h}&quot; rx=&quot;4&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`;<br>                      return `<br>                        &lt;g onclick=&quot;event.stopPropagation(); appState.ui.selectedAnnotationId = &#39;${ann.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer&quot;&gt;<br>                          ${shape}<br>                          &lt;rect x=&quot;${ann.x}&quot; y=&quot;${Math.max(0, ann.y - 20)}&quot; width=&quot;${Math.max(68, ann.label.length * 7 + 12)}&quot; height=&quot;18&quot; rx=&quot;4&quot; fill=&quot;${ann.color}&quot; /&gt;<br>                          &lt;text x=&quot;${ann.x + 6}&quot; y=&quot;${Math.max(13, ann.y - 7)}&quot; font-family=&quot;sans-serif&quot; font-size=&quot;11&quot; font-weight=&quot;bold&quot; fill=&quot;#ffffff&quot;&gt;${escapeHtml(ann.label)}&lt;/text&gt;<br>                        &lt;/g&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/svg&gt;<br>                &lt;/div&gt;<br>              ` : `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;Upload or capture a screenshot to draw QA annotations.&lt;/div&gt;`}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center justify-between text-[11px] text-slate-400&quot;&gt;<br>              &lt;span&gt;Click &amp; drag on the image to draw a QA annotation for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt;.&lt;/span&gt;<br>              ${activeShot ? `&lt;button onclick=&quot;exportAnnotatedEvidenceImage()&quot; class=&quot;text-brand-500 font-semibold hover:underline&quot;&gt;Export Annotated PNG&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Page Annotations (${(page.annotations || []).length})&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${(page.annotations || []).length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No annotations on this Main Page yet.&lt;/div&gt;` : (page.annotations || []).map(ann =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${appState.ui.selectedAnnotationId === ann.id ? &#39;border-brand-500 bg-brand-500/5&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} space-y-2 text-xs&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                    &lt;span class=&quot;font-bold&quot; style=&quot;color:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/span&gt;<br>                    &lt;button onclick=&quot;deleteAnnotation(&#39;${ann.id}&#39;)&quot; class=&quot;text-rose-500 hover:underline text-[11px]&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                  &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.comment || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;comment&#39;, this.value)&quot; placeholder=&quot;Evidence comment...&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                  &lt;div class=&quot;grid grid-cols-2 gap-1.5&quot;&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.fieldRef || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;fieldRef&#39;, this.value)&quot; placeholder=&quot;Linked Field&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.defectId || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;defectId&#39;, this.value)&quot; placeholder=&quot;Defect ID&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-1 pt-1&quot;&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, -10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;←&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;→&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, -10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↑&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↓&lt;/button&gt;<br>                    &lt;button onclick=&quot;resizeAnnotation(&#39;${ann.id}&#39;, 15, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;+Size&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initAnnotationCanvasEvents() {<br>      const wrapper = document.getElementById(&#39;annotation-canvas-wrapper&#39;);<br>      if (!wrapper) return;<br>      let startX = 0, startY = 0, drawing = false;<br><br>      wrapper.onmousedown = (e) =&gt; {<br>        const rect = wrapper.getBoundingClientRect();<br>        startX = e.clientX - rect.left;<br>        startY = e.clientY - rect.top;<br>        drawing = true;<br>      };<br><br>      wrapper.onmouseup = (e) =&gt; {<br>        if (!drawing) return;<br>        drawing = false;<br>        const rect = wrapper.getBoundingClientRect();<br>        const endX = e.clientX - rect.left;<br>        const endY = e.clientY - rect.top;<br>        const w = Math.abs(endX - startX);<br>        const h = Math.abs(endY - startY);<br>        if (w &lt; 12 || h &lt; 12) return;<br><br>        const page = getActiveMainPage();<br>        if (!page) return;<br>        const qaNum = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br>        if ((page.annotations || []).some(a =&gt; Number(a.qaLabel) === Number(qaNum))) {<br>          return showToast(`QA-${qaNum} is already assigned on ${page.name}. Pick an unused label.`, &#39;warning&#39;);<br>        }<br><br>        page.annotations = page.annotations || [];<br>        const newAnn = {<br>          id: &#39;ann_&#39; + Date.now(),<br>          qaLabel: qaNum,<br>          type: appState.ui.annotationTool,<br>          x: Math.round(Math.min(startX, endX)),<br>          y: Math.round(Math.min(startY, endY)),<br>          w: Math.round(w),<br>          h: Math.round(h),<br>          color: appState.ui.annotationColor,<br>          label: `QA-${qaNum}`,<br>          comment: &#39;&#39;,<br>          fieldRef: &#39;&#39;,<br>          testCaseId: &#39;&#39;,<br>          defectId: &#39;&#39;<br>        };<br>        page.annotations.push(newAnn);<br>        appState.ui.selectedAnnotationId = newAnn.id;<br>        if (appState.settings.qaAutoIncrement) {<br>          appState.ui.selectedQaLabel = getNextAvailableQaLabel(page);<br>        }<br>        scheduleAutosave(&#39;Added evidence annotation&#39;);<br>        renderApp();<br>      };<br>    }<br><br>    function nudgeAnnotation(annId, dx, dy) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.x = Math.max(0, ann.x + dx);<br>      ann.y = Math.max(0, ann.y + dy);<br>      scheduleAutosave(&#39;Moved annotation&#39;);<br>      renderApp();<br>    }<br><br>    function resizeAnnotation(annId, dw, dh) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.w = Math.max(20, ann.w + dw);<br>      ann.h = Math.max(20, ann.h + dh);<br>      scheduleAutosave(&#39;Resized annotation&#39;);<br>      renderApp();<br>    }<br><br>    function updateAnnotationProp(annId, key, val) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann[key] = val;<br>      scheduleAutosave(&#39;Updated annotation metadata&#39;);<br>    }<br><br>    function deleteAnnotation(annId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.annotations = (page.annotations || []).filter(a =&gt; a.id !== annId);<br>      scheduleAutosave(&#39;Deleted annotation&#39;);<br>      renderApp();<br>    }<br><br>    function increaseQaLabelLimit() {<br>      appState.settings.qaLabelMax = (appState.settings.qaLabelMax || 200) + 50;<br>      scheduleAutosave(&#39;Increased QA label count&#39;);<br>      showToast(`QA label pool increased to 1–${appState.settings.qaLabelMax}.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function handleUploadScreenshots(e) {<br>      const proj = getActiveProject();<br>      const files = Array.from(e.target.files || []);<br>      if (!proj || !files.length) return;<br>      files.forEach(file =&gt; {<br>        const reader = new FileReader();<br>        reader.onload = (ev) =&gt; {<br>          proj.screenshots.push({<br>            id: &#39;scr_&#39; + Date.now() + &#39;_&#39; + Math.random().toString(36).slice(2, 5),<br>            name: file.name,<br>            dataUrl: ev.target.result,<br>            capturedAt: new Date().toISOString(),<br>            source: &#39;Uploaded File&#39;,<br>            isMerged: false<br>          });<br>          scheduleAutosave(&#39;Uploaded screenshot&#39;);<br>          renderApp();<br>        };<br>        reader.readAsDataURL(file);<br>      });<br>    }<br><br>    async function captureBrowserScreen() {<br>      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {<br>        return showToast(&#39;Screen capture API is not supported in this browser context.&#39;, &#39;warning&#39;);<br>      }<br>      try {<br>        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br>        const video = document.createElement(&#39;video&#39;);<br>        video.srcObject = stream;<br>        await video.play();<br><br>        const canvas = document.createElement(&#39;canvas&#39;);<br>        canvas.width = video.videoWidth;<br>        canvas.height = video.videoHeight;<br>        canvas.getContext(&#39;2d&#39;).drawImage(video, 0, 0);<br>        stream.getTracks().forEach(t =&gt; t.stop());<br><br>        const proj = getActiveProject();<br>        proj.screenshots.push({<br>          id: &#39;scr_cap_&#39; + Date.now(),<br>          name: `Screen_Capture_${new Date().toISOString().slice(11, 19).replace(/:/g, &#39;-&#39;)}.png`,<br>          dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>          capturedAt: new Date().toISOString(),<br>          source: &#39;Browser Screen Share&#39;,<br>          isMerged: false<br>        });<br>        activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>        scheduleAutosave(&#39;Captured browser screen&#39;);<br>        showToast(&#39;Screen captured and added to QA Studio.&#39;, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;Screen capture cancelled or permission denied.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    function toggleScreenshotMergeSelect(scrId) {<br>      const sel = appState.ui.selectedScreenshotsForMerge;<br>      const idx = sel.indexOf(scrId);<br>      if (idx &gt;= 0) sel.splice(idx, 1);<br>      else sel.push(scrId);<br>      renderApp();<br>    }<br><br>    function moveScreenshot(idx, dir) {<br>      const proj = getActiveProject();<br>      const target = idx + dir;<br>      if (!proj || target &lt; 0 || target &gt;= proj.screenshots.length) return;<br>      const tmp = proj.screenshots[idx];<br>      proj.screenshots[idx] = proj.screenshots[target];<br>      proj.screenshots[target] = tmp;<br>      scheduleAutosave(&#39;Reordered screenshots&#39;);<br>      renderApp();<br>    }<br><br>    function deleteScreenshot(scrId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.screenshots = proj.screenshots.filter(s =&gt; s.id !== scrId);<br>      appState.ui.selectedScreenshotsForMerge = appState.ui.selectedScreenshotsForMerge.filter(id =&gt; id !== scrId);<br>      scheduleAutosave(&#39;Deleted screenshot&#39;);<br>      renderApp();<br>    }<br><br>    async function mergeSelectedScreenshots(direction = &#39;vertical&#39;) {<br>      const proj = getActiveProject();<br>      const ids = appState.ui.selectedScreenshotsForMerge;<br>      if (!proj || ids.length &lt; 2) {<br>        return showToast(&#39;Select at least 2 screenshots using the checkboxes to merge.&#39;, &#39;warning&#39;);<br>      }<br>      const chosen = ids.map(id =&gt; proj.screenshots.find(s =&gt; s.id === id)).filter(Boolean);<br>      const loadedImgs = await Promise.all(chosen.map(s =&gt; new Promise(res =&gt; {<br>        const img = new Image();<br>        img.onload = () =&gt; res(img);<br>        img.src = s.dataUrl;<br>      })));<br><br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      if (direction === &#39;vertical&#39;) {<br>        canvas.width = Math.max(...loadedImgs.map(i =&gt; i.width));<br>        canvas.height = loadedImgs.reduce((sum, i) =&gt; sum + i.height, 0);<br>      } else {<br>        canvas.width = loadedImgs.reduce((sum, i) =&gt; sum + i.width, 0);<br>        canvas.height = Math.max(...loadedImgs.map(i =&gt; i.height));<br>      }<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      let offset = 0;<br>      loadedImgs.forEach(img =&gt; {<br>        if (direction === &#39;vertical&#39;) {<br>          ctx.drawImage(img, 0, offset);<br>          offset += img.height;<br>        } else {<br>          ctx.drawImage(img, offset, 0);<br>          offset += img.width;<br>        }<br>      });<br><br>      const mergedObj = {<br>        id: &#39;scr_merged_&#39; + Date.now(),<br>        name: `Merged_${direction}_${chosen.length}imgs.png`,<br>        dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>        capturedAt: new Date().toISOString(),<br>        source: `Merged (${direction})`,<br>        isMerged: true<br>      };<br>      proj.screenshots.push(mergedObj);<br>      proj.mergeHistory = proj.mergeHistory || [];<br>      proj.mergeHistory.push({ id: mergedObj.id, sourceIds: [...ids], direction, timestamp: mergedObj.capturedAt });<br>      activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>      scheduleAutosave(&#39;Merged screenshots&#39;);<br>      showToast(`Merged ${chosen.length} screenshots (${direction}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function resetMergeHistory() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.mergeHistory = [];<br>      appState.ui.selectedScreenshotsForMerge = [];<br>      scheduleAutosave(&#39;Reset merge history&#39;);<br>      showToast(&#39;Merge selection &amp; history cleared.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportAnnotatedEvidenceImage() {<br>      const img = document.getElementById(&#39;annotation-base-img&#39;);<br>      const page = getActiveMainPage();<br>      if (!img || !page) return;<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      canvas.width = img.naturalWidth || img.width;<br>      canvas.height = img.naturalHeight || img.height;<br>      const scaleX = canvas.width / img.width;<br>      const scaleY = canvas.height / img.height;<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>      (page.annotations || []).forEach(ann =&gt; {<br>        ctx.strokeStyle = ann.color;<br>        ctx.lineWidth = 3 * scaleX;<br>        if (ann.type === &#39;circle&#39;) {<br>          ctx.beginPath();<br>          ctx.ellipse((ann.x + ann.w / 2) * scaleX, (ann.y + ann.h / 2) * scaleY, Math.abs(ann.w / 2) * scaleX, Math.abs(ann.h / 2) * scaleY, 0, 0, Math.PI * 2);<br>          ctx.stroke();<br>        } else {<br>          ctx.strokeRect(ann.x * scaleX, ann.y * scaleY, ann.w * scaleX, ann.h * scaleY);<br>        }<br>        ctx.fillStyle = ann.color;<br>        ctx.fillRect(ann.x * scaleX, Math.max(0, (ann.y - 22) * scaleY), 110 * scaleX, 22 * scaleY);<br>        ctx.fillStyle = &#39;#ffffff&#39;;<br>        ctx.font = `bold ${Math.round(12 * scaleX)}px sans-serif`;<br>        ctx.fillText(ann.label, (ann.x + 6) * scaleX, Math.max(15 * scaleY, (ann.y - 6) * scaleY));<br>      });<br><br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = canvas.toDataURL(&#39;image/png&#39;);<br>      a.download = `${page.name.replace(/[^a-z0-9]/gi, &#39;_&#39;)}_annotated_evidence.png`;<br>      a.click();<br>      showToast(&#39;Exported annotated evidence PNG.&#39;, &#39;success&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 7 VIEW: TEST CASE MANAGEMENT<br>     ****************************************************************************/<br>    let tcSearchQuery = &#39;&#39;;<br>    let tcStatusFilter = &#39;ALL&#39;;<br><br>    function renderTestCasesModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br>      const list = (proj.testCases || []).filter(tc =&gt; {<br>        const matchText = tc.id.toLowerCase().includes(tcSearchQuery.toLowerCase()) || tc.title.toLowerCase().includes(tcSearchQuery.toLowerCase());<br>        const matchStatus = tcStatusFilter === &#39;ALL&#39; || tc.status === tcStatusFilter;<br>        return matchText &amp;&amp; matchStatus;<br>      });<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(tcSearchQuery)}&quot; oninput=&quot;tcSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search test cases...&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;select onchange=&quot;tcStatusFilter = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;ALL&quot; ${tcStatusFilter === &#39;ALL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Statuses&lt;/option&gt;<br>                &lt;option value=&quot;PASS&quot; ${tcStatusFilter === &#39;PASS&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PASS&lt;/option&gt;<br>                &lt;option value=&quot;FAIL&quot; ${tcStatusFilter === &#39;FAIL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;FAIL&lt;/option&gt;<br>                &lt;option value=&quot;PENDING&quot; ${tcStatusFilter === &#39;PENDING&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PENDING&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openTestCaseModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Test Case&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;ID&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Title &amp; Module&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Linked Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Priority&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${list.map(tc =&gt; {<br>                  const mp = proj.mainPages.find(m =&gt; m.id === tc.mainPageId);<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-mono font-bold&quot;&gt;${escapeHtml(tc.id)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 pr-3&quot;&gt;<br>                        &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(tc.title)}&lt;/div&gt;<br>                        &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;${escapeHtml(tc.module)} • Tester: ${escapeHtml(tc.tester)}&lt;/div&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp ? escapeHtml(mp.name) : &#39;-&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 font-medium&quot;&gt;${escapeHtml(tc.priority)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;<br>                        &lt;select onchange=&quot;updateTestCaseStatus(&#39;${tc.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-bold&quot;&gt;<br>                          ${[&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;, &#39;BLOCKED&#39;].map(st =&gt; `&lt;option value=&quot;${st}&quot; ${tc.status === st ? &#39;selected&#39; : &#39;&#39;}&gt;${st}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;openTestCaseModal(&#39;${tc.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 font-semibold mr-1&quot;&gt;Edit&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteTestCase(&#39;${tc.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Delete&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openTestCaseModal(tcId = null) {<br>      const proj = getActiveProject();<br>      const existing = tcId ? proj.testCases.find(t =&gt; t.id === tcId) : null;<br>      const tc = existing || {<br>        id: `TC-${String((proj.testCases?.length || 0) + 1).padStart(3, &#39;0&#39;)}`,<br>        title: &#39;&#39;,<br>        module: &#39;EIS Settlement&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: &#39;&#39;,<br>        expectedResult: &#39;&#39;,<br>        actualResult: &#39;&#39;,<br>        status: &#39;PENDING&#39;,<br>        priority: &#39;High&#39;,<br>        tester: proj.owner || &#39;QA Analyst&#39;,<br>        mainPageId: appState.activeMainPageId || &#39;&#39;<br>      };<br><br>      openModal({<br>        title: existing ? `Edit Test Case (${tc.id})` : &#39;Create Test Case&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Test Case ID&lt;/label&gt;&lt;input id=&quot;tc-id&quot; value=&quot;${escapeHtml(tc.id)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Priority&lt;/label&gt;&lt;select id=&quot;tc-prio&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;${[&#39;Critical&#39;, &#39;High&#39;, &#39;Medium&#39;, &#39;Low&#39;].map(p =&gt; `&lt;option ${tc.priority === p ? &#39;selected&#39; : &#39;&#39;}&gt;${p}&lt;/option&gt;`).join(&#39;&#39;)}&lt;/select&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Title *&lt;/label&gt;&lt;input id=&quot;tc-title&quot; value=&quot;${escapeHtml(tc.title)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Linked Main Page&lt;/label&gt;&lt;select id=&quot;tc-mp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option value=&quot;&quot;&gt;None&lt;/option&gt;${proj.mainPages.map(m =&gt; `&lt;option value=&quot;${m.id}&quot; ${tc.mainPageId === m.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(m.name)}&lt;/option&gt;`).join(&#39;&#39;)}&lt;/select&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Steps&lt;/label&gt;&lt;textarea id=&quot;tc-steps&quot; rows=&quot;3&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot;&gt;${escapeHtml(tc.steps)}&lt;/textarea&gt;&lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Expected Result&lt;/label&gt;&lt;input id=&quot;tc-exp&quot; value=&quot;${escapeHtml(tc.expectedResult)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Actual Result&lt;/label&gt;&lt;input id=&quot;tc-act&quot; value=&quot;${escapeHtml(tc.actualResult)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveTestCaseFromModal(${existing ? `&#39;${existing.id}&#39;` : &#39;null&#39;})&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Test Case&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveTestCaseFromModal(existingId) {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;tc-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Test case title is required.&#39;, &#39;warning&#39;);<br><br>      const record = {<br>        id: document.getElementById(&#39;tc-id&#39;).value.trim() || `TC-${Date.now()}`,<br>        title,<br>        module: &#39;EIS Settlement&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: document.getElementById(&#39;tc-steps&#39;).value,<br>        expectedResult: document.getElementById(&#39;tc-exp&#39;).value,<br>        actualResult: document.getElementById(&#39;tc-act&#39;).value,<br>        status: existingId ? (proj.testCases.find(t =&gt; t.id === existingId)?.status || &#39;PENDING&#39;) : &#39;PENDING&#39;,<br>        priority: document.getElementById(&#39;tc-prio&#39;).value,<br>        tester: proj.owner || &#39;QA Analyst&#39;,<br>        executionDate: new Date().toISOString().slice(0, 10),<br>        mainPageId: document.getElementById(&#39;tc-mp&#39;).value<br>      };<br><br>      if (existingId) {<br>        const idx = proj.testCases.findIndex(t =&gt; t.id === existingId);<br>        if (idx &gt;= 0) proj.testCases[idx] = record;<br>      } else {<br>        proj.testCases.unshift(record);<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Saved test case&#39;);<br>      showToast(&#39;Saved test case.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateTestCaseStatus(tcId, status) {<br>      const proj = getActiveProject();<br>      const tc = proj?.testCases.find(t =&gt; t.id === tcId);<br>      if (!tc) return;<br>      tc.status = status;<br>      scheduleAutosave(&#39;Updated test case status&#39;);<br>      renderApp();<br>    }<br><br>    function deleteTestCase(tcId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.testCases = proj.testCases.filter(t =&gt; t.id !== tcId);<br>      scheduleAutosave(&#39;Deleted test case&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 8 VIEW: DEFECT MANAGEMENT<br>     ****************************************************************************/<br>    function renderDefectsModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;QA Defects &amp; Discrepancies (${(proj.defects || []).length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Log EIS receipt calculation errors, CWT mismatches, or UI/OCR issues and copy formatted bug summaries.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openDefectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;bug&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Log New Defect&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            ${(proj.defects || []).length === 0 ? `&lt;div class=&quot;py-8 text-center text-xs text-slate-400&quot;&gt;No defects logged in this project.&lt;/div&gt;` : (proj.defects || []).map(def =&gt; `<br>              &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 bg-slate-50/60 dark:bg-slate-950/40 space-y-2 text-xs&quot;&gt;<br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono font-bold text-rose-500&quot;&gt;${escapeHtml(def.id)}&lt;/span&gt;<br>                    &lt;span class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(def.title)}&lt;/span&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                    &lt;span class=&quot;px-2 py-0.5 rounded bg-slate-200 dark:bg-slate-800 font-semibold&quot;&gt;${escapeHtml(def.severity)}&lt;/span&gt;<br>                    ${statusBadge(def.status)}<br>                    &lt;button onclick=&quot;copyDefectSummary(&#39;${def.id}&#39;)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 font-semibold hover:bg-brand-500/20&quot;&gt;Copy Summary&lt;/button&gt;<br>                    &lt;button onclick=&quot;deleteDefect(&#39;${def.id}&#39;)&quot; class=&quot;px-2 py-1 rounded-lg text-rose-500 hover:bg-rose-500/10&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(def.description)}&lt;/p&gt;<br>                &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-2 font-mono text-[11px] bg-white dark:bg-slate-900 p-2.5 rounded-xl border border-slate-200 dark:border-slate-800&quot;&gt;<br>                  &lt;div&gt;&lt;span class=&quot;text-slate-400&quot;&gt;Expected:&lt;/span&gt; ${escapeHtml(def.expectedResult)}&lt;/div&gt;<br>                  &lt;div&gt;&lt;span class=&quot;text-slate-400&quot;&gt;Actual:&lt;/span&gt; &lt;span class=&quot;text-rose-500&quot;&gt;${escapeHtml(def.actualResult)}&lt;/span&gt;&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openDefectModal() {<br>      const proj = getActiveProject();<br>      const nextId = `DEF-${101 + (proj.defects?.length || 0)}`;<br>      openModal({<br>        title: &#39;Log New QA Defect&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-3 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Defect ID&lt;/label&gt;&lt;input id=&quot;def-id&quot; value=&quot;${nextId}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Severity&lt;/label&gt;&lt;select id=&quot;def-sev&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option&gt;Critical&lt;/option&gt;&lt;option selected&gt;High&lt;/option&gt;&lt;option&gt;Medium&lt;/option&gt;&lt;option&gt;Low&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Status&lt;/label&gt;&lt;select id=&quot;def-st&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;option selected&gt;Open&lt;/option&gt;&lt;option&gt;In Progress&lt;/option&gt;&lt;option&gt;Fixed&lt;/option&gt;&lt;option&gt;Closed&lt;/option&gt;&lt;/select&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Defect Title *&lt;/label&gt;&lt;input id=&quot;def-title&quot; placeholder=&quot;e.g. CWT deduction not subtracted from Net Total&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Description&lt;/label&gt;&lt;textarea id=&quot;def-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot;&gt;&lt;/textarea&gt;&lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Expected Result&lt;/label&gt;&lt;input id=&quot;def-exp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>              &lt;div&gt;&lt;label class=&quot;font-semibold block mb-1&quot;&gt;Actual Result&lt;/label&gt;&lt;input id=&quot;def-act&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800&quot; /&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveDefectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Save Defect&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveDefectFromModal() {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;def-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Defect title is required.&#39;, &#39;warning&#39;);<br><br>      proj.defects.unshift({<br>        id: document.getElementById(&#39;def-id&#39;).value.trim() || `DEF-${Date.now()}`,<br>        title,<br>        description: document.getElementById(&#39;def-desc&#39;).value.trim(),<br>        severity: document.getElementById(&#39;def-sev&#39;).value,<br>        priority: &#39;P1&#39;,<br>        status: document.getElementById(&#39;def-st&#39;).value,<br>        expectedResult: document.getElementById(&#39;def-exp&#39;).value.trim(),<br>        actualResult: document.getElementById(&#39;def-act&#39;).value.trim(),<br>        mainPageId: appState.activeMainPageId,<br>        dateReported: new Date().toISOString().slice(0, 10)<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Logged defect&#39;);<br>      showToast(&#39;Defect logged.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function copyDefectSummary(defId) {<br>      const def = getActiveProject()?.defects.find(d =&gt; d.id === defId);<br>      if (!def) return;<br>      const text = `[${def.id}] ${def.title} (Severity: ${def.severity}, Status: ${def.status})\nExpected: ${def.expectedResult}\nActual: ${def.actualResult}\nDetails: ${def.description}`;<br>      const ta = document.createElement(&#39;textarea&#39;);<br>      ta.value = text;<br>      document.body.appendChild(ta);<br>      ta.select();<br>      try { document.execCommand(&#39;copy&#39;); showToast(&#39;Copied defect summary to clipboard.&#39;, &#39;success&#39;); }<br>      catch (e) { showToast(&#39;Copy failed.&#39;, &#39;error&#39;); }<br>      ta.remove();<br>    }<br><br>    function deleteDefect(defId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.defects = proj.defects.filter(d =&gt; d.id !== defId);<br>      scheduleAutosave(&#39;Deleted defect&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 9 VIEW: TEMPLATES<br>     ****************************************************************************/<br>    function renderTemplatesModule() {<br>      const page = getActiveMainPage();<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Reusable EIS Fee &amp; Column Templates&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Apply a template to &lt;strong&gt;${escapeHtml(page ? page.name : &#39;Active Main Page&#39;)}&lt;/strong&gt; or save your current fee structure as a template.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;saveCurrentPageFeesAsTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              + Save Current Page Fees as Template<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 gap-4&quot;&gt;<br>            ${appState.templates.map(tpl =&gt; `<br>              &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 space-y-3&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                  &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(tpl.name)}&lt;/h4&gt;<br>                  &lt;button onclick=&quot;applyTemplateToActivePage(&#39;${tpl.id}&#39;)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                    Apply to ${escapeHtml(page ? page.name.split(&#39;:&#39;)[0] : &#39;Page&#39;)}<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(tpl.description)}&lt;/p&gt;<br>                ${tpl.columns &amp;&amp; tpl.columns.length ? `<br>                  &lt;div class=&quot;text-[11px] text-indigo-500 font-medium&quot;&gt;<br>                    Includes ${tpl.columns.length} saved column names: ${tpl.columns.slice(0, 6).map(c =&gt; escapeHtml(c.name)).join(&#39;, &#39;)}${tpl.columns.length &gt; 6 ? &#39;...&#39; : &#39;&#39;}<br>                  &lt;/div&gt;<br>                ` : &#39;&#39;}<br>                &lt;div class=&quot;text-xs font-mono bg-slate-50 dark:bg-slate-800/60 p-2.5 rounded-xl space-y-1&quot;&gt;<br>                  ${(tpl.fees || []).map(f =&gt; `&lt;div&gt;• ${escapeHtml(f.expectedName)} : &lt;strong&gt;${escapeHtml(f.expectedAmount)}&lt;/strong&gt; [${escapeHtml(f.expectedCode || (f.isCwt ? &#39;CWT&#39; : &#39;FEE&#39;))}]&lt;/div&gt;`).join(&#39;&#39;)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function saveCurrentPageFeesAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.fees.length) return showToast(&#39;Add at least one fee row first.&#39;, &#39;warning&#39;);<br>      const tpl = {<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name: `${page.name} Schema`,<br>        description: `Saved from ${page.name} (${page.fees.length} items)`,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      };<br>      appState.templates.push(tpl);<br>      scheduleAutosave(&#39;Saved template&#39;);<br>      showToast(`Saved template &quot;${tpl.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyTemplateToActivePage(tplId) {<br>      const page = getActiveMainPage();<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br>      if (!page || !tpl) return;<br><br>      if (tpl.columns &amp;&amp; tpl.columns.length) {<br>        tpl.columns.forEach((col, idx) =&gt; {<br>          if (page.fields[idx]) {<br>            page.fields[idx].name = col.name;<br>            page.fields[idx].dataType = col.dataType || page.fields[idx].dataType;<br>            page.fields[idx].required = Boolean(col.required);<br>            page.fields[idx].enabled = true;<br>          }<br>        });<br>      }<br><br>      if (tpl.fees &amp;&amp; tpl.fees.length) {<br>        page.fees = tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_tpl_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;Template&#39;<br>        }));<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Applied template&#39;);<br>      showToast(`Applied &quot;${tpl.name}&quot; to ${page.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 10 VIEW: SETTINGS, DIAGNOSTICS &amp; 12-POINT SELF-TEST SUITE<br>     ****************************************************************************/<br>    let diagnosticTestResults = [];<br><br>    function renderSettingsModule() {<br>      const s = appState.settings;<br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4 text-xs&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Validation &amp; OCR Settings&lt;/h3&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;font-semibold block mb-1&quot;&gt;Numeric Tolerance (±)&lt;/label&gt;<br>              &lt;input type=&quot;number&quot; step=&quot;0.01&quot; value=&quot;${s.numericTolerance}&quot; onchange=&quot;appState.settings.numericTolerance = parseFloat(this.value) || 0.01; scheduleAutosave(&#39;Updated tolerance&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;font-semibold block mb-1&quot;&gt;Auto-Accept OCR Confidence Threshold (%)&lt;/label&gt;<br>              &lt;input type=&quot;number&quot; min=&quot;0&quot; max=&quot;100&quot; value=&quot;${s.autoAcceptConfidenceThreshold}&quot; onchange=&quot;appState.settings.autoAcceptConfidenceThreshold = parseInt(this.value, 10) || 88; scheduleAutosave(&#39;Updated OCR threshold&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 font-mono&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;label class=&quot;flex items-center justify-between p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60 cursor-pointer&quot;&gt;<br>              &lt;span class=&quot;font-medium&quot;&gt;Case-Sensitive Fee &amp; Field Names&lt;/span&gt;<br>              &lt;input type=&quot;checkbox&quot; ${s.caseSensitiveNames ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.caseSensitiveNames = this.checked; scheduleAutosave(&#39;Updated case sensitivity&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>            &lt;/label&gt;<br><br>            &lt;label class=&quot;flex items-center justify-between p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60 cursor-pointer&quot;&gt;<br>              &lt;span class=&quot;font-medium&quot;&gt;Normalize Whitespace During Comparison&lt;/span&gt;<br>              &lt;input type=&quot;checkbox&quot; ${s.normalizeWhitespace ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.normalizeWhitespace = this.checked; scheduleAutosave(&#39;Updated whitespace setting&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>            &lt;/label&gt;<br><br>            &lt;div class=&quot;pt-2 border-t border-slate-200 dark:border-slate-800 flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;exportFullWorkspaceBackup()&quot; class=&quot;px-3.5 py-2 rounded-xl font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-slate-200&quot;&gt;Export Full Backup JSON&lt;/button&gt;<br>              &lt;button onclick=&quot;confirmResetSampleData()&quot; class=&quot;px-3.5 py-2 rounded-xl font-semibold text-rose-500 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;Reset to Sample Data&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;12-Point Automated Acceptance &amp; Math Test Suite&lt;/h3&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Verifies CWT math, negative/parenthetical signs, missing-info rules, multi-page isolation, and IndexedDB persistence.&lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;button onclick=&quot;runTwelvePointDiagnostics()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-bold bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm&quot;&gt;<br>                Run All 12 Checks<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;space-y-2 max-h-[460px] overflow-y-auto&quot;&gt;<br>              ${diagnosticTestResults.length === 0 ? `<br>                &lt;div class=&quot;p-8 text-center text-xs text-slate-400 border border-dashed border-slate-200 dark:border-slate-800 rounded-xl&quot;&gt;<br>                  Click &lt;strong&gt;Run All 12 Checks&lt;/strong&gt; to execute automated verification tests on the calculation, validation, and persistence engines.<br>                &lt;/div&gt;<br>              ` : diagnosticTestResults.map((r, i) =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${r.passed ? &#39;border-emerald-500/30 bg-emerald-500/5&#39; : &#39;border-rose-500/30 bg-rose-500/5&#39;} flex items-start justify-between gap-3 text-xs&quot;&gt;<br>                  &lt;div&gt;<br>                    &lt;div class=&quot;font-bold&quot;&gt;#${i + 1}. ${escapeHtml(r.name)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 mt-0.5&quot;&gt;${escapeHtml(r.detail)}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;span class=&quot;px-2 py-0.5 rounded font-bold text-[10px] shrink-0 ${r.passed ? &#39;bg-emerald-500/20 text-emerald-500&#39; : &#39;bg-rose-500/20 text-rose-500&#39;}&quot;&gt;${r.passed ? &#39;PASS&#39; : &#39;FAIL&#39;}&lt;/span&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    async function runTwelvePointDiagnostics() {<br>      const results = [];<br><br>      const t1 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;1000&#39;, actualAmount: &#39;1000&#39;, isCwt: false },<br>        { expectedAmount: &#39;250&#39;, actualAmount: &#39;250&#39;, isCwt: false },<br>        { expectedAmount: &#39;-50&#39;, actualAmount: &#39;-50&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;Fee 1 (1000) + Fee 2 (250) with CWT (-50) = Net 1200&#39;, passed: t1.actualGross === 1250 &amp;&amp; t1.actualCwt === 50 &amp;&amp; t1.actualNet === 1200, detail: `Gross=${t1.actualGross}, CWT=${t1.actualCwt}, Net=${t1.actualNet}` });<br><br>      const t2 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;1000&#39;, actualAmount: &#39;1000&#39;, isCwt: false },<br>        { expectedAmount: &#39;250&#39;, actualAmount: &#39;250&#39;, isCwt: false },<br>        { expectedAmount: &#39;(50)&#39;, actualAmount: &#39;(50)&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;Parenthetical CWT (50) deducted cleanly as 50&#39;, passed: t2.actualCwt === 50 &amp;&amp; t2.actualNet === 1200, detail: `CWT=${t2.actualCwt}, Net=${t2.actualNet}` });<br><br>      const t3 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;1200&#39;, actualCode: &#39;NC&#39;, isCwt: false });<br>      results.push({ name: &#39;Fee 1 Mismatch (1000 vs 1200) flags FAIL with +200.00 diff&#39;, passed: t3.status === &#39;FAIL&#39; &amp;&amp; t3.amountComparison.difference === &#39;200.00&#39;, detail: t3.explanation });<br><br>      const t4 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;&#39;, actualCode: &#39;NC&#39;, isCwt: false });<br>      results.push({ name: &#39;Missing Actual Amount evaluates as PENDING (not false PASS)&#39;, passed: t4.status === &#39;PENDING&#39;, detail: `Status=${t4.status}` });<br><br>      const t5 = ValidationEngine.validateFeeRow({ expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;1000&#39;, actualCode: &#39;&#39;, isCwt: false });<br>      results.push({ name: &#39;Missing Required Fee Code evaluates as PENDING&#39;, passed: t5.status === &#39;PENDING&#39;, detail: `Status=${t5.status}` });<br><br>      const t6 = FinancialCalculator.calculateTotals([<br>        { expectedAmount: &#39;500&#39;, actualAmount: &#39;500&#39;, isCwt: false },<br>        { expectedAmount: &#39;25&#39;, actualAmount: &#39;25&#39;, isCwt: true }<br>      ]);<br>      results.push({ name: &#39;CWT excluded from Gross Fees sum&#39;, passed: t6.actualGross === 500 &amp;&amp; t6.actualNet === 475, detail: `Gross=${t6.actualGross}, Net=${t6.actualNet}` });<br><br>      const qp = OcrMappingEngine.parseQuickPasteFees(&#39;Fee 1\n1000\nNC\nCWT\n50&#39;);<br>      results.push({ name: &#39;Quick Paste parser extracts multi-line fee &amp; CWT blocks&#39;, passed: qp.length === 2 &amp;&amp; qp[1].isCwt === true, detail: `Parsed ${qp.length} items` });<br><br>      const proj = getActiveProject();<br>      results.push({ name: &#39;Multi-Main-Page isolation within active project&#39;, passed: proj &amp;&amp; proj.mainPages.length &gt;= 2 &amp;&amp; proj.mainPages[0].id !== proj.mainPages[1].id, detail: `${proj?.mainPages.length || 0} isolated pages` });<br><br>      const savedOk = await PersistenceEngine.saveState(appState);<br>      const loadedState = await PersistenceEngine.loadState();<br>      results.push({ name: &#39;IndexedDB save &amp; reload persistence round-trip&#39;, passed: Boolean(savedOk &amp;&amp; loadedState &amp;&amp; loadedState.projects.length &gt; 0), detail: `Projects persisted: ${loadedState?.projects?.length || 0}` });<br><br>      results.push({ name: &#39;Configurable numbered fields initialized (1-50+)&#39;, passed: Boolean(proj?.mainPages[0]?.fields?.length &gt;= 50), detail: `Field count: ${proj?.mainPages[0]?.fields?.length || 0}` });<br><br>      results.push({ name: &#39;Dynamic QA label pool supports 1–200+ labels&#39;, passed: (appState.settings.qaLabelMax || 200) &gt;= 200, detail: `Max QA label: ${appState.settings.qaLabelMax}` });<br><br>      results.push({ name: &#39;Report export generator function available&#39;, passed: typeof exportReportFile === &#39;function&#39;, detail: &#39;CSV, HTML, DOC, JSON, TXT &amp; Print ready&#39; });<br><br>      diagnosticTestResults = results;<br>      const passCnt = results.filter(r =&gt; r.passed).length;<br>      showToast(`Diagnostics complete: ${passCnt}/${results.length} passed.`, passCnt === results.length ? &#39;success&#39; : &#39;warning&#39;);<br>      renderApp();<br>    }<br><br>    function exportFullWorkspaceBackup() {<br>      const blob = new Blob([JSON.stringify(appState, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `SMART_full_workspace_backup_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full workspace JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function confirmResetSampleData() {<br>      openModal({<br>        title: &#39;Reset Workspace to Sample Seed Data&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;This will replace current workspace projects with fresh sample EIS &amp; QA seed data. Export a JSON backup first if you wish to keep current edits.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;resetToSampleSeedData()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Reset Sample Data&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    async function resetToSampleSeedData() {<br>      appState = createSampleSeedState();<br>      closeModal();<br>      await PersistenceEngine.saveState(appState);<br>      showToast(&#39;Workspace reset to fresh sample data.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 11 VIEW: REPORTS HUB (ALL RESULTS, PROJECTS &amp; QA REPORTS)<br>     * Includes toggle control for embedding/excluding receipt images in HTML &amp; DOC exports.<br>     ****************************************************************************/<br>    let reportScope = &#39;active_page&#39;; // &#39;active_page&#39; | &#39;all_pages&#39; | &#39;all_projects&#39;<br>    let reportIncludeReceipts = true; // Toggle state for embedding receipt images in HTML &amp; Word (.doc) exports<br><br>    function setReportIncludeReceipts(checked) {<br>      reportIncludeReceipts = Boolean(checked);<br>      scheduleAutosave(&#39;Updated report receipt image export preference&#39;);<br>      renderApp();<br>    }<br><br>    function getReportDataset() {<br>      const activeProj = getActiveProject();<br>      const activePage = getActiveMainPage();<br><br>      if (reportScope === &#39;active_page&#39;) {<br>        return {<br>          title: `Main Page Validation &amp; QA Report — ${activePage?.name || &#39;Page&#39;}`,<br>          projects: activeProj ? [{<br>            ...activeProj,<br>            mainPages: activePage ? [activePage] : []<br>          }] : []<br>        };<br>      }<br>      if (reportScope === &#39;all_pages&#39;) {<br>        return {<br>          title: `Full Project EIS &amp; QA Report — ${activeProj?.name || &#39;Project&#39;}`,<br>          projects: activeProj ? [activeProj] : []<br>        };<br>      }<br>      return {<br>        title: `All Projects Master EIS &amp; QA Audit Report (${appState.projects.length} Projects)`,<br>        projects: appState.projects<br>      };<br>    }<br><br><br>    /****************************************************************************<br>     * REPORT SECTION BUILDERS: Side-by-Side Fee/CWT Comparison &amp;<br>     * Expected Row Columns vs Receipt Verification (used by preview + all exports)<br>     ****************************************************************************/<br>    function getReportRows(mp) {<br>      if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>      const feeRows = (mp.fees || []).map(f =&gt; ({ fee: f, v: f.lastValidation || ValidationEngine.validateFeeRow(f) }));<br>      const colRows = (mp.fields || [])<br>        .filter(f =&gt; (f.expectedValue !== &#39;&#39; &amp;&amp; f.expectedValue != null) || (f.actualValue !== &#39;&#39; &amp;&amp; f.actualValue != null))<br>        .map(f =&gt; ({ field: f, v: f.lastValidation || ValidationEngine.validateField(f) }));<br>      const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees || []);<br>      return { feeRows, colRows, fin };<br>    }<br><br>    function fmtSigned(n) {<br>      return `${n &gt; 0 ? &#39;+&#39; : &#39;&#39;}${Number(n).toFixed(2)}`;<br>    }<br><br>    function renderReportSideBySideApp(mp) {<br>      const { feeRows, fin } = getReportRows(mp);<br>      const threshold = appState.settings.autoAcceptConfidenceThreshold;<br>      return `<br>        &lt;div class=&quot;space-y-2&quot;&gt;<br>          &lt;h5 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Side-by-Side EIS Fee &amp;amp; CWT Comparison&lt;/h5&gt;<br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Fee Item&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Receipt Actual (Name / Amt / Code)&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-right&quot;&gt;Diff&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Conf&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody&gt;<br>                ${feeRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-4 text-center text-slate-400&quot;&gt;No fee rows configured on this Main Page.&lt;/td&gt;&lt;/tr&gt;` : feeRows.map(({ fee, v }) =&gt; `<br>                  &lt;tr class=&quot;border-t border-slate-100 dark:border-slate-800/70&quot;&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-semibold&quot;&gt;${escapeHtml(fee.expectedName)} ${v.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-mono text-[11px]&quot;&gt;<br>                      &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 font-mono text-[11px]&quot;&gt;<br>                      &lt;div&gt;${escapeHtml(fee.actualName || &#39;-&#39;)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.actualAmount || &#39;-&#39;)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.actualCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 text-right font-mono font-bold ${v.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;${escapeHtml(v.amountComparison.difference)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; threshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(v.status)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                  &lt;tr class=&quot;text-[11px] text-slate-500 bg-slate-50/60 dark:bg-slate-950/40&quot;&gt;<br>                    &lt;td colspan=&quot;6&quot; class=&quot;px-2 py-1&quot;&gt;&lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(v.explanation)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-3 gap-2 text-xs pt-1&quot;&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold&quot;&gt;${fin.expectedGross.toFixed(2)} / ${fin.actualGross.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;CWT Deduction (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold text-amber-500&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Net Total (Exp / Receipt)&lt;/div&gt;&lt;div class=&quot;font-mono font-bold text-emerald-500&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)} &lt;span class=&quot;${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;(${fmtSigned(fin.netDifference)})&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;Formula: ${escapeHtml(fin.formulaExplanation)}&lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderReportColumnsApp(mp) {<br>      const { colRows } = getReportRows(mp);<br>      const matched = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>      return `<br>        &lt;div class=&quot;space-y-2&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>            &lt;h5 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h5&gt;<br>            &lt;span class=&quot;px-2.5 py-0.5 rounded-full text-[11px] font-bold ${colRows.length &amp;&amp; matched === colRows.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;${matched} / ${colRows.length} Expected Columns Matched&lt;/span&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Col&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Field Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Expected Row Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-1.5&quot;&gt;Explanation&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${colRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-4 text-center text-slate-400&quot;&gt;No expected row columns pasted or configured for this Main Page.&lt;/td&gt;&lt;/tr&gt;` : colRows.map(({ field, v }) =&gt; `<br>                  &lt;tr&gt;<br>                    &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(field.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(field.name)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(field.expectedValue || &#39;-&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 font-mono&quot;&gt;${escapeHtml(field.actualValue || &#39;-&#39;)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(v.status)}&lt;/td&gt;<br>                    &lt;td class=&quot;py-2 text-[11px] text-slate-500&quot;&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>                  &lt;/tr&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderReportSideBySideStandalone(mp) {<br>      const { feeRows, fin } = getReportRows(mp);<br>      return `<br>        &lt;div class=&quot;section-title&quot;&gt;Side-by-Side EIS Fee &amp;amp; CWT Comparison&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th&gt;#&lt;/th&gt;<br>              &lt;th&gt;Fee Item&lt;/th&gt;<br>              &lt;th&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>              &lt;th&gt;Receipt Actual (Name / Amt / Code)&lt;/th&gt;<br>              &lt;th&gt;Diff&lt;/th&gt;<br>              &lt;th&gt;Conf&lt;/th&gt;<br>              &lt;th&gt;Status&lt;/th&gt;<br>              &lt;th&gt;Rule Evaluation&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            ${feeRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;8&quot; class=&quot;muted&quot;&gt;No fee rows configured on this Main Page.&lt;/td&gt;&lt;/tr&gt;` : feeRows.map(({ fee, v }, i) =&gt; `<br>              &lt;tr&gt;<br>                &lt;td&gt;${i + 1}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.expectedName)}${v.isCwt ? &#39; &lt;span class=&quot;badge REVIEW&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.expectedName)} / ${escapeHtml(fee.expectedAmount)} / ${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(fee.actualName || &#39;-&#39;)} / ${escapeHtml(fee.actualAmount || &#39;-&#39;)} / ${escapeHtml(fee.actualCode || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td class=&quot;num&quot;&gt;${escapeHtml(v.amountComparison.difference)}&lt;/td&gt;<br>                &lt;td class=&quot;num&quot;&gt;${fee.ocrConfidence ? escapeHtml(fee.ocrConfidence) + &#39;%&#39; : &#39;Manual&#39;}&lt;/td&gt;<br>                &lt;td&gt;&lt;span class=&quot;badge ${escapeHtml(v.status)}&quot;&gt;${escapeHtml(v.status)}&lt;/span&gt;&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>              &lt;/tr&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>        &lt;div class=&quot;section-title&quot;&gt;CWT &amp;amp; Net Settlement Reconciliation&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Measure&lt;/th&gt;&lt;th&gt;Expected&lt;/th&gt;&lt;th&gt;Receipt&lt;/th&gt;&lt;th&gt;Variance&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>          &lt;tbody&gt;<br>            &lt;tr&gt;&lt;td&gt;Gross Fees (non-CWT)&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.grossDifference)}&lt;/td&gt;&lt;/tr&gt;<br>            &lt;tr&gt;&lt;td&gt;Total CWT Deduction&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.cwtDifference)}&lt;/td&gt;&lt;/tr&gt;<br>            &lt;tr&gt;&lt;td&gt;&lt;strong&gt;Net Total&lt;/strong&gt;&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;&lt;td class=&quot;num&quot;&gt;${fmtSigned(fin.netDifference)}&lt;/td&gt;&lt;/tr&gt;<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>        &lt;p class=&quot;muted&quot;&gt;Formula: ${escapeHtml(fin.formulaExplanation)}&lt;/p&gt;<br>      `;<br>    }<br><br>    function renderReportColumnsStandalone(mp) {<br>      const { colRows } = getReportRows(mp);<br>      const matched = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>      return `<br>        &lt;div class=&quot;section-title&quot;&gt;Expected Row Columns vs Receipt Verification — ${matched} / ${colRows.length} Expected Columns Matched&lt;/div&gt;<br>        &lt;table&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th&gt;Col&lt;/th&gt;<br>              &lt;th&gt;Field Name&lt;/th&gt;<br>              &lt;th&gt;Expected Row Value&lt;/th&gt;<br>              &lt;th&gt;Found on Receipt&lt;/th&gt;<br>              &lt;th&gt;Status&lt;/th&gt;<br>              &lt;th&gt;Explanation&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            ${colRows.length === 0 ? `&lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;muted&quot;&gt;No expected row columns pasted or configured for this Main Page.&lt;/td&gt;&lt;/tr&gt;` : colRows.map(({ field, v }) =&gt; `<br>              &lt;tr&gt;<br>                &lt;td&gt;C${String(field.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.name)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.expectedValue || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(field.actualValue || &#39;-&#39;)}&lt;/td&gt;<br>                &lt;td&gt;&lt;span class=&quot;badge ${escapeHtml(v.status)}&quot;&gt;${escapeHtml(v.status)}&lt;/span&gt;&lt;/td&gt;<br>                &lt;td&gt;${escapeHtml(v.explanation)}&lt;/td&gt;<br>              &lt;/tr&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>      `;<br>    }<br><br>    function renderReportsModule() {<br>      const dataset = getReportDataset();<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br><br>      let totalPages = 0, totalFees = 0, totalPass = 0, totalFail = 0, totalReview = 0, totalPending = 0;<br>      let totalGross = 0, totalCwt = 0, totalNet = 0;<br><br>      dataset.projects.forEach(p =&gt; {<br>        (p.mainPages || []).forEach(mp =&gt; {<br>          totalPages++;<br>          if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>          const s = mp.validationSummary;<br>          totalFees += (mp.fees || []).length;<br>          totalPass += s.counts.pass;<br>          totalFail += s.counts.fail;<br>          totalReview += s.counts.review;<br>          totalPending += s.counts.pending;<br>          totalGross += s.financials.actualGross;<br>          totalCwt += s.financials.actualCwt;<br>          totalNet += s.financials.actualNet;<br>        });<br>      });<br><br>      const allTestCases = dataset.projects.flatMap(p =&gt; (p.testCases || []).map(tc =&gt; ({ ...tc, projectName: p.name })));<br>      const allDefects = dataset.projects.flatMap(p =&gt; (p.defects || []).map(df =&gt; ({ ...df, projectName: p.name })));<br><br>      return `<br>        &lt;!-- Report Scope &amp; Export Controls --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4 no-print&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Unified EIS &amp; QA Reporting Center&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Export all validation results, CWT calculations, test cases, defects, and project summaries.&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;label class=&quot;text-xs font-semibold text-slate-500&quot;&gt;Report Scope:&lt;/label&gt;<br>              &lt;select onchange=&quot;reportScope = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot;&gt;<br>                &lt;option value=&quot;active_page&quot; ${reportScope === &#39;active_page&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;Active Main Page (${escapeHtml(page?.name || &#39;&#39;)})&lt;/option&gt;<br>                &lt;option value=&quot;all_pages&quot; ${reportScope === &#39;all_pages&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Main Pages in Active Project (${escapeHtml(proj?.name || &#39;&#39;)})&lt;/option&gt;<br>                &lt;option value=&quot;all_projects&quot; ${reportScope === &#39;all_projects&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Projects (${appState.projects.length})&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;!-- Toggle for Including/Excluding Receipt Images in HTML &amp; Word (.doc) Exports --&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-2.5 px-3.5 py-2 rounded-xl bg-slate-50 dark:bg-slate-800/80 border border-slate-200 dark:border-slate-700 cursor-pointer select-none text-xs font-semibold&quot;&gt;<br>              &lt;input id=&quot;toggle-include-receipts&quot; type=&quot;checkbox&quot; ${reportIncludeReceipts ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;setReportIncludeReceipts(this.checked)&quot; class=&quot;rounded text-brand-600 focus:ring-brand-500 cursor-pointer&quot; /&gt;<br>              &lt;span&gt;Include receipt images in HTML &amp;amp; Word (.doc) exports&lt;/span&gt;<br>              &lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold ${reportIncludeReceipts ? &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400&#39; : &#39;bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300&#39;}&quot;&gt;${reportIncludeReceipts ? &#39;INCLUDED&#39; : &#39;EXCLUDED&#39;}&lt;/span&gt;<br>            &lt;/label&gt;<br><br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;csv&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-spreadsheet&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export CSV&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;html&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-code&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export HTML&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;doc&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-600 hover:bg-indigo-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;file-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Export Word (.doc)&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;window.print()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-900 text-white dark:bg-slate-700&quot;&gt;<br>                &lt;i data-lucide=&quot;printer&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Print / Save PDF&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;json&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                JSON<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;exportReportFile(&#39;txt&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                TXT<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Live Printable / Previewable Report Document --&gt;<br>        &lt;div id=&quot;printable-report-area&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-6 space-y-6&quot;&gt;<br>          &lt;div class=&quot;border-b border-slate-200 dark:border-slate-800 pb-4 flex flex-col sm:flex-row sm:items-center justify-between gap-2&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;text-[11px] font-bold uppercase tracking-wider text-brand-500&quot;&gt;SMART EIS &amp; QA VALIDATION STUDIO&lt;/div&gt;<br>              &lt;h2 class=&quot;text-lg font-extrabold mt-0.5&quot;&gt;${escapeHtml(dataset.title)}&lt;/h2&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Generated: ${new Date().toLocaleString()} • Schema v${APP_SCHEMA_VERSION}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;text-xs font-mono text-slate-500&quot;&gt;<br>              Pages: &lt;strong&gt;${totalPages}&lt;/strong&gt; • Fee Rows: &lt;strong&gt;${totalFees}&lt;/strong&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3 text-xs&quot;&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;PASS&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-emerald-500&quot;&gt;${totalPass}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;FAIL&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-rose-500&quot;&gt;${totalFail}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;REVIEW&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-amber-500&quot;&gt;${totalReview}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;PENDING&lt;/div&gt;&lt;div class=&quot;text-base font-extrabold text-sky-500&quot;&gt;${totalPending}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Gross Actual&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold&quot;&gt;${totalGross.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;CWT Deducted&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold text-amber-500&quot;&gt;-${totalCwt.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>            &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;&lt;div class=&quot;text-slate-400&quot;&gt;Net Actual&lt;/div&gt;&lt;div class=&quot;text-base font-mono font-bold text-emerald-500&quot;&gt;${totalNet.toFixed(2)}&lt;/div&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${dataset.projects.map(p =&gt; `<br>            &lt;div class=&quot;space-y-4&quot;&gt;<br>              &lt;div class=&quot;bg-slate-100 dark:bg-slate-800/80 px-4 py-2.5 rounded-xl flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                &lt;div&gt;&lt;strong&gt;Project:&lt;/strong&gt; ${escapeHtml(p.name)} &lt;span class=&quot;font-mono text-slate-500&quot;&gt;(${escapeHtml(p.reference)})&lt;/span&gt;&lt;/div&gt;<br>                &lt;div&gt;&lt;strong&gt;Owner:&lt;/strong&gt; ${escapeHtml(p.owner)} • &lt;strong&gt;Status:&lt;/strong&gt; ${escapeHtml(p.status)}&lt;/div&gt;<br>              &lt;/div&gt;<br><br>              ${(p.mainPages || []).map(mp =&gt; {<br>                const fin = mp.validationSummary.financials;<br>                return `<br>                  &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-3&quot;&gt;<br>                    &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                      &lt;div&gt;<br>                        &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(mp.name)}&lt;/h4&gt;<br>                        &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(mp.description)}&lt;/p&gt;<br>                      &lt;/div&gt;<br>                      &lt;div class=&quot;flex items-center gap-3 text-xs&quot;&gt;<br>                        &lt;span class=&quot;font-mono&quot;&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; | CWT: &lt;strong class=&quot;text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; | Net: &lt;strong class=&quot;text-emerald-500&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt;&lt;/span&gt;<br>                        ${statusBadge(mp.validationSummary.overallStatus)}<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br><br>                    ${renderReportSideBySideApp(mp)}<br>                    ${renderReportColumnsApp(mp)}<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          `).join(&#39;&#39;)}<br><br>          &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-2 gap-5 pt-2&quot;&gt;<br>            &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2&quot;&gt;<br>              &lt;h4 class=&quot;font-bold text-xs uppercase tracking-wider text-slate-400&quot;&gt;Test Cases (${allTestCases.length})&lt;/h4&gt;<br>              ${allTestCases.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;No test cases in scope.&lt;/div&gt;` : allTestCases.map(tc =&gt; `<br>                &lt;div class=&quot;flex items-center justify-between text-xs py-1.5 border-b border-slate-100 dark:divide-slate-800&quot;&gt;<br>                  &lt;span class=&quot;truncate pr-2&quot;&gt;&lt;strong class=&quot;font-mono&quot;&gt;${escapeHtml(tc.id)}&lt;/strong&gt;: ${escapeHtml(tc.title)}&lt;/span&gt;<br>                  ${statusBadge(tc.status)}<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-2&quot;&gt;<br>              &lt;h4 class=&quot;font-bold text-xs uppercase tracking-wider text-slate-400&quot;&gt;Defects (${allDefects.length})&lt;/h4&gt;<br>              ${allDefects.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;No defects in scope.&lt;/div&gt;` : allDefects.map(df =&gt; `<br>                &lt;div class=&quot;flex items-center justify-between text-xs py-1.5 border-b border-slate-100 dark:divide-slate-800&quot;&gt;<br>                  &lt;span class=&quot;truncate pr-2&quot;&gt;&lt;strong class=&quot;font-mono text-rose-500&quot;&gt;${escapeHtml(df.id)}&lt;/strong&gt;: ${escapeHtml(df.title)}&lt;/span&gt;<br>                  ${statusBadge(df.status)}<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function buildStandaloneHtmlReport(dataset, includeReceipts = true) {<br>      const receiptNotice = includeReceipts<br>        ? &#39;Receipt &amp;amp; evidence images: &lt;strong&gt;Included&lt;/strong&gt;&#39;<br>        : &#39;Receipt &amp;amp; evidence images: &lt;strong&gt;Excluded by user toggle&lt;/strong&gt;&#39;;<br><br>      const pagesHtml = dataset.projects.map(p =&gt; `<br>        &lt;div class=&quot;project-block&quot;&gt;<br>          &lt;h2&gt;Project: ${escapeHtml(p.name)} (${escapeHtml(p.reference)})&lt;/h2&gt;<br>          &lt;p class=&quot;meta&quot;&gt;Owner: ${escapeHtml(p.owner)} | Status: ${escapeHtml(p.status)} | ${receiptNotice}&lt;/p&gt;<br>          ${(p.mainPages || []).map(mp =&gt; {<br>            const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees);<br>            const overall = mp.validationSummary?.overallStatus || &#39;PENDING&#39;;<br>            const receiptPages = (mp.receipt?.pages || []).map(sanitizeImageSrc).filter(Boolean);<br><br>            const receiptSectionHtml = includeReceipts ? `<br>              &lt;div class=&quot;receipt-section&quot;&gt;<br>                &lt;div class=&quot;receipt-title&quot;&gt;Attached Receipt Evidence (${escapeHtml(mp.receipt?.fileName || &#39;Receipt&#39;)} — ${receiptPages.length ? receiptPages.length + &#39; page(s)&#39; : &#39;No image attached&#39;})&lt;/div&gt;<br>                ${receiptPages.length ? receiptPages.map((src, idx) =&gt; `<br>                  &lt;div class=&quot;receipt-img-wrap&quot;&gt;<br>                    &lt;div class=&quot;receipt-page-label&quot;&gt;Page ${idx + 1}&lt;/div&gt;<br>                    &lt;img src=&quot;${src}&quot; alt=&quot;Receipt Page ${idx + 1} for ${escapeHtml(mp.name)}&quot; class=&quot;receipt-img&quot; /&gt;<br>                  &lt;/div&gt;<br>                `).join(&#39;&#39;) : `&lt;p class=&quot;muted&quot;&gt;No receipt image file attached to this Main Page.&lt;/p&gt;`}<br>              &lt;/div&gt;<br>            ` : &#39;&#39;;<br><br>            return `<br>              &lt;div class=&quot;page-block&quot;&gt;<br>                &lt;div class=&quot;page-header&quot;&gt;<br>                  &lt;h3&gt;${escapeHtml(mp.name)}&lt;/h3&gt;<br>                  &lt;span class=&quot;badge ${escapeHtml(overall)}&quot;&gt;${escapeHtml(overall)}&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;desc&quot;&gt;${escapeHtml(mp.description || &#39;&#39;)}&lt;/p&gt;<br>                &lt;p class=&quot;fin&quot;&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; | CWT: &lt;strong&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; | Net Actual: &lt;strong&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt; (Expected Net: ${fin.expectedNet.toFixed(2)})&lt;/p&gt;<br>                ${renderReportSideBySideStandalone(mp)}<br>                ${renderReportColumnsStandalone(mp)}<br>                ${receiptSectionHtml}<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `).join(&#39;&#39;);<br><br>      return `&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;title&gt;${escapeHtml(dataset.title)}&lt;/title&gt;<br>  &lt;style&gt;<br>    body { font-family: Arial, Helvetica, sans-serif; color: #0f172a; background: #ffffff; margin: 24px; line-height: 1.45; }<br>    h1 { margin: 0 0 6px; font-size: 20px; }<br>    h2 { font-size: 16px; margin: 20px 0 6px; color: #1e293b; border-bottom: 2px solid #e2e8f0; padding-bottom: 4px; }<br>    h3 { font-size: 14px; margin: 0; }<br>    .meta, .desc, .muted { font-size: 12px; color: #64748b; margin: 4px 0 10px; }<br>    .fin { font-size: 12px; background: #f8fafc; padding: 8px 10px; border-radius: 6px; border: 1px solid #e2e8f0; }<br>    .page-block { border: 1px solid #cbd5e1; border-radius: 8px; padding: 14px; margin: 14px 0; }<br>    .page-header { display: flex; justify-content: space-between; align-items: center; }<br>    table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 12px; }<br>    th, td { border: 1px solid #cbd5e1; padding: 6px 8px; text-align: left; }<br>    th { background: #f1f5f9; font-weight: bold; }<br>    td.num { text-align: right; font-family: Consolas, monospace; }<br>    .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 10px; font-weight: bold; background: #e2e8f0; color: #1e293b; }<br>    .badge.PASS { background: #dcfce7; color: #166534; }<br>    .badge.FAIL { background: #fee2e2; color: #991b1b; }<br>    .badge.REVIEW { background: #fef3c7; color: #92400e; }<br>    .badge.PENDING { background: #e0f2fe; color: #075985; }<br>    .receipt-section { margin-top: 12px; padding-top: 10px; border-top: 1px dashed #cbd5e1; }<br>    .receipt-title { font-size: 12px; font-weight: bold; margin-bottom: 8px; color: #334155; }<br>    .receipt-img-wrap { margin-bottom: 10px; }<br>    .receipt-page-label { font-size: 11px; color: #64748b; margin-bottom: 4px; }<br>    .receipt-img { max-width: 460px; width: 100%; height: auto; border: 1px solid #cbd5e1; border-radius: 6px; display: block; }<br>    .section-title { font-size: 13px; font-weight: bold; margin: 16px 0 4px; color: #334155; }<br>    td.muted { text-align: center; }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;${escapeHtml(dataset.title)}&lt;/h1&gt;<br>  &lt;div class=&quot;meta&quot;&gt;Generated: ${escapeHtml(new Date().toLocaleString())} | ${receiptNotice}&lt;/div&gt;<br>  ${pagesHtml}<br>&lt;/body&gt;<br>&lt;/html&gt;`;<br>    }<br><br>    function exportReportFile(format) {<br>      const dataset = getReportDataset();<br>      const stamp = new Date().toISOString().slice(0, 10);<br>      const includeReceipts = Boolean(reportIncludeReceipts);<br><br>      if (format === &#39;json&#39;) {<br>        const payload = {<br>          title: dataset.title,<br>          exportedAt: new Date().toISOString(),<br>          includeReceiptImages: includeReceipts,<br>          projects: dataset.projects,<br>          reportSections: dataset.projects.flatMap(p =&gt; (p.mainPages || []).map(mp =&gt; {<br>            const { feeRows, colRows, fin } = getReportRows(mp);<br>            return {<br>              project: p.name,<br>              mainPage: mp.name,<br>              sideBySideFeeCwtComparison: feeRows.map(({ fee, v }) =&gt; ({ feeItem: fee.expectedName, isCwt: v.isCwt, expected: { name: fee.expectedName, amount: fee.expectedAmount, code: fee.expectedCode }, receipt: { name: fee.actualName, amount: fee.actualAmount, code: fee.actualCode }, difference: v.amountComparison.difference, confidence: fee.ocrConfidence ?? null, status: v.status, explanation: v.explanation })),<br>              netReconciliation: fin,<br>              expectedRowColumnsVerification: colRows.map(({ field, v }) =&gt; ({ column: &#39;C&#39; + String(field.number).padStart(2, &#39;0&#39;), fieldName: field.name, expectedValue: field.expectedValue, foundOnReceipt: field.actualValue, status: v.status, explanation: v.explanation }))<br>            };<br>          }))<br>        };<br>        downloadBlob(JSON.stringify(payload, null, 2), `SMART_report_${stamp}.json`, &#39;application/json&#39;);<br>      } else if (format === &#39;csv&#39;) {<br>        const rows = [[&#39;Section&#39;, &#39;Project&#39;, &#39;Main Page&#39;, &#39;Fee / Field Name&#39;, &#39;Expected Name&#39;, &#39;Expected Amount&#39;, &#39;Expected Code&#39;, &#39;Receipt Name&#39;, &#39;Receipt Amount&#39;, &#39;Receipt Code&#39;, &#39;Diff&#39;, &#39;Confidence&#39;, &#39;Status&#39;, &#39;Explanation&#39;]];<br>        dataset.projects.forEach(p =&gt; {<br>          (p.mainPages || []).forEach(mp =&gt; {<br>            const { feeRows, colRows } = getReportRows(mp);<br>            feeRows.forEach(({ fee: f, v }) =&gt; {<br>              rows.push([&#39;Fee &amp; CWT Comparison&#39;, p.name, mp.name, f.expectedName, f.expectedName, f.expectedAmount, f.expectedCode, f.actualName, f.actualAmount, f.actualCode, v.amountComparison.difference, f.ocrConfidence ?? &#39;Manual&#39;, v.status, v.explanation]);<br>            });<br>            colRows.forEach(({ field, v }) =&gt; {<br>              rows.push([&#39;Expected Row Column Verification&#39;, p.name, mp.name, `C${String(field.number).padStart(2, &#39;0&#39;)} ${field.name}`, &#39;&#39;, field.expectedValue, &#39;&#39;, &#39;&#39;, field.actualValue, &#39;&#39;, v.difference ?? &#39;&#39;, &#39;&#39;, v.status, v.explanation]);<br>            });<br>          });<br>        });<br>        const csv = rows.map(r =&gt; r.map(c =&gt; `&quot;${String(c ?? &#39;&#39;).replace(/&quot;/g, &#39;&quot;&quot;&#39;)}&quot;`).join(&#39;,&#39;)).join(&#39;\n&#39;);<br>        downloadBlob(csv, `SMART_report_${stamp}.csv`, &#39;text/csv&#39;);<br>      } else if (format === &#39;txt&#39;) {<br>        const lines = [dataset.title, `Generated: ${new Date().toLocaleString()}`, &#39;========================================&#39;];<br>        dataset.projects.forEach(p =&gt; {<br>          lines.push(`\nProject: ${p.name} (${p.reference})`);<br>          (p.mainPages || []).forEach(mp =&gt; {<br>            const fin = mp.validationSummary?.financials || FinancialCalculator.calculateTotals(mp.fees);<br>            lines.push(`  Main Page: ${mp.name} [${mp.validationSummary?.overallStatus || &#39;PENDING&#39;}] — Gross ${fin.actualGross.toFixed(2)}, CWT -${fin.actualCwt.toFixed(2)}, Net ${fin.actualNet.toFixed(2)}`);<br>            const { feeRows, colRows } = getReportRows(mp);<br>            lines.push(&#39;    [Side-by-Side EIS Fee &amp; CWT Comparison]&#39;);<br>            feeRows.forEach(({ fee: f, v }) =&gt; {<br>              lines.push(`    - ${f.expectedName}${v.isCwt ? &#39; (CWT)&#39; : &#39;&#39;}: Expected ${f.expectedName} / ${f.expectedAmount} / ${f.expectedCode || &#39;-&#39;} | Receipt ${f.actualName || &#39;-&#39;} / ${f.actualAmount || &#39;-&#39;} / ${f.actualCode || &#39;-&#39;} | Diff=${v.amountComparison.difference} | ${v.status}`);<br>              lines.push(`        Rule: ${v.explanation}`);<br>            });<br>            const matchedCols = colRows.filter(r =&gt; r.v.status === &#39;PASS&#39;).length;<br>            lines.push(`    [Expected Row Columns vs Receipt Verification: ${matchedCols}/${colRows.length} matched]`);<br>            colRows.forEach(({ field, v }) =&gt; {<br>              lines.push(`    - C${String(field.number).padStart(2, &#39;0&#39;)} ${field.name}: Expected=${field.expectedValue || &#39;-&#39;} | Receipt=${field.actualValue || &#39;-&#39;} | ${v.status}`);<br>            });<br>          });<br>        });<br>        downloadBlob(lines.join(&#39;\n&#39;), `SMART_report_${stamp}.txt`, &#39;text/plain&#39;);<br>      } else if (format === &#39;html&#39;) {<br>        const htmlContent = buildStandaloneHtmlReport(dataset, includeReceipts);<br>        downloadBlob(htmlContent, `SMART_report_${stamp}.html`, &#39;text/html&#39;);<br>      } else if (format === &#39;doc&#39;) {<br>        // Word-compatible HTML document (.doc) honoring receipt image toggle<br>        const docBodyHtml = buildStandaloneHtmlReport(dataset, includeReceipts);<br>        const wordHtml = `&lt;html xmlns:o=&quot;urn:schemas-microsoft-com:office:office&quot; xmlns:w=&quot;urn:schemas-microsoft-com:office:word&quot; xmlns=&quot;http://www.w3.org/TR/REC-html40&quot;&gt;${docBodyHtml.replace(/^[\s\S]*&lt;html[^&gt;]*&gt;|&lt;\/html&gt;\s*$/gi, &#39;&#39;)}&lt;/html&gt;`;<br>        downloadBlob(wordHtml, `SMART_report_${stamp}.doc`, &#39;application/msword&#39;);<br>      }<br><br>      showToast(`Exported ${format.toUpperCase()} report${(format === &#39;html&#39; || format === &#39;doc&#39;) ? (includeReceipts ? &#39; (with receipt images)&#39; : &#39; (receipt images excluded)&#39;) : &#39;&#39;}.`, &#39;success&#39;);<br>    }<br><br>    function downloadBlob(content, filename, mimeType) {<br>      const blob = new Blob([content], { type: mimeType });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = filename;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>    }<br><br>    /****************************************************************************<br>     * GLOBAL KEYBOARD SHORTCUTS &amp; PASTE LISTENER<br>     ****************************************************************************/<br>    document.addEventListener(&#39;keydown&#39;, (e) =&gt; {<br>      if ((e.ctrlKey || e.metaKey) &amp;&amp; e.key.toLowerCase() === &#39;s&#39;) {<br>        e.preventDefault();<br>        manualSaveProject();<br>      }<br>      if (e.key === &#39;Escape&#39;) {<br>        closeModal();<br>      }<br>    });<br><br>    document.addEventListener(&#39;paste&#39;, async (e) =&gt; {<br>      const activeTag = document.activeElement?.tagName?.toLowerCase();<br>      if (activeTag === &#39;input&#39; || activeTag === &#39;textarea&#39;) return;<br>      const items = e.clipboardData?.items;<br>      if (!items) return;<br>      for (const item of items) {<br>        if (item.type &amp;&amp; item.type.startsWith(&#39;image/&#39;)) {<br>          const blob = item.getAsFile();<br>          if (blob &amp;&amp; appState.activeModule === &#39;validation&#39;) {<br>            e.preventDefault();<br>            const file = new File([blob], `clipboard_receipt_${Date.now()}.png`, { type: item.type });<br>            await processUploadedReceiptFile(file);<br>          }<br>        }<br>      }<br>    });<br><br>    /****************************************************************************<br>     * APPLICATION BOOTSTRAP<br>     ****************************************************************************/<br>    async function bootApplication() {<br>      try {<br>        const rawLoaded = await PersistenceEngine.loadState();<br>        const migrated = PersistenceEngine.migrateState(rawLoaded);<br>        if (migrated &amp;&amp; Array.isArray(migrated.projects) &amp;&amp; migrated.projects.length &gt; 0) {<br>          appState = migrated;<br>        } else {<br>          appState = createSampleSeedState();<br>          await PersistenceEngine.saveState(appState);<br>        }<br><br>        if (!appState.activeProjectId || !appState.projects.some(p =&gt; p.id === appState.activeProjectId)) {<br>          appState.activeProjectId = appState.projects[0]?.id || null;<br>        }<br>        const proj = getActiveProject();<br>        if (proj &amp;&amp; (!appState.activeMainPageId || !proj.mainPages.some(mp =&gt; mp.id === appState.activeMainPageId))) {<br>          appState.activeMainPageId = proj.mainPages[0]?.id || null;<br>        }<br><br>        proj?.mainPages?.forEach(mp =&gt; {<br>          if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        });<br><br>        renderApp();<br>        updateSaveIndicator(&#39;saved&#39;);<br>      } catch (err) {<br>        console.error(&#39;Boot error:&#39;, err);<br>        appState = createSampleSeedState();<br>        renderApp();<br>        showToast(&#39;Loaded fallback seed state due to storage notice: &#39; + err.message, &#39;warning&#39;);<br>      }<br>    }<br><br>    window.addEventListener(&#39;DOMContentLoaded&#39;, bootApplication);<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe7e5c8f600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NEXUS EIS & QA Validation Studio v2]]></title>
            <link>https://medium.com/@barabonajansen/nexus-eis-qa-validation-studio-v2-889bb86296c1?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/889bb86296c1</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 06:10:20 GMT</pubDate>
            <atom:updated>2026-11-19T06:10:20.072Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot; class=&quot;dark&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>  &lt;title&gt;NEXUS EIS &amp; QA Validation Studio&lt;/title&gt;<br><br>  &lt;!-- Google Fonts: Inter &amp; JetBrains Mono --&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt;<br>  &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt;<br>  &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&amp;family=JetBrains+Mono:wght@400;500;600&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br><br>  &lt;!-- Tailwind CSS --&gt;<br>  &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    tailwind.config = {<br>      darkMode: &#39;class&#39;,<br>      theme: {<br>        extend: {<br>          fontFamily: {<br>            sans: [&#39;Inter&#39;, &#39;system-ui&#39;, &#39;sans-serif&#39;],<br>            mono: [&#39;JetBrains Mono&#39;, &#39;monospace&#39;]<br>          },<br>          colors: {<br>            brand: {<br>              50: &#39;#eef2ff&#39;,<br>              100: &#39;#e0e7ff&#39;,<br>              400: &#39;#818cf8&#39;,<br>              500: &#39;#6366f1&#39;,<br>              600: &#39;#4f46e5&#39;,<br>              700: &#39;#4338ca&#39;,<br>              900: &#39;#312e81&#39;,<br>              950: &#39;#1e1b4b&#39;<br>            }<br>          }<br>        }<br>      }<br>    };<br>  &lt;/script&gt;<br><br>  &lt;!-- Lucide Icons --&gt;<br>  &lt;script src=&quot;https://unpkg.com/lucide@latest&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Chart.js for Dashboard Analytics --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- PDF.js for Multi-Page PDF Receipt Rendering &amp; Text Extraction --&gt;<br>  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Tesseract.js for Client-Side Local-First OCR --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;style&gt;<br>    * { box-sizing: border-box; }<br>    body { font-family: &#39;Inter&#39;, system-ui, sans-serif; overflow-x: hidden; }<br>    ::-webkit-scrollbar { width: 6px; height: 6px; }<br>    ::-webkit-scrollbar-track { background: transparent; }<br>    ::-webkit-scrollbar-thumb { background: rgba(100, 116, 139, 0.35); border-radius: 9999px; }<br>    ::-webkit-scrollbar-thumb:hover { background: rgba(100, 116, 139, 0.6); }<br><br>    @media print {<br>      body * { visibility: hidden; }<br>      #printable-report-area, #printable-report-area * { visibility: visible; }<br>      #printable-report-area {<br>        position: absolute;<br>        left: 0;<br>        top: 0;<br>        width: 100%;<br>        background: #ffffff !important;<br>        color: #0f172a !important;<br>        padding: 20px;<br>      }<br>      .no-print { display: none !important; }<br>      .page-break { page-break-before: always; }<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100 antialiased selection:bg-brand-500 selection:text-white&quot;&gt;<br><br>  &lt;!-- Main Application Shell --&gt;<br>  &lt;div id=&quot;app-shell&quot; class=&quot;min-h-screen flex flex-col lg:flex-row&quot;&gt;<br><br>    &lt;!-- Mobile Top Header --&gt;<br>    &lt;header class=&quot;lg:hidden flex items-center justify-between px-4 py-3 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 sticky top-0 z-40&quot;&gt;<br>      &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>        &lt;button id=&quot;mobile-menu-btn&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; aria-label=&quot;Toggle Menu&quot;&gt;<br>          &lt;i data-lucide=&quot;menu&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>          &lt;div class=&quot;w-8 h-8 rounded-xl bg-gradient-to-br from-brand-500 to-indigo-600 flex items-center justify-center text-white font-bold shadow-md&quot;&gt;N&lt;/div&gt;<br>          &lt;span class=&quot;font-bold tracking-tight text-sm&quot;&gt;NEXUS EIS &amp; QA&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>        &lt;span id=&quot;mobile-save-badge&quot; class=&quot;text-xs px-2 py-1 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium&quot;&gt;Saved&lt;/span&gt;<br>        &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Toggle Theme&quot;&gt;<br>          &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/header&gt;<br><br>    &lt;!-- Collapsible Navigation Sidebar --&gt;<br>    &lt;aside id=&quot;sidebar&quot; class=&quot;fixed inset-y-0 left-0 z-50 w-72 lg:w-64 transform -translate-x-full lg:translate-x-0 lg:static transition-all duration-200 bg-white dark:bg-slate-900 border-r border-slate-200 dark:border-slate-800 flex flex-col shrink-0&quot;&gt;<br>      &lt;!-- Brand Header --&gt;<br>      &lt;div class=&quot;p-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 overflow-hidden&quot;&gt;<br>          &lt;div class=&quot;w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500 via-indigo-600 to-violet-600 flex items-center justify-center text-white font-extrabold shadow-lg shrink-0&quot;&gt;<br>            N<br>          &lt;/div&gt;<br>          &lt;div class=&quot;sidebar-label truncate&quot;&gt;<br>            &lt;div class=&quot;font-bold text-sm tracking-tight&quot;&gt;NEXUS Studio&lt;/div&gt;<br>            &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 truncate&quot;&gt;EIS Receipt &amp; QA Engine&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;button onclick=&quot;toggleSidebarCollapse()&quot; class=&quot;hidden lg:flex p-1.5 rounded-lg text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Collapse Sidebar&quot;&gt;<br>          &lt;i data-lucide=&quot;panel-left-close&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>        &lt;button onclick=&quot;toggleMobileSidebar()&quot; class=&quot;lg:hidden p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- Active Project Quick Switcher --&gt;<br>      &lt;div class=&quot;p-3 border-b border-slate-200 dark:border-slate-800 sidebar-label&quot;&gt;<br>        &lt;label class=&quot;block text-[10px] font-semibold uppercase tracking-wider text-slate-400 mb-1&quot;&gt;Active Project&lt;/label&gt;<br>        &lt;select id=&quot;sidebar-project-select&quot; onchange=&quot;switchActiveProject(this.value)&quot; class=&quot;w-full text-xs font-medium bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-2.5 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br><br>      &lt;!-- 11 Core Modules Navigation --&gt;<br>      &lt;nav id=&quot;sidebar-nav&quot; class=&quot;flex-1 overflow-y-auto p-2.5 space-y-1&quot;&gt;<br>        &lt;!-- Populated dynamically --&gt;<br>      &lt;/nav&gt;<br><br>      &lt;!-- Footer Status &amp; Privacy Badge --&gt;<br>      &lt;div class=&quot;p-3 border-t border-slate-200 dark:border-slate-800 sidebar-label space-y-2&quot;&gt;<br>        &lt;div class=&quot;flex items-center justify-between text-xs&quot;&gt;<br>          &lt;span class=&quot;text-slate-500 dark:text-slate-400 flex items-center gap-1.5&quot;&gt;<br>            &lt;span class=&quot;w-2 h-2 rounded-full bg-emerald-500 animate-pulse&quot;&gt;&lt;/span&gt;<br>            IndexedDB Local<br>          &lt;/span&gt;<br>          &lt;span id=&quot;sidebar-version-tag&quot; class=&quot;font-mono text-[11px] text-slate-400&quot;&gt;v2.4.0&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-[11px] text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-800/70 rounded-xl p-2 flex items-center gap-2&quot;&gt;<br>          &lt;i data-lucide=&quot;shield-check&quot; class=&quot;w-4 h-4 text-emerald-500 shrink-0&quot;&gt;&lt;/i&gt;<br>          &lt;span&gt;Local-first storage. Zero external receipt uploads.&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/aside&gt;<br><br>    &lt;!-- Backdrop for mobile drawer --&gt;<br>    &lt;div id=&quot;mobile-backdrop&quot; onclick=&quot;toggleMobileSidebar()&quot; class=&quot;fixed inset-0 bg-slate-950/60 backdrop-blur-xs z-40 hidden lg:hidden&quot;&gt;&lt;/div&gt;<br><br>    &lt;!-- Main Content Workspace --&gt;<br>    &lt;div class=&quot;flex-1 flex flex-col min-w-0&quot;&gt;<br><br>      &lt;!-- Desktop Top Workspace Bar --&gt;<br>      &lt;header class=&quot;hidden lg:flex items-center justify-between px-6 py-3.5 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 sticky top-0 z-30&quot;&gt;<br>        &lt;div class=&quot;flex items-center gap-3 min-w-0&quot;&gt;<br>          &lt;h1 id=&quot;topbar-title&quot; class=&quot;text-base font-bold tracking-tight truncate&quot;&gt;Dashboard&lt;/h1&gt;<br>          &lt;span id=&quot;topbar-subtitle&quot; class=&quot;text-xs text-slate-500 dark:text-slate-400 hidden xl:inline truncate&quot;&gt;Enterprise EIS Receipt &amp; QA Evidence Overview&lt;/span&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;flex items-center gap-2.5&quot;&gt;<br>          &lt;!-- Autosave Status Pill --&gt;<br>          &lt;div id=&quot;save-status-pill&quot; class=&quot;flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20&quot;&gt;<br>            &lt;i data-lucide=&quot;check-circle-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span id=&quot;save-status-text&quot;&gt;All changes saved&lt;/span&gt;<br>          &lt;/div&gt;<br><br>          &lt;!-- Manual Save Button --&gt;<br>          &lt;button onclick=&quot;manualSaveProject()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Save Project Now (Ctrl+S)&quot;&gt;<br>            &lt;i data-lucide=&quot;save&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Save&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Run Validation CTA --&gt;<br>          &lt;button onclick=&quot;runActivePageValidation(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm transition&quot;&gt;<br>            &lt;i data-lucide=&quot;play&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;Validate Active Page&lt;/span&gt;<br>          &lt;/button&gt;<br><br>          &lt;!-- Theme Switcher --&gt;<br>          &lt;button onclick=&quot;toggleTheme()&quot; class=&quot;p-2 rounded-xl bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 transition&quot; title=&quot;Toggle Dark/Light Theme&quot;&gt;<br>            &lt;i data-lucide=&quot;sun-moon&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br><br>      &lt;!-- Dynamic Module Viewport --&gt;<br>      &lt;main id=&quot;main-viewport&quot; class=&quot;flex-1 p-4 sm:p-6 max-w-[1600px] w-full mx-auto space-y-6&quot;&gt;<br>        &lt;!-- Active module renders here --&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Toast Notification Container --&gt;<br>  &lt;div id=&quot;toast-container&quot; class=&quot;fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-sm w-full pointer-events-none px-4 sm:px-0&quot;&gt;&lt;/div&gt;<br><br>  &lt;!-- Reusable Modal Container --&gt;<br>  &lt;div id=&quot;modal-overlay&quot; class=&quot;fixed inset-0 z-50 bg-slate-950/70 backdrop-blur-xs hidden items-center justify-center p-4&quot;&gt;<br>    &lt;div id=&quot;modal-box&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] flex flex-col overflow-hidden&quot;&gt;<br>      &lt;div class=&quot;px-5 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between&quot;&gt;<br>        &lt;h3 id=&quot;modal-title&quot; class=&quot;font-bold text-base&quot;&gt;Modal Title&lt;/h3&gt;<br>        &lt;button onclick=&quot;closeModal()&quot; class=&quot;p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>          &lt;i data-lucide=&quot;x&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;modal-body&quot; class=&quot;p-5 overflow-y-auto space-y-4 text-sm&quot;&gt;&lt;/div&gt;<br>      &lt;div id=&quot;modal-footer&quot; class=&quot;px-5 py-3.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-end gap-2 bg-slate-50 dark:bg-slate-900/50&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;script&gt;<br>    /****************************************************************************<br>     * NEXUS EIS &amp; QA VALIDATION STUDIO — MODULAR ARCHITECTURE<br>     * 1. Persistence &amp; Backup Engine (IndexedDB + Versioned Migration)<br>     * 2. Financial Calculator &amp; EIS Fee Validation Engine (Deterministic)<br>     * 3. Intelligent OCR &amp; Smart Field Mapping Engine (PDF.js + Tesseract.js)<br>     * 4. QA Screenshot &amp; Vector Annotation Engine<br>     * 5. Test Case, Defect &amp; Unified Reporting Engine<br>     * 6. Automated 12-Point Acceptance Test Suite<br>     ****************************************************************************/<br><br>    // Configure PDF.js worker<br>    if (window.pdfjsLib) {<br>      pdfjsLib.GlobalWorkerOptions.workerSrc = &#39;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js&#39;;<br>    }<br><br>    const APP_SCHEMA_VERSION = 3;<br>    const DB_NAME = &#39;NexusEisQaStudioDB&#39;;<br>    const DB_VERSION = 1;<br>    const STORE_NAME = &#39;workspaceState&#39;;<br><br>    const MODULES = [<br>      { id: &#39;dashboard&#39;, label: &#39;Dashboard&#39;, icon: &#39;layout-dashboard&#39;, subtitle: &#39;Real-time EIS validation metrics &amp; QA progress&#39; },<br>      { id: &#39;projects&#39;, label: &#39;Projects&#39;, icon: &#39;folder-kanban&#39;, subtitle: &#39;Manage isolated audit workspaces, backups &amp; imports&#39; },<br>      { id: &#39;main-pages&#39;, label: &#39;Main Pages&#39;, icon: &#39;file-spreadsheet&#39;, subtitle: &#39;Configure numbered fields (1–50+), per-page dynamic rows &amp; fees&#39; },<br>      { id: &#39;validation&#39;, label: &#39;Receipt Validation&#39;, icon: &#39;split-square-horizontal&#39;, subtitle: &#39;Side-by-side receipt comparison, OCR boxes &amp; mismatch review&#39; },<br>      { id: &#39;ocr-intel&#39;, label: &#39;OCR &amp; Doc Intel&#39;, icon: &#39;scan-text&#39;, subtitle: &#39;Preprocessing pipeline, confidence inspection &amp; block mapping&#39; },<br>      { id: &#39;screenshots&#39;, label: &#39;QA Screenshot Studio&#39;, icon: &#39;camera&#39;, subtitle: &#39;Screen capture, image merging &amp; dynamic QA evidence labels (1–200+)&#39; },<br>      { id: &#39;test-cases&#39;, label: &#39;Test Cases&#39;, icon: &#39;check-square&#39;, subtitle: &#39;QA test execution, preconditions &amp; linked receipt evidence&#39; },<br>      { id: &#39;defects&#39;, label: &#39;Defect Management&#39;, icon: &#39;bug&#39;, subtitle: &#39;Issue tracking, severity triage &amp; copy-ready Jira markup&#39; },<br>      { id: &#39;reports&#39;, label: &#39;Validation Reports&#39;, icon: &#39;file-bar-chart-2&#39;, subtitle: &#39;Unified executive &amp; technical reports (CSV, JSON, Print/PDF)&#39; },<br>      { id: &#39;templates&#39;, label: &#39;Templates&#39;, icon: &#39;copy-plus&#39;, subtitle: &#39;Reusable EIS fee schemas, column mappings &amp; project templates&#39; },<br>      { id: &#39;settings&#39;, label: &#39;Settings &amp; Diagnostics&#39;, icon: &#39;settings&#39;, subtitle: &#39;Validation tolerances, OCR rules &amp; 12-point self-test suite&#39; }<br>    ];<br><br>    // Global Application State<br>    let appState = {<br>      schemaVersion: APP_SCHEMA_VERSION,<br>      theme: &#39;dark&#39;,<br>      sidebarCollapsed: false,<br>      activeModule: &#39;dashboard&#39;,<br>      activeProjectId: null,<br>      activeMainPageId: null,<br>      lastSavedAt: null,<br>      settings: {<br>        numericTolerance: 0.01,<br>        caseSensitiveNames: false,<br>        normalizeWhitespace: true,<br>        autoAcceptConfidenceThreshold: 88,<br>        cwtDeductionMode: &#39;absolute&#39;,<br>        qaLabelMax: 200,<br>        qaAutoIncrement: true<br>      },<br>      templates: [],<br>      projects: [],<br>      ui: {<br>        viewerZoom: 1,<br>        viewerRotation: 0,<br>        showOcrBoxes: true,<br>        selectedComparisonRowId: null,<br>        selectedScreenshotsForMerge: [],<br>        annotationTool: &#39;rect&#39;,<br>        annotationColor: &#39;#ef4444&#39;,<br>        selectedAnnotationId: null,<br>        selectedQaLabel: 1<br>      }<br>    };<br><br>    let chartInstances = {};<br>    let autosaveTimer = null;<br><br>    function escapeHtml(str) {<br>      if (str === null || str === undefined) return &#39;&#39;;<br>      return String(str)<br>        .replace(/&amp;/g, &#39;&amp;amp;&#39;)<br>        .replace(/&lt;/g, &#39;&amp;lt;&#39;)<br>        .replace(/&gt;/g, &#39;&amp;gt;&#39;)<br>        .replace(/&quot;/g, &#39;&amp;quot;&#39;)<br>        .replace(/&#39;/g, &#39;&amp;#039;&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1: PERSISTENCE &amp; BACKUP ENGINE (IndexedDB)<br>     ****************************************************************************/<br>    const PersistenceEngine = {<br>      openDB() {<br>        return new Promise((resolve, reject) =&gt; {<br>          const req = indexedDB.open(DB_NAME, DB_VERSION);<br>          req.onupgradeneeded = (e) =&gt; {<br>            const db = e.target.result;<br>            if (!db.objectStoreNames.contains(STORE_NAME)) {<br>              db.createObjectStore(STORE_NAME, { keyPath: &#39;id&#39; });<br>            }<br>          };<br>          req.onsuccess = () =&gt; resolve(req.result);<br>          req.onerror = () =&gt; reject(req.error);<br>        });<br>      },<br><br>      async saveState(stateObj) {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readwrite&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const payload = {<br>            id: &#39;primary_workspace&#39;,<br>            updatedAt: new Date().toISOString(),<br>            data: JSON.parse(JSON.stringify(stateObj))<br>          };<br>          store.put(payload);<br>          return new Promise((resolve, reject) =&gt; {<br>            tx.oncomplete = () =&gt; {<br>              appState.lastSavedAt = payload.updatedAt;<br>              updateSaveIndicator(&#39;saved&#39;);<br>              resolve(true);<br>            };<br>            tx.onerror = () =&gt; reject(tx.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Save Error:&#39;, err);<br>          updateSaveIndicator(&#39;error&#39;);<br>          return false;<br>        }<br>      },<br><br>      async loadState() {<br>        try {<br>          const db = await this.openDB();<br>          const tx = db.transaction(STORE_NAME, &#39;readonly&#39;);<br>          const store = tx.objectStore(STORE_NAME);<br>          const req = store.get(&#39;primary_workspace&#39;);<br>          return new Promise((resolve, reject) =&gt; {<br>            req.onsuccess = () =&gt; resolve(req.result ? req.result.data : null);<br>            req.onerror = () =&gt; reject(req.error);<br>          });<br>        } catch (err) {<br>          console.error(&#39;IndexedDB Load Error:&#39;, err);<br>          return null;<br>        }<br>      },<br><br>      migrateState(raw) {<br>        if (!raw) return null;<br>        if (!raw.schemaVersion || raw.schemaVersion &lt; APP_SCHEMA_VERSION) {<br>          raw.schemaVersion = APP_SCHEMA_VERSION;<br>          raw.settings = Object.assign({<br>            numericTolerance: 0.01,<br>            caseSensitiveNames: false,<br>            normalizeWhitespace: true,<br>            autoAcceptConfidenceThreshold: 88,<br>            cwtDeductionMode: &#39;absolute&#39;,<br>            qaLabelMax: 200,<br>            qaAutoIncrement: true<br>          }, raw.settings || {});<br>        }<br>        (raw.projects || []).forEach(proj =&gt; {<br>          (proj.mainPages || []).forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>          });<br>        });<br>        return raw;<br>      }<br>    };<br><br>    function scheduleAutosave(reason = &#39;&#39;) {<br>      updateSaveIndicator(&#39;saving&#39;);<br>      if (autosaveTimer) clearTimeout(autosaveTimer);<br>      autosaveTimer = setTimeout(async () =&gt; {<br>        const proj = getActiveProject();<br>        if (proj) proj.lastModified = new Date().toISOString();<br>        await PersistenceEngine.saveState(appState);<br>      }, 450);<br>    }<br><br>    async function manualSaveProject() {<br>      const proj = getActiveProject();<br>      if (proj) proj.lastModified = new Date().toISOString();<br>      await PersistenceEngine.saveState(appState);<br>      showToast(&#39;Project state persisted to IndexedDB.&#39;, &#39;success&#39;);<br>    }<br><br>    function updateSaveIndicator(status) {<br>      const textEl = document.getElementById(&#39;save-status-text&#39;);<br>      const mobileBadge = document.getElementById(&#39;mobile-save-badge&#39;);<br>      if (status === &#39;saving&#39;) {<br>        if (textEl) textEl.textContent = &#39;Saving...&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saving...&#39;;<br>      } else if (status === &#39;saved&#39;) {<br>        const t = new Date().toLocaleTimeString([], { hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39;, second: &#39;2-digit&#39; });<br>        if (textEl) textEl.textContent = `Saved ${t}`;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Saved&#39;;<br>      } else {<br>        if (textEl) textEl.textContent = &#39;Save error&#39;;<br>        if (mobileBadge) mobileBadge.textContent = &#39;Error&#39;;<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2: FINANCIAL CALCULATOR &amp; EIS FEE VALIDATION ENGINE<br>     ****************************************************************************/<br>    const FinancialCalculator = {<br>      parseAmount(raw) {<br>        if (raw === null || raw === undefined || raw === &#39;&#39;) return null;<br>        if (typeof raw === &#39;number&#39;) return Number.isFinite(raw) ? raw : null;<br>        let str = String(raw).trim();<br>        if (!str) return null;<br><br>        let isNegative = false;<br>        if (/^\(.*\)$/.test(str)) {<br>          isNegative = true;<br>          str = str.replace(/^\(|\)$/g, &#39;&#39;).trim();<br>        }<br>        if (str.startsWith(&#39;-&#39;)) {<br>          isNegative = true;<br>          str = str.slice(1).trim();<br>        }<br>        str = str.replace(/[^0-9.\-]/g, &#39;&#39;);<br>        if (!str || str === &#39;.&#39; || str === &#39;-&#39;) return null;<br>        const val = parseFloat(str);<br>        if (!Number.isFinite(val)) return null;<br>        return isNegative ? -Math.abs(val) : val;<br>      },<br><br>      isCwtEntry(fee) {<br>        if (!fee) return false;<br>        if (fee.isCwt === true) return true;<br>        const code = String(fee.code || fee.actualCode || &#39;&#39;).trim().toUpperCase();<br>        const name = String(fee.name || fee.actualName || &#39;&#39;).trim().toUpperCase();<br>        return code === &#39;CWT&#39; || /\bCWT\b|WITHHOLDING/.test(name);<br>      },<br><br>      calculateTotals(fees = []) {<br>        let expectedGross = 0;<br>        let expectedCwt = 0;<br>        let actualGross = 0;<br>        let actualCwt = 0;<br>        let hasMissingActual = false;<br><br>        fees.forEach(fee =&gt; {<br>          const isCwt = this.isCwtEntry(fee);<br>          const expAmt = this.parseAmount(fee.expectedAmount);<br>          const actAmt = this.parseAmount(fee.actualAmount);<br><br>          if (expAmt !== null) {<br>            if (isCwt) {<br>              expectedCwt += Math.abs(expAmt);<br>            } else {<br>              expectedGross += expAmt;<br>            }<br>          }<br><br>          if (actAmt !== null) {<br>            if (isCwt) {<br>              actualCwt += Math.abs(actAmt);<br>            } else {<br>              actualGross += actAmt;<br>            }<br>          } else {<br>            hasMissingActual = true;<br>          }<br>        });<br><br>        expectedGross = Number(expectedGross.toFixed(2));<br>        expectedCwt = Number(expectedCwt.toFixed(2));<br>        actualGross = Number(actualGross.toFixed(2));<br>        actualCwt = Number(actualCwt.toFixed(2));<br><br>        const expectedNet = Number((expectedGross - expectedCwt).toFixed(2));<br>        const actualNet = Number((actualGross - actualCwt).toFixed(2));<br>        const netDifference = Number((actualNet - expectedNet).toFixed(2));<br>        const grossDifference = Number((actualGross - expectedGross).toFixed(2));<br>        const cwtDifference = Number((actualCwt - expectedCwt).toFixed(2));<br><br>        return {<br>          expectedGross,<br>          expectedCwt,<br>          expectedNet,<br>          actualGross,<br>          actualCwt,<br>          actualNet,<br>          grossDifference,<br>          cwtDifference,<br>          netDifference,<br>          hasMissingActual,<br>          formulaExplanation: `Gross Fees (non-CWT sum) - |CWT Deductions| = Net Total (${actualGross.toFixed(2)} - ${actualCwt.toFixed(2)} = ${actualNet.toFixed(2)})`<br>        };<br>      }<br>    };<br><br>    const ValidationEngine = {<br>      normalizeText(str, settings = appState.settings) {<br>        if (str === null || str === undefined) return &#39;&#39;;<br>        let s = String(str);<br>        if (settings.normalizeWhitespace) s = s.replace(/\s+/g, &#39; &#39;).trim();<br>        if (!settings.caseSensitiveNames) s = s.toLowerCase();<br>        return s;<br>      },<br><br>      validateFeeRow(fee, settings = appState.settings) {<br>        const tolerance = Number(settings.numericTolerance ?? 0.01);<br>        const timestamp = new Date().toISOString();<br>        const isCwt = FinancialCalculator.isCwtEntry(fee);<br><br>        const expName = String(fee.expectedName || &#39;&#39;).trim();<br>        const actName = String(fee.actualName || &#39;&#39;).trim();<br>        const expCode = String(fee.expectedCode || &#39;&#39;).trim();<br>        const actCode = String(fee.actualCode || &#39;&#39;).trim();<br>        const expAmt = FinancialCalculator.parseAmount(fee.expectedAmount);<br>        const actAmt = FinancialCalculator.parseAmount(fee.actualAmount);<br><br>        const nameResult = this.compareTextAttribute(&#39;Fee Name&#39;, expName, actName, true, fee.ocrConfidence, settings);<br><br>        let amtStatus = &#39;PENDING&#39;;<br>        let amtDiff = null;<br>        let amtExplanation = &#39;&#39;;<br>        if (expAmt === null &amp;&amp; actAmt === null) {<br>          amtStatus = &#39;NOT APPLICABLE&#39;;<br>          amtExplanation = &#39;No expected or receipt amount configured.&#39;;<br>        } else if (expAmt === null) {<br>          amtStatus = &#39;REVIEW&#39;;<br>          amtExplanation = `Receipt has ${actAmt.toFixed(2)} but Expected Amount is blank.`;<br>        } else if (actAmt === null) {<br>          amtStatus = &#39;PENDING&#39;;<br>          amtExplanation = `Missing receipt amount for expected ${expAmt.toFixed(2)}.`;<br>        } else {<br>          const cmpExp = isCwt ? Math.abs(expAmt) : expAmt;<br>          const cmpAct = isCwt ? Math.abs(actAmt) : actAmt;<br>          amtDiff = Number((cmpAct - cmpExp).toFixed(2));<br>          if (Math.abs(amtDiff) &lt;= tolerance) {<br>            amtStatus = (fee.ocrConfidence !== null &amp;&amp; fee.ocrConfidence !== undefined &amp;&amp; fee.ocrConfidence &lt; settings.autoAcceptConfidenceThreshold &amp;&amp; !fee.manuallyVerified)<br>              ? &#39;REVIEW&#39;<br>              : &#39;PASS&#39;;<br>            amtExplanation = isCwt<br>              ? `CWT deduction magnitude matches (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`<br>              : `Amount matches within ±${tolerance} tolerance (${cmpAct.toFixed(2)} vs ${cmpExp.toFixed(2)}).`;<br>          } else {<br>            amtStatus = &#39;FAIL&#39;;<br>            amtExplanation = `Amount mismatch: Expected ${cmpExp.toFixed(2)}, Receipt ${cmpAct.toFixed(2)}, Difference ${amtDiff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${amtDiff.toFixed(2)}.`;<br>          }<br>        }<br><br>        const codeResult = this.compareTextAttribute(&#39;Fee Code&#39;, expCode, actCode, true, fee.ocrConfidence, settings, true);<br><br>        const statuses = [nameResult.status, amtStatus, codeResult.status];<br>        let overallStatus = &#39;PASS&#39;;<br>        if (statuses.includes(&#39;FAIL&#39;)) overallStatus = &#39;FAIL&#39;;<br>        else if (statuses.includes(&#39;PENDING&#39;)) overallStatus = &#39;PENDING&#39;;<br>        else if (statuses.includes(&#39;REVIEW&#39;)) overallStatus = &#39;REVIEW&#39;;<br>        else if (statuses.every(s =&gt; s === &#39;NOT APPLICABLE&#39;)) overallStatus = &#39;NOT APPLICABLE&#39;;<br><br>        const explanations = [nameResult.explanation, amtExplanation, codeResult.explanation].filter(Boolean);<br><br>        return {<br>          feeId: fee.id,<br>          isCwt,<br>          nameComparison: nameResult,<br>          amountComparison: {<br>            rule: isCwt ? &#39;CWT Absolute Value Match&#39; : `Numeric Tolerance (±${tolerance})`,<br>            expected: expAmt !== null ? expAmt.toFixed(2) : &#39;&#39;,<br>            actual: actAmt !== null ? actAmt.toFixed(2) : &#39;&#39;,<br>            difference: amtDiff !== null ? amtDiff.toFixed(2) : &#39;N/A&#39;,<br>            status: amtStatus,<br>            explanation: amtExplanation<br>          },<br>          codeComparison: codeResult,<br>          status: overallStatus,<br>          explanation: explanations.join(&#39; | &#39;),<br>          ocrConfidence: fee.ocrConfidence ?? null,<br>          sourceLocation: fee.sourceLocation || &#39;Manual / Unmapped&#39;,<br>          evaluatedAt: timestamp<br>        };<br>      },<br><br>      compareTextAttribute(label, expected, actual, required, confidence, settings, exactCode = false) {<br>        if (!expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual: &#39;&#39;,<br>            difference: &#39;0&#39;,<br>            status: required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            explanation: required ? `${label} is missing on both Expected and Receipt.` : `${label} not configured.`<br>          };<br>        }<br>        if (!expected &amp;&amp; actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected: &#39;&#39;,<br>            actual,<br>            difference: &#39;Unconfigured expected&#39;,<br>            status: &#39;REVIEW&#39;,<br>            explanation: `${label} &quot;${actual}&quot; found on receipt, but expected value is empty.`<br>          };<br>        }<br>        if (expected &amp;&amp; !actual) {<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual: &#39;&#39;,<br>            difference: &#39;Missing on receipt&#39;,<br>            status: &#39;PENDING&#39;,<br>            explanation: `Required ${label} &quot;${expected}&quot; is missing from receipt extraction.`<br>          };<br>        }<br><br>        const normExp = exactCode ? expected.trim().toUpperCase() : this.normalizeText(expected, settings);<br>        const normAct = exactCode ? actual.trim().toUpperCase() : this.normalizeText(actual, settings);<br><br>        if (normExp === normAct) {<br>          const lowConf = confidence !== null &amp;&amp; confidence !== undefined &amp;&amp; confidence &lt; settings.autoAcceptConfidenceThreshold;<br>          return {<br>            rule: `${label} Match`,<br>            expected,<br>            actual,<br>            difference: &#39;0&#39;,<br>            status: lowConf ? &#39;REVIEW&#39; : &#39;PASS&#39;,<br>            explanation: lowConf ? `${label} matched (&quot;${actual}&quot;), flagged REVIEW due to ${confidence}% OCR confidence.` : `${label} matched (&quot;${actual}&quot;).`<br>          };<br>        }<br><br>        return {<br>          rule: `${label} Match`,<br>          expected,<br>          actual,<br>          difference: `&quot;${expected}&quot; ≠ &quot;${actual}&quot;`,<br>          status: &#39;FAIL&#39;,<br>          explanation: `${label} mismatch: Expected &quot;${expected}&quot;, Receipt &quot;${actual}&quot;.`<br>        };<br>      },<br><br>      validateField(field, settings = appState.settings) {<br>        if (!field.enabled &amp;&amp; !field.expectedValue &amp;&amp; !field.actualValue) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: &#39;Field disabled / unused.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        const exp = String(field.expectedValue ?? &#39;&#39;).trim();<br>        const act = String(field.actualValue ?? &#39;&#39;).trim();<br><br>        if (!exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: field.required ? &#39;PENDING&#39; : &#39;NOT APPLICABLE&#39;,<br>            difference: &#39;N/A&#39;,<br>            explanation: field.required ? &#39;Required field has no expected or actual value.&#39; : &#39;Optional field blank.&#39;,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (exp &amp;&amp; !act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;PENDING&#39;,<br>            difference: &#39;Missing actual&#39;,<br>            explanation: `Expected &quot;${exp}&quot;, awaiting receipt/system value.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br>        if (!exp &amp;&amp; act) {<br>          return {<br>            fieldId: field.id,<br>            status: &#39;REVIEW&#39;,<br>            difference: &#39;Missing expected&#39;,<br>            explanation: `Actual &quot;${act}&quot; present, but Expected value is blank.`,<br>            evaluatedAt: new Date().toISOString()<br>          };<br>        }<br><br>        if (field.dataType === &#39;Currency&#39; || field.dataType === &#39;Number&#39; || field.dataType === &#39;Percentage&#39;) {<br>          const nExp = FinancialCalculator.parseAmount(exp);<br>          const nAct = FinancialCalculator.parseAmount(act);<br>          const tol = Number(field.tolerance ?? settings.numericTolerance ?? 0.01);<br>          if (nExp !== null &amp;&amp; nAct !== null) {<br>            const diff = Number((nAct - nExp).toFixed(4));<br>            const pass = Math.abs(diff) &lt;= tol;<br>            return {<br>              fieldId: field.id,<br>              status: pass ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>              difference: diff === 0 ? &#39;0.00&#39; : `${diff &gt; 0 ? &#39;+&#39; : &#39;&#39;}${diff.toFixed(2)}`,<br>              explanation: pass ? `Numeric match within ±${tol}.` : `Expected ${nExp}, found ${nAct} (Diff: ${diff}).`,<br>              evaluatedAt: new Date().toISOString()<br>            };<br>          }<br>        }<br><br>        const normExp = this.normalizeText(exp, settings);<br>        const normAct = this.normalizeText(act, settings);<br>        const match = normExp === normAct;<br>        return {<br>          fieldId: field.id,<br>          status: match ? &#39;PASS&#39; : &#39;FAIL&#39;,<br>          difference: match ? &#39;0&#39; : `&quot;${exp}&quot; ≠ &quot;${act}&quot;`,<br>          explanation: match ? &#39;Value matched.&#39; : `Expected &quot;${exp}&quot;, got &quot;${act}&quot;.`,<br>          evaluatedAt: new Date().toISOString()<br>        };<br>      },<br><br>      validateMainPage(mainPage, recordHistory = false) {<br>        if (!mainPage) return null;<br>        const feeResults = (mainPage.fees || []).map(f =&gt; {<br>          const res = this.validateFeeRow(f);<br>          f.lastValidation = res;<br>          return res;<br>        });<br><br>        const fieldResults = (mainPage.fields || []).map(fld =&gt; {<br>          const res = this.validateField(fld);<br>          fld.lastValidation = res;<br>          return res;<br>        });<br><br>        const financials = FinancialCalculator.calculateTotals(mainPage.fees || []);<br><br>        const activeStatuses = [<br>          ...feeResults.map(r =&gt; r.status),<br>          ...fieldResults.filter(r =&gt; r.status !== &#39;NOT APPLICABLE&#39;).map(r =&gt; r.status)<br>        ];<br><br>        let overallStatus = &#39;PENDING&#39;;<br>        if (activeStatuses.length === 0) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;FAIL&#39;)) {<br>          overallStatus = &#39;FAIL&#39;;<br>        } else if (activeStatuses.includes(&#39;PENDING&#39;)) {<br>          overallStatus = &#39;PENDING&#39;;<br>        } else if (activeStatuses.includes(&#39;REVIEW&#39;)) {<br>          overallStatus = &#39;REVIEW&#39;;<br>        } else {<br>          overallStatus = &#39;PASS&#39;;<br>        }<br><br>        const summary = {<br>          overallStatus,<br>          feeResults,<br>          fieldResults,<br>          financials,<br>          counts: {<br>            pass: activeStatuses.filter(s =&gt; s === &#39;PASS&#39;).length,<br>            fail: activeStatuses.filter(s =&gt; s === &#39;FAIL&#39;).length,<br>            review: activeStatuses.filter(s =&gt; s === &#39;REVIEW&#39;).length,<br>            pending: activeStatuses.filter(s =&gt; s === &#39;PENDING&#39;).length<br>          },<br>          validatedAt: new Date().toISOString()<br>        };<br><br>        mainPage.validationSummary = summary;<br><br>        if (recordHistory) {<br>          mainPage.validationHistory = mainPage.validationHistory || [];<br>          mainPage.validationHistory.unshift({<br>            id: &#39;vh_&#39; + Date.now(),<br>            timestamp: summary.validatedAt,<br>            overallStatus: summary.overallStatus,<br>            counts: { ...summary.counts },<br>            netTotal: financials.actualNet<br>          });<br>          if (mainPage.validationHistory.length &gt; 25) mainPage.validationHistory.pop();<br>        }<br><br>        return summary;<br>      }<br>    };<br><br>    /****************************************************************************<br>     * MODULE 3: INTELLIGENT OCR, ROW PARSER &amp; SMART FIELD MAPPING ENGINE<br>     ****************************************************************************/<br>    const RowToFieldsEngine = {<br>      parseSpreadsheetRow(rawText, hasHeaderRow = false) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br>        if (!lines.length) return { headers: [], values: [], delimiter: &#39;None&#39; };<br><br>        const detectDelimiter = (line) =&gt; {<br>          if (line.includes(&#39;\t&#39;)) return &#39;\t&#39;;<br>          if (line.includes(&#39;|&#39;)) return &#39;|&#39;;<br>          if (line.includes(&#39;,&#39;)) return &#39;,&#39;;<br>          return &#39;\t&#39;;<br>        };<br><br>        const splitLine = (line, delim) =&gt; {<br>          if (delim === &#39;,&#39;) {<br>            const matches = line.match(/(&quot;.*?&quot;|[^&quot;,]+)(?=\s*,|\s*$)/g);<br>            return matches ? matches.map(c =&gt; c.replace(/^&quot;|&quot;$/g, &#39;&#39;).trim()) : line.split(&#39;,&#39;).map(c =&gt; c.trim());<br>          }<br>          return line.split(delim).map(c =&gt; c.trim());<br>        };<br><br>        const delim = detectDelimiter(lines[0]);<br>        const delimLabel = delim === &#39;\t&#39; ? &#39;Tab (Excel/Sheets)&#39; : delim === &#39;|&#39; ? &#39;Pipe (|)&#39; : &#39;CSV (,)&#39;;<br><br>        if (hasHeaderRow &amp;&amp; lines.length &gt;= 2) {<br>          return {<br>            headers: splitLine(lines[0], delim),<br>            values: splitLine(lines[1], delim),<br>            delimiter: delimLabel<br>          };<br>        }<br><br>        return {<br>          headers: [],<br>          values: splitLine(lines[0], delim),<br>          delimiter: delimLabel<br>        };<br>      },<br><br>      inferDataType(val) {<br>        const s = String(val || &#39;&#39;).trim();<br>        if (!s) return &#39;Dynamic&#39;;<br>        if (/^\d{4}-\d{2}-\d{2}$/.test(s) || /^\d{1,2}\/\d{1,2}\/\d{2,4}$/.test(s)) return &#39;Date&#39;;<br>        if (/^[$₱€£]?\s*\(?-?\d{1,3}(,\d{3})*(\.\d+)?\)?$/.test(s)) return &#39;Currency&#39;;<br>        if (/^[A-Z]{2,5}$/.test(s)) return &#39;Code&#39;;<br>        return &#39;Dynamic&#39;;<br>      },<br><br>      autoMatchReceiptAgainstExpectedFields(mainPage) {<br>        if (!mainPage || !mainPage.receipt || !mainPage.receipt.ocrRawText) {<br>          return { matched: 0, total: 0 };<br>        }<br>        const rawText = mainPage.receipt.ocrRawText;<br>        const normReceipt = rawText.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>        const compactReceipt = rawText.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br>        const lines = rawText.split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br><br>        let matched = 0;<br>        let total = 0;<br><br>        (mainPage.fields || []).forEach(f =&gt; {<br>          const exp = String(f.expectedValue || &#39;&#39;).trim();<br>          if (!exp) return;<br>          total++;<br><br>          const normExp = exp.replace(/\s+/g, &#39; &#39;).toLowerCase();<br>          const compactExp = exp.replace(/[,$\s₱]/g, &#39;&#39;).toLowerCase();<br><br>          if (normReceipt.includes(normExp) || (compactExp.length &gt;= 2 &amp;&amp; compactReceipt.includes(compactExp))) {<br>            f.actualValue = exp;<br>            f.enabled = true;<br>            matched++;<br>            return;<br>          }<br><br>          const labelNorm = f.name.toLowerCase();<br>          const labelLine = lines.find(l =&gt; l.toLowerCase().includes(labelNorm));<br>          if (labelLine) {<br>            const afterColon = labelLine.split(/[:\-]/).slice(1).join(&#39;:&#39;).trim();<br>            if (afterColon) {<br>              f.actualValue = afterColon;<br>              f.enabled = true;<br>            }<br>          }<br>        });<br><br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { matched, total };<br>      }<br>    };<br><br>    const OcrMappingEngine = {<br>      parseQuickPasteFees(rawText) {<br>        const lines = String(rawText || &#39;&#39;)<br>          .split(/\r?\n/)<br>          .map(l =&gt; l.trim())<br>          .filter(l =&gt; l.length &gt; 0);<br><br>        const parsed = [];<br>        let i = 0;<br><br>        while (i &lt; lines.length) {<br>          const line = lines[i];<br><br>          if (line.includes(&#39;|&#39;) || line.includes(&#39;\t&#39;)) {<br>            const parts = line.split(/\||\t/).map(p =&gt; p.trim()).filter(Boolean);<br>            const name = parts[0] || `Fee ${parsed.length + 1}`;<br>            const amount = parts[1] || &#39;0&#39;;<br>            const isCwt = /\bcwt\b|withholding/i.test(name) || (parts[2] &amp;&amp; parts[2].toUpperCase() === &#39;CWT&#39;);<br>            const code = parts[2] || (isCwt ? &#39;CWT&#39; : &#39;&#39;);<br>            parsed.push({ name, amount, code, isCwt });<br>            i += 1;<br>            continue;<br>          }<br><br>          const name = line;<br>          const amount = lines[i + 1] !== undefined ? lines[i + 1] : &#39;&#39;;<br>          const isCwtName = /\bcwt\b|withholding/i.test(name);<br>          const possibleCode = lines[i + 2];<br><br>          const looksLikeCode = possibleCode !== undefined &amp;&amp;<br>            /^[A-Za-z0-9_-]{1,12}$/.test(possibleCode) &amp;&amp;<br>            !/^\d+(\.\d+)?$/.test(possibleCode);<br><br>          if (looksLikeCode) {<br>            const isCwt = isCwtName || possibleCode.toUpperCase() === &#39;CWT&#39;;<br>            parsed.push({ name, amount, code: possibleCode.toUpperCase(), isCwt });<br>            i += 3;<br>          } else {<br>            parsed.push({<br>              name,<br>              amount,<br>              code: isCwtName ? &#39;CWT&#39; : &#39;&#39;,<br>              isCwt: isCwtName<br>            });<br>            i += 2;<br>          }<br>        }<br><br>        return parsed;<br>      },<br><br>      parseReceiptTextToBlocks(rawText, pageNum = 1, baseConfidence = 92) {<br>        const lines = String(rawText || &#39;&#39;).split(/\r?\n/).map(l =&gt; l.trim()).filter(Boolean);<br>        const blocks = [];<br><br>        lines.forEach((line, idx) =&gt; {<br>          const yPct = Math.min(92, 8 + idx * 7);<br>          const pipeOrCol = line.split(/\||\t|\s{2,}/).map(s =&gt; s.trim()).filter(Boolean);<br>          if (pipeOrCol.length &gt;= 2) {<br>            const name = pipeOrCol[0];<br>            const amtMatch = pipeOrCol.find(p =&gt; /^\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?$/.test(p)) || pipeOrCol[1];<br>            const codeMatch = pipeOrCol.find(p =&gt; /^[A-Z0-9]{2,8}$/.test(p) &amp;&amp; p !== amtMatch) || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;);<br>            blocks.push({<br>              id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>              page: pageNum,<br>              rawLine: line,<br>              detectedName: name,<br>              detectedAmount: amtMatch,<br>              detectedCode: codeMatch,<br>              confidence: baseConfidence,<br>              bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>              mappedToFeeId: null,<br>              status: &#39;UNMAPPED&#39;<br>            });<br>          } else {<br>            const regex = /^(.+?)\s+(\(?-?[$₱€]?\s*\d[\d,]*(\.\d+)?\)?)(?:\s+([A-Za-z0-9_-]{2,10}))?$/;<br>            const m = line.match(regex);<br>            if (m) {<br>              const name = m[1].trim();<br>              const amt = m[2].trim();<br>              const code = (m[4] || (/\bcwt\b/i.test(name) ? &#39;CWT&#39; : &#39;&#39;)).toUpperCase();<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: name,<br>                detectedAmount: amt,<br>                detectedCode: code,<br>                confidence: baseConfidence,<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;UNMAPPED&#39;<br>              });<br>            } else {<br>              blocks.push({<br>                id: `blk_${pageNum}_${idx}_${Date.now()}`,<br>                page: pageNum,<br>                rawLine: line,<br>                detectedName: line,<br>                detectedAmount: &#39;&#39;,<br>                detectedCode: &#39;&#39;,<br>                confidence: Math.max(65, baseConfidence - 10),<br>                bbox: { x: 8, y: yPct, w: 84, h: 5.5 },<br>                mappedToFeeId: null,<br>                status: &#39;TEXT_ONLY&#39;<br>              });<br>            }<br>          }<br>        });<br><br>        return blocks;<br>      },<br><br>      autoMapBlocksToMainPage(mainPage) {<br>        if (!mainPage || !mainPage.receipt) return { autoAccepted: 0, reviewNeeded: 0 };<br>        const blocks = (mainPage.receipt.ocrBlocks || []).filter(b =&gt; b.detectedAmount !== &#39;&#39;);<br>        const fees = mainPage.fees || [];<br>        let autoAccepted = 0;<br>        let reviewNeeded = 0;<br><br>        const usedBlockIds = new Set();<br><br>        fees.forEach((fee, feeIdx) =&gt; {<br>          const expNameNorm = ValidationEngine.normalizeText(fee.expectedName);<br>          const expCodeNorm = String(fee.expectedCode || &#39;&#39;).trim().toUpperCase();<br><br>          let bestBlock = null;<br>          let bestScore = 0;<br><br>          blocks.forEach(blk =&gt; {<br>            if (usedBlockIds.has(blk.id)) return;<br>            let score = 0;<br>            const blkNameNorm = ValidationEngine.normalizeText(blk.detectedName);<br>            const blkCodeNorm = String(blk.detectedCode || &#39;&#39;).trim().toUpperCase();<br><br>            if (expNameNorm &amp;&amp; blkNameNorm === expNameNorm) score += 50;<br>            else if (expNameNorm &amp;&amp; (blkNameNorm.includes(expNameNorm) || expNameNorm.includes(blkNameNorm))) score += 30;<br><br>            if (expCodeNorm &amp;&amp; blkCodeNorm === expCodeNorm) score += 40;<br>            if (blocks.indexOf(blk) === feeIdx) score += 15;<br><br>            if (score &gt; bestScore) {<br>              bestScore = score;<br>              bestBlock = blk;<br>            }<br>          });<br><br>          if (bestBlock &amp;&amp; bestScore &gt;= 30) {<br>            usedBlockIds.add(bestBlock.id);<br>            fee.actualName = bestBlock.detectedName;<br>            fee.actualAmount = bestBlock.detectedAmount;<br>            fee.actualCode = bestBlock.detectedCode || fee.actualCode;<br>            fee.ocrConfidence = bestBlock.confidence;<br>            fee.sourceLocation = `Page ${bestBlock.page} (Y:${Math.round(bestBlock.bbox.y)}%)`;<br>            bestBlock.mappedToFeeId = fee.id;<br><br>            if (bestScore &gt;= 65 &amp;&amp; bestBlock.confidence &gt;= appState.settings.autoAcceptConfidenceThreshold) {<br>              bestBlock.status = &#39;AUTO_ACCEPTED&#39;;<br>              autoAccepted++;<br>            } else {<br>              bestBlock.status = &#39;REVIEW&#39;;<br>              reviewNeeded++;<br>            }<br>          }<br>        });<br><br>        RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(mainPage);<br>        ValidationEngine.validateMainPage(mainPage, true);<br>        return { autoAccepted, reviewNeeded };<br>      },<br><br>      async preprocessImageCanvas(imageDataUrl, opts = {}) {<br>        return new Promise((resolve) =&gt; {<br>          const img = new Image();<br>          img.onload = () =&gt; {<br>            const scale = opts.scale || 1.5;<br>            const canvas = document.createElement(&#39;canvas&#39;);<br>            canvas.width = Math.round(img.width * scale);<br>            canvas.height = Math.round(img.height * scale);<br>            const ctx = canvas.getContext(&#39;2d&#39;);<br>            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>            if (opts.grayscale || opts.contrast || opts.sharpen) {<br>              const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);<br>              const d = imgData.data;<br>              const contrastFactor = opts.contrast ? 1.35 : 1.0;<br>              for (let i = 0; i &lt; d.length; i += 4) {<br>                let r = d[i], g = d[i + 1], b = d[i + 2];<br>                if (opts.grayscale) {<br>                  const gray = 0.299 * r + 0.587 * g + 0.114 * b;<br>                  r = g = b = gray;<br>                }<br>                if (opts.contrast) {<br>                  r = Math.min(255, Math.max(0, (r - 128) * contrastFactor + 128));<br>                  g = Math.min(255, Math.max(0, (g - 128) * contrastFactor + 128));<br>                  b = Math.min(255, Math.max(0, (b - 128) * contrastFactor + 128));<br>                }<br>                d[i] = r; d[i + 1] = g; d[i + 2] = b;<br>              }<br>              ctx.putImageData(imgData, 0, 0);<br>            }<br>            resolve(canvas.toDataURL(&#39;image/png&#39;));<br>          };<br>          img.onerror = () =&gt; resolve(imageDataUrl);<br>          img.src = imageDataUrl;<br>        });<br>      },<br><br>      async runRealTesseractOCR(imageDataUrl, onProgress) {<br>        if (!window.Tesseract) {<br>          throw new Error(&#39;Tesseract.js library is unavailable offline.&#39;);<br>        }<br>        const worker = await Tesseract.createWorker(&#39;eng&#39;, 1, {<br>          logger: m =&gt; {<br>            if (onProgress &amp;&amp; m.status === &#39;recognizing text&#39;) {<br>              onProgress(Math.round((m.progress || 0) * 100));<br>            }<br>          }<br>        });<br>        const ret = await worker.recognize(imageDataUrl);<br>        await worker.terminate();<br>        return {<br>          text: ret.data.text || &#39;&#39;,<br>          confidence: Math.round(ret.data.confidence || 85)<br>        };<br>      }<br>    };<br><br>    /****************************************************************************<br>     * SAMPLE DATA &amp; SVG RECEIPT GENERATOR (100% SELF-CONTAINED)<br>     ****************************************************************************/<br>    function generateSyntheticReceiptSvgDataUrl({ title, invoiceNo, date, lines, footer }) {<br>      const lineRows = lines.map((l, idx) =&gt; {<br>        const y = 135 + idx * 32;<br>        return `<br>          &lt;text x=&quot;28&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; fill=&quot;#1e293b&quot;&gt;${escapeHtml(l.label)}&lt;/text&gt;<br>          &lt;text x=&quot;315&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(l.amount)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;${y}&quot; font-family=&quot;monospace&quot; font-size=&quot;13&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#4f46e5&quot;&gt;${escapeHtml(l.code)}&lt;/text&gt;<br>        `;<br>      }).join(&#39;&#39;);<br><br>      const svg = `<br>        &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;400&quot; height=&quot;420&quot; viewBox=&quot;0 0 400 420&quot;&gt;<br>          &lt;rect width=&quot;400&quot; height=&quot;420&quot; fill=&quot;#ffffff&quot; rx=&quot;8&quot;/&gt;<br>          &lt;rect x=&quot;12&quot; y=&quot;12&quot; width=&quot;376&quot; height=&quot;396&quot; fill=&quot;none&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1.5&quot; stroke-dasharray=&quot;4 3&quot; rx=&quot;6&quot;/&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;45&quot; font-family=&quot;sans-serif&quot; font-size=&quot;16&quot; font-weight=&quot;800&quot; text-anchor=&quot;middle&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(title)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;66&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;middle&quot; fill=&quot;#64748b&quot;&gt;OFFICIAL EIS ELECTRONIC RECEIPT&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;80&quot; x2=&quot;376&quot; y2=&quot;80&quot; stroke=&quot;#94a3b8&quot; stroke-width=&quot;1&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; fill=&quot;#334155&quot;&gt;REF: ${escapeHtml(invoiceNo)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;100&quot; font-family=&quot;monospace&quot; font-size=&quot;12&quot; text-anchor=&quot;end&quot; fill=&quot;#334155&quot;&gt;${escapeHtml(date)}&lt;/text&gt;<br>          &lt;line x1=&quot;24&quot; y1=&quot;112&quot; x2=&quot;376&quot; y2=&quot;112&quot; stroke=&quot;#cbd5e1&quot; stroke-width=&quot;1&quot;/&gt;<br>          ${lineRows}<br>          &lt;line x1=&quot;24&quot; y1=&quot;315&quot; x2=&quot;376&quot; y2=&quot;315&quot; stroke=&quot;#0f172a&quot; stroke-width=&quot;1.5&quot;/&gt;<br>          &lt;text x=&quot;28&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;14&quot; font-weight=&quot;bold&quot; fill=&quot;#0f172a&quot;&gt;${escapeHtml(footer.label)}&lt;/text&gt;<br>          &lt;text x=&quot;372&quot; y=&quot;342&quot; font-family=&quot;monospace&quot; font-size=&quot;15&quot; font-weight=&quot;bold&quot; text-anchor=&quot;end&quot; fill=&quot;#059669&quot;&gt;${escapeHtml(footer.value)}&lt;/text&gt;<br>          &lt;text x=&quot;200&quot; y=&quot;385&quot; font-family=&quot;monospace&quot; font-size=&quot;10&quot; text-anchor=&quot;middle&quot; fill=&quot;#94a3b8&quot;&gt;EIS-AUTH-HASH: 9F82-77C1-NEXUS-QA&lt;/text&gt;<br>        &lt;/svg&gt;<br>      `;<br>      return &#39;data:image/svg+xml;charset=utf-8,&#39; + encodeURIComponent(svg);<br>    }<br><br>    function createDefaultFields(count = 50) {<br>      const presets = [<br>        { name: &#39;Invoice / Receipt Number&#39;, type: &#39;Reference&#39;, req: true },<br>        { name: &#39;Transaction Date&#39;, type: &#39;Date&#39;, req: true },<br>        { name: &#39;Merchant / Taxpayer TIN&#39;, type: &#39;Reference&#39;, req: false },<br>        { name: &#39;Currency Code&#39;, type: &#39;Code&#39;, req: true },<br>        { name: &#39;Gross Settlement Total&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;CWT Withholding Amount&#39;, type: &#39;Currency&#39;, req: false },<br>        { name: &#39;Net Payable Amount&#39;, type: &#39;Currency&#39;, req: true },<br>        { name: &#39;EIS Acknowledgement ID&#39;, type: &#39;Reference&#39;, req: false }<br>      ];<br>      const list = [];<br>      for (let i = 1; i &lt;= count; i++) {<br>        const p = presets[i - 1];<br>        list.push({<br>          id: `fld_${i}_${Math.random().toString(36).slice(2, 6)}`,<br>          number: i,<br>          name: p ? p.name : `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: p ? p.type : &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: p ? p.req : false,<br>          tolerance: 0.01,<br>          description: p ? `Standard EIS ${p.name}` : `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: i &lt;= 8<br>        });<br>      }<br>      return list;<br>    }<br><br>    function createSampleSeedState() {<br>      const now = new Date().toISOString();<br><br>      // Page 1: PASS (Fee 1 = 1000/NC, Fee 2 = 250/IC, CWT = -50 -&gt; Gross 1250, CWT 50, Net 1200)<br>      const p1ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;MANILA LOGISTICS &amp; FREIGHT CORP.&#39;,<br>        invoiceNo: &#39;EIS-2026-1001&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Fee 1 Charge&#39;, amount: &#39;1,000.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Fee 2 Charge&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;-50.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,200.00&#39; }<br>      });<br><br>      const p1RawText = `Fee 1 Charge | 1000.00 | NC\nFee 2 Charge | 250.00 | IC\nCWT | -50.00 | CWT`;<br>      const page1 = {<br>        id: &#39;mp_manila_01&#39;,<br>        name: &#39;MP-01: Manila HQ Settlement&#39;,<br>        description: &#39;Standard two-fee transaction with negative CWT notation (-50).&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;EIS-2026-1001\t2026-11-19\t004-892-110-000\tPHP\t1250.00\t50.00\t1200.00&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_01&#39;,<br>          fileName: &#39;manila_eis_receipt_1001.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p1ReceiptImg],<br>          ocrRawText: p1RawText,<br>          ocrConfidence: 96,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p1RawText, 1, 96),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_1a&#39;, expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1 Charge&#39;, actualAmount: &#39;1000.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 97, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_1b&#39;, expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 2 Charge&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 95, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_1c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;-50&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;-50.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 96, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_1&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#10b981&#39;, label: &#39;QA-1: Fee 1 Verified&#39;, comment: &#39;Matches 1000.00 NC&#39;, fieldRef: &#39;Fee 1 Charge&#39;, testCaseId: &#39;TC-001&#39;, defectId: &#39;&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page1.fields[0].expectedValue = &#39;EIS-2026-1001&#39;; page1.fields[0].actualValue = &#39;EIS-2026-1001&#39;;<br>      page1.fields[1].expectedValue = &#39;2026-11-19&#39;; page1.fields[1].actualValue = &#39;2026-11-19&#39;;<br>      page1.fields[2].expectedValue = &#39;004-892-110-000&#39;; page1.fields[2].actualValue = &#39;004-892-110-000&#39;;<br>      page1.fields[3].expectedValue = &#39;PHP&#39;; page1.fields[3].actualValue = &#39;PHP&#39;;<br>      page1.fields[4].expectedValue = &#39;1250.00&#39;; page1.fields[4].actualValue = &#39;1250.00&#39;;<br>      page1.fields[5].expectedValue = &#39;50.00&#39;; page1.fields[5].actualValue = &#39;50.00&#39;;<br>      page1.fields[6].expectedValue = &#39;1200.00&#39;; page1.fields[6].actualValue = &#39;1200.00&#39;;<br><br>      // Page 2: FAIL (Fee 1 Expected 1000 vs Receipt 1200 -&gt; Diff +200, CWT = (50))<br>      const p2ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;CEBU PORT TERMINAL SERVICES&#39;,<br>        invoiceNo: &#39;EIS-2026-2044&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Terminal Handling&#39;, amount: &#39;1,200.00&#39;, code: &#39;NC&#39; },<br>          { label: &#39;Documentation Fee&#39;, amount: &#39;250.00&#39;, code: &#39;IC&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;(50.00)&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 1,400.00&#39; }<br>      });<br>      const p2RawText = `Terminal Handling | 1200.00 | NC\nDocumentation Fee | 250.00 | IC\nCWT | (50.00) | CWT`;<br>      const page2 = {<br>        id: &#39;mp_cebu_02&#39;,<br>        name: &#39;MP-02: Cebu Hub Clearance&#39;,<br>        description: &#39;Demonstrates Fee 1 amount mismatch (Expected 1000 vs Receipt 1200) &amp; parenthetical CWT (50).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_02&#39;,<br>          fileName: &#39;cebu_eis_receipt_2044.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p2ReceiptImg],<br>          ocrRawText: p2RawText,<br>          ocrConfidence: 93,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p2RawText, 1, 93),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_2a&#39;, expectedName: &#39;Terminal Handling&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Terminal Handling&#39;, actualAmount: &#39;1200.00&#39;, actualCode: &#39;NC&#39;, isCwt: false, ocrConfidence: 94, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_2b&#39;, expectedName: &#39;Documentation Fee&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Documentation Fee&#39;, actualAmount: &#39;250.00&#39;, actualCode: &#39;IC&#39;, isCwt: false, ocrConfidence: 93, sourceLocation: &#39;Page 1 Row 2&#39; },<br>          { id: &#39;fee_2c&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;(50)&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;(50.00)&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 92, sourceLocation: &#39;Page 1 Row 3&#39; }<br>        ],<br>        annotations: [<br>          { id: &#39;ann_2&#39;, qaLabel: 1, type: &#39;rect&#39;, x: 18, y: 120, w: 360, h: 36, color: &#39;#ef4444&#39;, label: &#39;QA-1: Overcharge +200&#39;, comment: &#39;Expected 1000.00, Receipt shows 1200.00&#39;, fieldRef: &#39;Terminal Handling&#39;, testCaseId: &#39;TC-002&#39;, defectId: &#39;DEF-101&#39; }<br>        ],<br>        validationHistory: []<br>      };<br>      page2.fields[0].expectedValue = &#39;EIS-2026-2044&#39;; page2.fields[0].actualValue = &#39;EIS-2026-2044&#39;;<br>      page2.fields[3].expectedValue = &#39;PHP&#39;; page2.fields[3].actualValue = &#39;PHP&#39;;<br><br>      // Page 3: PENDING (Missing Fee Code on Inspection Fee -&gt; verifies missing info never auto-passes)<br>      const p3ReceiptImg = generateSyntheticReceiptSvgDataUrl({<br>        title: &#39;DAVAO AGRI-EXPORT GATEWAY&#39;,<br>        invoiceNo: &#39;EIS-2026-3099&#39;,<br>        date: &#39;2026-11-19&#39;,<br>        lines: [<br>          { label: &#39;Export Inspection&#39;, amount: &#39;800.00&#39;, code: &#39;&#39; },<br>          { label: &#39;CWT&#39;, amount: &#39;40.00&#39;, code: &#39;CWT&#39; }<br>        ],<br>        footer: { label: &#39;NET AMOUNT DUE&#39;, value: &#39;PHP 760.00&#39; }<br>      });<br>      const p3RawText = `Export Inspection | 800.00\nCWT | 40.00 | CWT`;<br>      const page3 = {<br>        id: &#39;mp_davao_03&#39;,<br>        name: &#39;MP-03: Davao Branch Export&#39;,<br>        description: &#39;Demonstrates missing required fee code evaluation (PENDING rather than false PASS).&#39;,<br>        rowPasteEnabled: false,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: {<br>          id: &#39;rec_03&#39;,<br>          fileName: &#39;davao_eis_receipt_3099.svg&#39;,<br>          mimeType: &#39;image/svg+xml&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [p3ReceiptImg],<br>          ocrRawText: p3RawText,<br>          ocrConfidence: 89,<br>          ocrBlocks: OcrMappingEngine.parseReceiptTextToBlocks(p3RawText, 1, 89),<br>          history: [{ action: &#39;Initial Upload &amp; OCR Extraction&#39;, timestamp: now }]<br>        },<br>        fields: createDefaultFields(),<br>        fees: [<br>          { id: &#39;fee_3a&#39;, expectedName: &#39;Export Inspection&#39;, expectedAmount: &#39;800&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Export Inspection&#39;, actualAmount: &#39;800.00&#39;, actualCode: &#39;&#39;, isCwt: false, ocrConfidence: 89, sourceLocation: &#39;Page 1 Row 1&#39; },<br>          { id: &#39;fee_3b&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;40&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;40.00&#39;, actualCode: &#39;CWT&#39;, isCwt: true, ocrConfidence: 91, sourceLocation: &#39;Page 1 Row 2&#39; }<br>        ],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      page3.fields[0].expectedValue = &#39;EIS-2026-3099&#39;; page3.fields[0].actualValue = &#39;EIS-2026-3099&#39;;<br><br>      [page1, page2, page3].forEach(p =&gt; ValidationEngine.validateMainPage(p, true));<br><br>      const sampleProject = {<br>        id: &#39;proj_eis_2026_q4&#39;,<br>        name: &#39;EIS Q4 Release — Core Settlement &amp; CWT Audit&#39;,<br>        reference: &#39;PRJ-EIS-2026-04&#39;,<br>        description: &#39;End-to-end EIS electronic receipt validation, CWT deduction accuracy, and QA screenshot evidence suite.&#39;,<br>        owner: &#39;A. Reyes (Lead QA Analyst)&#39;,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [page1, page2, page3],<br>        screenshots: [<br>          {<br>            id: &#39;scr_01&#39;,<br>            name: &#39;EIS_Portal_Manila_Settlement.svg&#39;,<br>            dataUrl: p1ReceiptImg,<br>            capturedAt: now,<br>            source: &#39;Sample Evidence&#39;,<br>            isMerged: false<br>          }<br>        ],<br>        mergeHistory: [],<br>        testCases: [<br>          {<br>            id: &#39;TC-001&#39;,<br>            title: &#39;Verify Standard 2-Fee Gross &amp; Negative CWT (-50) Net Settlement&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Manila HQ Settlement Main Page configured with Fee 1 (1000/NC), Fee 2 (250/IC), CWT (-50).&#39;,<br>            steps: &#39;1. Upload official EIS receipt.\n2. Run OCR extraction &amp; auto-mapping.\n3. Verify Gross = 1250.00, CWT = 50.00, Net = 1200.00.&#39;,<br>            expectedResult: &#39;All fee names, amounts, and codes PASS; Net Total equals 1200.00.&#39;,<br>            actualResult: &#39;Gross 1250.00 - CWT 50.00 = Net 1200.00. Status: PASS.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;A. Reyes&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_manila_01&#39;,<br>            linkedDefectId: &#39;&#39;<br>          },<br>          {<br>            id: &#39;TC-002&#39;,<br>            title: &#39;Detect Fee 1 Overcharge Mismatch &amp; Parenthetical CWT (50)&#39;,<br>            module: &#39;EIS Fee &amp; CWT Engine&#39;,<br>            preconditions: &#39;Cebu Hub Main Page expects Terminal Handling = 1000.00 NC.&#39;,<br>            steps: &#39;1. Attach Cebu receipt showing 1200.00 NC.\n2. Execute validation engine.&#39;,<br>            expectedResult: &#39;System flags FAIL with +200.00 difference while deducting 50.00 for (50) CWT.&#39;,<br>            actualResult: &#39;Flagged FAIL (+200.00 variance). Defect DEF-101 logged.&#39;,<br>            status: &#39;FAIL&#39;,<br>            priority: &#39;Critical&#39;,<br>            tester: &#39;A. Reyes&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            linkedDefectId: &#39;DEF-101&#39;<br>          },<br>          {<br>            id: &#39;TC-003&#39;,<br>            title: &#39;Verify Missing Fee Code Triggers PENDING Instead of False PASS&#39;,<br>            module: &#39;Validation Rules&#39;,<br>            preconditions: &#39;Davao Branch receipt omits IC fee code on Export Inspection.&#39;,<br>            steps: &#39;1. Validate Davao Branch Main Page.&#39;,<br>            expectedResult: &#39;Status evaluates to PENDING until code is verified.&#39;,<br>            actualResult: &#39;Evaluated as PENDING as expected.&#39;,<br>            status: &#39;PASS&#39;,<br>            priority: &#39;High&#39;,<br>            tester: &#39;A. Reyes&#39;,<br>            executionDate: now.slice(0, 10),<br>            mainPageId: &#39;mp_davao_03&#39;,<br>            linkedDefectId: &#39;&#39;<br>          }<br>        ],<br>        defects: [<br>          {<br>            id: &#39;DEF-101&#39;,<br>            title: &#39;Terminal Handling Fee billed at 1,200.00 instead of contracted 1,000.00 (+200.00 variance)&#39;,<br>            description: &#39;EIS receipt #EIS-2026-2044 reflects 1,200.00 NC for Terminal Handling, exceeding Main Page expected tariff by 200.00.&#39;,<br>            stepsToReproduce: &#39;1. Open MP-02: Cebu Hub Clearance.\n2. Compare Fee 1 expected (1000.00 NC) against uploaded receipt.\n3. Observe +200.00 variance.&#39;,<br>            expectedResult: &#39;Terminal Handling = 1,000.00 NC; Net Payable = 1,200.00&#39;,<br>            actualResult: &#39;Terminal Handling = 1,200.00 NC; Net Payable = 1,400.00&#39;,<br>            severity: &#39;High&#39;,<br>            priority: &#39;P1&#39;,<br>            status: &#39;Open&#39;,<br>            environment: &#39;EIS Staging v4.12&#39;,<br>            linkedTestCaseId: &#39;TC-002&#39;,<br>            mainPageId: &#39;mp_cebu_02&#39;,<br>            annotationRef: &#39;QA-1: Overcharge +200&#39;,<br>            dateReported: now.slice(0, 10),<br>            assignee: &#39;M. Santos (Billing Dev)&#39;<br>          }<br>        ],<br>        activityLog: [<br>          { timestamp: now, action: &#39;Initialized Workspace&#39;, detail: &#39;Loaded sample project PRJ-EIS-2026-04 with 3 isolated Main Pages.&#39; }<br>        ]<br>      };<br><br>      const defaultTemplates = [<br>        {<br>          id: &#39;tpl_standard_cwt&#39;,<br>          name: &#39;Standard 2-Fee + CWT Settlement&#39;,<br>          description: &#39;Includes Fee 1 (NC), Fee 2 (IC), and CWT deduction rule.&#39;,<br>          fees: [<br>            { expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, isCwt: false },<br>            { expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;50&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        },<br>        {<br>          id: &#39;tpl_brokerage_3fee&#39;,<br>          name: &#39;Customs Brokerage 3-Fee + 2% CWT&#39;,<br>          description: &#39;Brokerage, Arrastre, Wharfage, and Withholding Tax.&#39;,<br>          fees: [<br>            { expectedName: &#39;Brokerage Fee&#39;, expectedAmount: &#39;2500&#39;, expectedCode: &#39;BRK&#39;, isCwt: false },<br>            { expectedName: &#39;Arrastre Charge&#39;, expectedAmount: &#39;850&#39;, expectedCode: &#39;ARR&#39;, isCwt: false },<br>            { expectedName: &#39;Wharfage Fee&#39;, expectedAmount: &#39;400&#39;, expectedCode: &#39;WHF&#39;, isCwt: false },<br>            { expectedName: &#39;CWT&#39;, expectedAmount: &#39;75&#39;, expectedCode: &#39;CWT&#39;, isCwt: true }<br>          ]<br>        }<br>      ];<br><br>      return {<br>        schemaVersion: APP_SCHEMA_VERSION,<br>        theme: &#39;dark&#39;,<br>        sidebarCollapsed: false,<br>        activeModule: &#39;dashboard&#39;,<br>        activeProjectId: sampleProject.id,<br>        activeMainPageId: page1.id,<br>        lastSavedAt: now,<br>        settings: {<br>          numericTolerance: 0.01,<br>          caseSensitiveNames: false,<br>          normalizeWhitespace: true,<br>          autoAcceptConfidenceThreshold: 88,<br>          cwtDeductionMode: &#39;absolute&#39;,<br>          qaLabelMax: 200,<br>          qaAutoIncrement: true<br>        },<br>        templates: defaultTemplates,<br>        projects: [sampleProject],<br>        ui: {<br>          viewerZoom: 1,<br>          viewerRotation: 0,<br>          showOcrBoxes: true,<br>          selectedComparisonRowId: null,<br>          selectedScreenshotsForMerge: [],<br>          annotationTool: &#39;rect&#39;,<br>          annotationColor: &#39;#ef4444&#39;,<br>          selectedAnnotationId: null,<br>          selectedQaLabel: 1<br>        }<br>      };<br>    }<br><br>    /****************************************************************************<br>     * STATE HELPERS &amp; NAVIGATION<br>     ****************************************************************************/<br>    function getActiveProject() {<br>      return appState.projects.find(p =&gt; p.id === appState.activeProjectId) || appState.projects[0] || null;<br>    }<br><br>    function getActiveMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj || !proj.mainPages || proj.mainPages.length === 0) return null;<br>      return proj.mainPages.find(mp =&gt; mp.id === appState.activeMainPageId) || proj.mainPages[0];<br>    }<br><br>    function logActivity(action, detail) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.activityLog = proj.activityLog || [];<br>      proj.activityLog.unshift({ timestamp: new Date().toISOString(), action, detail });<br>      if (proj.activityLog.length &gt; 40) proj.activityLog.pop();<br>    }<br><br>    function navigateTo(moduleId) {<br>      appState.activeModule = moduleId;<br>      closeMobileSidebar();<br>      renderApp();<br>    }<br><br>    function switchActiveProject(projectId) {<br>      appState.activeProjectId = projectId;<br>      const proj = getActiveProject();<br>      appState.activeMainPageId = proj &amp;&amp; proj.mainPages[0] ? proj.mainPages[0].id : null;<br>      scheduleAutosave(&#39;Switched active project&#39;);<br>      renderApp();<br>    }<br><br>    function switchActiveMainPage(pageId) {<br>      appState.activeMainPageId = pageId;<br>      appState.ui.selectedComparisonRowId = null;<br>      appState.ui.selectedAnnotationId = null;<br>      scheduleAutosave(&#39;Switched Main Page&#39;);<br>      renderApp();<br>    }<br><br>    function toggleTheme() {<br>      appState.theme = appState.theme === &#39;dark&#39; ? &#39;light&#39; : &#39;dark&#39;;<br>      applyTheme();<br>      scheduleAutosave(&#39;Theme changed&#39;);<br>    }<br><br>    function applyTheme() {<br>      const html = document.documentElement;<br>      if (appState.theme === &#39;dark&#39;) html.classList.add(&#39;dark&#39;);<br>      else html.classList.remove(&#39;dark&#39;);<br>    }<br><br>    function toggleSidebarCollapse() {<br>      appState.sidebarCollapsed = !appState.sidebarCollapsed;<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const labels = document.querySelectorAll(&#39;.sidebar-label&#39;);<br>      if (appState.sidebarCollapsed) {<br>        sidebar.classList.remove(&#39;lg:w-64&#39;);<br>        sidebar.classList.add(&#39;lg:w-20&#39;);<br>        labels.forEach(el =&gt; el.classList.add(&#39;lg:hidden&#39;));<br>      } else {<br>        sidebar.classList.remove(&#39;lg:w-20&#39;);<br>        sidebar.classList.add(&#39;lg:w-64&#39;);<br>        labels.forEach(el =&gt; el.classList.remove(&#39;lg:hidden&#39;));<br>      }<br>    }<br><br>    function toggleMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      const isOpen = !sidebar.classList.contains(&#39;-translate-x-full&#39;);<br>      if (isOpen) {<br>        closeMobileSidebar();<br>      } else {<br>        sidebar.classList.remove(&#39;-translate-x-full&#39;);<br>        backdrop.classList.remove(&#39;hidden&#39;);<br>      }<br>    }<br><br>    function closeMobileSidebar() {<br>      const sidebar = document.getElementById(&#39;sidebar&#39;);<br>      const backdrop = document.getElementById(&#39;mobile-backdrop&#39;);<br>      if (sidebar) sidebar.classList.add(&#39;-translate-x-full&#39;);<br>      if (backdrop) backdrop.classList.add(&#39;hidden&#39;);<br>    }<br><br>    function showToast(message, type = &#39;info&#39;) {<br>      const container = document.getElementById(&#39;toast-container&#39;);<br>      if (!container) return;<br>      const colors = {<br>        success: &#39;bg-emerald-600 text-white border-emerald-500&#39;,<br>        error: &#39;bg-rose-600 text-white border-rose-500&#39;,<br>        warning: &#39;bg-amber-500 text-slate-950 border-amber-400&#39;,<br>        info: &#39;bg-slate-800 text-white border-slate-700&#39;<br>      };<br>      const el = document.createElement(&#39;div&#39;);<br>      el.className = `pointer-events-auto px-4 py-3 rounded-xl shadow-xl border text-xs font-medium flex items-center justify-between gap-3 transition-all ${colors[type] || colors.info}`;<br>      el.innerHTML = `&lt;span&gt;${escapeHtml(message)}&lt;/span&gt;&lt;button onclick=&quot;this.parentElement.remove()&quot; class=&quot;opacity-75 hover:opacity-100&quot;&gt;&amp;times;&lt;/button&gt;`;<br>      container.appendChild(el);<br>      setTimeout(() =&gt; { if (el.parentElement) el.remove(); }, 4200);<br>    }<br><br>    function openModal({ title, bodyHtml, footerHtml = &#39;&#39; }) {<br>      document.getElementById(&#39;modal-title&#39;).textContent = title;<br>      document.getElementById(&#39;modal-body&#39;).innerHTML = bodyHtml;<br>      document.getElementById(&#39;modal-footer&#39;).innerHTML = footerHtml;<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.remove(&#39;hidden&#39;);<br>      overlay.classList.add(&#39;flex&#39;);<br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    function closeModal() {<br>      const overlay = document.getElementById(&#39;modal-overlay&#39;);<br>      overlay.classList.add(&#39;hidden&#39;);<br>      overlay.classList.remove(&#39;flex&#39;);<br>    }<br><br>    function statusBadge(status) {<br>      const s = String(status || &#39;PENDING&#39;).toUpperCase();<br>      const styles = {<br>        PASS: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;,<br>        FAIL: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        REVIEW: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        PENDING: &#39;bg-sky-500/15 text-sky-600 dark:text-sky-400 border-sky-500/30&#39;,<br>        &#39;NOT APPLICABLE&#39;: &#39;bg-slate-500/15 text-slate-500 dark:text-slate-400 border-slate-500/30&#39;,<br>        OPEN: &#39;bg-rose-500/15 text-rose-600 dark:text-rose-400 border-rose-500/30&#39;,<br>        &#39;IN PROGRESS&#39;: &#39;bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30&#39;,<br>        FIXED: &#39;bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border-indigo-500/30&#39;,<br>        RETEST: &#39;bg-purple-500/15 text-purple-600 dark:text-purple-400 border-purple-500/30&#39;,<br>        CLOSED: &#39;bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39;<br>      };<br>      return `&lt;span class=&quot;inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide border ${styles[s] || styles.PENDING}&quot;&gt;${escapeHtml(s)}&lt;/span&gt;`;<br>    }<br><br>    function runActivePageValidation(notify = false) {<br>      const mp = getActiveMainPage();<br>      if (!mp) return showToast(&#39;No active Main Page selected.&#39;, &#39;warning&#39;);<br>      const res = ValidationEngine.validateMainPage(mp, true);<br>      logActivity(&#39;Validated Main Page&#39;, `${mp.name} → ${res.overallStatus}`);<br>      scheduleAutosave(&#39;Validated Main Page&#39;);<br>      if (notify) showToast(`${mp.name}: ${res.overallStatus} (${res.counts.pass} Pass, ${res.counts.fail} Fail, ${res.counts.review} Review, ${res.counts.pending} Pending)`, res.overallStatus === &#39;PASS&#39; ? &#39;success&#39; : res.overallStatus === &#39;FAIL&#39; ? &#39;error&#39; : &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * SHELL &amp; NAVIGATION RENDERER<br>     ****************************************************************************/<br>    function renderShellChrome() {<br>      const projSelect = document.getElementById(&#39;sidebar-project-select&#39;);<br>      if (projSelect) {<br>        projSelect.innerHTML = appState.projects.map(p =&gt;<br>          `&lt;option value=&quot;${escapeHtml(p.id)}&quot; ${p.id === appState.activeProjectId ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(p.name)} ${p.archived ? &#39;(Archived)&#39; : &#39;&#39;}&lt;/option&gt;`<br>        ).join(&#39;&#39;);<br>      }<br><br>      const nav = document.getElementById(&#39;sidebar-nav&#39;);<br>      if (nav) {<br>        nav.innerHTML = MODULES.map(m =&gt; {<br>          const active = appState.activeModule === m.id;<br>          return `<br>            &lt;button onclick=&quot;navigateTo(&#39;${m.id}&#39;)&quot; class=&quot;w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-xs font-semibold transition ${<br>              active<br>                ? &#39;bg-brand-600 text-white shadow-sm&#39;<br>                : &#39;text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800/80&#39;<br>            }&quot;&gt;<br>              &lt;i data-lucide=&quot;${m.icon}&quot; class=&quot;w-4 h-4 shrink-0&quot;&gt;&lt;/i&gt;<br>              &lt;span class=&quot;sidebar-label truncate&quot;&gt;${escapeHtml(m.label)}&lt;/span&gt;<br>            &lt;/button&gt;<br>          `;<br>        }).join(&#39;&#39;);<br>      }<br><br>      const activeMod = MODULES.find(m =&gt; m.id === appState.activeModule) || MODULES[0];<br>      const topTitle = document.getElementById(&#39;topbar-title&#39;);<br>      const topSub = document.getElementById(&#39;topbar-subtitle&#39;);<br>      if (topTitle) topTitle.textContent = activeMod.label;<br>      if (topSub) topSub.textContent = activeMod.subtitle;<br>    }<br><br>    function renderApp() {<br>      applyTheme();<br>      renderShellChrome();<br>      const viewport = document.getElementById(&#39;main-viewport&#39;);<br>      if (!viewport) return;<br><br>      Object.values(chartInstances).forEach(c =&gt; { try { c.destroy(); } catch (e) {} });<br>      chartInstances = {};<br><br>      switch (appState.activeModule) {<br>        case &#39;dashboard&#39;: viewport.innerHTML = renderDashboardModule(); initDashboardCharts(); break;<br>        case &#39;projects&#39;: viewport.innerHTML = renderProjectsModule(); break;<br>        case &#39;main-pages&#39;: viewport.innerHTML = renderMainPagesModule(); break;<br>        case &#39;validation&#39;: viewport.innerHTML = renderValidationWorkspaceModule(); break;<br>        case &#39;ocr-intel&#39;: viewport.innerHTML = renderOcrIntelligenceModule(); break;<br>        case &#39;screenshots&#39;: viewport.innerHTML = renderScreenshotStudioModule(); initAnnotationCanvasEvents(); break;<br>        case &#39;test-cases&#39;: viewport.innerHTML = renderTestCasesModule(); break;<br>        case &#39;defects&#39;: viewport.innerHTML = renderDefectsModule(); break;<br>        case &#39;reports&#39;: viewport.innerHTML = renderReportsModule(); break;<br>        case &#39;templates&#39;: viewport.innerHTML = renderTemplatesModule(); break;<br>        case &#39;settings&#39;: viewport.innerHTML = renderSettingsModule(); break;<br>        default: viewport.innerHTML = renderDashboardModule();<br>      }<br><br>      if (window.lucide) lucide.createIcons();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 1 VIEW: DASHBOARD<br>     ****************************************************************************/<br>    function renderDashboardModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return `&lt;div class=&quot;p-8 text-center&quot;&gt;No project found. Create one in Projects.&lt;/div&gt;`;<br><br>      const totalProjects = appState.projects.length;<br>      const totalMainPages = proj.mainPages.length;<br>      const totalReceipts = proj.mainPages.filter(mp =&gt; mp.receipt).length;<br>      const totalScreenshots = (proj.screenshots || []).length;<br><br>      let passCount = 0, failCount = 0, reviewCount = 0, pendingCount = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>        const c = mp.validationSummary.counts;<br>        passCount += c.pass;<br>        failCount += c.fail;<br>        reviewCount += c.review;<br>        pendingCount += c.pending;<br>      });<br>      const totalChecks = passCount + failCount + reviewCount + pendingCount;<br><br>      const totalTC = (proj.testCases || []).length;<br>      const passedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>      const failedTC = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>      const openDefects = (proj.defects || []).filter(d =&gt; d.status !== &#39;Closed&#39; &amp;&amp; d.status !== &#39;Rejected&#39;).length;<br><br>      return `<br>        &lt;div class=&quot;bg-gradient-to-r from-brand-600 via-indigo-600 to-violet-700 rounded-2xl p-6 text-white shadow-lg flex flex-col lg:flex-row lg:items-center justify-between gap-4&quot;&gt;<br>          &lt;div class=&quot;space-y-1&quot;&gt;<br>            &lt;div class=&quot;inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-white/15 text-xs font-semibold&quot;&gt;<br>              &lt;span&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>              &lt;span&gt;•&lt;/span&gt;<br>              &lt;span&gt;${escapeHtml(proj.status)}&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;h2 class=&quot;text-xl sm:text-2xl font-extrabold tracking-tight&quot;&gt;${escapeHtml(proj.name)}&lt;/h2&gt;<br>            &lt;p class=&quot;text-xs sm:text-sm text-indigo-100 max-w-2xl&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap gap-2.5 shrink-0&quot;&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;validation&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white text-brand-700 font-bold text-xs shadow hover:bg-indigo-50 transition&quot;&gt;<br>              Open Side-by-Side Validator<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;px-4 py-2.5 rounded-xl bg-white/15 hover:bg-white/25 text-white font-semibold text-xs border border-white/20 transition&quot;&gt;<br>              Configure Main Pages (${totalMainPages})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3.5&quot;&gt;<br>          ${renderKpiCard(&#39;Projects&#39;, totalProjects, &#39;folder-kanban&#39;, &#39;text-brand-500&#39;)}<br>          ${renderKpiCard(&#39;Main Pages&#39;, totalMainPages, &#39;file-spreadsheet&#39;, &#39;text-indigo-500&#39;)}<br>          ${renderKpiCard(&#39;Receipts Attached&#39;, totalReceipts, &#39;receipt&#39;, &#39;text-emerald-500&#39;)}<br>          ${renderKpiCard(&#39;QA Screenshots&#39;, totalScreenshots, &#39;camera&#39;, &#39;text-violet-500&#39;)}<br>          ${renderKpiCard(&#39;Test Cases Passed&#39;, `${passedTC}/${totalTC}`, &#39;check-square&#39;, &#39;text-sky-500&#39;)}<br>          ${renderKpiCard(&#39;Open Defects&#39;, openDefects, &#39;bug&#39;, &#39;text-rose-500&#39;)}<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-2 lg:grid-cols-5 gap-3.5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;Total Checks&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold mt-1&quot;&gt;${totalChecks}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-emerald-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-emerald-600 dark:text-emerald-400 font-semibold&quot;&gt;PASS&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-emerald-600 dark:text-emerald-400 mt-1&quot;&gt;${passCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-rose-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-rose-600 dark:text-rose-400 font-semibold&quot;&gt;FAIL&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-rose-600 dark:text-rose-400 mt-1&quot;&gt;${failCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-amber-500/30 rounded-2xl p-4&quot;&gt;<br>            &lt;div class=&quot;text-xs text-amber-600 dark:text-amber-400 font-semibold&quot;&gt;REVIEW&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-amber-600 dark:text-amber-400 mt-1&quot;&gt;${reviewCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-sky-500/30 rounded-2xl p-4 col-span-2 lg:col-span-1&quot;&gt;<br>            &lt;div class=&quot;text-xs text-sky-600 dark:text-sky-400 font-semibold&quot;&gt;PENDING&lt;/div&gt;<br>            &lt;div class=&quot;text-2xl font-extrabold text-sky-600 dark:text-sky-400 mt-1&quot;&gt;${pendingCount}&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Validation Status Distribution&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-validation-dist&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;Main Page Net Totals (Expected vs Actual)&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-page-financials&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-3&quot;&gt;QA Execution &amp; Defects&lt;/h3&gt;<br>            &lt;div class=&quot;h-56&quot;&gt;&lt;canvas id=&quot;chart-qa-health&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-3 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 overflow-x-auto&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between mb-4&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Main Pages Validation Matrix&lt;/h3&gt;<br>              &lt;button onclick=&quot;navigateTo(&#39;main-pages&#39;)&quot; class=&quot;text-xs font-semibold text-brand-500 hover:underline&quot;&gt;+ Add Main Page&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold&quot;&gt;Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Gross&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;CWT&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Net Actual&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 font-semibold text-right&quot;&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800/70&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; {<br>                  const fin = mp.validationSummary.financials;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-semibold&quot;&gt;${escapeHtml(mp.name)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp.receipt ? escapeHtml(mp.receipt.fileName) : &#39;&lt;span class=&quot;text-amber-500&quot;&gt;None&lt;/span&gt;&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono text-amber-500&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right font-mono font-bold&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(mp.validationSummary.overallStatus)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right&quot;&gt;<br>                        &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;); navigateTo(&#39;validation&#39;);&quot; class=&quot;px-2.5 py-1 rounded-lg bg-brand-500/10 text-brand-500 hover:bg-brand-500/20 font-semibold&quot;&gt;Inspect&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold mb-4&quot;&gt;Recent Audit Activity&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-3 max-h-72 overflow-y-auto pr-1&quot;&gt;<br>              ${(proj.activityLog || []).slice(0, 12).map(item =&gt; `<br>                &lt;div class=&quot;flex items-start gap-2.5 text-xs border-b border-slate-100 dark:border-slate-800/60 pb-2.5&quot;&gt;<br>                  &lt;span class=&quot;w-2 h-2 rounded-full bg-brand-500 mt-1.5 shrink-0&quot;&gt;&lt;/span&gt;<br>                  &lt;div class=&quot;min-w-0 flex-1&quot;&gt;<br>                    &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(item.action)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-slate-500 dark:text-slate-400 truncate&quot;&gt;${escapeHtml(item.detail)}&lt;/div&gt;<br>                    &lt;div class=&quot;text-[10px] text-slate-400 mt-0.5&quot;&gt;${new Date(item.timestamp).toLocaleString()}&lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderKpiCard(label, value, icon, colorClass) {<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex items-center justify-between&quot;&gt;<br>          &lt;div&gt;<br>            &lt;div class=&quot;text-xs text-slate-500 dark:text-slate-400 font-medium&quot;&gt;${escapeHtml(label)}&lt;/div&gt;<br>            &lt;div class=&quot;text-xl font-extrabold mt-1&quot;&gt;${escapeHtml(value)}&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;w-10 h-10 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center ${colorClass}&quot;&gt;<br>            &lt;i data-lucide=&quot;${icon}&quot; class=&quot;w-5 h-5&quot;&gt;&lt;/i&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initDashboardCharts() {<br>      const proj = getActiveProject();<br>      if (!proj || !window.Chart) return;<br><br>      let pass = 0, fail = 0, review = 0, pending = 0;<br>      proj.mainPages.forEach(mp =&gt; {<br>        pass += mp.validationSummary.counts.pass;<br>        fail += mp.validationSummary.counts.fail;<br>        review += mp.validationSummary.counts.review;<br>        pending += mp.validationSummary.counts.pending;<br>      });<br><br>      const ctx1 = document.getElementById(&#39;chart-validation-dist&#39;);<br>      if (ctx1) {<br>        chartInstances.dist = new Chart(ctx1, {<br>          type: &#39;doughnut&#39;,<br>          data: {<br>            labels: [&#39;PASS&#39;, &#39;FAIL&#39;, &#39;REVIEW&#39;, &#39;PENDING&#39;],<br>            datasets: [{<br>              data: [pass, fail, review, pending],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f59e0b&#39;, &#39;#0ea5e9&#39;],<br>              borderWidth: 0<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: &#39;bottom&#39;, labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx2 = document.getElementById(&#39;chart-page-financials&#39;);<br>      if (ctx2) {<br>        chartInstances.fin = new Chart(ctx2, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: proj.mainPages.map(p =&gt; p.name.split(&#39;:&#39;)[0]),<br>            datasets: [<br>              { label: &#39;Expected Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.expectedNet), backgroundColor: &#39;#6366f1&#39;, borderRadius: 6 },<br>              { label: &#39;Actual Net&#39;, data: proj.mainPages.map(p =&gt; p.validationSummary.financials.actualNet), backgroundColor: &#39;#10b981&#39;, borderRadius: 6 }<br>            ]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39; } } }, plugins: { legend: { labels: { color: &#39;#94a3b8&#39;, font: { size: 11 } } } } }<br>        });<br>      }<br><br>      const ctx3 = document.getElementById(&#39;chart-qa-health&#39;);<br>      if (ctx3) {<br>        const tcPass = (proj.testCases || []).filter(t =&gt; t.status === &#39;PASS&#39;).length;<br>        const tcFail = (proj.testCases || []).filter(t =&gt; t.status === &#39;FAIL&#39;).length;<br>        const defOpen = (proj.defects || []).filter(d =&gt; d.status === &#39;Open&#39;).length;<br>        const defClosed = (proj.defects || []).filter(d =&gt; d.status === &#39;Closed&#39;).length;<br>        chartInstances.qa = new Chart(ctx3, {<br>          type: &#39;bar&#39;,<br>          data: {<br>            labels: [&#39;TC Pass&#39;, &#39;TC Fail&#39;, &#39;Open Defects&#39;, &#39;Closed Defects&#39;],<br>            datasets: [{<br>              label: &#39;Count&#39;,<br>              data: [tcPass, tcFail, defOpen, defClosed],<br>              backgroundColor: [&#39;#10b981&#39;, &#39;#ef4444&#39;, &#39;#f97316&#39;, &#39;#64748b&#39;],<br>              borderRadius: 6<br>            }]<br>          },<br>          options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: &#39;#94a3b8&#39; } }, y: { ticks: { color: &#39;#94a3b8&#39;, stepSize: 1 } } } }<br>        });<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 2 VIEW: PROJECT MANAGEMENT<br>     ****************************************************************************/<br>    let projectSearchQuery = &#39;&#39;;<br><br>    function renderProjectsModule() {<br>      const filtered = appState.projects.filter(p =&gt;<br>        p.name.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.reference.toLowerCase().includes(projectSearchQuery.toLowerCase()) ||<br>        p.owner.toLowerCase().includes(projectSearchQuery.toLowerCase())<br>      );<br><br>      return `<br>        &lt;div class=&quot;flex flex-col sm:flex-row sm:items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;relative flex-1 max-w-md&quot;&gt;<br>            &lt;i data-lucide=&quot;search&quot; class=&quot;w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2&quot;&gt;&lt;/i&gt;<br>            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(projectSearchQuery)}&quot; oninput=&quot;projectSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search projects by name, reference, or owner...&quot; class=&quot;w-full pl-10 pr-4 py-2.5 rounded-xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot; /&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-xl text-xs font-semibold bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Import Project JSON&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.json&quot; onchange=&quot;importProjectJson(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;openCreateProjectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Project&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5&quot;&gt;<br>          ${filtered.map(proj =&gt; {<br>            const isActive = proj.id === appState.activeProjectId;<br>            return `<br>              &lt;div class=&quot;bg-white dark:bg-slate-900 border ${isActive ? &#39;border-brand-500 ring-2 ring-brand-500/20&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 flex flex-col justify-between gap-4&quot;&gt;<br>                &lt;div class=&quot;space-y-2.5&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between gap-2&quot;&gt;<br>                    &lt;span class=&quot;font-mono text-[11px] px-2.5 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(proj.reference)}&lt;/span&gt;<br>                    &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                      ${isActive ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-brand-500/15 text-brand-500&quot;&gt;ACTIVE&lt;/span&gt;&#39; : &#39;&#39;}<br>                      ${proj.archived ? &#39;&lt;span class=&quot;px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/15 text-amber-500&quot;&gt;ARCHIVED&lt;/span&gt;&#39; : &#39;&#39;}<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;h3 class=&quot;font-bold text-base leading-snug&quot;&gt;${escapeHtml(proj.name)}&lt;/h3&gt;<br>                  &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400 line-clamp-2&quot;&gt;${escapeHtml(proj.description)}&lt;/p&gt;<br>                  &lt;div class=&quot;grid grid-cols-3 gap-2 pt-2 text-center&quot;&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${proj.mainPages.length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Main Pages&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.testCases || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Test Cases&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-2&quot;&gt;<br>                      &lt;div class=&quot;text-sm font-bold&quot;&gt;${(proj.defects || []).length}&lt;/div&gt;<br>                      &lt;div class=&quot;text-[10px] text-slate-400&quot;&gt;Defects&lt;/div&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;text-[11px] text-slate-400 pt-1&quot;&gt;<br>                    Owner: &lt;span class=&quot;text-slate-600 dark:text-slate-300 font-medium&quot;&gt;${escapeHtml(proj.owner)}&lt;/span&gt; • Updated ${new Date(proj.lastModified).toLocaleDateString()}<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;pt-3 border-t border-slate-100 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                  &lt;button onclick=&quot;switchActiveProject(&#39;${proj.id}&#39;); navigateTo(&#39;dashboard&#39;);&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                    Open Workspace<br>                  &lt;/button&gt;<br>                  &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                    &lt;button onclick=&quot;openRenameProjectModal(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Rename Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;pencil&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;duplicateProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Duplicate Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;exportProjectJson(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Export Project JSON&quot;&gt;<br>                      &lt;i data-lucide=&quot;download&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;toggleArchiveProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400&quot; title=&quot;Archive / Unarchive&quot;&gt;<br>                      &lt;i data-lucide=&quot;archive&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;confirmDeleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;p-1.5 rounded-lg hover:bg-rose-500/10 text-rose-500&quot; title=&quot;Delete Project&quot;&gt;<br>                      &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openCreateProjectModal() {<br>      openModal({<br>        title: &#39;Create New EIS &amp; QA Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name *&lt;/label&gt;<br>              &lt;input id=&quot;new-proj-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Phase 2 — Regional Port Audit&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Reference&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-ref&quot; type=&quot;text&quot; value=&quot;PRJ-EIS-${Math.floor(1000 + Math.random() * 9000)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Owner / QA Lead&lt;/label&gt;<br>                &lt;input id=&quot;new-proj-owner&quot; type=&quot;text&quot; value=&quot;QA Analyst&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Fee Template (Optional)&lt;/label&gt;<br>              &lt;select id=&quot;new-proj-template&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;&quot;&gt;Blank Main Page (No pre-configured fees)&lt;/option&gt;<br>                ${appState.templates.map(t =&gt; `&lt;option value=&quot;${t.id}&quot;&gt;${escapeHtml(t.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;new-proj-desc&quot; rows=&quot;2&quot; placeholder=&quot;Scope of receipt validation and QA evidence...&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;createNewProjectFromModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;Create Project&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function createNewProjectFromModal() {<br>      const name = document.getElementById(&#39;new-proj-name&#39;).value.trim();<br>      if (!name) return showToast(&#39;Project name is required.&#39;, &#39;warning&#39;);<br>      const ref = document.getElementById(&#39;new-proj-ref&#39;).value.trim() || `PRJ-${Date.now()}`;<br>      const owner = document.getElementById(&#39;new-proj-owner&#39;).value.trim() || &#39;QA Tester&#39;;<br>      const desc = document.getElementById(&#39;new-proj-desc&#39;).value.trim();<br>      const tplId = document.getElementById(&#39;new-proj-template&#39;).value;<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br><br>      const now = new Date().toISOString();<br>      const firstPage = {<br>        id: &#39;mp_&#39; + Date.now(),<br>        name: &#39;MP-01: Primary Receipt Page&#39;,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: tpl ? tpl.fees.map((f, idx) =&gt; ({<br>          id: `fee_${Date.now()}_${idx}`,<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          actualName: &#39;&#39;,<br>          actualAmount: &#39;&#39;,<br>          actualCode: &#39;&#39;,<br>          isCwt: Boolean(f.isCwt),<br>          ocrConfidence: null,<br>          sourceLocation: &#39;&#39;<br>        })) : [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(firstPage);<br><br>      const proj = {<br>        id: &#39;proj_&#39; + Date.now(),<br>        name,<br>        reference: ref,<br>        description: desc || &#39;EIS Receipt Validation &amp; QA Evidence Workspace&#39;,<br>        owner,<br>        status: &#39;Active&#39;,<br>        archived: false,<br>        createdAt: now,<br>        lastModified: now,<br>        mainPages: [firstPage],<br>        screenshots: [],<br>        mergeHistory: [],<br>        testCases: [],<br>        defects: [],<br>        activityLog: [{ timestamp: now, action: &#39;Project Created&#39;, detail: `Created ${name}` }]<br>      };<br><br>      appState.projects.unshift(proj);<br>      appState.activeProjectId = proj.id;<br>      appState.activeMainPageId = firstPage.id;<br>      closeModal();<br>      scheduleAutosave(&#39;Created project&#39;);<br>      showToast(`Created project &quot;${name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function openRenameProjectModal(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      openModal({<br>        title: &#39;Rename Project&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Project Name&lt;/label&gt;<br>              &lt;input id=&quot;rename-proj-input&quot; type=&quot;text&quot; value=&quot;${escapeHtml(proj.name)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description&lt;/label&gt;<br>              &lt;textarea id=&quot;rename-proj-desc&quot; rows=&quot;2&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;${escapeHtml(proj.description)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveProjectRename(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Changes&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveProjectRename(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      const val = document.getElementById(&#39;rename-proj-input&#39;).value.trim();<br>      if (!val) return showToast(&#39;Project name cannot be empty.&#39;, &#39;warning&#39;);<br>      proj.name = val;<br>      proj.description = document.getElementById(&#39;rename-proj-desc&#39;).value.trim();<br>      closeModal();<br>      scheduleAutosave(&#39;Renamed project&#39;);<br>      showToast(&#39;Project updated.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateProject(projId) {<br>      const orig = appState.projects.find(p =&gt; p.id === projId);<br>      if (!orig) return;<br>      const copy = JSON.parse(JSON.stringify(orig));<br>      copy.id = &#39;proj_&#39; + Date.now();<br>      copy.name = orig.name + &#39; (Copy)&#39;;<br>      copy.reference = orig.reference + &#39;-COPY&#39;;<br>      copy.createdAt = new Date().toISOString();<br>      copy.lastModified = copy.createdAt;<br>      appState.projects.unshift(copy);<br>      scheduleAutosave(&#39;Duplicated project&#39;);<br>      showToast(`Duplicated &quot;${orig.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function toggleArchiveProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      proj.archived = !proj.archived;<br>      proj.status = proj.archived ? &#39;Archived&#39; : &#39;Active&#39;;<br>      scheduleAutosave(&#39;Toggled archive&#39;);<br>      showToast(proj.archived ? &#39;Project archived.&#39; : &#39;Project restored.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function confirmDeleteProject(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId);<br>      if (!proj) return;<br>      if (appState.projects.length &lt;= 1) {<br>        return showToast(&#39;Cannot delete the only remaining project.&#39;, &#39;warning&#39;);<br>      }<br>      openModal({<br>        title: &#39;Confirm Project Deletion&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Are you sure you want to permanently delete &lt;strong&gt;${escapeHtml(proj.name)}&lt;/strong&gt; (${proj.mainPages.length} Main Pages, receipts, and QA evidence)? This action cannot be undone unless you have exported a JSON backup.&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;deleteProject(&#39;${proj.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;Delete Permanently&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function deleteProject(projId) {<br>      appState.projects = appState.projects.filter(p =&gt; p.id !== projId);<br>      if (appState.activeProjectId === projId) {<br>        appState.activeProjectId = appState.projects[0].id;<br>        appState.activeMainPageId = appState.projects[0].mainPages[0]?.id || null;<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted project&#39;);<br>      showToast(&#39;Project deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportProjectJson(projId) {<br>      const proj = appState.projects.find(p =&gt; p.id === projId) || getActiveProject();<br>      if (!proj) return;<br>      const exportObj = {<br>        nexusExportVersion: APP_SCHEMA_VERSION,<br>        exportedAt: new Date().toISOString(),<br>        project: proj<br>      };<br>      const blob = new Blob([JSON.stringify(exportObj, null, 2)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `${proj.reference || &#39;nexus_project&#39;}_${new Date().toISOString().slice(0, 10)}.json`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;Exported full project JSON backup.&#39;, &#39;success&#39;);<br>    }<br><br>    function importProjectJson(event) {<br>      const file = event.target.files[0];<br>      if (!file) return;<br>      const reader = new FileReader();<br>      reader.onload = (e) =&gt; {<br>        try {<br>          const parsed = JSON.parse(e.target.result);<br>          const importedProj = parsed.project || parsed;<br>          if (!importedProj || !importedProj.name || !Array.isArray(importedProj.mainPages)) {<br>            throw new Error(&#39;Invalid NEXUS project JSON schema.&#39;);<br>          }<br>          importedProj.id = &#39;proj_&#39; + Date.now();<br>          importedProj.lastModified = new Date().toISOString();<br>          importedProj.mainPages.forEach(mp =&gt; {<br>            if (typeof mp.rowPasteEnabled === &#39;undefined&#39;) mp.rowPasteEnabled = true;<br>            if (typeof mp.rowPasteInput === &#39;undefined&#39;) mp.rowPasteInput = &#39;&#39;;<br>            if (typeof mp.rowPasteHasHeaders === &#39;undefined&#39;) mp.rowPasteHasHeaders = false;<br>            if (typeof mp.autoRenameFieldsFromHeaders === &#39;undefined&#39;) mp.autoRenameFieldsFromHeaders = false;<br>            ValidationEngine.validateMainPage(mp);<br>          });<br>          appState.projects.unshift(importedProj);<br>          appState.activeProjectId = importedProj.id;<br>          appState.activeMainPageId = importedProj.mainPages[0]?.id || null;<br>          scheduleAutosave(&#39;Imported project JSON&#39;);<br>          showToast(`Imported &quot;${importedProj.name}&quot; successfully!`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;Import failed: &#39; + err.message, &#39;error&#39;);<br>        }<br>      };<br>      reader.readAsText(file);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 3 VIEW: MAIN PAGE MANAGEMENT (1-50+ Fields, Per-Page Dynamic Row &amp; Fees)<br>     ****************************************************************************/<br>    let fieldSearchQuery = &#39;&#39;;<br>    let showAll50Fields = false;<br><br>    function renderMainPagesModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page found.&lt;/div&gt;`;<br><br>      const fin = page.validationSummary ? page.validationSummary.financials : FinancialCalculator.calculateTotals(page.fees);<br>      const visibleFields = page.fields.filter(f =&gt; {<br>        if (!showAll50Fields &amp;&amp; !f.enabled &amp;&amp; f.number &gt; 10) return false;<br>        if (!fieldSearchQuery) return true;<br>        const q = fieldSearchQuery.toLowerCase();<br>        return String(f.number).includes(q) || f.name.toLowerCase().includes(q) || String(f.expectedValue).toLowerCase().includes(q) || String(f.actualValue).toLowerCase().includes(q);<br>      });<br><br>      const isRowPasteEnabled = page.rowPasteEnabled !== false;<br>      const pageRowInput = page.rowPasteInput || &#39;&#39;;<br>      const pageRowHasHeaders = Boolean(page.rowPasteHasHeaders);<br>      const parsedPreview = RowToFieldsEngine.parseSpreadsheetRow(pageRowInput, pageRowHasHeaders);<br><br>      return `<br>        &lt;!-- Main Page Selector Tabs --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center gap-2 overflow-x-auto pb-1&quot;&gt;<br>              ${proj.mainPages.map(mp =&gt; {<br>                const active = mp.id === page.id;<br>                const st = mp.validationSummary ? mp.validationSummary.overallStatus : &#39;PENDING&#39;;<br>                return `<br>                  &lt;button onclick=&quot;switchActiveMainPage(&#39;${mp.id}&#39;)&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold border transition flex items-center gap-2 shrink-0 ${<br>                    active<br>                      ? &#39;bg-brand-600 text-white border-brand-600 shadow-sm&#39;<br>                      : &#39;bg-slate-50 dark:bg-slate-800/70 border-slate-200 dark:border-slate-700 hover:border-brand-500/50&#39;<br>                  }&quot;&gt;<br>                    &lt;span&gt;${escapeHtml(mp.name)}&lt;/span&gt;<br>                    &lt;span class=&quot;px-1.5 py-0.2 rounded text-[10px] font-bold ${active ? &#39;bg-white/20 text-white&#39; : &#39;bg-slate-200 dark:bg-slate-700&#39;}&quot;&gt;${st}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;addNewMainPage()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;New Main Page&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;duplicateActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Duplicate Main Page&quot;&gt;<br>                &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>              ${proj.mainPages.length &gt; 1 ? `<br>                &lt;button onclick=&quot;deleteActiveMainPage()&quot; class=&quot;p-2 rounded-xl border border-rose-500/30 text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Delete Main Page&quot;&gt;<br>                  &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;/button&gt;<br>              ` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;!-- Isolated Main Page Metadata --&gt;<br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-3 gap-3 pt-2 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Main Page Name (Isolated Record)&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.name)}&quot; onchange=&quot;updateMainPageMeta(&#39;name&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;md:col-span-2&quot;&gt;<br>              &lt;label class=&quot;block text-[11px] font-semibold text-slate-400 mb-1&quot;&gt;Page Scenario Description&lt;/label&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(page.description)}&quot; onchange=&quot;updateMainPageMeta(&#39;description&#39;, this.value)&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- 1-Row Spreadsheet-to-Columns Expected Output Paste Studio (Per-Page Dynamic Config) --&gt;<br>        &lt;div class=&quot;bg-gradient-to-br from-brand-500/5 via-white to-indigo-500/5 dark:from-brand-950/30 dark:via-slate-900 dark:to-indigo-950/20 border ${isRowPasteEnabled ? &#39;border-brand-500/30&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} rounded-2xl p-5 space-y-4 shadow-sm transition&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-start justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap mb-1&quot;&gt;<br>                &lt;span class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-brand-600/15 text-brand-600 dark:text-brand-400&quot;&gt;<br>                  &lt;i data-lucide=&quot;table-2&quot; class=&quot;w-3 h-3&quot;&gt;&lt;/i&gt;<br>                  &lt;span&gt;Per-Page Dynamic Row Mapper • ${escapeHtml(page.name)}&lt;/span&gt;<br>                &lt;/span&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[11px] font-semibold border cursor-pointer ${isRowPasteEnabled ? &#39;bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${isRowPasteEnabled ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteConfig(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;${isRowPasteEnabled ? &#39;Enabled for this page&#39; : &#39;Not Applicable for this page&#39;}&lt;/span&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Paste Expected Receipt Row (Excel / Sheets / CSV / Pipe)&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;${isRowPasteEnabled<br>                ? &#39;Independent dynamic configuration for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Custom column names are preserved by default; header-based renaming is opt-in.&#39;<br>                : &#39;Row-paste mapping is marked &lt;strong&gt;Not Applicable&lt;/strong&gt; for &lt;strong&gt;&#39; + escapeHtml(page.name) + &#39;&lt;/strong&gt;. Toggle above if this page uses spreadsheet row expectations.&#39;}&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            ${isRowPasteEnabled ? `<br>              &lt;div class=&quot;flex items-center gap-2 flex-wrap&quot;&gt;<br>                &lt;button onclick=&quot;saveFieldSchemaAsTemplate()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:border-brand-500/50&quot;&gt;<br>                  Save Column Names as Template<br>                &lt;/button&gt;<br>                &lt;button onclick=&quot;clearExpectedRowValues()&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold text-rose-600 dark:text-rose-400 border border-rose-500/30 hover:bg-rose-500/10&quot;&gt;<br>                  Clear This Page&#39;s Row<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          ${isRowPasteEnabled ? `<br>            &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-4&quot;&gt;<br>              &lt;div class=&quot;lg:col-span-6 space-y-2.5&quot;&gt;<br>                &lt;textarea id=&quot;row-to-fields-textarea&quot; rows=&quot;3&quot; oninput=&quot;updatePageRowPasteInput(this.value)&quot; placeholder=&quot;Paste 1 dynamic row for ${escapeHtml(page.name)} (Tab-separated, CSV, or Pipe):&amp;#10;INV-2026-88410 2026-11-15 004-892-110-000 APEX GLOBAL PHP 1250.00 50.00 1200.00&quot; class=&quot;w-full p-3 rounded-xl bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-700 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-brand-500&quot;&gt;${escapeHtml(pageRowInput)}&lt;/textarea&gt;<br><br>                &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 text-xs&quot;&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${pageRowHasHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;togglePageRowPasteHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;First pasted row contains column headers&lt;/span&gt;<br>                  &lt;/label&gt;<br>                  &lt;label class=&quot;inline-flex items-center gap-2 cursor-pointer text-slate-600 dark:text-slate-300 font-medium&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; ${page.autoRenameFieldsFromHeaders ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleAutoRenameFieldsFromHeaders(this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                    &lt;span&gt;Allow pasted headers to rename my fields&lt;/span&gt;<br>                  &lt;/label&gt;<br><br>                  &lt;button onclick=&quot;applyPastedRowToMainPageFields()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold bg-brand-600 hover:bg-brand-700 text-white shadow-sm&quot;&gt;<br>                    &lt;i data-lucide=&quot;arrow-down-to-line&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                    &lt;span&gt;Apply Dynamic Row to ${escapeHtml(page.name.split(&#39;:&#39;)[0])}&lt;/span&gt;<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br><br>              &lt;!-- Live Column -&gt; Field Preview --&gt;<br>              &lt;div class=&quot;lg:col-span-6 bg-white/80 dark:bg-slate-950/70 border border-slate-200 dark:border-slate-800 rounded-xl p-3 flex flex-col justify-between&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between mb-2&quot;&gt;<br>                  &lt;span class=&quot;text-[11px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Live Dynamic Mapping Preview (${parsedPreview.values.length} cols • ${parsedPreview.delimiter})&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div id=&quot;row-paste-preview-grid&quot; class=&quot;flex flex-wrap gap-1.5 max-h-28 overflow-y-auto&quot;&gt;<br>                  ${renderRowPastePreviewChips(page, parsedPreview)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          ` : &#39;&#39;}<br>        &lt;/div&gt;<br><br>        &lt;!-- EIS Fee &amp; CWT Configuration Engine --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;EIS Fee &amp; CWT Line-Item Configuration&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Independent Fee Name, Amount &amp; Code per row. CWT deducts absolute magnitude without double-counting in Gross Fees.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;button onclick=&quot;openQuickPasteFeeModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/20&quot;&gt;<br>                &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Quick Paste Fees&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(false)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                &lt;i data-lucide=&quot;plus&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add Fee&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addFeeRow(true)&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30 hover:bg-amber-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;minus-circle&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Add CWT&lt;/span&gt;<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-10&quot;&gt;#&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Fee Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Amount&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Actual Amt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Receipt Code&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${page.fees.length === 0 ? `<br>                  &lt;tr&gt;&lt;td colspan=&quot;10&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No fees configured yet. Click &lt;strong&gt;Add Fee&lt;/strong&gt; or &lt;strong&gt;Quick Paste Fees&lt;/strong&gt;.&lt;/td&gt;&lt;/tr&gt;<br>                ` : page.fees.map((fee, idx) =&gt; {<br>                  const isCwt = FinancialCalculator.isCwtEntry(fee);<br>                  const st = fee.lastValidation ? fee.lastValidation.status : &#39;PENDING&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-slate-400&quot;&gt;${idx + 1}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;button onclick=&quot;toggleFeeCwtFlag(&#39;${fee.id}&#39;)&quot; class=&quot;px-2 py-0.5 rounded text-[10px] font-bold border ${isCwt ? &#39;bg-amber-500/15 text-amber-500 border-amber-500/30&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-500 border-slate-200 dark:border-slate-700&#39;}&quot; title=&quot;Click to toggle Fee vs CWT Deduction&quot;&gt;<br>                          ${isCwt ? &#39;CWT (-)&#39; : &#39;FEE (+)&#39;}<br>                        &lt;/button&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedName&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-medium&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedAmount&#39;, this.value)&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.expectedCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;expectedCode&#39;, this.value)&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; placeholder=&quot;OCR / Receipt&quot; class=&quot;w-full px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; placeholder=&quot;0.00&quot; class=&quot;w-28 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;updateFeeField(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; placeholder=&quot;Code&quot; class=&quot;w-20 px-2.5 py-1.5 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono uppercase&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, -1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;&lt;i data-lucide=&quot;arrow-up&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveFeeRow(${idx}, 1)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;&lt;i data-lucide=&quot;arrow-down&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;duplicateFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-slate-400 hover:text-slate-200&quot; title=&quot;Duplicate&quot;&gt;&lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;removeFeeRow(&#39;${fee.id}&#39;)&quot; class=&quot;p-1 text-rose-500 hover:bg-rose-500/10 rounded&quot; title=&quot;Remove&quot;&gt;&lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-4 gap-3 pt-3 border-t border-slate-100 dark:border-slate-800&quot;&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Gross Fees (Expected / Actual)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)} / &lt;span class=&quot;text-brand-500&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/span&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Total CWT Deduction (|CWT|)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)} / -${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Total (Gross - CWT)&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm text-emerald-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)} / ${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;bg-slate-50 dark:bg-slate-800/60 rounded-xl p-3&quot;&gt;<br>              &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;Net Variance&lt;/div&gt;<br>              &lt;div class=&quot;font-mono font-bold text-sm ${fin.netDifference === 0 ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;} mt-0.5&quot;&gt;${fin.netDifference &gt; 0 ? &#39;+&#39; : &#39;&#39;}${fin.netDifference.toFixed(2)}&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Configurable Columns / Numbered Main Page Fields (1-50+) --&gt;<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Configurable Column Fields (1–${page.fields.length})&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Edit professional field names directly. Names are saved per Main Page and stay unchanged when you paste rows unless header-based renaming is enabled above.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fieldSearchQuery)}&quot; oninput=&quot;fieldSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search fields...&quot; class=&quot;px-3 py-1.5 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;button onclick=&quot;showAll50Fields = !showAll50Fields; renderApp();&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;<br>                ${showAll50Fields ? &#39;Show Active / First 10&#39; : `Show All ${page.fields.length} Fields`}<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;addMoreNumberedFields(10)&quot; class=&quot;px-3 py-1.5 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                + Add 10 More Fields<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto max-h-[420px]&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead class=&quot;sticky top-0 bg-white dark:bg-slate-900 z-10&quot;&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5 w-14&quot;&gt;Col #&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Configurable Field / Column Name&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Type&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Expected Value&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Found on Receipt&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Req&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${visibleFields.map(f =&gt; {<br>                  const st = f.lastValidation ? f.lastValidation.status : &#39;NOT APPLICABLE&#39;;<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-2 font-mono font-semibold text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.name)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;name&#39;, this.value)&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-semibold&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;select onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;dataType&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700&quot;&gt;<br>                          ${[&#39;Dynamic&#39;, &#39;Text&#39;, &#39;Number&#39;, &#39;Currency&#39;, &#39;Date&#39;, &#39;Percentage&#39;, &#39;Code&#39;, &#39;Reference&#39;, &#39;Boolean&#39;].map(t =&gt; `&lt;option value=&quot;${t}&quot; ${f.dataType === t ? &#39;selected&#39; : &#39;&#39;}&gt;${t}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.expectedValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;expectedValue&#39;, this.value)&quot; placeholder=&quot;Expected&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; placeholder=&quot;Receipt value&quot; class=&quot;w-full px-2.5 py-1 rounded-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${f.required ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;required&#39;, this.checked)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function renderRowPastePreviewChips(page, parsed) {<br>      if (!parsed.values.length) {<br>        return `&lt;span class=&quot;text-xs text-slate-400 italic&quot;&gt;Paste a row on the left to preview how each column maps into C01, C02, C03...&lt;/span&gt;`;<br>      }<br>      return parsed.values.map((val, idx) =&gt; {<br>        const colNum = idx + 1;<br>        const existingField = page.fields[idx];<br>        const colName = parsed.headers[idx] || (existingField ? existingField.name : `Custom Field ${colNum}`);<br>        return `<br>          &lt;div class=&quot;px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot;&gt;<br>            &lt;div class=&quot;text-[10px] font-bold text-brand-500&quot;&gt;C${String(colNum).padStart(2, &#39;0&#39;)}: ${escapeHtml(colName)}&lt;/div&gt;<br>            &lt;div class=&quot;font-mono font-semibold truncate max-w-[160px]&quot;&gt;${escapeHtml(val || &#39;(blank)&#39;)}&lt;/div&gt;<br>          &lt;/div&gt;<br>        `;<br>      }).join(&#39;&#39;);<br>    }<br><br>    function updateRowPastePreviewOnly() {<br>      const page = getActiveMainPage();<br>      const grid = document.getElementById(&#39;row-paste-preview-grid&#39;);<br>      if (!page || !grid) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      grid.innerHTML = renderRowPastePreviewChips(page, parsed);<br>    }<br><br>    function togglePageRowPasteConfig(enabled) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteEnabled = Boolean(enabled);<br>      scheduleAutosave(`Updated row mapper config on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function updatePageRowPasteInput(val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteInput = val;<br>      updateRowPastePreviewOnly();<br>      scheduleAutosave(`Updated dynamic row input on ${page.name}`);<br>    }<br><br>    function togglePageRowPasteHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.rowPasteHasHeaders = Boolean(checked);<br>      scheduleAutosave(`Toggled row headers on ${page.name}`);<br>      renderApp();<br>    }<br><br>    function toggleAutoRenameFieldsFromHeaders(checked) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.autoRenameFieldsFromHeaders = Boolean(checked);<br>      scheduleAutosave(&#39;Updated column header rename preference on &#39; + page.name);<br>      showToast(checked<br>        ? &#39;Pasted headers can now rename fields on this page.&#39;<br>        : &#39;Custom field names are protected from pasted headers.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function applyPastedRowToMainPageFields() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const parsed = RowToFieldsEngine.parseSpreadsheetRow(page.rowPasteInput || &#39;&#39;, Boolean(page.rowPasteHasHeaders));<br>      if (!parsed.values.length) {<br>        return showToast(&#39;Paste at least 1 row of values first.&#39;, &#39;warning&#39;);<br>      }<br><br>      while (page.fields.length &lt; parsed.values.length) {<br>        const num = page.fields.length + 1;<br>        page.fields.push({<br>          id: `fld_${num}_${Date.now()}_${num}`,<br>          number: num,<br>          name: `Custom Field ${num}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: true,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${num}`,<br>          pageOverride: true,<br>          enabled: true<br>        });<br>      }<br><br>      parsed.values.forEach((val, idx) =&gt; {<br>        const fld = page.fields[idx];<br>        if (parsed.headers[idx] &amp;&amp; page.autoRenameFieldsFromHeaders === true) {<br>          fld.name = parsed.headers[idx];<br>        }<br>        fld.expectedValue = val;<br>        fld.enabled = true;<br>        fld.pageOverride = true;<br>        if (val !== &#39;&#39;) {<br>          fld.required = true;<br>          fld.dataType = &#39;Dynamic&#39;;<br>        }<br>      });<br><br>      let matchInfo = &#39;&#39;;<br>      if (page.receipt &amp;&amp; page.receipt.ocrRawText) {<br>        const m = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>        matchInfo = ` • Auto-matched ${m.matched}/${m.total} against attached receipt`;<br>      } else {<br>        ValidationEngine.validateMainPage(page);<br>      }<br><br>      logActivity(&#39;Pasted Dynamic Row&#39;, `Applied ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`);<br>      scheduleAutosave(&#39;Applied dynamic expected row&#39;);<br>      showToast(`Mapped ${parsed.values.length} dynamic columns to ${page.name}${matchInfo}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function clearExpectedRowValues() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fields.forEach(f =&gt; {<br>        f.expectedValue = &#39;&#39;;<br>        f.actualValue = &#39;&#39;;<br>        if (f.number &gt; 10) f.enabled = false;<br>      });<br>      page.rowPasteInput = &#39;&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Cleared expected row values&#39;);<br>      showToast(&#39;Cleared expected &amp; actual field values on &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function saveFieldSchemaAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const activeCols = page.fields.filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10);<br>      openModal({<br>        title: &#39;Save Configurable Column Names as Reusable Template&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Save your current &lt;strong&gt;${activeCols.length} configurable column headers&lt;/strong&gt; (plus any fee rows) so you can apply this exact column layout to future Main Pages with one click.&lt;/p&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Template Name&lt;/label&gt;<br>              &lt;input id=&quot;col-schema-tpl-name&quot; type=&quot;text&quot; placeholder=&quot;e.g. EIS Standard 8-Column Export Layout&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmSaveFieldSchemaTemplate()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Schema Template&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmSaveFieldSchemaTemplate() {<br>      const page = getActiveMainPage();<br>      const name = document.getElementById(&#39;col-schema-tpl-name&#39;).value.trim();<br>      if (!page || !name) return showToast(&#39;Enter a template name.&#39;, &#39;warning&#39;);<br><br>      const activeCols = page.fields<br>        .filter(f =&gt; f.enabled || f.expectedValue || f.number &lt;= 10)<br>        .map(f =&gt; ({ number: f.number, name: f.name, dataType: f.dataType, required: f.required }));<br><br>      appState.templates.push({<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name,<br>        description: `${activeCols.length} configured columns + ${page.fees.length} fee rows`,<br>        columns: activeCols,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      });<br><br>      closeModal();<br>      scheduleAutosave(&#39;Saved column schema template&#39;);<br>      showToast(`Saved template &quot;${name}&quot;`, &#39;success&#39;);<br>    }<br><br>    function addNewMainPage() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const idx = proj.mainPages.length + 1;<br>      const newPage = {<br>        id: &#39;mp_&#39; + Date.now() + &#39;_&#39; + idx,<br>        name: `MP-0${idx}: New Receipt Page`,<br>        description: &#39;Isolated Main Page validation record&#39;,<br>        rowPasteEnabled: true,<br>        rowPasteInput: &#39;&#39;,<br>        rowPasteHasHeaders: false,<br>        receipt: null,<br>        fields: createDefaultFields(),<br>        fees: [],<br>        annotations: [],<br>        validationHistory: []<br>      };<br>      ValidationEngine.validateMainPage(newPage);<br>      proj.mainPages.push(newPage);<br>      appState.activeMainPageId = newPage.id;<br>      logActivity(&#39;Added Main Page&#39;, newPage.name);<br>      scheduleAutosave(&#39;Added Main Page&#39;);<br>      showToast(`Created ${newPage.name}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return;<br>      const copy = JSON.parse(JSON.stringify(page));<br>      copy.id = &#39;mp_&#39; + Date.now();<br>      copy.name = page.name + &#39; (Copy)&#39;;<br>      proj.mainPages.push(copy);<br>      appState.activeMainPageId = copy.id;<br>      scheduleAutosave(&#39;Duplicated Main Page&#39;);<br>      showToast(`Duplicated &quot;${page.name}&quot;`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function deleteActiveMainPage() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page || proj.mainPages.length &lt;= 1) return;<br>      openModal({<br>        title: &#39;Delete Main Page&#39;,<br>        bodyHtml: `&lt;p class=&quot;text-xs text-slate-500 dark:text-slate-300&quot;&gt;Delete &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; and its attached receipt &amp; fee rules?&lt;/p&gt;`,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;confirmDeleteMainPage(&#39;${page.id}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Delete Page&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function confirmDeleteMainPage(pageId) {<br>      const proj = getActiveProject();<br>      proj.mainPages = proj.mainPages.filter(p =&gt; p.id !== pageId);<br>      appState.activeMainPageId = proj.mainPages[0].id;<br>      closeModal();<br>      scheduleAutosave(&#39;Deleted Main Page&#39;);<br>      showToast(&#39;Main Page deleted.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function updateMainPageMeta(key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page[key] = val;<br>      scheduleAutosave(&#39;Updated Main Page metadata&#39;);<br>      renderApp();<br>    }<br><br>    function addFeeRow(isCwt = false) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const idx = page.fees.length + 1;<br>      page.fees.push({<br>        id: &#39;fee_&#39; + Date.now() + &#39;_&#39; + idx,<br>        expectedName: isCwt ? &#39;CWT&#39; : `Fee ${idx} Charge`,<br>        expectedAmount: isCwt ? &#39;50&#39; : &#39;100&#39;,<br>        expectedCode: isCwt ? &#39;CWT&#39; : &#39;NC&#39;,<br>        actualName: &#39;&#39;,<br>        actualAmount: &#39;&#39;,<br>        actualCode: &#39;&#39;,<br>        isCwt,<br>        ocrConfidence: null,<br>        sourceLocation: &#39;&#39;<br>      });<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Added fee row&#39;);<br>      renderApp();<br>    }<br><br>    function updateFeeField(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const fee = page.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee[key] = val;<br>      if (key === &#39;expectedCode&#39; &amp;&amp; val.trim().toUpperCase() === &#39;CWT&#39;) fee.isCwt = true;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated fee&#39;);<br>      renderApp();<br>    }<br><br>    function toggleFeeCwtFlag(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      fee.isCwt = !FinancialCalculator.isCwtEntry(fee);<br>      if (fee.isCwt &amp;&amp; !fee.expectedCode) fee.expectedCode = &#39;CWT&#39;;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Toggled CWT flag&#39;);<br>      renderApp();<br>    }<br><br>    function moveFeeRow(idx, dir) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const target = idx + dir;<br>      if (target &lt; 0 || target &gt;= page.fees.length) return;<br>      const temp = page.fees[idx];<br>      page.fees[idx] = page.fees[target];<br>      page.fees[target] = temp;<br>      scheduleAutosave(&#39;Reordered fees&#39;);<br>      renderApp();<br>    }<br><br>    function duplicateFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const copy = JSON.parse(JSON.stringify(fee));<br>      copy.id = &#39;fee_&#39; + Date.now();<br>      page.fees.push(copy);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Duplicated fee&#39;);<br>      renderApp();<br>    }<br><br>    function removeFeeRow(feeId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.fees = page.fees.filter(f =&gt; f.id !== feeId);<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Removed fee&#39;);<br>      renderApp();<br>    }<br><br>    function openQuickPasteFeeModal() {<br>      openModal({<br>        title: &#39;Quick Paste EIS Fees &amp; CWT&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;p class=&quot;text-xs text-slate-500 dark:text-slate-400&quot;&gt;Paste multi-line blocks (Name / Amount / Code) or pipe-delimited rows. CWT entries are automatically recognized.&lt;/p&gt;<br>            &lt;textarea id=&quot;quick-paste-fee-input&quot; rows=&quot;9&quot; placeholder=&quot;Fee 1 Charge&amp;#10;1000&amp;#10;NC&amp;#10;Fee 2 Charge&amp;#10;250&amp;#10;IC&amp;#10;CWT&amp;#10;50&quot; class=&quot;w-full p-3 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;div class=&quot;flex items-center gap-4 text-xs&quot;&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;expected&quot; checked /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Expected&lt;/strong&gt; Main Page Fees&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;inline-flex items-center gap-1.5 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;radio&quot; name=&quot;qp-target&quot; value=&quot;actual&quot; /&gt;<br>                &lt;span&gt;Populate &lt;strong&gt;Actual / Receipt&lt;/strong&gt; Values&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;applyQuickPasteFees()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Parse &amp; Apply Fees&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function applyQuickPasteFees() {<br>      const page = getActiveMainPage();<br>      const raw = document.getElementById(&#39;quick-paste-fee-input&#39;).value;<br>      const target = document.querySelector(&#39;input[name=&quot;qp-target&quot;]:checked&#39;)?.value || &#39;expected&#39;;<br>      const parsed = OcrMappingEngine.parseQuickPasteFees(raw);<br>      if (!parsed.length) return showToast(&#39;No valid fee rows detected.&#39;, &#39;warning&#39;);<br><br>      if (target === &#39;expected&#39;) {<br>        parsed.forEach((p, idx) =&gt; {<br>          page.fees.push({<br>            id: `fee_qp_${Date.now()}_${idx}`,<br>            expectedName: p.name,<br>            expectedAmount: p.amount,<br>            expectedCode: p.code,<br>            actualName: &#39;&#39;,<br>            actualAmount: &#39;&#39;,<br>            actualCode: &#39;&#39;,<br>            isCwt: p.isCwt,<br>            ocrConfidence: null,<br>            sourceLocation: &#39;Quick Paste&#39;<br>          });<br>        });<br>      } else {<br>        parsed.forEach((p, idx) =&gt; {<br>          if (page.fees[idx]) {<br>            page.fees[idx].actualName = p.name;<br>            page.fees[idx].actualAmount = p.amount;<br>            page.fees[idx].actualCode = p.code;<br>            page.fees[idx].sourceLocation = &#39;Quick Paste Receipt&#39;;<br>          } else {<br>            page.fees.push({<br>              id: `fee_qp_${Date.now()}_${idx}`,<br>              expectedName: p.name,<br>              expectedAmount: &#39;&#39;,<br>              expectedCode: p.code,<br>              actualName: p.name,<br>              actualAmount: p.amount,<br>              actualCode: p.code,<br>              isCwt: p.isCwt,<br>              ocrConfidence: 100,<br>              sourceLocation: &#39;Quick Paste Receipt&#39;<br>            });<br>          }<br>        });<br>      }<br><br>      ValidationEngine.validateMainPage(page, true);<br>      closeModal();<br>      scheduleAutosave(&#39;Quick pasted fees&#39;);<br>      showToast(`Imported ${parsed.length} fee entries.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateNumberedField(fieldId, key, val) {<br>      const page = getActiveMainPage();<br>      const fld = page?.fields.find(f =&gt; f.id === fieldId);<br>      if (!fld) return;<br>      fld[key] = val;<br>      if (key === &#39;expectedValue&#39; || key === &#39;actualValue&#39;) fld.enabled = true;<br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Updated numbered field&#39;);<br>      renderApp();<br>    }<br><br>    function addMoreNumberedFields(count = 10) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const start = page.fields.length + 1;<br>      for (let i = start; i &lt; start + count; i++) {<br>        page.fields.push({<br>          id: `fld_${i}_${Date.now()}`,<br>          number: i,<br>          name: `Custom Field ${i}`,<br>          expectedValue: &#39;&#39;,<br>          actualValue: &#39;&#39;,<br>          dataType: &#39;Dynamic&#39;,<br>          validationRule: &#39;Exact / Tolerance Match&#39;,<br>          ocrEnabled: true,<br>          required: false,<br>          tolerance: 0.01,<br>          description: `Dynamic Column #${i}`,<br>          pageOverride: false,<br>          enabled: true<br>        });<br>      }<br>      showAll50Fields = true;<br>      scheduleAutosave(&#39;Added numbered fields&#39;);<br>      showToast(`Added ${count} fields (Total: ${page.fields.length}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 4 VIEW: SIDE-BY-SIDE RECEIPT VALIDATION WORKSPACE<br>     ****************************************************************************/<br>    function renderValidationWorkspaceModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      if (!page.validationSummary) ValidationEngine.validateMainPage(page);<br>      const summary = page.validationSummary;<br>      const fin = summary.financials;<br>      const rec = page.receipt;<br>      const currentImg = rec &amp;&amp; rec.pages &amp;&amp; rec.pages[rec.currentPage - 1] ? rec.pages[rec.currentPage - 1] : null;<br>      const selectedRowId = appState.ui.selectedComparisonRowId;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-[10px] font-bold uppercase tracking-wider text-slate-400&quot;&gt;Active Main Page (Isolated)&lt;/label&gt;<br>              &lt;select onchange=&quot;switchActiveMainPage(this.value)&quot; class=&quot;mt-0.5 text-xs font-bold bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-1.5&quot;&gt;<br>                ${proj.mainPages.map(mp =&gt; `&lt;option value=&quot;${mp.id}&quot; ${mp.id === page.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(mp.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;pt-3&quot;&gt;${statusBadge(summary.overallStatus)}&lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;${rec ? &#39;Replace Receipt&#39; : &#39;Upload Receipt (PNG/JPG/WEBP/PDF)&#39;}&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;.png,.jpg,.jpeg,.webp,.pdf,image/*,application/pdf&quot; onchange=&quot;handleReceiptUpload(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;pasteReceiptFromClipboardButton()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700&quot; title=&quot;Or press Ctrl+V / Cmd+V anywhere on this screen&quot;&gt;<br>              &lt;i data-lucide=&quot;clipboard-paste&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Paste Image (Ctrl+V)&lt;/span&gt;<br>            &lt;/button&gt;<br>            ${rec ? `<br>              &lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>                &lt;i data-lucide=&quot;scan-text&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Re-Run OCR &amp; Auto-Match&lt;/span&gt;<br>              &lt;/button&gt;<br>              &lt;button onclick=&quot;removeReceiptAttachment()&quot; class=&quot;p-2 rounded-xl text-rose-500 hover:bg-rose-500/10&quot; title=&quot;Remove Receipt Attachment&quot;&gt;<br>                &lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>              &lt;/button&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 xl:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;xl:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl flex flex-col overflow-hidden&quot;&gt;<br>            &lt;div class=&quot;px-4 py-3 border-b border-slate-200 dark:border-slate-800 flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>              &lt;div class=&quot;text-xs font-bold flex items-center gap-2&quot;&gt;<br>                &lt;i data-lucide=&quot;file-check-2&quot; class=&quot;w-4 h-4 text-brand-500&quot;&gt;&lt;/i&gt;<br>                &lt;span&gt;Original Receipt (${escapeHtml(page.name)})&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex items-center gap-1&quot;&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(-0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom Out&quot;&gt;&lt;i data-lucide=&quot;zoom-out&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;span class=&quot;text-[11px] font-mono px-1&quot;&gt;${Math.round(appState.ui.viewerZoom * 100)}%&lt;/span&gt;<br>                &lt;button onclick=&quot;adjustViewerZoom(0.15)&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Zoom In&quot;&gt;&lt;i data-lucide=&quot;zoom-in&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;rotateViewer()&quot; class=&quot;p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800&quot; title=&quot;Rotate 90°&quot;&gt;&lt;i data-lucide=&quot;rotate-cw&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.showOcrBoxes = !appState.ui.showOcrBoxes; renderApp();&quot; class=&quot;px-2 py-1 rounded-lg text-[10px] font-bold border ${appState.ui.showOcrBoxes ? &#39;bg-brand-500/15 text-brand-500 border-brand-500/30&#39; : &#39;border-slate-300 dark:border-slate-700&#39;}&quot;&gt;<br>                  OCR Boxes<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div ondragover=&quot;event.preventDefault()&quot; ondrop=&quot;handleReceiptDrop(event)&quot; class=&quot;relative flex-1 min-h-[420px] max-h-[600px] overflow-auto bg-slate-100 dark:bg-slate-950 flex items-center justify-center p-4&quot;&gt;<br>              ${currentImg ? `<br>                &lt;div class=&quot;relative inline-block transition-transform duration-150&quot; style=&quot;transform: scale(${appState.ui.viewerZoom}) rotate(${appState.ui.viewerRotation}deg);&quot;&gt;<br>                  &lt;img src=&quot;${currentImg}&quot; alt=&quot;Original Receipt&quot; class=&quot;max-w-full rounded-lg shadow-lg border border-slate-300 dark:border-slate-700&quot; /&gt;<br>                  ${appState.ui.showOcrBoxes ? (rec.ocrBlocks || []).filter(b =&gt; b.page === rec.currentPage).map(blk =&gt; {<br>                    const isHighlighted = selectedRowId &amp;&amp; blk.mappedToFeeId === selectedRowId;<br>                    return `<br>                      &lt;div onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${blk.mappedToFeeId || &#39;&#39;}&#39;; renderApp();&quot;<br>                           style=&quot;left:${blk.bbox.x}%; top:${blk.bbox.y}%; width:${blk.bbox.w}%; height:${blk.bbox.h}%;&quot;<br>                           title=&quot;${escapeHtml(blk.rawLine)} (${blk.confidence}% conf)&quot;<br>                           class=&quot;absolute cursor-pointer rounded border-2 transition ${<br>                             isHighlighted<br>                               ? &#39;border-rose-500 bg-rose-500/25 ring-2 ring-rose-400&#39;<br>                               : &#39;border-brand-500/70 bg-brand-500/10 hover:bg-brand-500/25&#39;<br>                           }&quot;&gt;<br>                      &lt;/div&gt;<br>                    `;<br>                  }).join(&#39;&#39;) : &#39;&#39;}<br>                &lt;/div&gt;<br>              ` : `<br>                &lt;div class=&quot;text-center max-w-xs space-y-2 p-6 border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-2xl&quot;&gt;<br>                  &lt;i data-lucide=&quot;file-up&quot; class=&quot;w-8 h-8 text-slate-400 mx-auto&quot;&gt;&lt;/i&gt;<br>                  &lt;div class=&quot;text-xs font-bold&quot;&gt;No Receipt Attached to ${escapeHtml(page.name)}&lt;/div&gt;<br>                  &lt;p class=&quot;text-[11px] text-slate-500&quot;&gt;Drag &amp; drop a PNG, JPG, WEBP, or multi-page PDF receipt here, or press &lt;strong&gt;Ctrl+V&lt;/strong&gt; to paste a receipt screenshot.&lt;/p&gt;<br>                &lt;/div&gt;<br>              `}<br>            &lt;/div&gt;<br><br>            ${rec ? `<br>              &lt;div class=&quot;px-4 py-2.5 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between text-xs bg-slate-50 dark:bg-slate-900&quot;&gt;<br>                &lt;span class=&quot;truncate text-slate-500&quot;&gt;${escapeHtml(rec.fileName)} • Conf: &lt;strong&gt;${rec.ocrConfidence}%&lt;/strong&gt;&lt;/span&gt;<br>                &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(-1)&quot; ${rec.currentPage &lt;= 1 ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;lt;&lt;/button&gt;<br>                  &lt;span class=&quot;font-mono&quot;&gt;Page ${rec.currentPage}/${rec.totalPages}&lt;/span&gt;<br>                  &lt;button onclick=&quot;changeReceiptPage(1)&quot; ${rec.currentPage &gt;= rec.totalPages ? &#39;disabled&#39; : &#39;&#39;} class=&quot;px-2 py-1 rounded bg-slate-200 dark:bg-slate-800 disabled:opacity-40&quot;&gt;&amp;gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            ` : &#39;&#39;}<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;xl:col-span-7 space-y-5&quot;&gt;<br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Side-by-Side EIS Fee &amp; CWT Comparison&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] text-slate-400&quot;&gt;Click any row to highlight OCR location&lt;/span&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                  &lt;thead&gt;<br>                    &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Fee Item&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Expected (Name / Amt / Code)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2&quot;&gt;Receipt Actual (Editable)&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-right&quot;&gt;Diff&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                      &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                    &lt;/tr&gt;<br>                  &lt;/thead&gt;<br>                  &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                    ${page.fees.map(fee =&gt; {<br>                      const val = fee.lastValidation || ValidationEngine.validateFeeRow(fee);<br>                      const isSel = selectedRowId === fee.id;<br>                      return `<br>                        &lt;tr onclick=&quot;appState.ui.selectedComparisonRowId = &#39;${fee.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer transition ${isSel ? &#39;bg-brand-500/10&#39; : &#39;hover:bg-slate-50 dark:hover:bg-slate-800/40&#39;}&quot;&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-semibold&quot;&gt;<br>                            ${escapeHtml(fee.expectedName)}<br>                            ${val.isCwt ? &#39;&lt;span class=&quot;ml-1 px-1.5 py-0.2 rounded text-[9px] bg-amber-500/15 text-amber-500 font-bold&quot;&gt;CWT&lt;/span&gt;&#39; : &#39;&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 font-mono text-[11px]&quot;&gt;<br>                            &lt;div&gt;${escapeHtml(fee.expectedName)}&lt;/div&gt;<br>                            &lt;div class=&quot;text-slate-500&quot;&gt;${escapeHtml(fee.expectedAmount)} • &lt;span class=&quot;font-bold text-indigo-500&quot;&gt;${escapeHtml(fee.expectedCode || &#39;-&#39;)}&lt;/span&gt;&lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 space-y-1&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                            &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualName)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualName&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                            &lt;div class=&quot;flex gap-1&quot;&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualAmount)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualAmount&#39;, this.value)&quot; class=&quot;w-24 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(fee.actualCode)}&quot; onchange=&quot;correctReceiptFeeValue(&#39;${fee.id}&#39;, &#39;actualCode&#39;, this.value)&quot; class=&quot;w-16 px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono uppercase text-[11px]&quot; /&gt;<br>                            &lt;/div&gt;<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-right font-mono font-bold ${val.amountComparison.difference === &#39;0.00&#39; ? &#39;text-emerald-500&#39; : &#39;text-rose-500&#39;}&quot;&gt;<br>                            ${escapeHtml(val.amountComparison.difference)}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 pr-2 text-center font-mono text-[11px] ${fee.ocrConfidence &amp;&amp; fee.ocrConfidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-slate-400&#39;}&quot;&gt;<br>                            ${fee.ocrConfidence ? fee.ocrConfidence + &#39;%&#39; : &#39;Manual&#39;}<br>                          &lt;/td&gt;<br>                          &lt;td class=&quot;py-3 text-center&quot;&gt;${statusBadge(val.status)}&lt;/td&gt;<br>                        &lt;/tr&gt;<br>                        &lt;tr class=&quot;bg-slate-50/60 dark:bg-slate-950/40 text-[11px] text-slate-500&quot;&gt;<br>                          &lt;td colspan=&quot;6&quot; class=&quot;px-3 py-1.5&quot;&gt;<br>                            &lt;span class=&quot;font-semibold text-slate-600 dark:text-slate-300&quot;&gt;Rule Evaluation:&lt;/span&gt; ${escapeHtml(val.explanation)}<br>                          &lt;/td&gt;<br>                        &lt;/tr&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/tbody&gt;<br>                &lt;/table&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;!-- Pasted Dynamic Column Fields Verification --&gt;<br>            ${(() =&gt; {<br>              const configuredCols = page.fields.filter(f =&gt; f.expectedValue !== &#39;&#39; || f.actualValue !== &#39;&#39;);<br>              if (!configuredCols.length) return &#39;&#39;;<br>              const matchedCols = configuredCols.filter(f =&gt; f.lastValidation &amp;&amp; f.lastValidation.status === &#39;PASS&#39;).length;<br>              return `<br>                &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>                  &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Expected Row Columns vs Receipt Verification&lt;/h3&gt;<br>                      &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Auto-searches uploaded/pasted receipt text for every expected column value.&lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                      &lt;span class=&quot;px-2.5 py-1 rounded-full text-xs font-bold ${matchedCols === configuredCols.length ? &#39;bg-emerald-500/15 text-emerald-500&#39; : &#39;bg-amber-500/15 text-amber-500&#39;}&quot;&gt;<br>                        ${matchedCols} / ${configuredCols.length} Expected Columns Matched<br>                      &lt;/span&gt;<br>                      &lt;button onclick=&quot;reMatchExpectedColumnsNow()&quot; class=&quot;px-2.5 py-1 rounded-xl text-xs font-semibold bg-brand-500/10 text-brand-500 hover:bg-brand-500/20&quot;&gt;<br>                        Re-Scan Receipt<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>                    &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                      &lt;thead&gt;<br>                        &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Col&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Configurable Field Name&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Expected Row Value&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2&quot;&gt;Found on Receipt (Editable)&lt;/th&gt;<br>                          &lt;th class=&quot;pb-2 text-center&quot;&gt;Status&lt;/th&gt;<br>                        &lt;/tr&gt;<br>                      &lt;/thead&gt;<br>                      &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                        ${configuredCols.map(f =&gt; {<br>                          const st = f.lastValidation ? f.lastValidation.status : &#39;PENDING&#39;;<br>                          return `<br>                            &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-slate-400&quot;&gt;C${String(f.number).padStart(2, &#39;0&#39;)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-semibold&quot;&gt;${escapeHtml(f.name)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 font-mono text-indigo-500&quot;&gt;${escapeHtml(f.expectedValue)}&lt;/td&gt;<br>                              &lt;td class=&quot;py-2 pr-2&quot;&gt;<br>                                &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(f.actualValue)}&quot; onchange=&quot;updateNumberedField(&#39;${f.id}&#39;, &#39;actualValue&#39;, this.value)&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono text-[11px]&quot; /&gt;<br>                              &lt;/td&gt;<br>                              &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(st)}&lt;/td&gt;<br>                            &lt;/tr&gt;<br>                          `;<br>                        }).join(&#39;&#39;)}<br>                      &lt;/tbody&gt;<br>                    &lt;/table&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            })()}<br><br>            &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-3&quot;&gt;<br>              &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;CWT &amp; Net Settlement Reconciliation&lt;/h3&gt;<br>                &lt;span class=&quot;text-[11px] font-mono text-slate-400&quot;&gt;Deterministic Engine&lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs&quot;&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.expectedGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Expected)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.expectedCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Expected Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-indigo-500 mt-0.5&quot;&gt;${fin.expectedNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Gross Fees (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold mt-0.5&quot;&gt;${fin.actualGross.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Total CWT (Receipt)&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-amber-500 mt-0.5&quot;&gt;-${fin.actualCwt.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;p-3 rounded-xl bg-slate-50 dark:bg-slate-800/60&quot;&gt;<br>                  &lt;div class=&quot;text-slate-400&quot;&gt;Actual Net Total&lt;/div&gt;<br>                  &lt;div class=&quot;text-base font-mono font-bold text-emerald-500 mt-0.5&quot;&gt;${fin.actualNet.toFixed(2)}&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;text-[11px] font-mono text-slate-500 bg-slate-100 dark:bg-slate-800/80 px-3 py-2 rounded-xl&quot;&gt;<br>                Formula: ${escapeHtml(fin.formulaExplanation)}<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function correctReceiptFeeValue(feeId, key, val) {<br>      const page = getActiveMainPage();<br>      const fee = page?.fees.find(f =&gt; f.id === feeId);<br>      if (!fee) return;<br>      const oldVal = fee[key];<br>      fee[key] = val;<br>      fee.manuallyVerified = true;<br>      fee.ocrConfidence = 100;<br>      logActivity(&#39;Manual OCR Correction&#39;, `${page.name}: ${fee.expectedName} (${key}: &quot;${oldVal}&quot; → &quot;${val}&quot;)`);<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manual receipt value correction&#39;);<br>      showToast(&#39;Updated receipt value &amp; recalculated validation.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function adjustViewerZoom(delta) {<br>      appState.ui.viewerZoom = Math.min(2.5, Math.max(0.5, Number((appState.ui.viewerZoom + delta).toFixed(2))));<br>      renderApp();<br>    }<br><br>    function rotateViewer() {<br>      appState.ui.viewerRotation = (appState.ui.viewerRotation + 90) % 360;<br>      renderApp();<br>    }<br><br>    function changeReceiptPage(delta) {<br>      const rec = getActiveMainPage()?.receipt;<br>      if (!rec) return;<br>      const next = rec.currentPage + delta;<br>      if (next &gt;= 1 &amp;&amp; next &lt;= rec.totalPages) {<br>        rec.currentPage = next;<br>        renderApp();<br>      }<br>    }<br><br>    function removeReceiptAttachment() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.receipt = null;<br>      scheduleAutosave(&#39;Removed receipt attachment&#39;);<br>      showToast(&#39;Receipt removed from &#39; + page.name, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function handleReceiptDrop(e) {<br>      e.preventDefault();<br>      const file = e.dataTransfer?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    function handleReceiptUpload(e) {<br>      const file = e.target?.files?.[0];<br>      if (file) processUploadedReceiptFile(file);<br>    }<br><br>    async function processUploadedReceiptFile(file) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br><br>      const allowed = [&#39;image/png&#39;, &#39;image/jpeg&#39;, &#39;image/webp&#39;, &#39;image/svg+xml&#39;, &#39;application/pdf&#39;];<br>      if (!allowed.includes(file.type) &amp;&amp; !/\.(png|jpg|jpeg|webp|pdf)$/i.test(file.name)) {<br>        return showToast(&#39;Unsupported file type. Upload PNG, JPG, WEBP, or PDF.&#39;, &#39;error&#39;);<br>      }<br><br>      showToast(`Processing &quot;${file.name}&quot; for ${page.name}...`, &#39;info&#39;);<br>      const now = new Date().toISOString();<br><br>      if (file.type === &#39;application/pdf&#39; || /\.pdf$/i.test(file.name)) {<br>        try {<br>          const arrayBuf = await file.arrayBuffer();<br>          const pdf = await pdfjsLib.getDocument({ data: arrayBuf }).promise;<br>          const pageImages = [];<br>          let combinedText = &#39;&#39;;<br><br>          for (let pNum = 1; pNum &lt;= pdf.numPages; pNum++) {<br>            const pdfPage = await pdf.getPage(pNum);<br>            const viewport = pdfPage.getViewport({ scale: 1.5 });<br>            const canvas = document.createElement(&#39;canvas&#39;);<br>            canvas.width = viewport.width;<br>            canvas.height = viewport.height;<br>            const ctx = canvas.getContext(&#39;2d&#39;);<br>            await pdfPage.render({ canvasContext: ctx, viewport }).promise;<br>            pageImages.push(canvas.toDataURL(&#39;image/png&#39;));<br><br>            const txtContent = await pdfPage.getTextContent();<br>            const pageText = txtContent.items.map(it =&gt; it.str).join(&#39; &#39;);<br>            combinedText += pageText + &#39;\n&#39;;<br>          }<br><br>          const blocks = OcrMappingEngine.parseReceiptTextToBlocks(combinedText, 1, 94);<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: &#39;application/pdf&#39;,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: pdf.numPages,<br>            pages: pageImages,<br>            ocrRawText: combinedText.trim(),<br>            ocrConfidence: 94,<br>            ocrBlocks: blocks,<br>            history: [{ action: `Uploaded ${pdf.numPages}-page PDF &amp; Extracted Text`, timestamp: now }]<br>          };<br><br>          const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>          logActivity(&#39;Uploaded PDF Receipt&#39;, `${file.name} (${pdf.numPages} pages) → ${page.name}`);<br>          scheduleAutosave(&#39;Uploaded PDF receipt&#39;);<br>          showToast(`PDF loaded (${pdf.numPages} pages). Auto-mapped ${mapRes.autoAccepted} items.`, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          showToast(&#39;PDF parsing error: &#39; + err.message, &#39;error&#39;);<br>        }<br>      } else {<br>        const reader = new FileReader();<br>        reader.onload = async (ev) =&gt; {<br>          const dataUrl = ev.target.result;<br>          page.receipt = {<br>            id: &#39;rec_&#39; + Date.now(),<br>            fileName: file.name,<br>            mimeType: file.type,<br>            uploadedAt: now,<br>            currentPage: 1,<br>            totalPages: 1,<br>            pages: [dataUrl],<br>            ocrRawText: &#39;&#39;,<br>            ocrConfidence: 0,<br>            ocrBlocks: [],<br>            history: [{ action: &#39;Uploaded Image Receipt&#39;, timestamp: now }]<br>          };<br>          scheduleAutosave(&#39;Uploaded receipt image&#39;);<br>          renderApp();<br>          await runOcrOnActiveReceipt();<br>        };<br>        reader.readAsDataURL(file);<br>      }<br>    }<br><br>    async function runOcrOnActiveReceipt() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Attach a receipt first.&#39;, &#39;warning&#39;);<br><br>      const rec = page.receipt;<br>      const imgUrl = rec.pages[rec.currentPage - 1];<br>      if (!imgUrl) return;<br><br>      showToast(&#39;Running local OCR preprocessing &amp; extraction...&#39;, &#39;info&#39;);<br>      try {<br>        const preprocessed = await OcrMappingEngine.preprocessImageCanvas(imgUrl, { grayscale: true, contrast: true, scale: 1.5 });<br>        const ocrOut = await OcrMappingEngine.runRealTesseractOCR(preprocessed);<br>        rec.ocrRawText = ocrOut.text;<br>        rec.ocrConfidence = ocrOut.confidence;<br>        rec.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(ocrOut.text, rec.currentPage, ocrOut.confidence);<br>        rec.history.unshift({ action: `OCR Re-run (${ocrOut.confidence}% confidence)`, timestamp: new Date().toISOString() });<br><br>        const mapRes = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>        scheduleAutosave(&#39;Completed OCR extraction&#39;);<br>        showToast(`OCR complete (${ocrOut.confidence}% conf). Auto-mapped: ${mapRes.autoAccepted}, Review: ${mapRes.reviewNeeded}`, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;OCR notice: &#39; + err.message + &#39;. You can also enter/edit extracted text in OCR &amp; Doc Intel.&#39;, &#39;warning&#39;);<br>      }<br>    }<br><br>    function reMatchExpectedColumnsNow() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.receipt) return showToast(&#39;Upload or paste a receipt first.&#39;, &#39;warning&#39;);<br>      const res = RowToFieldsEngine.autoMatchReceiptAgainstExpectedFields(page);<br>      scheduleAutosave(&#39;Re-matched expected columns against receipt&#39;);<br>      showToast(`Matched ${res.matched} of ${res.total} expected columns against receipt.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    async function pasteReceiptFromClipboardButton() {<br>      try {<br>        if (!navigator.clipboard || !navigator.clipboard.read) {<br>          return showToast(&#39;Press Ctrl+V (or Cmd+V) directly on the page to paste your receipt screenshot.&#39;, &#39;info&#39;);<br>        }<br>        const items = await navigator.clipboard.read();<br>        for (const item of items) {<br>          const imgType = item.types.find(t =&gt; t.startsWith(&#39;image/&#39;));<br>          if (imgType) {<br>            const blob = await item.getType(imgType);<br>            const file = new File([blob], `pasted_receipt_${Date.now()}.png`, { type: imgType });<br>            await processUploadedReceiptFile(file);<br>            return;<br>          }<br>        }<br>        showToast(&#39;No image found in clipboard. Copy a receipt screenshot first, then press Ctrl+V.&#39;, &#39;warning&#39;);<br>      } catch (e) {<br>        showToast(&#39;Press Ctrl+V (or Cmd+V) anywhere in Receipt Validation to paste your clipboard image.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    /****************************************************************************<br>     * MODULE 5 VIEW: OCR &amp; DOCUMENT INTELLIGENCE<br>     ****************************************************************************/<br>    function renderOcrIntelligenceModule() {<br>      const page = getActiveMainPage();<br>      const rec = page?.receipt;<br>      if (!page) return `&lt;div class=&quot;p-6&quot;&gt;No Main Page selected.&lt;/div&gt;`;<br><br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;OCR Preprocessing &amp; Raw Text Editor&lt;/h3&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Edit or paste raw receipt OCR text for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt; to re-parse blocks and test smart field mapping.&lt;/p&gt;<br><br>            &lt;div class=&quot;grid grid-cols-2 gap-2 text-xs&quot;&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Grayscale Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Contrast Enhancement (1.35x)&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;1.5x Resolution Upscale&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 dark:bg-slate-800/70&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; checked disabled class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;CWT Sign Normalization&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Extracted / Manual Receipt Text&lt;/label&gt;<br>              &lt;textarea id=&quot;ocr-manual-raw-text&quot; rows=&quot;10&quot; placeholder=&quot;Fee 1 Charge | 1000.00 | NC&amp;#10;Fee 2 Charge | 250.00 | IC&amp;#10;CWT | -50.00 | CWT&quot; class=&quot;w-full p-3 rounded-xl bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 font-mono text-xs&quot;&gt;${escapeHtml(rec ? rec.ocrRawText : &#39;&#39;)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;applyManualOcrTextAndMap()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                Parse Text &amp; Auto-Map to Main Page<br>              &lt;/button&gt;<br>              ${rec ? `&lt;button onclick=&quot;runOcrOnActiveReceipt()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700&quot;&gt;Re-Run Image OCR&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Detected Document Structure &amp; Smart Mapping&lt;/h3&gt;<br>              &lt;span class=&quot;text-xs text-slate-400&quot;&gt;Auto-Accept Threshold: ≥${appState.settings.autoAcceptConfidenceThreshold}%&lt;/span&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>              &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                &lt;thead&gt;<br>                  &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Page&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Detected Label&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Amount&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Code&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2 text-center&quot;&gt;Conf&lt;/th&gt;<br>                    &lt;th class=&quot;pb-2&quot;&gt;Mapped Main Page Fee&lt;/th&gt;<br>                  &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                  ${!rec || !(rec.ocrBlocks || []).length ? `<br>                    &lt;tr&gt;&lt;td colspan=&quot;6&quot; class=&quot;py-8 text-center text-slate-400&quot;&gt;No OCR blocks detected yet. Upload a receipt or parse raw text on the left.&lt;/td&gt;&lt;/tr&gt;<br>                  ` : rec.ocrBlocks.map(blk =&gt; `<br>                    &lt;tr&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;P${blk.page}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-medium&quot;&gt;${escapeHtml(blk.detectedName)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono&quot;&gt;${escapeHtml(blk.detectedAmount || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 font-mono text-indigo-500&quot;&gt;${escapeHtml(blk.detectedCode || &#39;-&#39;)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5 text-center font-mono ${blk.confidence &lt; appState.settings.autoAcceptConfidenceThreshold ? &#39;text-amber-500 font-bold&#39; : &#39;text-emerald-500&#39;}&quot;&gt;${blk.confidence}%&lt;/td&gt;<br>                      &lt;td class=&quot;py-2.5&quot;&gt;<br>                        &lt;select onchange=&quot;manuallyMapOcrBlock(&#39;${blk.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                          &lt;option value=&quot;&quot;&gt;-- Unmapped --&lt;/option&gt;<br>                          ${page.fees.map(f =&gt; `&lt;option value=&quot;${f.id}&quot; ${blk.mappedToFeeId === f.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(f.expectedName)} (${escapeHtml(f.expectedCode)})&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `).join(&#39;&#39;)}<br>                &lt;/tbody&gt;<br>              &lt;/table&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function applyManualOcrTextAndMap() {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      const rawText = document.getElementById(&#39;ocr-manual-raw-text&#39;).value;<br>      const now = new Date().toISOString();<br>      if (!page.receipt) {<br>        page.receipt = {<br>          id: &#39;rec_manual_&#39; + Date.now(),<br>          fileName: &#39;manual_ocr_transcript.txt&#39;,<br>          mimeType: &#39;text/plain&#39;,<br>          uploadedAt: now,<br>          currentPage: 1,<br>          totalPages: 1,<br>          pages: [],<br>          ocrRawText: rawText,<br>          ocrConfidence: 95,<br>          ocrBlocks: [],<br>          history: []<br>        };<br>      }<br>      page.receipt.ocrRawText = rawText;<br>      page.receipt.ocrConfidence = 95;<br>      page.receipt.ocrBlocks = OcrMappingEngine.parseReceiptTextToBlocks(rawText, page.receipt.currentPage || 1, 95);<br>      page.receipt.history.unshift({ action: &#39;Manual Text Parsed &amp; Mapped&#39;, timestamp: now });<br><br>      const res = OcrMappingEngine.autoMapBlocksToMainPage(page);<br>      scheduleAutosave(&#39;Mapped manual OCR text&#39;);<br>      showToast(`Parsed ${page.receipt.ocrBlocks.length} blocks. Auto-mapped: ${res.autoAccepted}, Review: ${res.reviewNeeded}`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function manuallyMapOcrBlock(blockId, feeId) {<br>      const page = getActiveMainPage();<br>      const blk = page?.receipt?.ocrBlocks.find(b =&gt; b.id === blockId);<br>      if (!blk) return;<br>      blk.mappedToFeeId = feeId || null;<br>      if (feeId) {<br>        const fee = page.fees.find(f =&gt; f.id === feeId);<br>        if (fee) {<br>          fee.actualName = blk.detectedName;<br>          fee.actualAmount = blk.detectedAmount;<br>          fee.actualCode = blk.detectedCode || fee.actualCode;<br>          fee.ocrConfidence = blk.confidence;<br>          fee.sourceLocation = `Page ${blk.page} (Manual Map)`;<br>        }<br>      }<br>      ValidationEngine.validateMainPage(page, true);<br>      scheduleAutosave(&#39;Manually mapped OCR block&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 6 VIEW: QA SCREENSHOT STUDIO &amp; EVIDENCE ANNOTATIONS (1-200+)<br>     ****************************************************************************/<br>    let activeStudioScreenshotIdx = 0;<br><br>    function getNextAvailableQaLabel(page) {<br>      const used = new Set((page?.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      const max = appState.settings.qaLabelMax || 200;<br>      for (let i = 1; i &lt;= max; i++) {<br>        if (!used.has(i)) return i;<br>      }<br>      return max + 1;<br>    }<br><br>    function renderScreenshotStudioModule() {<br>      const proj = getActiveProject();<br>      const page = getActiveMainPage();<br>      if (!proj || !page) return `&lt;div class=&quot;p-6&quot;&gt;No active project.&lt;/div&gt;`;<br><br>      const screenshots = proj.screenshots || [];<br>      if (activeStudioScreenshotIdx &gt;= screenshots.length) activeStudioScreenshotIdx = Math.max(0, screenshots.length - 1);<br>      const activeShot = screenshots[activeStudioScreenshotIdx] || null;<br>      const nextLabel = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br><br>      const labelOptions = [];<br>      const maxLbl = appState.settings.qaLabelMax || 200;<br>      const usedLabels = new Set((page.annotations || []).map(a =&gt; Number(a.qaLabel)));<br>      for (let i = 1; i &lt;= maxLbl; i++) {<br>        labelOptions.push(`&lt;option value=&quot;${i}&quot; ${i === nextLabel ? &#39;selected&#39; : &#39;&#39;}&gt;QA-${i} ${usedLabels.has(i) ? &#39;(Assigned)&#39; : &#39;&#39;}&lt;/option&gt;`);<br>      }<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;label class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white cursor-pointer&quot;&gt;<br>              &lt;i data-lucide=&quot;image-plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Upload Screenshots&lt;/span&gt;<br>              &lt;input type=&quot;file&quot; accept=&quot;image/*&quot; multiple onchange=&quot;handleUploadScreenshots(event)&quot; class=&quot;hidden&quot; /&gt;<br>            &lt;/label&gt;<br>            &lt;button onclick=&quot;captureBrowserScreen()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-indigo-500/15 text-indigo-600 dark:text-indigo-400 border border-indigo-500/30 hover:bg-indigo-500/25&quot;&gt;<br>              &lt;i data-lucide=&quot;monitor-dot&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Capture Screen (Browser Permission)&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;vertical&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Vertical (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;mergeSelectedScreenshots(&#39;horizontal&#39;)&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Merge Horizontal (${appState.ui.selectedScreenshotsForMerge.length})<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;resetMergeHistory()&quot; class=&quot;px-3 py-2 rounded-xl text-xs font-semibold text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>              Reset Merge History (${(proj.mergeHistory || []).length})<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Captures (${screenshots.length})&lt;/h3&gt;<br>              &lt;span class=&quot;text-[10px] text-slate-400&quot;&gt;Check to merge&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${screenshots.length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No screenshots yet.&lt;/div&gt;` : screenshots.map((scr, idx) =&gt; {<br>                const isChecked = appState.ui.selectedScreenshotsForMerge.includes(scr.id);<br>                const isActive = idx === activeStudioScreenshotIdx;<br>                return `<br>                  &lt;div onclick=&quot;activeStudioScreenshotIdx = ${idx}; renderApp();&quot; class=&quot;p-2.5 rounded-xl border cursor-pointer transition ${isActive ? &#39;border-brand-500 bg-brand-500/10&#39; : &#39;border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50&#39;}&quot;&gt;<br>                    &lt;div class=&quot;flex items-center justify-between gap-2 mb-1.5&quot; onclick=&quot;event.stopPropagation()&quot;&gt;<br>                      &lt;label class=&quot;inline-flex items-center gap-1.5 text-[11px] font-semibold truncate&quot;&gt;<br>                        &lt;input type=&quot;checkbox&quot; ${isChecked ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;toggleScreenshotMergeSelect(&#39;${scr.id}&#39;)&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                        &lt;span class=&quot;truncate&quot;&gt;${escapeHtml(scr.name)}&lt;/span&gt;<br>                      &lt;/label&gt;<br>                      &lt;div class=&quot;flex items-center gap-1 shrink-0&quot;&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, -1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Up&quot;&gt;↑&lt;/button&gt;<br>                        &lt;button onclick=&quot;moveScreenshot(${idx}, 1)&quot; class=&quot;text-slate-400 hover:text-slate-200&quot; title=&quot;Move Down&quot;&gt;↓&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteScreenshot(&#39;${scr.id}&#39;)&quot; class=&quot;text-rose-500 hover:opacity-80&quot; title=&quot;Delete&quot;&gt;&amp;times;&lt;/button&gt;<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;img src=&quot;${scr.dataUrl}&quot; alt=&quot;${escapeHtml(scr.name)}&quot; class=&quot;w-full h-24 object-cover rounded-lg bg-slate-950&quot; /&gt;<br>                    &lt;div class=&quot;flex items-center justify-between text-[10px] text-slate-400 mt-1&quot;&gt;<br>                      &lt;span&gt;${scr.isMerged ? &#39;Merged Output&#39; : escapeHtml(scr.source)}&lt;/span&gt;<br>                      &lt;a href=&quot;${scr.dataUrl}&quot; download=&quot;${escapeHtml(scr.name)}.png&quot; onclick=&quot;event.stopPropagation()&quot; class=&quot;text-brand-500 hover:underline&quot;&gt;Download&lt;/a&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                `;<br>              }).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2 pb-2 border-b border-slate-200 dark:border-slate-800&quot;&gt;<br>              &lt;div class=&quot;flex items-center gap-1.5&quot;&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;rect&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;rect&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Rectangle&lt;/button&gt;<br>                &lt;button onclick=&quot;appState.ui.annotationTool = &#39;circle&#39;; renderApp();&quot; class=&quot;px-2.5 py-1.5 rounded-lg text-xs font-semibold ${appState.ui.annotationTool === &#39;circle&#39; ? &#39;bg-brand-600 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800&#39;}&quot;&gt;Circle&lt;/button&gt;<br>                &lt;input type=&quot;color&quot; value=&quot;${appState.ui.annotationColor}&quot; onchange=&quot;appState.ui.annotationColor = this.value&quot; class=&quot;w-8 h-8 rounded cursor-pointer bg-transparent&quot; title=&quot;Annotation Color&quot; /&gt;<br>              &lt;/div&gt;<br><br>              &lt;div class=&quot;flex items-center gap-2 text-xs&quot;&gt;<br>                &lt;select onchange=&quot;appState.ui.selectedQaLabel = Number(this.value)&quot; class=&quot;px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot;&gt;<br>                  ${labelOptions.join(&#39;&#39;)}<br>                &lt;/select&gt;<br>                &lt;label class=&quot;inline-flex items-center gap-1 cursor-pointer&quot; title=&quot;Auto-increment to next unused QA label&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; ${appState.settings.qaAutoIncrement ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.qaAutoIncrement = this.checked; scheduleAutosave(&#39;Toggled QA auto-increment&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                  &lt;span&gt;Auto-Inc&lt;/span&gt;<br>                &lt;/label&gt;<br>                &lt;button onclick=&quot;increaseQaLabelLimit()&quot; class=&quot;px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[11px]&quot; title=&quot;Increase Max QA Labels&quot;&gt;+50&lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div id=&quot;annotation-stage&quot; class=&quot;relative min-h-[420px] bg-slate-950 rounded-xl overflow-auto flex items-center justify-center p-2 select-none&quot;&gt;<br>              ${activeShot ? `<br>                &lt;div id=&quot;annotation-canvas-wrapper&quot; class=&quot;relative inline-block cursor-crosshair&quot;&gt;<br>                  &lt;img id=&quot;annotation-base-img&quot; src=&quot;${activeShot.dataUrl}&quot; alt=&quot;Evidence Canvas&quot; class=&quot;max-w-full rounded-lg pointer-events-none&quot; /&gt;<br>                  &lt;svg id=&quot;annotation-svg-overlay&quot; class=&quot;absolute inset-0 w-full h-full&quot;&gt;<br>                    ${(page.annotations || []).map(ann =&gt; {<br>                      const isSel = appState.ui.selectedAnnotationId === ann.id;<br>                      const shape = ann.type === &#39;circle&#39;<br>                        ? `&lt;ellipse cx=&quot;${ann.x + ann.w / 2}&quot; cy=&quot;${ann.y + ann.h / 2}&quot; rx=&quot;${Math.abs(ann.w / 2)}&quot; ry=&quot;${Math.abs(ann.h / 2)}&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`<br>                        : `&lt;rect x=&quot;${ann.x}&quot; y=&quot;${ann.y}&quot; width=&quot;${ann.w}&quot; height=&quot;${ann.h}&quot; rx=&quot;4&quot; fill=&quot;${ann.color}22&quot; stroke=&quot;${ann.color}&quot; stroke-width=&quot;${isSel ? 3.5 : 2.5}&quot; /&gt;`;<br>                      return `<br>                        &lt;g onclick=&quot;event.stopPropagation(); appState.ui.selectedAnnotationId = &#39;${ann.id}&#39;; renderApp();&quot; class=&quot;cursor-pointer&quot;&gt;<br>                          ${shape}<br>                          &lt;rect x=&quot;${ann.x}&quot; y=&quot;${Math.max(0, ann.y - 20)}&quot; width=&quot;${Math.max(68, ann.label.length * 7 + 12)}&quot; height=&quot;18&quot; rx=&quot;4&quot; fill=&quot;${ann.color}&quot; /&gt;<br>                          &lt;text x=&quot;${ann.x + 6}&quot; y=&quot;${Math.max(13, ann.y - 7)}&quot; font-family=&quot;sans-serif&quot; font-size=&quot;11&quot; font-weight=&quot;bold&quot; fill=&quot;#ffffff&quot;&gt;${escapeHtml(ann.label)}&lt;/text&gt;<br>                        &lt;/g&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/svg&gt;<br>                &lt;/div&gt;<br>              ` : `&lt;div class=&quot;text-xs text-slate-400&quot;&gt;Upload or capture a screenshot to draw QA annotations.&lt;/div&gt;`}<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex items-center justify-between text-[11px] text-slate-400&quot;&gt;<br>              &lt;span&gt;Click &amp; drag on the image to draw a QA annotation for &lt;strong&gt;${escapeHtml(page.name)}&lt;/strong&gt;.&lt;/span&gt;<br>              ${activeShot ? `&lt;button onclick=&quot;exportAnnotatedEvidenceImage()&quot; class=&quot;text-brand-500 font-semibold hover:underline&quot;&gt;Export Annotated PNG&lt;/button&gt;` : &#39;&#39;}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 space-y-3&quot;&gt;<br>            &lt;h3 class=&quot;text-xs font-bold uppercase tracking-wider text-slate-400&quot;&gt;Page Annotations (${(page.annotations || []).length})&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-2.5 max-h-[540px] overflow-y-auto pr-1&quot;&gt;<br>              ${(page.annotations || []).length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-6 text-center&quot;&gt;No annotations on this Main Page yet.&lt;/div&gt;` : (page.annotations || []).map(ann =&gt; `<br>                &lt;div class=&quot;p-3 rounded-xl border ${appState.ui.selectedAnnotationId === ann.id ? &#39;border-brand-500 bg-brand-500/5&#39; : &#39;border-slate-200 dark:border-slate-800&#39;} space-y-2 text-xs&quot;&gt;<br>                  &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                    &lt;span class=&quot;font-bold&quot; style=&quot;color:${ann.color}&quot;&gt;${escapeHtml(ann.label)}&lt;/span&gt;<br>                    &lt;button onclick=&quot;deleteAnnotation(&#39;${ann.id}&#39;)&quot; class=&quot;text-rose-500 hover:underline text-[11px]&quot;&gt;Delete&lt;/button&gt;<br>                  &lt;/div&gt;<br>                  &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.comment || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;comment&#39;, this.value)&quot; placeholder=&quot;Evidence comment...&quot; class=&quot;w-full px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px]&quot; /&gt;<br>                  &lt;div class=&quot;grid grid-cols-2 gap-1.5&quot;&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.fieldRef || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;fieldRef&#39;, this.value)&quot; placeholder=&quot;Linked Field&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                    &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(ann.defectId || &#39;&#39;)}&quot; onchange=&quot;updateAnnotationProp(&#39;${ann.id}&#39;, &#39;defectId&#39;, this.value)&quot; placeholder=&quot;Defect ID&quot; class=&quot;px-2 py-1 rounded bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[10px]&quot; /&gt;<br>                  &lt;/div&gt;<br>                  &lt;div class=&quot;flex items-center gap-1 pt-1&quot;&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, -10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;←&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 10, 0)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;→&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, -10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↑&lt;/button&gt;<br>                    &lt;button onclick=&quot;nudgeAnnotation(&#39;${ann.id}&#39;, 0, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;↓&lt;/button&gt;<br>                    &lt;button onclick=&quot;resizeAnnotation(&#39;${ann.id}&#39;, 15, 10)&quot; class=&quot;px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-[10px]&quot;&gt;+Size&lt;/button&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `).join(&#39;&#39;)}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function initAnnotationCanvasEvents() {<br>      const wrapper = document.getElementById(&#39;annotation-canvas-wrapper&#39;);<br>      if (!wrapper) return;<br>      let startX = 0, startY = 0, drawing = false;<br><br>      wrapper.onmousedown = (e) =&gt; {<br>        const rect = wrapper.getBoundingClientRect();<br>        startX = e.clientX - rect.left;<br>        startY = e.clientY - rect.top;<br>        drawing = true;<br>      };<br><br>      wrapper.onmouseup = (e) =&gt; {<br>        if (!drawing) return;<br>        drawing = false;<br>        const rect = wrapper.getBoundingClientRect();<br>        const endX = e.clientX - rect.left;<br>        const endY = e.clientY - rect.top;<br>        const w = Math.abs(endX - startX);<br>        const h = Math.abs(endY - startY);<br>        if (w &lt; 12 || h &lt; 12) return;<br><br>        const page = getActiveMainPage();<br>        if (!page) return;<br>        const qaNum = appState.settings.qaAutoIncrement ? getNextAvailableQaLabel(page) : appState.ui.selectedQaLabel;<br>        if ((page.annotations || []).some(a =&gt; Number(a.qaLabel) === Number(qaNum))) {<br>          return showToast(`QA-${qaNum} is already assigned on ${page.name}. Pick an unused label.`, &#39;warning&#39;);<br>        }<br><br>        page.annotations = page.annotations || [];<br>        const newAnn = {<br>          id: &#39;ann_&#39; + Date.now(),<br>          qaLabel: qaNum,<br>          type: appState.ui.annotationTool,<br>          x: Math.round(Math.min(startX, endX)),<br>          y: Math.round(Math.min(startY, endY)),<br>          w: Math.round(w),<br>          h: Math.round(h),<br>          color: appState.ui.annotationColor,<br>          label: `QA-${qaNum}`,<br>          comment: &#39;&#39;,<br>          fieldRef: &#39;&#39;,<br>          testCaseId: &#39;&#39;,<br>          defectId: &#39;&#39;<br>        };<br>        page.annotations.push(newAnn);<br>        appState.ui.selectedAnnotationId = newAnn.id;<br>        if (appState.settings.qaAutoIncrement) {<br>          appState.ui.selectedQaLabel = getNextAvailableQaLabel(page);<br>        }<br>        scheduleAutosave(&#39;Added evidence annotation&#39;);<br>        renderApp();<br>      };<br>    }<br><br>    function nudgeAnnotation(annId, dx, dy) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.x = Math.max(0, ann.x + dx);<br>      ann.y = Math.max(0, ann.y + dy);<br>      scheduleAutosave(&#39;Moved annotation&#39;);<br>      renderApp();<br>    }<br><br>    function resizeAnnotation(annId, dw, dh) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann.w = Math.max(20, ann.w + dw);<br>      ann.h = Math.max(20, ann.h + dh);<br>      scheduleAutosave(&#39;Resized annotation&#39;);<br>      renderApp();<br>    }<br><br>    function updateAnnotationProp(annId, key, val) {<br>      const ann = getActiveMainPage()?.annotations?.find(a =&gt; a.id === annId);<br>      if (!ann) return;<br>      ann[key] = val;<br>      scheduleAutosave(&#39;Updated annotation metadata&#39;);<br>    }<br><br>    function deleteAnnotation(annId) {<br>      const page = getActiveMainPage();<br>      if (!page) return;<br>      page.annotations = (page.annotations || []).filter(a =&gt; a.id !== annId);<br>      scheduleAutosave(&#39;Deleted annotation&#39;);<br>      renderApp();<br>    }<br><br>    function increaseQaLabelLimit() {<br>      appState.settings.qaLabelMax = (appState.settings.qaLabelMax || 200) + 50;<br>      scheduleAutosave(&#39;Increased QA label count&#39;);<br>      showToast(`QA label pool increased to 1–${appState.settings.qaLabelMax}.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function handleUploadScreenshots(e) {<br>      const proj = getActiveProject();<br>      const files = Array.from(e.target.files || []);<br>      if (!proj || !files.length) return;<br>      files.forEach(file =&gt; {<br>        const reader = new FileReader();<br>        reader.onload = (ev) =&gt; {<br>          proj.screenshots.push({<br>            id: &#39;scr_&#39; + Date.now() + &#39;_&#39; + Math.random().toString(36).slice(2, 5),<br>            name: file.name,<br>            dataUrl: ev.target.result,<br>            capturedAt: new Date().toISOString(),<br>            source: &#39;Uploaded File&#39;,<br>            isMerged: false<br>          });<br>          scheduleAutosave(&#39;Uploaded screenshot&#39;);<br>          renderApp();<br>        };<br>        reader.readAsDataURL(file);<br>      });<br>    }<br><br>    async function captureBrowserScreen() {<br>      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {<br>        return showToast(&#39;Screen capture API is not supported in this browser context.&#39;, &#39;warning&#39;);<br>      }<br>      try {<br>        const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br>        const video = document.createElement(&#39;video&#39;);<br>        video.srcObject = stream;<br>        await video.play();<br><br>        const canvas = document.createElement(&#39;canvas&#39;);<br>        canvas.width = video.videoWidth;<br>        canvas.height = video.videoHeight;<br>        canvas.getContext(&#39;2d&#39;).drawImage(video, 0, 0);<br>        stream.getTracks().forEach(t =&gt; t.stop());<br><br>        const proj = getActiveProject();<br>        proj.screenshots.push({<br>          id: &#39;scr_cap_&#39; + Date.now(),<br>          name: `Screen_Capture_${new Date().toISOString().slice(11, 19).replace(/:/g, &#39;-&#39;)}.png`,<br>          dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>          capturedAt: new Date().toISOString(),<br>          source: &#39;Browser Screen Share&#39;,<br>          isMerged: false<br>        });<br>        activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>        scheduleAutosave(&#39;Captured browser screen&#39;);<br>        showToast(&#39;Screen captured and added to QA Studio.&#39;, &#39;success&#39;);<br>        renderApp();<br>      } catch (err) {<br>        showToast(&#39;Screen capture cancelled or permission denied.&#39;, &#39;info&#39;);<br>      }<br>    }<br><br>    function toggleScreenshotMergeSelect(scrId) {<br>      const sel = appState.ui.selectedScreenshotsForMerge;<br>      const idx = sel.indexOf(scrId);<br>      if (idx &gt;= 0) sel.splice(idx, 1);<br>      else sel.push(scrId);<br>      renderApp();<br>    }<br><br>    function moveScreenshot(idx, dir) {<br>      const proj = getActiveProject();<br>      const target = idx + dir;<br>      if (!proj || target &lt; 0 || target &gt;= proj.screenshots.length) return;<br>      const tmp = proj.screenshots[idx];<br>      proj.screenshots[idx] = proj.screenshots[target];<br>      proj.screenshots[target] = tmp;<br>      scheduleAutosave(&#39;Reordered screenshots&#39;);<br>      renderApp();<br>    }<br><br>    function deleteScreenshot(scrId) {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.screenshots = proj.screenshots.filter(s =&gt; s.id !== scrId);<br>      appState.ui.selectedScreenshotsForMerge = appState.ui.selectedScreenshotsForMerge.filter(id =&gt; id !== scrId);<br>      scheduleAutosave(&#39;Deleted screenshot&#39;);<br>      renderApp();<br>    }<br><br>    async function mergeSelectedScreenshots(direction = &#39;vertical&#39;) {<br>      const proj = getActiveProject();<br>      const ids = appState.ui.selectedScreenshotsForMerge;<br>      if (!proj || ids.length &lt; 2) {<br>        return showToast(&#39;Select at least 2 screenshots using the checkboxes to merge.&#39;, &#39;warning&#39;);<br>      }<br>      const chosen = ids.map(id =&gt; proj.screenshots.find(s =&gt; s.id === id)).filter(Boolean);<br>      const loadedImgs = await Promise.all(chosen.map(s =&gt; new Promise(res =&gt; {<br>        const img = new Image();<br>        img.onload = () =&gt; res(img);<br>        img.src = s.dataUrl;<br>      })));<br><br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      if (direction === &#39;vertical&#39;) {<br>        canvas.width = Math.max(...loadedImgs.map(i =&gt; i.width));<br>        canvas.height = loadedImgs.reduce((sum, i) =&gt; sum + i.height, 0);<br>      } else {<br>        canvas.width = loadedImgs.reduce((sum, i) =&gt; sum + i.width, 0);<br>        canvas.height = Math.max(...loadedImgs.map(i =&gt; i.height));<br>      }<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      let offset = 0;<br>      loadedImgs.forEach(img =&gt; {<br>        if (direction === &#39;vertical&#39;) {<br>          ctx.drawImage(img, 0, offset);<br>          offset += img.height;<br>        } else {<br>          ctx.drawImage(img, offset, 0);<br>          offset += img.width;<br>        }<br>      });<br><br>      const mergedObj = {<br>        id: &#39;scr_merged_&#39; + Date.now(),<br>        name: `Merged_${direction}_${chosen.length}imgs.png`,<br>        dataUrl: canvas.toDataURL(&#39;image/png&#39;),<br>        capturedAt: new Date().toISOString(),<br>        source: `Merged (${direction})`,<br>        isMerged: true<br>      };<br>      proj.screenshots.push(mergedObj);<br>      proj.mergeHistory = proj.mergeHistory || [];<br>      proj.mergeHistory.push({ id: mergedObj.id, sourceIds: [...ids], direction, timestamp: mergedObj.capturedAt });<br>      activeStudioScreenshotIdx = proj.screenshots.length - 1;<br>      scheduleAutosave(&#39;Merged screenshots&#39;);<br>      showToast(`Merged ${chosen.length} screenshots (${direction}).`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function resetMergeHistory() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      proj.mergeHistory = [];<br>      appState.ui.selectedScreenshotsForMerge = [];<br>      scheduleAutosave(&#39;Reset merge history&#39;);<br>      showToast(&#39;Merge selection &amp; history cleared.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    function exportAnnotatedEvidenceImage() {<br>      const img = document.getElementById(&#39;annotation-base-img&#39;);<br>      const page = getActiveMainPage();<br>      if (!img || !page) return;<br>      const canvas = document.createElement(&#39;canvas&#39;);<br>      canvas.width = img.naturalWidth || img.width;<br>      canvas.height = img.naturalHeight || img.height;<br>      const scaleX = canvas.width / img.width;<br>      const scaleY = canvas.height / img.height;<br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br><br>      (page.annotations || []).forEach(ann =&gt; {<br>        ctx.strokeStyle = ann.color;<br>        ctx.lineWidth = 3 * scaleX;<br>        if (ann.type === &#39;circle&#39;) {<br>          ctx.beginPath();<br>          ctx.ellipse((ann.x + ann.w / 2) * scaleX, (ann.y + ann.h / 2) * scaleY, Math.abs(ann.w / 2) * scaleX, Math.abs(ann.h / 2) * scaleY, 0, 0, Math.PI * 2);<br>          ctx.stroke();<br>        } else {<br>          ctx.strokeRect(ann.x * scaleX, ann.y * scaleY, ann.w * scaleX, ann.h * scaleY);<br>        }<br>        ctx.fillStyle = ann.color;<br>        ctx.fillRect(ann.x * scaleX, Math.max(0, (ann.y - 22) * scaleY), 110 * scaleX, 22 * scaleY);<br>        ctx.fillStyle = &#39;#ffffff&#39;;<br>        ctx.font = `bold ${Math.round(12 * scaleX)}px sans-serif`;<br>        ctx.fillText(ann.label, (ann.x + 6) * scaleX, Math.max(15 * scaleY, (ann.y - 6) * scaleY));<br>      });<br><br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = canvas.toDataURL(&#39;image/png&#39;);<br>      a.download = `${page.name.replace(/[^a-z0-9]/gi, &#39;_&#39;)}_annotated_evidence.png`;<br>      a.click();<br>      showToast(&#39;Exported annotated evidence PNG.&#39;, &#39;success&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 7 VIEW: TEST CASE MANAGEMENT<br>     ****************************************************************************/<br>    let tcSearchQuery = &#39;&#39;;<br>    let tcStatusFilter = &#39;ALL&#39;;<br><br>    function renderTestCasesModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br>      const list = (proj.testCases || []).filter(tc =&gt; {<br>        const matchText = tc.id.toLowerCase().includes(tcSearchQuery.toLowerCase()) || tc.title.toLowerCase().includes(tcSearchQuery.toLowerCase());<br>        const matchStatus = tcStatusFilter === &#39;ALL&#39; || tc.status === tcStatusFilter;<br>        return matchText &amp;&amp; matchStatus;<br>      });<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>              &lt;input type=&quot;text&quot; value=&quot;${escapeHtml(tcSearchQuery)}&quot; oninput=&quot;tcSearchQuery = this.value; renderApp();&quot; placeholder=&quot;Search test cases...&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;select onchange=&quot;tcStatusFilter = this.value; renderApp();&quot; class=&quot;px-3 py-2 rounded-xl bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                &lt;option value=&quot;ALL&quot; ${tcStatusFilter === &#39;ALL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;All Statuses&lt;/option&gt;<br>                &lt;option value=&quot;PASS&quot; ${tcStatusFilter === &#39;PASS&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PASS&lt;/option&gt;<br>                &lt;option value=&quot;FAIL&quot; ${tcStatusFilter === &#39;FAIL&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;FAIL&lt;/option&gt;<br>                &lt;option value=&quot;PENDING&quot; ${tcStatusFilter === &#39;PENDING&#39; ? &#39;selected&#39; : &#39;&#39;}&gt;PENDING&lt;/option&gt;<br>              &lt;/select&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openTestCaseModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;plus&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;New Test Case&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>              &lt;thead&gt;<br>                &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;ID&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Title &amp; Module&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Linked Main Page&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5&quot;&gt;Priority&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                  &lt;th class=&quot;pb-2.5 text-right&quot;&gt;Actions&lt;/th&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                ${list.map(tc =&gt; {<br>                  const mp = proj.mainPages.find(m =&gt; m.id === tc.mainPageId);<br>                  return `<br>                    &lt;tr class=&quot;hover:bg-slate-50 dark:hover:bg-slate-800/40&quot;&gt;<br>                      &lt;td class=&quot;py-3 font-mono font-bold&quot;&gt;${escapeHtml(tc.id)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 pr-3&quot;&gt;<br>                        &lt;div class=&quot;font-semibold&quot;&gt;${escapeHtml(tc.title)}&lt;/div&gt;<br>                        &lt;div class=&quot;text-[11px] text-slate-400&quot;&gt;${escapeHtml(tc.module)} • Tester: ${escapeHtml(tc.tester)}&lt;/div&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-slate-500&quot;&gt;${mp ? escapeHtml(mp.name) : &#39;-&#39;}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3&quot;&gt;${escapeHtml(tc.priority)}&lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-center&quot;&gt;<br>                        &lt;select onchange=&quot;updateTestCaseStatus(&#39;${tc.id}&#39;, this.value)&quot; class=&quot;px-2 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-[11px] font-bold&quot;&gt;<br>                          ${[&#39;PASS&#39;, &#39;FAIL&#39;, &#39;PENDING&#39;, &#39;REVIEW&#39;].map(st =&gt; `&lt;option value=&quot;${st}&quot; ${tc.status === st ? &#39;selected&#39; : &#39;&#39;}&gt;${st}&lt;/option&gt;`).join(&#39;&#39;)}<br>                        &lt;/select&gt;<br>                      &lt;/td&gt;<br>                      &lt;td class=&quot;py-3 text-right whitespace-nowrap&quot;&gt;<br>                        &lt;button onclick=&quot;openTestCaseModal(&#39;${tc.id}&#39;)&quot; class=&quot;p-1.5 text-slate-400 hover:text-slate-200&quot; title=&quot;Edit&quot;&gt;&lt;i data-lucide=&quot;pencil&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                        &lt;button onclick=&quot;deleteTestCase(&#39;${tc.id}&#39;)&quot; class=&quot;p-1.5 text-rose-500 hover:bg-rose-500/10 rounded&quot; title=&quot;Delete&quot;&gt;&lt;i data-lucide=&quot;trash-2&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  `;<br>                }).join(&#39;&#39;)}<br>              &lt;/tbody&gt;<br>            &lt;/table&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openTestCaseModal(tcId = null) {<br>      const proj = getActiveProject();<br>      const tc = tcId ? proj.testCases.find(t =&gt; t.id === tcId) : null;<br>      openModal({<br>        title: tc ? `Edit Test Case ${tc.id}` : &#39;Create QA Test Case&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Test Case ID&lt;/label&gt;<br>                &lt;input id=&quot;tc-id&quot; type=&quot;text&quot; value=&quot;${escapeHtml(tc ? tc.id : `TC-00${proj.testCases.length + 1}`)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Linked Main Page&lt;/label&gt;<br>                &lt;select id=&quot;tc-mp&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                  ${proj.mainPages.map(m =&gt; `&lt;option value=&quot;${m.id}&quot; ${tc &amp;&amp; tc.mainPageId === m.id ? &#39;selected&#39; : &#39;&#39;}&gt;${escapeHtml(m.name)}&lt;/option&gt;`).join(&#39;&#39;)}<br>                &lt;/select&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Test Case Title *&lt;/label&gt;<br>              &lt;input id=&quot;tc-title&quot; type=&quot;text&quot; value=&quot;${escapeHtml(tc ? tc.title : &#39;&#39;)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Test Steps&lt;/label&gt;<br>              &lt;textarea id=&quot;tc-steps&quot; rows=&quot;3&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;${escapeHtml(tc ? tc.steps : &#39;&#39;)}&lt;/textarea&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Expected Result&lt;/label&gt;<br>                &lt;input id=&quot;tc-exp&quot; type=&quot;text&quot; value=&quot;${escapeHtml(tc ? tc.expectedResult : &#39;&#39;)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Actual Result&lt;/label&gt;<br>                &lt;input id=&quot;tc-act&quot; type=&quot;text&quot; value=&quot;${escapeHtml(tc ? tc.actualResult : &#39;&#39;)}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveTestCaseModal(&#39;${tc ? tc.id : &#39;&#39;}&#39;)&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;Save Test Case&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveTestCaseModal(existingId) {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;tc-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Test case title is required.&#39;, &#39;warning&#39;);<br>      const payload = {<br>        id: document.getElementById(&#39;tc-id&#39;).value.trim() || `TC-${Date.now()}`,<br>        title,<br>        module: &#39;EIS Validation&#39;,<br>        preconditions: &#39;&#39;,<br>        steps: document.getElementById(&#39;tc-steps&#39;).value,<br>        expectedResult: document.getElementById(&#39;tc-exp&#39;).value,<br>        actualResult: document.getElementById(&#39;tc-act&#39;).value,<br>        status: &#39;PENDING&#39;,<br>        priority: &#39;High&#39;,<br>        tester: proj.owner,<br>        executionDate: new Date().toISOString().slice(0, 10),<br>        mainPageId: document.getElementById(&#39;tc-mp&#39;).value,<br>        linkedDefectId: &#39;&#39;<br>      };<br>      if (existingId) {<br>        const idx = proj.testCases.findIndex(t =&gt; t.id === existingId);<br>        if (idx &gt;= 0) proj.testCases[idx] = Object.assign(proj.testCases[idx], payload);<br>      } else {<br>        proj.testCases.push(payload);<br>      }<br>      closeModal();<br>      scheduleAutosave(&#39;Saved test case&#39;);<br>      showToast(&#39;Test case saved.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateTestCaseStatus(tcId, status) {<br>      const tc = getActiveProject()?.testCases.find(t =&gt; t.id === tcId);<br>      if (!tc) return;<br>      tc.status = status;<br>      tc.executionDate = new Date().toISOString().slice(0, 10);<br>      scheduleAutosave(&#39;Updated test case status&#39;);<br>      renderApp();<br>    }<br><br>    function deleteTestCase(tcId) {<br>      const proj = getActiveProject();<br>      proj.testCases = proj.testCases.filter(t =&gt; t.id !== tcId);<br>      scheduleAutosave(&#39;Deleted test case&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * MODULE 8 VIEW: DEFECT MANAGEMENT &amp; JIRA EXPORT<br>     ****************************************************************************/<br>    function renderDefectsModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center justify-between gap-3&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Defect Tracker &amp; Jira Report Generator&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Document receipt mismatches with linked Main Page &amp; QA annotation references.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;openDefectModal()&quot; class=&quot;inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;bug&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Log New Defect&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            ${(proj.defects || []).length === 0 ? `&lt;div class=&quot;text-xs text-slate-400 py-8 text-center&quot;&gt;No defects logged in this project.&lt;/div&gt;` : (proj.defects || []).map(def =&gt; {<br>              const mp = proj.mainPages.find(m =&gt; m.id === def.mainPageId);<br>              return `<br>                &lt;div class=&quot;p-4 rounded-2xl border border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-950/50 space-y-2.5&quot;&gt;<br>                  &lt;div class=&quot;flex flex-wrap items-center justify-between gap-2&quot;&gt;<br>                    &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                      &lt;span class=&quot;font-mono text-xs font-bold text-rose-500&quot;&gt;${escapeHtml(def.id)}&lt;/span&gt;<br>                      &lt;span class=&quot;px-2 py-0.5 rounded text-[10px] font-bold bg-rose-500/15 text-rose-500&quot;&gt;${escapeHtml(def.severity)}&lt;/span&gt;<br>                      &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(def.title)}&lt;/h4&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;flex items-center gap-2&quot;&gt;<br>                      &lt;select onchange=&quot;updateDefectStatus(&#39;${def.id}&#39;, this.value)&quot; class=&quot;px-2.5 py-1 rounded-lg bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-semibold&quot;&gt;<br>                        ${[&#39;Open&#39;, &#39;In Progress&#39;, &#39;Fixed&#39;, &#39;Retest&#39;, &#39;Closed&#39;, &#39;Rejected&#39;].map(st =&gt; `&lt;option value=&quot;${st}&quot; ${def.status === st ? &#39;selected&#39; : &#39;&#39;}&gt;${st}&lt;/option&gt;`).join(&#39;&#39;)}<br>                      &lt;/select&gt;<br>                      &lt;button onclick=&quot;copyJiraDefectReport(&#39;${def.id}&#39;)&quot; class=&quot;inline-flex items-center gap-1 px-3 py-1 rounded-lg text-xs font-semibold bg-indigo-500/15 text-indigo-500 hover:bg-indigo-500/25&quot;&gt;<br>                        &lt;i data-lucide=&quot;copy&quot; class=&quot;w-3.5 h-3.5&quot;&gt;&lt;/i&gt;<br>                        &lt;span&gt;Copy Jira Markup&lt;/span&gt;<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                  &lt;p class=&quot;text-xs text-slate-600 dark:text-slate-300&quot;&gt;${escapeHtml(def.description)}&lt;/p&gt;<br>                  &lt;div class=&quot;flex flex-wrap items-center gap-4 text-[11px] text-slate-400&quot;&gt;<br>                    &lt;span&gt;Main Page: &lt;strong&gt;${mp ? escapeHtml(mp.name) : &#39;-&#39;}&lt;/strong&gt;&lt;/span&gt;<br>                    &lt;span&gt;Test Case: &lt;strong&gt;${escapeHtml(def.linkedTestCaseId || &#39;-&#39;)}&lt;/strong&gt;&lt;/span&gt;<br>                    &lt;span&gt;Evidence Ref: &lt;strong&gt;${escapeHtml(def.annotationRef || &#39;-&#39;)}&lt;/strong&gt;&lt;/span&gt;<br>                    &lt;span&gt;Assignee: &lt;strong&gt;${escapeHtml(def.assignee)}&lt;/strong&gt;&lt;/span&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              `;<br>            }).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function openDefectModal() {<br>      const proj = getActiveProject();<br>      openModal({<br>        title: &#39;Log EIS Validation Defect&#39;,<br>        bodyHtml: `<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Defect ID&lt;/label&gt;<br>                &lt;input id=&quot;def-id&quot; type=&quot;text&quot; value=&quot;DEF-${101 + proj.defects.length}&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Severity&lt;/label&gt;<br>                &lt;select id=&quot;def-sev&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;<br>                  &lt;option&gt;Critical&lt;/option&gt;&lt;option selected&gt;High&lt;/option&gt;&lt;option&gt;Medium&lt;/option&gt;&lt;option&gt;Low&lt;/option&gt;<br>                &lt;/select&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Defect Summary Title *&lt;/label&gt;<br>              &lt;input id=&quot;def-title&quot; type=&quot;text&quot; placeholder=&quot;e.g. Fee 1 amount mismatch on receipt&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>              &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Description &amp; Steps to Reproduce&lt;/label&gt;<br>              &lt;textarea id=&quot;def-desc&quot; rows=&quot;3&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot;&gt;&lt;/textarea&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Expected Result&lt;/label&gt;<br>                &lt;input id=&quot;def-exp&quot; type=&quot;text&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block text-xs font-semibold mb-1&quot;&gt;Actual Result&lt;/label&gt;<br>                &lt;input id=&quot;def-act&quot; type=&quot;text&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-xs&quot; /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        `,<br>        footerHtml: `<br>          &lt;button onclick=&quot;closeModal()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold&quot;&gt;Cancel&lt;/button&gt;<br>          &lt;button onclick=&quot;saveNewDefect()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-rose-600 text-white&quot;&gt;Save Defect&lt;/button&gt;<br>        `<br>      });<br>    }<br><br>    function saveNewDefect() {<br>      const proj = getActiveProject();<br>      const title = document.getElementById(&#39;def-title&#39;).value.trim();<br>      if (!title) return showToast(&#39;Defect title is required.&#39;, &#39;warning&#39;);<br>      proj.defects.unshift({<br>        id: document.getElementById(&#39;def-id&#39;).value.trim(),<br>        title,<br>        description: document.getElementById(&#39;def-desc&#39;).value,<br>        stepsToReproduce: document.getElementById(&#39;def-desc&#39;).value,<br>        expectedResult: document.getElementById(&#39;def-exp&#39;).value,<br>        actualResult: document.getElementById(&#39;def-act&#39;).value,<br>        severity: document.getElementById(&#39;def-sev&#39;).value,<br>        priority: &#39;P1&#39;,<br>        status: &#39;Open&#39;,<br>        environment: &#39;EIS QA&#39;,<br>        linkedTestCaseId: &#39;&#39;,<br>        mainPageId: appState.activeMainPageId,<br>        annotationRef: &#39;&#39;,<br>        dateReported: new Date().toISOString().slice(0, 10),<br>        assignee: &#39;Unassigned&#39;<br>      });<br>      closeModal();<br>      scheduleAutosave(&#39;Logged defect&#39;);<br>      showToast(&#39;Defect logged.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function updateDefectStatus(defId, status) {<br>      const def = getActiveProject()?.defects.find(d =&gt; d.id === defId);<br>      if (!def) return;<br>      def.status = status;<br>      scheduleAutosave(&#39;Updated defect status&#39;);<br>      renderApp();<br>    }<br><br>    function copyJiraDefectReport(defId) {<br>      const proj = getActiveProject();<br>      const def = proj?.defects.find(d =&gt; d.id === defId);<br>      if (!def) return;<br>      const mp = proj.mainPages.find(m =&gt; m.id === def.mainPageId);<br>      const jiraText = [<br>        `h2. [${def.id}] ${def.title}`,<br>        `*Project:* ${proj.name} (${proj.reference})`,<br>        `*Severity:* ${def.severity} | *Status:* ${def.status}`,<br>        `*Main Page:* ${mp ? mp.name : &#39;N/A&#39;} | *Evidence Ref:* ${def.annotationRef || &#39;N/A&#39;}`,<br>        ``,<br>        `h3. Description &amp; Steps to Reproduce`,<br>        `${def.description}`,<br>        ``,<br>        `h3. Expected vs Actual`,<br>        `* *Expected:* ${def.expectedResult}`,<br>        `* *Actual:* ${def.actualResult}`<br>      ].join(&#39;\n&#39;);<br><br>      const ta = document.createElement(&#39;textarea&#39;);<br>      ta.value = jiraText;<br>      document.body.appendChild(ta);<br>      ta.select();<br>      document.execCommand(&#39;copy&#39;);<br>      ta.remove();<br>      showToast(&#39;Jira-formatted defect report copied to clipboard!&#39;, &#39;success&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 9 VIEW: UNIFIED VALIDATION REPORTS (CSV, JSON, PRINT/PDF)<br>     ****************************************************************************/<br>    function renderReportsModule() {<br>      const proj = getActiveProject();<br>      if (!proj) return &#39;&#39;;<br><br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-4 flex flex-wrap items-center justify-between gap-3 no-print&quot;&gt;<br>          &lt;div&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Unified Validation &amp; QA Evidence Report&lt;/h3&gt;<br>            &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Export real project calculations, fee-by-fee variances, CWT deductions, and QA status.&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;flex flex-wrap items-center gap-2&quot;&gt;<br>            &lt;button onclick=&quot;exportReportCsv()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;file-spreadsheet&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Export CSV&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;exportProjectJson(&#39;${proj.id}&#39;)&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-slate-100 dark:bg-slate-800 hover:bg-slate-200&quot;&gt;<br>              &lt;i data-lucide=&quot;file-json&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Export JSON&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;button onclick=&quot;window.print()&quot; class=&quot;inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>              &lt;i data-lucide=&quot;printer&quot; class=&quot;w-4 h-4&quot;&gt;&lt;/i&gt;<br>              &lt;span&gt;Print / Save as PDF&lt;/span&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;div id=&quot;printable-report-area&quot; class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-6 space-y-6&quot;&gt;<br>          &lt;div class=&quot;border-b border-slate-200 dark:border-slate-800 pb-4 flex flex-wrap items-start justify-between gap-4&quot;&gt;<br>            &lt;div&gt;<br>              &lt;div class=&quot;text-xs font-mono text-brand-500 font-bold&quot;&gt;NEXUS EIS &amp; QA VALIDATION REPORT&lt;/div&gt;<br>              &lt;h2 class=&quot;text-xl font-extrabold mt-1&quot;&gt;${escapeHtml(proj.name)}&lt;/h2&gt;<br>              &lt;p class=&quot;text-xs text-slate-500 mt-0.5&quot;&gt;Reference: ${escapeHtml(proj.reference)} • Owner: ${escapeHtml(proj.owner)} • Generated: ${new Date().toLocaleString()}&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;text-right text-xs&quot;&gt;<br>              &lt;div&gt;Main Pages: &lt;strong&gt;${proj.mainPages.length}&lt;/strong&gt;&lt;/div&gt;<br>              &lt;div&gt;Test Cases: &lt;strong&gt;${proj.testCases.length}&lt;/strong&gt; | Defects: &lt;strong&gt;${proj.defects.length}&lt;/strong&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          ${proj.mainPages.map(mp =&gt; {<br>            if (!mp.validationSummary) ValidationEngine.validateMainPage(mp);<br>            const fin = mp.validationSummary.financials;<br>            return `<br>              &lt;div class=&quot;border border-slate-200 dark:border-slate-800 rounded-xl p-4 space-y-3&quot;&gt;<br>                &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>                  &lt;div&gt;<br>                    &lt;h3 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(mp.name)}&lt;/h3&gt;<br>                    &lt;p class=&quot;text-xs text-slate-500&quot;&gt;${escapeHtml(mp.description)}&lt;/p&gt;<br>                  &lt;/div&gt;<br>                  ${statusBadge(mp.validationSummary.overallStatus)}<br>                &lt;/div&gt;<br><br>                &lt;table class=&quot;w-full text-left text-xs&quot;&gt;<br>                  &lt;thead&gt;<br>                    &lt;tr class=&quot;border-b border-slate-200 dark:border-slate-800 text-slate-500&quot;&gt;<br>                      &lt;th class=&quot;py-1.5&quot;&gt;Fee Name&lt;/th&gt;<br>                      &lt;th class=&quot;py-1.5&quot;&gt;Expected&lt;/th&gt;<br>                      &lt;th class=&quot;py-1.5&quot;&gt;Receipt Actual&lt;/th&gt;<br>                      &lt;th class=&quot;py-1.5&quot;&gt;Code (Exp / Act)&lt;/th&gt;<br>                      &lt;th class=&quot;py-1.5 text-right&quot;&gt;Diff&lt;/th&gt;<br>                      &lt;th class=&quot;py-1.5 text-center&quot;&gt;Status&lt;/th&gt;<br>                    &lt;/tr&gt;<br>                  &lt;/thead&gt;<br>                  &lt;tbody class=&quot;divide-y divide-slate-100 dark:divide-slate-800&quot;&gt;<br>                    ${mp.fees.map(f =&gt; {<br>                      const val = f.lastValidation || ValidationEngine.validateFeeRow(f);<br>                      return `<br>                        &lt;tr&gt;<br>                          &lt;td class=&quot;py-2 font-medium&quot;&gt;${escapeHtml(f.expectedName)}&lt;/td&gt;<br>                          &lt;td class=&quot;py-2 font-mono&quot;&gt;${escapeHtml(f.expectedAmount)}&lt;/td&gt;<br>                          &lt;td class=&quot;py-2 font-mono&quot;&gt;${escapeHtml(f.actualAmount || &#39;-&#39;)}&lt;/td&gt;<br>                          &lt;td class=&quot;py-2 font-mono&quot;&gt;${escapeHtml(f.expectedCode)} / ${escapeHtml(f.actualCode || &#39;-&#39;)}&lt;/td&gt;<br>                          &lt;td class=&quot;py-2 text-right font-mono&quot;&gt;${escapeHtml(val.amountComparison.difference)}&lt;/td&gt;<br>                          &lt;td class=&quot;py-2 text-center&quot;&gt;${statusBadge(val.status)}&lt;/td&gt;<br>                        &lt;/tr&gt;<br>                      `;<br>                    }).join(&#39;&#39;)}<br>                  &lt;/tbody&gt;<br>                &lt;/table&gt;<br><br>                &lt;div class=&quot;grid grid-cols-3 gap-2 pt-2 border-t border-slate-100 dark:border-slate-800 text-xs font-mono&quot;&gt;<br>                  &lt;div&gt;Gross: &lt;strong&gt;${fin.actualGross.toFixed(2)}&lt;/strong&gt; (Exp: ${fin.expectedGross.toFixed(2)})&lt;/div&gt;<br>                  &lt;div&gt;CWT: &lt;strong&gt;-${fin.actualCwt.toFixed(2)}&lt;/strong&gt; (Exp: -${fin.expectedCwt.toFixed(2)})&lt;/div&gt;<br>                  &lt;div&gt;Net Total: &lt;strong&gt;${fin.actualNet.toFixed(2)}&lt;/strong&gt; (Exp: ${fin.expectedNet.toFixed(2)})&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            `;<br>          }).join(&#39;&#39;)}<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function exportReportCsv() {<br>      const proj = getActiveProject();<br>      if (!proj) return;<br>      const rows = [[&#39;Project&#39;, &#39;Main Page&#39;, &#39;Fee Name&#39;, &#39;Expected Amount&#39;, &#39;Actual Amount&#39;, &#39;Expected Code&#39;, &#39;Actual Code&#39;, &#39;Difference&#39;, &#39;Status&#39;, &#39;Explanation&#39;]];<br>      proj.mainPages.forEach(mp =&gt; {<br>        mp.fees.forEach(f =&gt; {<br>          const val = f.lastValidation || ValidationEngine.validateFeeRow(f);<br>          rows.push([<br>            proj.name,<br>            mp.name,<br>            f.expectedName,<br>            f.expectedAmount,<br>            f.actualAmount,<br>            f.expectedCode,<br>            f.actualCode,<br>            val.amountComparison.difference,<br>            val.status,<br>            val.explanation<br>          ]);<br>        });<br>      });<br>      const csv = rows.map(r =&gt; r.map(cell =&gt; `&quot;${String(cell ?? &#39;&#39;).replace(/&quot;/g, &#39;&quot;&quot;&#39;)}&quot;`).join(&#39;,&#39;)).join(&#39;\n&#39;);<br>      const blob = new Blob([csv], { type: &#39;text/csv;charset=utf-8;&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `${proj.reference}_validation_report.csv`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>      showToast(&#39;CSV Validation Report downloaded.&#39;, &#39;success&#39;);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 10 VIEW: TEMPLATES<br>     ****************************************************************************/<br>    function renderTemplatesModule() {<br>      return `<br>        &lt;div class=&quot;bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>          &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>            &lt;div&gt;<br>              &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Reusable EIS Fee &amp; Column Schema Templates&lt;/h3&gt;<br>              &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Apply standardized fee structures or custom column header schemas to the active Main Page.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;button onclick=&quot;saveActivePageAsTemplate()&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 text-white&quot;&gt;<br>              Save Active Page as Template<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;grid grid-cols-1 md:grid-cols-2 gap-4&quot;&gt;<br>            ${appState.templates.map(tpl =&gt; `<br>              &lt;div class=&quot;p-4 rounded-xl border border-slate-200 dark:border-slate-800 flex flex-col justify-between gap-3&quot;&gt;<br>                &lt;div&gt;<br>                  &lt;h4 class=&quot;font-bold text-sm&quot;&gt;${escapeHtml(tpl.name)}&lt;/h4&gt;<br>                  &lt;p class=&quot;text-xs text-slate-500 mt-0.5&quot;&gt;${escapeHtml(tpl.description)}&lt;/p&gt;<br>                  ${tpl.columns &amp;&amp; tpl.columns.length ? `<br>                    &lt;div class=&quot;flex flex-wrap gap-1.5 mt-2&quot;&gt;<br>                      ${tpl.columns.map(c =&gt; `&lt;span class=&quot;px-2 py-0.5 rounded bg-indigo-500/10 text-indigo-500 font-mono text-[11px]&quot;&gt;C${String(c.number).padStart(2, &#39;0&#39;)}: ${escapeHtml(c.name)}&lt;/span&gt;`).join(&#39;&#39;)}<br>                    &lt;/div&gt;<br>                  ` : &#39;&#39;}<br>                  ${tpl.fees &amp;&amp; tpl.fees.length ? `<br>                    &lt;div class=&quot;flex flex-wrap gap-1.5 mt-2&quot;&gt;<br>                      ${tpl.fees.map(f =&gt; `&lt;span class=&quot;px-2 py-0.5 rounded bg-slate-100 dark:bg-slate-800 font-mono text-[11px]&quot;&gt;${escapeHtml(f.expectedName)} (${escapeHtml(f.expectedCode)})&lt;/span&gt;`).join(&#39;&#39;)}<br>                    &lt;/div&gt;<br>                  ` : &#39;&#39;}<br>                &lt;/div&gt;<br>                &lt;button onclick=&quot;applyTemplateToActiveMainPage(&#39;${tpl.id}&#39;)&quot; class=&quot;self-start px-3 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/15 text-brand-500 hover:bg-brand-500/25&quot;&gt;<br>                  Apply to Active Main Page<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            `).join(&#39;&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    function applyTemplateToActiveMainPage(tplId) {<br>      const page = getActiveMainPage();<br>      const tpl = appState.templates.find(t =&gt; t.id === tplId);<br>      if (!page || !tpl) return;<br><br>      if (tpl.columns &amp;&amp; tpl.columns.length) {<br>        tpl.columns.forEach((col, idx) =&gt; {<br>          if (!page.fields[idx]) {<br>            page.fields.push({<br>              id: `fld_${idx + 1}_${Date.now()}`,<br>              number: idx + 1,<br>              name: col.name,<br>              expectedValue: &#39;&#39;,<br>              actualValue: &#39;&#39;,<br>              dataType: col.dataType || &#39;Dynamic&#39;,<br>              validationRule: &#39;Exact / Tolerance Match&#39;,<br>              ocrEnabled: true,<br>              required: Boolean(col.required),<br>              tolerance: 0.01,<br>              description: `Template Column #${idx + 1}`,<br>              pageOverride: true,<br>              enabled: true<br>            });<br>          } else {<br>            page.fields[idx].name = col.name;<br>            page.fields[idx].dataType = col.dataType || &#39;Dynamic&#39;;<br>            page.fields[idx].required = Boolean(col.required);<br>            page.fields[idx].enabled = true;<br>          }<br>        });<br>      }<br><br>      if (tpl.fees &amp;&amp; tpl.fees.length) {<br>        tpl.fees.forEach((f, idx) =&gt; {<br>          page.fees.push({<br>            id: `fee_tpl_${Date.now()}_${idx}`,<br>            expectedName: f.expectedName,<br>            expectedAmount: f.expectedAmount,<br>            expectedCode: f.expectedCode,<br>            actualName: &#39;&#39;,<br>            actualAmount: &#39;&#39;,<br>            actualCode: &#39;&#39;,<br>            isCwt: Boolean(f.isCwt),<br>            ocrConfidence: null,<br>            sourceLocation: &#39;&#39;<br>          });<br>        });<br>      }<br><br>      ValidationEngine.validateMainPage(page);<br>      scheduleAutosave(&#39;Applied template&#39;);<br>      showToast(`Applied &quot;${tpl.name}&quot; to ${page.name}`, &#39;success&#39;);<br>      navigateTo(&#39;main-pages&#39;);<br>    }<br><br>    function saveActivePageAsTemplate() {<br>      const page = getActiveMainPage();<br>      if (!page || !page.fees.length) return showToast(&#39;Configure at least one fee on the active Main Page first.&#39;, &#39;warning&#39;);<br>      appState.templates.push({<br>        id: &#39;tpl_&#39; + Date.now(),<br>        name: `${page.name} Template`,<br>        description: `${page.fees.length} configured EIS fee/CWT items`,<br>        fees: page.fees.map(f =&gt; ({<br>          expectedName: f.expectedName,<br>          expectedAmount: f.expectedAmount,<br>          expectedCode: f.expectedCode,<br>          isCwt: FinancialCalculator.isCwtEntry(f)<br>        }))<br>      });<br>      scheduleAutosave(&#39;Saved fee template&#39;);<br>      showToast(&#39;Saved active page fee schema as a reusable template.&#39;, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    function exportFullWorkspaceBackup() {<br>      const payload = {<br>        nexusWorkspaceBackupVersion: 1,<br>        appSchemaVersion: APP_SCHEMA_VERSION,<br>        exportedAt: new Date().toISOString(),<br>        appState: appState<br>      };<br>      const blob = new Blob([JSON.stringify(payload)], { type: &#39;application/json&#39; });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `NEXUS_Full_Workspace_${new Date().toISOString().slice(0, 10)}.json`;<br>      document.body.appendChild(a);<br>      a.click();<br>      a.remove();<br>      setTimeout(() =&gt; URL.revokeObjectURL(url), 1000);<br>      showToast(&#39;Full workspace backup exported, including saved attachments.&#39;, &#39;success&#39;);<br>    }<br><br>    function importFullWorkspaceBackup(event) {<br>      const file = event.target.files &amp;&amp; event.target.files[0];<br>      if (!file) return;<br>      const reader = new FileReader();<br>      reader.onload = async (e) =&gt; {<br>        try {<br>          const parsed = JSON.parse(e.target.result);<br>          const restored = parsed.appState;<br>          if (!restored || !Array.isArray(restored.projects) || !restored.settings) {<br>            throw new Error(&#39;This file is not a valid NEXUS full-workspace backup.&#39;);<br>          }<br>          if (!confirm(&#39;Restore this backup? Current browser workspace data will be replaced. Export a backup of the current workspace first if you need it.&#39;)) return;<br>          appState = PersistenceEngine.migrateState(restored);<br>          appState.schemaVersion = APP_SCHEMA_VERSION;<br>          const ok = await PersistenceEngine.saveState(appState);<br>          if (!ok) throw new Error(&#39;Browser storage could not save the restored workspace. Check available storage.&#39;);<br>          showToast(&#39;Workspace restored successfully, including backed-up attachments.&#39;, &#39;success&#39;);<br>          renderApp();<br>        } catch (err) {<br>          console.error(err);<br>          showToast(&#39;Restore failed: &#39; + (err.message || &#39;Invalid backup file.&#39;), &#39;error&#39;);<br>        } finally {<br>          event.target.value = &#39;&#39;;<br>        }<br>      };<br>      reader.readAsText(file);<br>    }<br><br>    /****************************************************************************<br>     * MODULE 11 VIEW: SETTINGS &amp; 12-POINT ACCEPTANCE DIAGNOSTICS<br>     ****************************************************************************/<br>    let acceptanceTestResults = null;<br><br>    function renderSettingsModule() {<br>      const s = appState.settings;<br>      return `<br>        &lt;div class=&quot;grid grid-cols-1 lg:grid-cols-12 gap-5&quot;&gt;<br>          &lt;div class=&quot;lg:col-span-5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Validation Engine &amp; OCR Thresholds&lt;/h3&gt;<br>            &lt;div class=&quot;space-y-3 text-xs&quot;&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block font-semibold mb-1&quot;&gt;Numeric Amount Tolerance (±)&lt;/label&gt;<br>                &lt;input type=&quot;number&quot; step=&quot;0.01&quot; value=&quot;${s.numericTolerance}&quot; onchange=&quot;appState.settings.numericTolerance = parseFloat(this.value) || 0; scheduleAutosave(&#39;Updated tolerance&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;div&gt;<br>                &lt;label class=&quot;block font-semibold mb-1&quot;&gt;OCR Auto-Accept Confidence Threshold (%)&lt;/label&gt;<br>                &lt;input type=&quot;number&quot; min=&quot;50&quot; max=&quot;100&quot; value=&quot;${s.autoAcceptConfidenceThreshold}&quot; onchange=&quot;appState.settings.autoAcceptConfidenceThreshold = parseInt(this.value, 10) || 85; scheduleAutosave(&#39;Updated OCR threshold&#39;);&quot; class=&quot;w-full px-3 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 font-mono&quot; /&gt;<br>              &lt;/div&gt;<br>              &lt;label class=&quot;flex items-center gap-2 pt-1 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; ${s.caseSensitiveNames ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.caseSensitiveNames = this.checked; scheduleAutosave(&#39;Updated case sensitivity&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Enforce case-sensitive Fee Name matching&lt;/span&gt;<br>              &lt;/label&gt;<br>              &lt;label class=&quot;flex items-center gap-2 cursor-pointer&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; ${s.normalizeWhitespace ? &#39;checked&#39; : &#39;&#39;} onchange=&quot;appState.settings.normalizeWhitespace = this.checked; scheduleAutosave(&#39;Updated whitespace rule&#39;);&quot; class=&quot;rounded text-brand-600&quot; /&gt;<br>                &lt;span&gt;Normalize extra whitespace before comparison&lt;/span&gt;<br>              &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;pt-4 border-t border-slate-200 dark:border-slate-800 space-y-2&quot;&gt;<br>              &lt;div&gt;<br>                &lt;h4 class=&quot;text-xs font-bold&quot;&gt;Complete Workspace Backup&lt;/h4&gt;<br>                &lt;p class=&quot;text-[11px] text-slate-500 dark:text-slate-400&quot;&gt;Exports projects, templates, settings, custom column names, receipt attachments, screenshots, annotations and QA records into one JSON backup.&lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;flex flex-wrap gap-2&quot;&gt;<br>                &lt;button onclick=&quot;exportFullWorkspaceBackup()&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold bg-brand-600 hover:bg-brand-700 text-white&quot;&gt;<br>                  &lt;i data-lucide=&quot;download&quot; class=&quot;w-3.5 h-3.5 inline&quot;&gt;&lt;/i&gt; Export Full Workspace<br>                &lt;/button&gt;<br>                &lt;label class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold border border-slate-200 dark:border-slate-700 cursor-pointer hover:bg-slate-100 dark:hover:bg-slate-800&quot;&gt;<br>                  &lt;i data-lucide=&quot;upload&quot; class=&quot;w-3.5 h-3.5 inline&quot;&gt;&lt;/i&gt; Restore Workspace Backup<br>                  &lt;input type=&quot;file&quot; accept=&quot;.json,application/json&quot; onchange=&quot;importFullWorkspaceBackup(event)&quot; class=&quot;hidden&quot; /&gt;<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>              &lt;p class=&quot;text-[10px] text-amber-600 dark:text-amber-400&quot;&gt;Keep backups somewhere safe. Browser storage can be cleared by browser cleanup, profile resets or manual deletion.&lt;/p&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;pt-4 border-t border-slate-200 dark:border-slate-800 flex flex-wrap gap-2&quot;&gt;<br>              &lt;button onclick=&quot;resetDemoWorkspace()&quot; class=&quot;px-3.5 py-2 rounded-xl text-xs font-semibold border border-amber-500/40 text-amber-500 hover:bg-amber-500/10&quot;&gt;<br>                Restore Default Sample Project<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br><br>          &lt;div class=&quot;lg:col-span-7 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 space-y-4&quot;&gt;<br>            &lt;div class=&quot;flex items-center justify-between&quot;&gt;<br>              &lt;div&gt;<br>                &lt;h3 class=&quot;text-sm font-bold&quot;&gt;Automated 12-Point Acceptance Test Suite&lt;/h3&gt;<br>                &lt;p class=&quot;text-xs text-slate-500&quot;&gt;Verifies Main Page isolation, CWT signs (-50 &amp; (50)), math accuracy, mismatch detection &amp; IndexedDB persistence.&lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;button onclick=&quot;runAllAcceptanceTests()&quot; class=&quot;px-4 py-2 rounded-xl text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm&quot;&gt;<br>                Run 12 Acceptance Tests<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br><br>            ${acceptanceTestResults ? `<br>              &lt;div class=&quot;space-y-2 max-h-[420px] overflow-y-auto pr-1&quot;&gt;<br>                ${acceptanceTestResults.map(t =&gt; `<br>                  &lt;div class=&quot;p-3 rounded-xl border ${t.passed ? &#39;border-emerald-500/30 bg-emerald-500/5&#39; : &#39;border-rose-500/30 bg-rose-500/5&#39;} flex items-center justify-between gap-3 text-xs&quot;&gt;<br>                    &lt;div&gt;<br>                      &lt;div class=&quot;font-bold&quot;&gt;${escapeHtml(t.name)}&lt;/div&gt;<br>                      &lt;div class=&quot;text-slate-500 dark:text-slate-400 text-[11px]&quot;&gt;${escapeHtml(t.detail)}&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    ${statusBadge(t.passed ? &#39;PASS&#39; : &#39;FAIL&#39;)}<br>                  &lt;/div&gt;<br>                `).join(&#39;&#39;)}<br>              &lt;/div&gt;<br>            ` : `&lt;div class=&quot;text-xs text-slate-400 py-10 text-center border border-dashed border-slate-300 dark:border-slate-700 rounded-xl&quot;&gt;Click &lt;strong&gt;Run 12 Acceptance Tests&lt;/strong&gt; to execute live verification checks against the engine.&lt;/div&gt;`}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>    }<br><br>    async function runAllAcceptanceTests() {<br>      const results = [];<br><br>      // TEST 1: Multiple Main Pages Isolation<br>      const pA = { id: &#39;t1&#39;, fees: [{ id: &#39;f1&#39;, expectedName: &#39;A&#39;, expectedAmount: &#39;100&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;A&#39;, actualAmount: &#39;100&#39;, actualCode: &#39;NC&#39; }], fields: [] };<br>      const pB = { id: &#39;t2&#39;, fees: [{ id: &#39;f2&#39;, expectedName: &#39;B&#39;, expectedAmount: &#39;200&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;B&#39;, actualAmount: &#39;200&#39;, actualCode: &#39;IC&#39; }], fields: [] };<br>      ValidationEngine.validateMainPage(pA);<br>      ValidationEngine.validateMainPage(pB);<br>      results.push({<br>        name: &#39;TEST 1 — Multiple Main Pages Isolation&#39;,<br>        passed: pA.validationSummary.financials.actualNet === 100 &amp;&amp; pB.validationSummary.financials.actualNet === 200,<br>        detail: `Page A Net = ${pA.validationSummary.financials.actualNet}, Page B Net = ${pB.validationSummary.financials.actualNet}`<br>      });<br><br>      // TEST 2: Receipt attachment linkage<br>      const proj = getActiveProject();<br>      const linkedOk = proj &amp;&amp; proj.mainPages.length &gt;= 2 &amp;&amp; proj.mainPages[0].receipt?.id !== proj.mainPages[1].receipt?.id;<br>      results.push({<br>        name: &#39;TEST 2 — Isolated Receipt Attachment Linkage&#39;,<br>        passed: Boolean(linkedOk),<br>        detail: `Verified distinct receipt attachments across Main Pages.`<br>      });<br><br>      // TEST 3 &amp; 4 &amp; 5: Fee validation, CWT -50 &amp; (50), Gross 1250, CWT 50, Net 1200<br>      const calcFees = [<br>        { id: &#39;c1&#39;, expectedName: &#39;Fee 1 Charge&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1 Charge&#39;, actualAmount: &#39;1000&#39;, actualCode: &#39;NC&#39; },<br>        { id: &#39;c2&#39;, expectedName: &#39;Fee 2 Charge&#39;, expectedAmount: &#39;250&#39;, expectedCode: &#39;IC&#39;, actualName: &#39;Fee 2 Charge&#39;, actualAmount: &#39;250&#39;, actualCode: &#39;IC&#39; },<br>        { id: &#39;c3&#39;, expectedName: &#39;CWT&#39;, expectedAmount: &#39;-50&#39;, expectedCode: &#39;CWT&#39;, actualName: &#39;CWT&#39;, actualAmount: &#39;(50)&#39;, actualCode: &#39;CWT&#39;, isCwt: true }<br>      ];<br>      const fin = FinancialCalculator.calculateTotals(calcFees);<br>      const cwtRowRes = ValidationEngine.validateFeeRow(calcFees[2]);<br>      results.push({<br>        name: &#39;TEST 3 — Independent Fee Name, Amount &amp; Code Check&#39;,<br>        passed: ValidationEngine.validateFeeRow(calcFees[0]).status === &#39;PASS&#39; &amp;&amp; ValidationEngine.validateFeeRow(calcFees[1]).status === &#39;PASS&#39;,<br>        detail: `Fee 1 (1000/NC) &amp; Fee 2 (250/IC) validated independently.`<br>      });<br>      results.push({<br>        name: &#39;TEST 4 — CWT Notation (-50 and (50))&#39;,<br>        passed: fin.actualCwt === 50 &amp;&amp; cwtRowRes.status === &#39;PASS&#39;,<br>        detail: `Parsed -50 and (50) as 50.00 CWT deduction.`<br>      });<br>      results.push({<br>        name: &#39;TEST 5 — Financial Calculation (Gross 1250, CWT 50, Net 1200)&#39;,<br>        passed: fin.actualGross === 1250 &amp;&amp; fin.actualCwt === 50 &amp;&amp; fin.actualNet === 1200,<br>        detail: `Gross: ${fin.actualGross}, CWT: ${fin.actualCwt}, Net: ${fin.actualNet}`<br>      });<br><br>      // TEST 6: Mismatch FAIL &amp; Diff 200<br>      const mismatchRes = ValidationEngine.validateFeeRow({<br>        id: &#39;m1&#39;, expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;,<br>        actualName: &#39;Fee 1&#39;, actualAmount: &#39;1200&#39;, actualCode: &#39;NC&#39;<br>      });<br>      results.push({<br>        name: &#39;TEST 6 — Amount Mismatch Detection (1000 vs 1200)&#39;,<br>        passed: mismatchRes.status === &#39;FAIL&#39; &amp;&amp; mismatchRes.amountComparison.difference === &#39;200.00&#39;,<br>        detail: `Status: ${mismatchRes.status}, Diff: ${mismatchRes.amountComparison.difference}`<br>      });<br><br>      // TEST 7: Missing Information -&gt; PENDING<br>      const missingRes = ValidationEngine.validateFeeRow({<br>        id: &#39;m2&#39;, expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;,<br>        actualName: &#39;Fee 1&#39;, actualAmount: &#39;1000&#39;, actualCode: &#39;&#39;<br>      });<br>      results.push({<br>        name: &#39;TEST 7 — Missing Required Code Triggers PENDING&#39;,<br>        passed: missingRes.status === &#39;PENDING&#39;,<br>        detail: `Missing actual code evaluated to ${missingRes.status} (never auto-PASS).`<br>      });<br><br>      // TEST 8: OCR Correction Recalculation<br>      const ocrFee = { id: &#39;o1&#39;, expectedName: &#39;Fee 1&#39;, expectedAmount: &#39;1000&#39;, expectedCode: &#39;NC&#39;, actualName: &#39;Fee 1&#39;, actualAmount: &#39;900&#39;, actualCode: &#39;NC&#39; };<br>      const before = ValidationEngine.validateFeeRow(ocrFee).status;<br>      ocrFee.actualAmount = &#39;1000&#39;;<br>      const after = ValidationEngine.validateFeeRow(ocrFee).status;<br>      results.push({<br>        name: &#39;TEST 8 — OCR Manual Correction &amp; Recalculation&#39;,<br>        passed: before === &#39;FAIL&#39; &amp;&amp; after === &#39;PASS&#39;,<br>        detail: `Transitioned from ${before} to ${after} upon correction.`<br>      });<br><br>      // TEST 9, 10, 11, 12: Engine &amp; Persistence checks<br>      const savedOk = await PersistenceEngine.saveState(appState);<br>      results.push({<br>        name: &#39;TEST 9 &amp; 11 — IndexedDB Persistence &amp; JSON Schema Serialization&#39;,<br>        passed: savedOk &amp;&amp; Boolean(JSON.stringify(appState)),<br>        detail: `IndexedDB write succeeded and state is serializable.`<br>      });<br>      results.push({<br>        name: &#39;TEST 10 &amp; 12 — Evidence Annotations &amp; CSV/Report Generation&#39;,<br>        passed: Array.isArray(proj.mainPages[0].annotations) &amp;&amp; typeof exportReportCsv === &#39;function&#39;,<br>        detail: `Evidence annotations stored (${proj.mainPages[0].annotations.length}) &amp; report exporters active.`<br>      });<br><br>      acceptanceTestResults = results;<br>      showToast(`Completed ${results.filter(r =&gt; r.passed).length}/${results.length} acceptance tests.`, &#39;success&#39;);<br>      renderApp();<br>    }<br><br>    async function resetDemoWorkspace() {<br>      appState = createSampleSeedState();<br>      await PersistenceEngine.saveState(appState);<br>      showToast(&#39;Restored clean sample EIS &amp; QA workspace.&#39;, &#39;info&#39;);<br>      renderApp();<br>    }<br><br>    /****************************************************************************<br>     * KEYBOARD SHORTCUTS &amp; INITIALIZATION<br>     ****************************************************************************/<br>    document.addEventListener(&#39;keydown&#39;, (e) =&gt; {<br>      if ((e.ctrlKey || e.metaKey) &amp;&amp; e.key.toLowerCase() === &#39;s&#39;) {<br>        e.preventDefault();<br>        manualSaveProject();<br>      }<br>    });<br><br>    // Global Clipboard Paste Support for Receipt Images (Ctrl+V / Cmd+V)<br>    document.addEventListener(&#39;paste&#39;, async (e) =&gt; {<br>      if (appState.activeModule !== &#39;validation&#39; &amp;&amp; appState.activeModule !== &#39;main-pages&#39;) return;<br>      const items = e.clipboardData?.items;<br>      if (!items) return;<br>      for (const item of items) {<br>        if (item.type.startsWith(&#39;image/&#39;)) {<br>          e.preventDefault();<br>          const file = item.getAsFile();<br>          if (file) {<br>            if (appState.activeModule !== &#39;validation&#39;) navigateTo(&#39;validation&#39;);<br>            await processUploadedReceiptFile(file);<br>          }<br>          break;<br>        }<br>      }<br>    });<br><br>    window.onload = async function () {<br>      try {<br>        const loaded = await PersistenceEngine.loadState();<br>        if (loaded &amp;&amp; loaded.projects &amp;&amp; loaded.projects.length &gt; 0) {<br>          appState = PersistenceEngine.migrateState(loaded);<br>        } else {<br>          appState = createSampleSeedState();<br>          await PersistenceEngine.saveState(appState);<br>        }<br>      } catch (err) {<br>        console.warn(&#39;Falling back to fresh seed state:&#39;, err);<br>        appState = createSampleSeedState();<br>      }<br>      renderApp();<br>    };<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=889bb86296c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QA Screenshot Studio + EIS Receipt Validator v12]]></title>
            <link>https://medium.com/@barabonajansen/qa-screenshot-studio-eis-receipt-validator-v12-48af39e27413?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/48af39e27413</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 06:09:01 GMT</pubDate>
            <atom:updated>2026-11-19T06:09:01.121Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;QA Screenshot Studio + EIS Receipt Validator v12&lt;/title&gt;<br>&lt;script async src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script type=&quot;module&quot;&gt;import * as pdfjsLib from &quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.min.mjs&quot;;window.pdfjsLib=pdfjsLib;pdfjsLib.GlobalWorkerOptions.workerSrc=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.mjs&quot;;&lt;/script&gt;<br>&lt;style&gt;<br>:root {<br>  --bg:#0b1020;--panel:#121a2d;--panel2:#192640;<br>  --border:#2b3b57;--text:#eaf0ff;--muted:#91a0ba;<br>  --accent:#6d8cff;--danger:#ff6477;--green:#31c48d;<br>}<br>*{box-sizing:border-box}<br>body{margin:0;background:var(--bg);color:var(--text);font:14px Arial,sans-serif}<br>button,input,textarea,select{font:inherit}<br>button{padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--panel2);color:var(--text);cursor:pointer}<br>button:hover{border-color:var(--accent)}<br>button:disabled{opacity:.45;cursor:not-allowed}<br>.primary{background:var(--accent);border-color:var(--accent);color:white}<br>.danger{color:#ff9ba6;border-color:#783b49}<br>.success{color:#75e3b5;border-color:#286b55}<br>.mini{padding:3px 7px;font-size:11px}<br>header{padding:17px 21px;background:#10182a;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}<br>h1{font-size:20px;margin:0}<br>h4{margin:12px 0 6px;font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}<br>header p{font-size:12px;color:var(--muted);margin:5px 0 0}<br>.app{display:grid;grid-template-columns:290px minmax(0,1fr) 270px;min-height:calc(100vh - 75px)}<br>.sidebar,.rightbar{padding:15px;background:var(--panel);overflow-y:auto}<br>.sidebar{border-right:1px solid var(--border)}<br>.rightbar{border-left:1px solid var(--border)}<br>.workspace{padding:16px;min-width:0}<br>.section{margin-bottom:22px}<br>.section h3{font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin:0 0 12px}<br>.panel{background:var(--panel);border:1px solid var(--border);border-radius:11px;padding:13px;margin-bottom:14px}<br>.panel-title{font-weight:bold;margin-bottom:12px}<br>details.panel&gt;summary{cursor:pointer;font-weight:bold}<br>.toolbar{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:10px;align-items:center}<br>.toolbar button.active{background:var(--accent);border-color:var(--accent)}<br>.small{font-size:11px;color:var(--muted);line-height:1.6}<br>input[type=text],input[type=number]{width:100%;background:#0c1425;border:1px solid var(--border);border-radius:7px;color:white;padding:9px}<br>textarea{width:100%;background:#0c1425;border:1px solid var(--border);border-radius:7px;color:white;padding:9px;font:12px/1.5 Consolas,monospace;resize:vertical}<br>select{background:#0c1425;border:1px solid var(--border);border-radius:6px;color:white;padding:5px;font-size:11px}<br>input[type=color]{width:42px;height:35px;border:0;background:transparent}<br>input[type=checkbox]{accent-color:var(--accent)}<br>.label-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;max-height:340px;overflow-y:auto;padding-right:3px}<br>.label-item{padding:7px 3px;border:1px solid var(--border);border-radius:7px;text-align:center;background:#0d1628;cursor:pointer;overflow:hidden}<br>.label-item.active{outline:2px solid var(--accent);background:#25365b}.label-item.used{cursor:not-allowed;filter:grayscale(.45)}<br>.label-item strong,.label-item span{display:block}<br>.label-item span{font-size:10px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}<br>.edit-label{display:flex;gap:7px;margin-top:9px}<br>.edit-label input[type=text]{flex:1;min-width:0}<br>.count-row{display:flex;gap:7px;margin:10px 0}<br>.count-row input{flex:1;min-width:0}<br>.toggle-row{display:flex;align-items:center;gap:8px;margin:12px 0;cursor:pointer}<br>.screenshot-list,.annotation-list{display:flex;flex-direction:column;gap:8px}<br>.screenshot-item{display:flex;flex-direction:column;gap:6px;padding:7px;border:1px solid var(--border);border-radius:8px;background:#0d1628;cursor:pointer}<br>.screenshot-item.active{border-color:var(--accent);background:#14213c}<br>.shot-top{display:flex;align-items:center;gap:6px}<br>.shot-meta{display:flex;align-items:center;gap:6px}<br>.shot-meta label{font-size:10px;color:var(--muted);display:flex;align-items:center;gap:3px;white-space:nowrap;cursor:pointer}<br>.shot-meta select{flex:1;min-width:0}<br>.screenshot-item img{width:55px;height:44px;object-fit:contain;background:#080d18}<br>.screenshot-info{flex:1;min-width:0}<br>.screenshot-info strong{display:block;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}<br>.screenshot-info span{font-size:10px;color:var(--muted)}<br>.delete-image{padding:5px 7px;font-size:11px}<br>.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px}<br>.stat{background:var(--panel);border:1px solid var(--border);padding:11px;border-radius:8px}<br>.stat strong{display:block;font-size:19px}<br>.stat span{font-size:11px;color:var(--muted)}<br>.stage-wrap{background:#080d18;border:1px dashed #35435e;border-radius:9px;min-height:350px;padding:12px;overflow:auto;display:flex;justify-content:center;align-items:flex-start}<br>.stage{position:relative;display:inline-block;line-height:0;max-width:100%}<br>#base{display:block;max-width:100%;height:auto;user-select:none}<br>#overlay{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:crosshair}<br>.empty{text-align:center;color:var(--muted);padding:100px 15px;line-height:1.8}<br>.annotation-item{display:flex;align-items:center;gap:8px;padding:8px;border:1px solid var(--border);border-radius:7px;background:#0d1628;cursor:pointer;font-size:11px}<br>.annotation-item.active{border-color:var(--accent)}<br>.annotation-dot{width:12px;height:12px;border-radius:50%;flex-shrink:0}<br>.annotation-item span:nth-child(2){flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}<br>.annotation-item button{padding:4px 6px}<br>.preview-video{display:block;width:100%;max-height:420px;background:#05080e;object-fit:contain;border-radius:8px}<br>.capture-status{padding:9px;border:1px solid var(--border);border-radius:8px;margin:8px 0;color:var(--muted);font-size:11px}<br>#livePanel{display:none}<br>.cfg-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:12px}<br>table.data-table{width:100%;border-collapse:collapse;font-size:12px}<br>.data-table th,.data-table td{border:1px solid var(--border);padding:6px 8px;text-align:left;vertical-align:middle}<br>.data-table th{background:#192640;font-size:11px;color:var(--muted)}<br>.data-table input[type=text],.data-table input[type=number]{padding:6px}<br>.data-table tr.sel td{background:#1a2848}<br>@media(max-width:1100px){.app{grid-template-columns:260px minmax(0,1fr)}.rightbar{grid-column:1/-1;border-left:0;border-top:1px solid var(--border)}}<br>@media(max-width:800px){.cfg-grid{grid-template-columns:1fr}}<br>@media(max-width:700px){.app{display:block}.sidebar,.rightbar{border:0;border-bottom:1px solid var(--border)}}<br><br>.annotation-edit-handle{cursor:nwse-resize}<br>#autosaveStatus{color:var(--green);font-size:12px}<br>.merge-list{max-height:175px;overflow-y:auto;border:1px solid var(--border);border-radius:8px;background:#0d1628;padding:6px;display:flex;flex-direction:column;gap:5px;margin:8px 0}<br>.merge-item{display:flex;align-items:center;gap:6px;font-size:11px;padding:4px 6px;border-radius:6px;background:#101b31;cursor:pointer}<br>.merge-item.merged-before{opacity:.68;border-left:2px solid #f59e0b}<br>.merge-item span.tag-merged{font-size:9px;padding:1px 5px;border-radius:4px;background:#3b2d14;color:#fbbf24;margin-left:auto;white-space:nowrap}<br>.page-progress-box{background:#0d1628;border:1px solid var(--border);border-radius:8px;padding:8px 10px;margin:8px 0;font-size:11px;line-height:1.5}<br>.page-progress-box strong{color:#93c5fd}<br>.modal-backdrop{position:fixed;inset:0;background:rgba(4,8,18,.82);z-index:9999;display:none;align-items:center;justify-content:center;padding:18px}<br>.modal-backdrop.open{display:flex}<br>.modal-card{background:var(--panel);border:1px solid var(--border);border-radius:12px;width:min(1080px,96vw);max-height:90vh;display:flex;flex-direction:column;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.65)}<br>.modal-head{padding:14px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;background:#10182a}<br>.modal-head h2{margin:0;font-size:17px}<br>.modal-body{padding:16px 18px;overflow-y:auto;flex:1}<br>.report-summary-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:14px}<br>.report-kpi{background:#0d1628;border:1px solid var(--border);border-radius:8px;padding:10px}<br>.report-kpi strong{display:block;font-size:18px}<br>.report-kpi span{font-size:11px;color:var(--muted)}<br>.report-page-card{background:#0d1628;border:1px solid var(--border);border-radius:9px;padding:12px;margin-bottom:14px}<br>.report-page-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;flex-wrap:wrap}<br>.report-thumb{max-width:260px;max-height:150px;border:1px solid var(--border);border-radius:6px;margin-top:8px;display:block}<br>@media print{<br> body&gt;*:not(#reportsModal){display:none!important}<br> #reportsModal{position:static!important;display:block!important;background:white!important;padding:0!important}<br> #reportsModal .modal-card{width:100%!important;max-height:none!important;border:0!important;box-shadow:none!important;background:white!important;color:#111!important}<br> #reportsModal .modal-head button,#reportsModal .no-print{display:none!important}<br> #reportsModal .report-page-card,#reportsModal .report-kpi{background:white!important;border:1px solid #ccc!important;color:#111!important;break-inside:avoid}<br> #reportsModal .data-table th{background:#eef2f7!important;color:#111!important}<br> #reportsModal .data-table td,#reportsModal .data-table th{border:1px solid #bbb!important;color:#111!important}<br>}<br><br>.modal-backdrop.fullscreen{padding:0}<br>.modal-backdrop.fullscreen .modal-card{width:100vw;height:100vh;max-height:100vh;border-radius:0;border:0}<br>.eis-tabs{display:flex;gap:8px;border-bottom:1px solid var(--border);padding:10px 18px;background:#0e1628;flex-wrap:wrap;align-items:center}<br>.eis-tab-btn{padding:7px 13px;border-radius:7px;font-size:12px;border:1px solid var(--border);background:var(--panel2);color:var(--text)}<br>.eis-tab-btn.active{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:bold}<br>.eis-split{display:grid;grid-template-columns:360px minmax(0,1fr);gap:14px}<br>@media(max-width:960px){.eis-split{grid-template-columns:1fr}}<br>.eis-card{background:#0d1628;border:1px solid var(--border);border-radius:10px;padding:12px;margin-bottom:12px}<br>.eis-att-item{border:1px solid var(--border);border-radius:8px;padding:9px;background:#101b32;margin-bottom:8px}<br>.eis-att-head{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}<br>.eis-att-preview{max-width:100%;max-height:180px;border:1px solid var(--border);border-radius:6px;margin-top:8px;display:block;background:#070c17}<br>.badge-pass{display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:bold;background:rgba(49,196,141,.18);color:#6ee7b7;border:1px solid rgba(49,196,141,.5)}<br>.badge-fail{display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:bold;background:rgba(255,100,119,.18);color:#fda4af;border:1px solid rgba(255,100,119,.5)}<br>.badge-warn{display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:bold;background:rgba(245,158,11,.18);color:#fcd34d;border:1px solid rgba(245,158,11,.5)}<br>.eis-dropzone{border:1px dashed var(--accent);border-radius:9px;padding:14px;text-align:center;background:#0b1324;cursor:pointer}<br>.eis-dropzone:hover{background:#121e38}<br><br>.fin-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.fin-cell{padding:9px;border:1px solid var(--border);border-radius:7px;background:#0b1426}.fin-cell strong{display:block;font-size:16px;margin-top:3px}@media(max-width:800px){.fin-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;header&gt;<br> &lt;div&gt;<br>  &lt;h1&gt;QA Screenshot &amp; Screen Capture Studio&lt;/h1&gt;<br>  &lt;p&gt;Windows screen capture · QA evidence · Annotations · OCR by number · Docs export&lt;/p&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;toolbar&quot;&gt;<br>  &lt;button class=&quot;primary&quot; onclick=&quot;startScreenCapture()&quot;&gt;▣ Capture Screen&lt;/button&gt;<br>  &lt;button onclick=&quot;document.getElementById(&#39;fileInput&#39;).click()&quot;&gt;＋ Upload Images&lt;/button&gt;<br>  &lt;button onclick=&quot;openConfig()&quot;&gt;⚙ Config&lt;/button&gt;<br>  &lt;button class=&quot;primary&quot; onclick=&quot;openEisModal()&quot;&gt;🧾 EIS Validation&lt;/button&gt;<br>  &lt;button onclick=&quot;openReportsModal()&quot;&gt;📊 View Reports&lt;/button&gt;<br>  &lt;button class=&quot;success&quot; onclick=&quot;exportDocx()&quot;&gt;⬇ Download Docs&lt;/button&gt;<br>  &lt;button onclick=&quot;saveProject()&quot;&gt;💾 Save Project&lt;/button&gt;<br>  &lt;button onclick=&quot;document.getElementById(&#39;projectFile&#39;).click()&quot;&gt;📂 Load Project&lt;/button&gt;<br> &lt;/div&gt;<br>&lt;/header&gt;<br><br>&lt;input type=&quot;file&quot; id=&quot;fileInput&quot; accept=&quot;image/*&quot; multiple hidden&gt;<br>&lt;input type=&quot;file&quot; id=&quot;projectFile&quot; accept=&quot;.json,application/json&quot; hidden&gt;<br>&lt;input type=&quot;file&quot; id=&quot;configFile&quot; accept=&quot;.json,application/json&quot; hidden&gt;<br><br>&lt;div class=&quot;app&quot;&gt;<br>&lt;aside class=&quot;sidebar&quot;&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Windows Screen Capture&lt;/h3&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;startScreenCapture()&quot;&gt;Choose Screen / Window / Tab&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;<br>   The next dialog lets you select your entire screen, an application window, or a browser tab.<br>  &lt;/div&gt;<br>  &lt;div id=&quot;captureStatus&quot; class=&quot;capture-status&quot;&gt;Screen capture is not active.&lt;/div&gt;<br>  &lt;div id=&quot;livePanel&quot;&gt;<br>   &lt;video id=&quot;liveVideo&quot; class=&quot;preview-video&quot; autoplay muted playsinline&gt;&lt;/video&gt;<br>   &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;captureFrame()&quot;&gt;Take Screenshot&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;stopScreenCapture()&quot;&gt;Stop Sharing&lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Pages &amp;amp; Docs&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;imageCount&quot;&gt;0 screenshots&lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;Click a page to work on it. Tick &quot;In docs&quot; and pick a header for each page. Use ▲▼ to reorder.&lt;/div&gt;<br>  &lt;div class=&quot;screenshot-list&quot; id=&quot;screenshots&quot; style=&quot;margin-top:8px&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; style=&quot;margin-top:12px&quot;&gt;Auto-assign headers from the config list, starting at page<br>   &lt;input type=&quot;number&quot; id=&quot;startPage&quot; value=&quot;1&quot; min=&quot;1&quot; style=&quot;width:62px;display:inline-block;padding:4px&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;autoAssignHeaders()&quot;&gt;Auto-assign headers&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;setAllInclude(true)&quot;&gt;All in docs&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;setAllInclude(false)&quot;&gt;None&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;label class=&quot;small&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;docImages&quot; checked&gt; Screenshots&lt;/label&gt;<br>   &lt;label class=&quot;small&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;docTables&quot; checked&gt; Data tables&lt;/label&gt;<br>  &lt;/div&gt;<br>  &lt;button class=&quot;primary&quot; style=&quot;width:100%&quot; onclick=&quot;exportDocx()&quot;&gt;⬇ Download Docs (.docx)&lt;/button&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Merge Images&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;Tick the images you want to merge:&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;selectMergeCandidates(&#39;unmerged&#39;)&quot;&gt;Select Unmerged&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;selectMergeCandidates(&#39;all&#39;)&quot;&gt;Select All&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;selectMergeCandidates(&#39;none&#39;)&quot;&gt;Clear&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;label class=&quot;toggle-row&quot; style=&quot;margin:6px 0;font-size:11px&quot;&gt;<br>   &lt;input type=&quot;checkbox&quot; id=&quot;excludePreviouslyMerged&quot; checked onchange=&quot;onExcludeMergedToggle()&quot;&gt;<br>   Exclude previously merged images<br>  &lt;/label&gt;<br>  &lt;div id=&quot;mergeChecklist&quot; class=&quot;merge-list&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;mergeSelectionStatus&quot;&gt;0 image(s) selected for merge.&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>   &lt;button onclick=&quot;mergeImages(&#39;vertical&#39;)&quot;&gt;Vertical&lt;/button&gt;<br>   &lt;button onclick=&quot;mergeImages(&#39;horizontal&#39;)&quot;&gt;Horizontal&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;resetMergedHistory()&quot; title=&quot;Allow previously merged images to be merged again&quot;&gt;Reset Merged&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;button class=&quot;danger&quot; onclick=&quot;removeAllImages()&quot;&gt;Delete All Images&lt;/button&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;QA Labels&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;Number of labels (1–999)&lt;/div&gt;<br>  &lt;div class=&quot;count-row&quot;&gt;<br>   &lt;input type=&quot;number&quot; id=&quot;labelCount&quot; min=&quot;1&quot; max=&quot;999&quot; value=&quot;200&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;applyLabelCount()&quot;&gt;Apply&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;label class=&quot;toggle-row&quot;&gt;<br>   &lt;input type=&quot;checkbox&quot; id=&quot;autoIncrement&quot;&gt;<br>   Auto-increment labels<br>  &lt;/label&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;autoStatus&quot;&gt;OFF: manually select labels.&lt;/div&gt;<br>  &lt;div class=&quot;page-progress-box&quot; id=&quot;pageTaskProgress&quot;&gt;<br>   &lt;strong&gt;Page Sequence:&lt;/strong&gt; Starts at #1 per page.&lt;br&gt;<br>   &lt;span class=&quot;small&quot;&gt;Select a page to see labeled boxes and continue where you left off.&lt;/span&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;label-grid&quot; id=&quot;labels&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;edit-label&quot;&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;labelName&quot; placeholder=&quot;Label name&quot;&gt;<br>   &lt;input type=&quot;color&quot; id=&quot;labelColor&quot; value=&quot;#ff4242&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;saveLabel()&quot;&gt;Save Label&lt;/button&gt;<br>   &lt;button onclick=&quot;resetLabels()&quot;&gt;Reset&lt;/button&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br><br>&lt;/aside&gt;<br><br>&lt;main class=&quot;workspace&quot;&gt;<br> &lt;div class=&quot;stats&quot;&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statImages&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Screenshots&lt;/span&gt;&lt;/div&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statAnnotations&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Annotations&lt;/span&gt;&lt;/div&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statLabels&quot;&gt;200&lt;/strong&gt;&lt;span&gt;QA Labels&lt;/span&gt;&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;details class=&quot;panel&quot; id=&quot;configPanel&quot;&gt;<br>  &lt;summary&gt;⚙ Config — page headers, numbered fields, OCR, project files&lt;/summary&gt;<br><br>  &lt;div class=&quot;cfg-grid&quot;&gt;<br>   &lt;div&gt;<br>    &lt;h4&gt;Project name&lt;/h4&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;projectName&quot; value=&quot;QA Evidence&quot;&gt;<br>    &lt;h4&gt;Page header titles (one per line)&lt;/h4&gt;<br>    &lt;textarea id=&quot;pageTitlesText&quot; rows=&quot;9&quot; placeholder=&quot;Login Page&amp;#10;Dashboard&amp;#10;Client Details&amp;#10;Payment Page&quot;&gt;&lt;/textarea&gt;<br>    &lt;div class=&quot;small&quot;&gt;Each page can be given one of these as its header in the docs file.&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div&gt;<br>    &lt;h4&gt;Paste field list (number + name)&lt;/h4&gt;<br>    &lt;textarea id=&quot;fieldsPaste&quot; rows=&quot;9&quot; placeholder=&quot;1 | Dynamic Value | my manual value&amp;#10;2 Client Name&amp;#10;3 Invoice Number&amp;#10;4. Total Amount&amp;#10;Address = 5&quot;&gt;&lt;/textarea&gt;<br>    &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>     &lt;button class=&quot;primary&quot; onclick=&quot;applyFieldList()&quot;&gt;Apply list&lt;/button&gt;<br>     &lt;button onclick=&quot;addFieldRow()&quot;&gt;+ Add field&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;small&quot;&gt;<br>     One field per line: &lt;b&gt;2 Client Name&lt;/b&gt;, &lt;b&gt;2. Client Name&lt;/b&gt;, &lt;b&gt;2: Client Name&lt;/b&gt; or &lt;b&gt;Client Name = 2&lt;/b&gt;.&lt;br&gt;<br>     Manual field (fixed value, no OCR): &lt;b&gt;1 | Dynamic Value | your value&lt;/b&gt; or &lt;b&gt;1 Dynamic Value = your value&lt;/b&gt;.<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;h4&gt;Fields (number → name)&lt;/h4&gt;<br>  &lt;table class=&quot;data-table&quot;&gt;<br>   &lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:80px&quot;&gt;#&lt;/th&gt;&lt;th&gt;Field name&lt;/th&gt;&lt;th style=&quot;width:115px&quot;&gt;Type&lt;/th&gt;&lt;th&gt;Manual value&lt;/th&gt;&lt;th style=&quot;width:44px&quot;&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>   &lt;tbody id=&quot;fieldsBody&quot;&gt;&lt;/tbody&gt;<br>  &lt;/table&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;fieldsMsg&quot;&gt;No fields yet. Paste a list above.&lt;/div&gt;<br><br>  &lt;h4&gt;OCR&lt;/h4&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;label class=&quot;small&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;autoOcr&quot; checked&gt; Auto-read text when a box is drawn&lt;/label&gt;<br>   &lt;span class=&quot;small&quot;&gt;Language:&lt;/span&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;ocrLang&quot; value=&quot;eng&quot; style=&quot;width:120px;padding:6px&quot; title=&quot;Tesseract language code, e.g. eng, eng+fra&quot;&gt;<br>   &lt;span class=&quot;small&quot; id=&quot;ocrStatus&quot;&gt;OCR engine loads on first use.&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;h4&gt;Files&lt;/h4&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;success&quot; onclick=&quot;saveProject()&quot;&gt;💾 Save Project (all + config)&lt;/button&gt;<br>   &lt;button onclick=&quot;document.getElementById(&#39;projectFile&#39;).click()&quot;&gt;📂 Load Project&lt;/button&gt;<br>   &lt;button onclick=&quot;exportConfig()&quot;&gt;Export Config JSON&lt;/button&gt;<br>   &lt;button onclick=&quot;document.getElementById(&#39;configFile&#39;).click()&quot;&gt;Import Config JSON&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;Config, images, annotations and page order are saved automatically in this browser using local storage (IndexedDB). They should return when you reopen this same browser and file location.&lt;/div&gt;<br>  &lt;div id=&quot;autosaveStatus&quot; class=&quot;small&quot;&gt;Auto-save is ready.&lt;/div&gt;<br> &lt;/details&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Annotation Tools&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button id=&quot;boxTool&quot; class=&quot;active&quot; onclick=&quot;setMode(&#39;box&#39;)&quot;&gt;▢ Rectangle&lt;/button&gt;<br>   &lt;button id=&quot;circleTool&quot; onclick=&quot;setMode(&#39;circle&#39;)&quot;&gt;◯ Circle&lt;/button&gt;<br>   &lt;button onclick=&quot;undo()&quot;&gt;↶ Undo&lt;/button&gt;<br>   &lt;button class=&quot;danger&quot; onclick=&quot;deleteSelected()&quot;&gt;Delete Selected&lt;/button&gt;<br>   &lt;button class=&quot;danger&quot; onclick=&quot;clearAnnotations()&quot;&gt;Clear Annotations&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;exportPNG()&quot;&gt;Export Current PNG&lt;/button&gt;<br>   &lt;button onclick=&quot;exportAllPNG()&quot;&gt;Export All PNG&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;toolStatus&quot;&gt;Current tool: Rectangle · Select a box to move it; drag its bottom-right handle to resize.&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Screenshot Workspace&lt;/div&gt;<br>  &lt;div class=&quot;stage-wrap&quot;&gt;<br>   &lt;div id=&quot;empty&quot; class=&quot;empty&quot;&gt;<br>    &lt;div style=&quot;font-size:40px&quot;&gt;▣&lt;/div&gt;<br>    &lt;strong&gt;No screenshot loaded&lt;/strong&gt;<br>    &lt;div&gt;Capture your Windows screen or upload an image.&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div id=&quot;stage&quot; class=&quot;stage&quot; hidden&gt;<br>    &lt;img id=&quot;base&quot; alt=&quot;Screenshot&quot;&gt;<br>    &lt;canvas id=&quot;overlay&quot;&gt;&lt;/canvas&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;imageStatus&quot; style=&quot;margin-top:9px&quot;&gt;No active screenshot.&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;panel&quot; id=&quot;pageFieldsPanel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Page-specific Fields &amp;amp; Client Details&lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;Fields belong only to the selected Main Page / receipt page. Format: &lt;b&gt;number | field name | expected value&lt;/b&gt;. Leave value blank for OCR/dynamic values.&lt;/div&gt;<br>  &lt;textarea id=&quot;pageFieldsPaste&quot; rows=&quot;5&quot; placeholder=&quot;1 | Client Name |&amp;#10;2 | TIN |&amp;#10;3 | Invoice Number |&amp;#10;10 | Total Fees |&quot;&gt;&lt;/textarea&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;&lt;button class=&quot;primary&quot; onclick=&quot;applyCurrentPageFields()&quot;&gt;Apply fields to this page&lt;/button&gt;&lt;button onclick=&quot;copyGlobalFieldsToPage()&quot;&gt;Copy global fields here&lt;/button&gt;&lt;button onclick=&quot;clearCurrentPageFields()&quot;&gt;Clear page overrides&lt;/button&gt;&lt;button class=&quot;success&quot; onclick=&quot;openEisForCurrentPage()&quot;&gt;🧾 Receipt Validation for Current Page&lt;/button&gt;&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;pageFieldsStatus&quot;&gt;No page selected.&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;currentPageReceiptStatus&quot; style=&quot;margin-top:6px&quot;&gt;Receipt validation: no receipt attached to the current page.&lt;/div&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Extracted Data (current page)&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button onclick=&quot;reOcrPage()&quot;&gt;Re-read all boxes (OCR)&lt;/button&gt;<br>   &lt;button onclick=&quot;copyExtracted(false)&quot;&gt;Copy page as TSV&lt;/button&gt;<br>   &lt;button onclick=&quot;copyExtracted(true)&quot;&gt;Copy all pages as TSV&lt;/button&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;openReportsModal()&quot;&gt;📊 All Reports / Save / Print&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;table class=&quot;data-table&quot;&gt;<br>   &lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:60px&quot;&gt;#&lt;/th&gt;&lt;th style=&quot;width:30%&quot;&gt;Field&lt;/th&gt;&lt;th&gt;Value (editable)&lt;/th&gt;&lt;th style=&quot;width:150px&quot;&gt;Status&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>   &lt;tbody id=&quot;dataBody&quot;&gt;&lt;/tbody&gt;<br>  &lt;/table&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;dataEmpty&quot;&gt;No extracted data yet. Manual-value fields from Config appear here automatically; OCR fields appear after you draw a box.&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;dataMsg&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/main&gt;<br><br>&lt;aside class=&quot;rightbar&quot;&gt;<br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Annotation History&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;annotationCount&quot;&gt;0 annotations&lt;/div&gt;<br>  &lt;div class=&quot;annotation-list&quot; id=&quot;annotations&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;How to use&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;<br>   1. Capture or upload pages.&lt;br&gt;&lt;br&gt;<br>   2. Open ⚙ Config: add page header titles and paste your numbered field list (e.g. &lt;b&gt;2 Client Name&lt;/b&gt;).&lt;br&gt;&lt;br&gt;<br>   3. Click a page to work on it, assign its header, tick &quot;In docs&quot;.&lt;br&gt;&lt;br&gt;<br>   4. Select a label number, then draw a box. The text inside is read automatically and appears under Extracted Data. Manual fields use the value from Config.&lt;br&gt;&lt;br&gt;<br>   5. Set Page-specific Fields so each page has its own client details and receipt values.&lt;br&gt;&lt;br&gt;6. Attach its receipt/PDF in EIS Validation and compare the receipt against that Main Page.&lt;br&gt;&lt;br&gt;<br>   6. Download Docs (.docx) or Save Project (.json).<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/aside&gt;<br>&lt;/div&gt;<br><br>&lt;div id=&quot;reportsModal&quot; class=&quot;modal-backdrop&quot; onclick=&quot;if(event.target===this)closeReportsModal()&quot;&gt;<br> &lt;div class=&quot;modal-card&quot;&gt;<br>  &lt;div class=&quot;modal-head&quot;&gt;<br>   &lt;div&gt;<br>    &lt;h2&gt;📊 QA Evidence &amp;amp; Extraction Reports&lt;/h2&gt;<br>    &lt;div class=&quot;small&quot; id=&quot;reportSubtitle&quot;&gt;Complete summary across all pages&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div class=&quot;toolbar no-print&quot; style=&quot;margin:0&quot;&gt;<br>    &lt;label class=&quot;small&quot; style=&quot;display:flex;align-items:center;gap:4px&quot;&gt;<br>     &lt;input type=&quot;checkbox&quot; id=&quot;reportIncludeThumbs&quot; checked onchange=&quot;renderReportsModal()&quot;&gt; Include annotated images<br>    &lt;/label&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;downloadReportHTML()&quot;&gt;⬇ Save HTML Report&lt;/button&gt;<br>    &lt;button onclick=&quot;downloadReportCSV()&quot;&gt;⬇ Download CSV&lt;/button&gt;<br>    &lt;button class=&quot;success&quot; onclick=&quot;exportDocx()&quot;&gt;⬇ Download DOCX&lt;/button&gt;<br>    &lt;button onclick=&quot;printReport()&quot;&gt;🖨 Print / Save PDF&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;closeReportsModal()&quot;&gt;✕ Close&lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;modal-body&quot; id=&quot;reportsModalBody&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div id=&quot;eisModal&quot; class=&quot;modal-backdrop fullscreen&quot;&gt;<br> &lt;div class=&quot;modal-card&quot;&gt;<br>  &lt;div class=&quot;modal-head&quot;&gt;<br>   &lt;div&gt;<br>    &lt;h2&gt;🧾 EIS Validation Studio (Full Screen)&lt;/h2&gt;<br>    &lt;div class=&quot;small&quot; id=&quot;eisSubtitle&quot;&gt;Attach receipts/images, target main workspace pages, validate all configured fees, and auto-sync PASS / FAIL results&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div class=&quot;toolbar&quot; style=&quot;margin:0&quot;&gt;<br>    &lt;button id=&quot;eisToggleConfigBtn&quot; onclick=&quot;toggleEisConfigPanel()&quot;&gt;⚙ Fees Config&lt;/button&gt;<br>    &lt;button onclick=&quot;runAllEisValidations()&quot;&gt;🔄 Re-Validate All&lt;/button&gt;<br>    &lt;button onclick=&quot;downloadEisReportCSV()&quot;&gt;⬇ Export EIS CSV&lt;/button&gt;<br>    &lt;button class=&quot;success&quot; onclick=&quot;saveProject()&quot;&gt;💾 Save Project&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;closeEisModal()&quot;&gt;✕ Close&lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;eis-tabs&quot;&gt;<br>   &lt;button class=&quot;eis-tab-btn active&quot; id=&quot;eisTabValidateBtn&quot; onclick=&quot;switchEisTab(&#39;validate&#39;)&quot;&gt;1. Attach &amp;amp; Validate Against Pages&lt;/button&gt;<br>   &lt;button class=&quot;eis-tab-btn&quot; id=&quot;eisTabConfigBtn&quot; onclick=&quot;switchEisTab(&#39;config&#39;)&quot;&gt;2. ⚙ EIS Fees Config (&lt;span id=&quot;eisFeeRuleCount&quot;&gt;0&lt;/span&gt; rules)&lt;/button&gt;<br>   &lt;span class=&quot;small&quot; id=&quot;eisGlobalSummary&quot; style=&quot;margin-left:auto&quot;&gt;Ready · Auto-saved in browser&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;modal-body&quot;&gt;<br>   &lt;!-- TAB 1: ATTACH &amp; VALIDATE --&gt;<br>   &lt;div id=&quot;eisViewValidate&quot;&gt;<br>    &lt;div class=&quot;report-summary-grid&quot;&gt;<br>     &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong id=&quot;eisKpiAttachments&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Attached Receipts&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong id=&quot;eisKpiChecks&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Total Fee Checks&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&quot;report-kpi&quot; style=&quot;border-color:#286b55&quot;&gt;&lt;strong id=&quot;eisKpiPass&quot; style=&quot;color:#6ee7b7&quot;&gt;0&lt;/strong&gt;&lt;span&gt;PASS&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&quot;report-kpi&quot; style=&quot;border-color:#783b49&quot;&gt;&lt;strong id=&quot;eisKpiFail&quot; style=&quot;color:#fda4af&quot;&gt;0&lt;/strong&gt;&lt;span&gt;FAIL&lt;/span&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;eis-split&quot;&gt;<br>     &lt;!-- LEFT: PER-PAGE EIS ATTACHMENTS (MIRRORING MAIN PAGES) --&gt;<br>     &lt;div&gt;<br>      &lt;div class=&quot;eis-card&quot;&gt;<br>       &lt;div style=&quot;display:flex;align-items:center;justify-content:space-between;gap:6px;margin-bottom:6px&quot;&gt;<br>        &lt;div class=&quot;panel-title&quot; style=&quot;margin:0&quot;&gt;Attach Original Receipts (Bulk or Per Page)&lt;/div&gt;<br>        &lt;button class=&quot;mini primary&quot; onclick=&quot;triggerBulkEisAttach()&quot;&gt;＋ Bulk Attach (Page 1..N)&lt;/button&gt;<br>       &lt;/div&gt;<br>       &lt;div class=&quot;small&quot; style=&quot;margin-bottom:8px&quot;&gt;<br>        Each Main Page has its own receipt slot. Attach the original receipt that belongs to that page. The system reads the receipt, compares configured fields and all three fee fields, then reports PASS / FAIL / REVIEW.<br>       &lt;/div&gt;<br>       &lt;input type=&quot;file&quot; id=&quot;eisFileInput&quot; accept=&quot;image/*,.json,.csv,.txt,.xml,.pdf&quot; multiple hidden&gt;<br>       &lt;input type=&quot;file&quot; id=&quot;eisSinglePageFileInput&quot; accept=&quot;image/*,.json,.csv,.txt,.xml,.pdf&quot; hidden&gt;<br>       &lt;div class=&quot;eis-dropzone&quot; onclick=&quot;triggerBulkEisAttach()&quot;&gt;<br>        &lt;div style=&quot;font-size:22px&quot;&gt;📎&lt;/div&gt;<br>        &lt;strong&gt;Click to Bulk-Attach Receipts (Auto-maps to Page 1, 2, 3…)&lt;/strong&gt;<br>        &lt;div class=&quot;small&quot;&gt;Or click &lt;b&gt;📎 Attach Receipt&lt;/b&gt; on any specific page slot below.&lt;/div&gt;<br>       &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;eis-card&quot;&gt;<br>       &lt;div style=&quot;display:flex;align-items:center;justify-content:space-between;gap:6px;margin-bottom:8px&quot;&gt;<br>        &lt;div class=&quot;panel-title&quot; style=&quot;margin:0&quot;&gt;Original Receipts per Main Page (&lt;span id=&quot;eisAttListCount&quot;&gt;0&lt;/span&gt; / &lt;span id=&quot;eisMainPageTotalCount&quot;&gt;0&lt;/span&gt;)&lt;/div&gt;<br>       &lt;/div&gt;<br>       &lt;div id=&quot;eisAttachmentsList&quot;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br><br>     &lt;!-- RIGHT: LIVE COMPARISON &amp; PASS / FAIL RESULTS --&gt;<br>     &lt;div&gt;<br>      &lt;div class=&quot;eis-card&quot;&gt;<br>       &lt;div style=&quot;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:10px&quot;&gt;<br>        &lt;div&gt;<br>         &lt;div class=&quot;panel-title&quot; style=&quot;margin:0&quot;&gt;Live Receipt Validation (Main Page vs Original Receipt)&lt;/div&gt;<br>         &lt;div class=&quot;small&quot; id=&quot;eisActiveCompareInfo&quot;&gt;Select or attach an receipt to inspect fee-by-fee PASS / FAIL validation.&lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;toolbar&quot; style=&quot;margin:0&quot;&gt;<br>         &lt;button class=&quot;mini&quot; onclick=&quot;reOcrActiveEisAttachment()&quot;&gt;🔍 Re-OCR Receipt&lt;/button&gt;<br>         &lt;button class=&quot;mini primary&quot; onclick=&quot;runAllEisValidations()&quot;&gt;▶ Validate Now&lt;/button&gt;<br>        &lt;/div&gt;<br>       &lt;/div&gt;<br><br>       &lt;div id=&quot;eisManualTextWrap&quot; style=&quot;margin-bottom:12px;display:none&quot;&gt;<br>        &lt;div class=&quot;small&quot; style=&quot;margin-bottom:4px&quot;&gt;&lt;strong&gt;Extracted / Raw EIS Text or Values&lt;/strong&gt; (editable if OCR needs adjustment — auto-revalidates):&lt;/div&gt;<br>        &lt;textarea id=&quot;eisAttachmentRawText&quot; rows=&quot;4&quot; oninput=&quot;onEisRawTextEdited()&quot;&gt;&lt;/textarea&gt;<br>       &lt;/div&gt;<br><br>       &lt;div class=&quot;eis-card&quot; style=&quot;margin:10px 0;background:#101b32&quot;&gt;&lt;div class=&quot;panel-title&quot;&gt;Receipt Fee Calculation&lt;/div&gt;&lt;div class=&quot;small&quot;&gt;Detected fee amounts are added to gross fees. Any fee line containing CWT / Creditable Withholding Tax is deducted.&lt;/div&gt;&lt;div id=&quot;eisFinancialSummaryBody&quot; class=&quot;small&quot;&gt;Attach a receipt to calculate totals.&lt;/div&gt;&lt;/div&gt;<br>        &lt;table class=&quot;data-table&quot;&gt;<br>        &lt;thead&gt;<br>         &lt;tr&gt;<br>          &lt;th style=&quot;width:95px&quot;&gt;Field # (Name / Amt / Code)&lt;/th&gt;<br>          &lt;th&gt;Field / Fee Name&lt;/th&gt;<br>          &lt;th style=&quot;width:11%&quot;&gt;Mode&lt;/th&gt;<br>          &lt;th style=&quot;width:15%&quot;&gt;Main Page Value&lt;/th&gt;<br>          &lt;th style=&quot;width:16%&quot;&gt;EIS Found / Row 1&lt;/th&gt;<br>          &lt;th style=&quot;width:12%&quot;&gt;Receipt Amount&lt;/th&gt;<br>          &lt;th style=&quot;width:13%&quot;&gt;Receipt Code / Value&lt;/th&gt;<br>          &lt;th style=&quot;width:88px&quot;&gt;Result&lt;/th&gt;<br>          &lt;th&gt;Details&lt;/th&gt;<br>         &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody id=&quot;eisComparisonBody&quot;&gt;&lt;/tbody&gt;<br>       &lt;/table&gt;<br>       &lt;div class=&quot;small&quot; id=&quot;eisComparisonEmpty&quot; style=&quot;margin-top:8px&quot;&gt;No fee rules or attached files yet. Configure fees in &lt;b&gt;⚙ Fees Config&lt;/b&gt; and attach an receipt to run validation.&lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;eis-card&quot;&gt;<br>       &lt;div class=&quot;panel-title&quot;&gt;All Receipts — Overall Validation Summary&lt;/div&gt;<br>       &lt;table class=&quot;data-table&quot;&gt;<br>        &lt;thead&gt;<br>         &lt;tr&gt;<br>          &lt;th&gt;Attached File&lt;/th&gt;<br>          &lt;th style=&quot;width:180px&quot;&gt;🎯 Target Main Page&lt;/th&gt;<br>          &lt;th style=&quot;width:90px&quot;&gt;Pass / Fail&lt;/th&gt;<br>          &lt;th style=&quot;width:95px&quot;&gt;Status&lt;/th&gt;<br>          &lt;th style=&quot;width:130px&quot;&gt;Actions&lt;/th&gt;<br>         &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody id=&quot;eisAllSummaryBody&quot;&gt;&lt;/tbody&gt;<br>       &lt;/table&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br><br>   &lt;!-- TAB 2: EIS FEES CONFIG --&gt;<br>   &lt;div id=&quot;eisViewConfig&quot; style=&quot;display:none&quot;&gt;<br>    &lt;div class=&quot;eis-card&quot;&gt;<br>     &lt;div style=&quot;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-bottom:10px&quot;&gt;<br>      &lt;div&gt;<br>       &lt;div class=&quot;panel-title&quot; style=&quot;margin:0&quot;&gt;⚙ EIS Fees Configuration&lt;/div&gt;<br>       &lt;div class=&quot;small&quot;&gt;Define every fee/field to validate across your Main Pages and attached receipts. Changes auto-save and auto-revalidate immediately.&lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;toolbar&quot; style=&quot;margin:0&quot;&gt;<br>       &lt;button class=&quot;mini&quot; onclick=&quot;importFeesFromMainConfig()&quot;&gt;⇄ Sync Fields from Main Config&lt;/button&gt;<br>       &lt;button class=&quot;mini primary&quot; onclick=&quot;addEisFeeRow()&quot;&gt;+ Add Fee Rule&lt;/button&gt;<br>       &lt;button class=&quot;mini&quot; onclick=&quot;exportEisFeesConfig()&quot;&gt;Export Fees JSON&lt;/button&gt;<br>       &lt;button class=&quot;mini&quot; onclick=&quot;document.getElementById(&#39;eisFeesConfigFile&#39;).click()&quot;&gt;Import Fees JSON&lt;/button&gt;<br>       &lt;input type=&quot;file&quot; id=&quot;eisFeesConfigFile&quot; accept=&quot;.json,application/json&quot; hidden&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br><br>     &lt;div class=&quot;cfg-grid&quot; style=&quot;margin-top:0;margin-bottom:12px&quot;&gt;<br>      &lt;div&gt;<br>       &lt;h4&gt;Quick Paste Fees List (3-Row Block or Pipe Format)&lt;/h4&gt;<br>       &lt;textarea id=&quot;eisFeesPaste&quot; rows=&quot;6&quot; placeholder=&quot;fee&#39;s 1 charge&amp;#10;1000&amp;#10;NC&amp;#10;&amp;#10;fee&#39;s 2 charge&amp;#10;250&amp;#10;IC&amp;#10;&amp;#10;CWT&amp;#10;50&quot;&gt;&lt;/textarea&gt;<br>       &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>        &lt;button class=&quot;mini primary&quot; onclick=&quot;applyEisFeesPaste()&quot;&gt;Apply Pasted Fees&lt;/button&gt;<br>        &lt;span class=&quot;small&quot; id=&quot;eisFeesMsg&quot;&gt;&lt;/span&gt;<br>       &lt;/div&gt;<br>       &lt;div class=&quot;small&quot;&gt;<br>        Paste 3-row blocks directly from your EIS sample (&lt;b&gt;Row 1 = Fee Name&lt;/b&gt;, &lt;b&gt;Row 2 = Expected Amount&lt;/b&gt;, &lt;b&gt;Row 3 = Code/Tag e.g. NC / IC&lt;/b&gt;) or use &lt;code&gt;Field# | Fee Name | 3rd Row Code | name_and_3rd_row&lt;/code&gt;.<br>       &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>       &lt;h4&gt;How 3-Row Fee Validation Works&lt;/h4&gt;<br>       &lt;div class=&quot;small&quot;&gt;<br>        • &lt;b&gt;Fee Name + 3rd Row Code (Dynamic Amount)&lt;/b&gt;: Finds &lt;b&gt;Row 1 (Fee Name)&lt;/b&gt; in the attached receipt, compares &lt;b&gt;Row 2 (Amount)&lt;/b&gt; against the Main Page / configured amount, and validates that &lt;b&gt;Row 3&lt;/b&gt; equals the configured code (e.g., &lt;code&gt;NC&lt;/code&gt;, &lt;code&gt;IC&lt;/code&gt;) or matches the Main Page.&lt;br&gt;<br>        • &lt;b&gt;Match Main Page &amp;amp; EIS&lt;/b&gt;: Compares the Main Page&#39;s extracted/manual value directly against the attached receipt.&lt;br&gt;<br>        • &lt;b&gt;Exact Value&lt;/b&gt;: Requires exact match against Expected Value.<br>       &lt;/div&gt;<br>       &lt;div style=&quot;display:flex;gap:8px;align-items:center;margin-top:8px&quot;&gt;<br>        &lt;label class=&quot;small&quot;&gt;Numeric Tolerance (±):&lt;/label&gt;<br>        &lt;input type=&quot;number&quot; id=&quot;eisTolerance&quot; step=&quot;0.01&quot; min=&quot;0&quot; value=&quot;0.01&quot; style=&quot;width:100px;padding:5px&quot; onchange=&quot;onEisConfigChanged()&quot;&gt;<br>       &lt;/div&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br><br>     &lt;div class=&quot;eis-card&quot; style=&quot;margin:12px 0;background:#101b32&quot;&gt;<br>      &lt;div class=&quot;panel-title&quot;&gt;Page-specific Fees — 3 Fields per Fee&lt;/div&gt;<br>      &lt;div class=&quot;small&quot;&gt;Each Main Page has its own fee list. Every fee uses three numbered fields: Fee Name, Fee Amount, and Fee Code. Add as many fees as that page needs; other pages are unaffected. Fee Name, Amount, and Code each have their own field number. Receipt Amount is compared with the Main Page amount when captured/configured; if blank, it is checked for presence. Receipt Code is compared with the Main Page code or configured code. CWT amount is always compared by absolute value and deducted from the total.&lt;/div&gt;<br>      &lt;div class=&quot;toolbar&quot; style=&quot;margin:10px 0&quot;&gt;<br>       &lt;label class=&quot;small&quot; for=&quot;pageFeePageSelect&quot;&gt;Configure page:&lt;/label&gt;<br>       &lt;select id=&quot;pageFeePageSelect&quot; style=&quot;min-width:180px&quot; onchange=&quot;renderPageFeeEditor()&quot;&gt;&lt;/select&gt;<br>       &lt;button class=&quot;mini primary&quot; onclick=&quot;addPageFee()&quot;&gt;＋ Add Fee (3 fields)&lt;/button&gt;<br>       &lt;button class=&quot;mini&quot; onclick=&quot;copyPageFeesToNext()&quot;&gt;Copy fees to next page&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;small&quot; id=&quot;pageFeeEditorStatus&quot;&gt;Select a Main Page to configure its fees.&lt;/div&gt;<br>      &lt;div style=&quot;overflow-x:auto&quot;&gt;<br>       &lt;table class=&quot;data-table&quot;&gt;<br>        &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Fee #&lt;/th&gt;&lt;th&gt;Name Field #&lt;/th&gt;&lt;th&gt;Fee Name&lt;/th&gt;&lt;th&gt;Amount Field #&lt;/th&gt;&lt;th&gt;Amount (optional expected)&lt;/th&gt;&lt;th&gt;Code Field #&lt;/th&gt;&lt;th&gt;Fee Code&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>        &lt;tbody id=&quot;pageFeeRowsBody&quot;&gt;&lt;/tbody&gt;<br>       &lt;/table&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br><br>     &lt;table class=&quot;data-table&quot;&gt;<br>      &lt;thead&gt;<br>       &lt;tr&gt;<br>        &lt;th style=&quot;width:75px&quot;&gt;Page Field #&lt;/th&gt;<br>        &lt;th&gt;Fee Name (Row 1)&lt;/th&gt;<br>        &lt;th&gt;Aliases / Keywords (comma-separated)&lt;/th&gt;<br>        &lt;th style=&quot;width:145px&quot;&gt;Expected 3rd Row / Code&lt;/th&gt;<br>        &lt;th style=&quot;width:195px&quot;&gt;Validation Rule&lt;/th&gt;<br>        &lt;th style=&quot;width:65px&quot;&gt;Active&lt;/th&gt;<br>        &lt;th style=&quot;width:45px&quot;&gt;&lt;/th&gt;<br>       &lt;/tr&gt;<br>      &lt;/thead&gt;<br>      &lt;tbody id=&quot;eisFeesBody&quot;&gt;&lt;/tbody&gt;<br>     &lt;/table&gt;<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;script&gt;<br>const $ = id =&gt; document.getElementById(id);<br>const DEFAULT_LABEL_COUNT=200;<br>const MAX_LABELS=999;<br>const CONFIG_KEY=&#39;qaStudioConfig_v2&#39;;<br><br>let images=[];<br>let current=-1;<br>function makeLabels(n,old=[]){<br> return Array.from({length:n},(_,i)=&gt;old[i]||{id:i+1,name:`QA ${i+1}`,color:&#39;#ff4242&#39;});<br>}<br>let labels=makeLabels(DEFAULT_LABEL_COUNT);<br>let selectedLabel=1;<br>let mode=&#39;box&#39;;<br>let annotations=[];<br>let selected=null;<br>let drag=null;<br>let history=[];<br>let screenStream=null;<br>let pageTitles=[];<br>let fields=[];   // {num,name,mode:&#39;ocr&#39;|&#39;manual&#39;,value}<br>let eisFeeRules=[]; // shared non-fee field rules<br>let pageFeeRules={}; // {pageIndex:[{id,feeIndex,nameFieldNum,name,amountFieldNum,amountExpected,codeFieldNum,codeExpected,enabled}]}<br>let activePageFeeEditor=0;<br>let eisTolerance=0.01;<br>let eisAttachments=[]; // {id,name,mime,targetPage,blob,url,isImage,rawText,ocrStatus,lastValidatedAt}<br>let activeEisAttachmentId=null;<br>let eisActiveTab=&#39;validate&#39;;<br>let pageFields={};<br><br>const base=$(&#39;base&#39;);<br>const overlay=$(&#39;overlay&#39;);<br>const ctx=overlay.getContext(&#39;2d&#39;);<br><br>// ---------- helpers ----------<br>function downloadBlob(blob,name){<br> const url=URL.createObjectURL(blob);<br> const link=document.createElement(&#39;a&#39;);<br> link.href=url;link.download=name;link.click();<br> setTimeout(()=&gt;URL.revokeObjectURL(url),2000);<br>}<br>function blobToDataURL(blob){<br> return new Promise((res,rej)=&gt;{const r=new FileReader();r.onload=()=&gt;res(r.result);r.onerror=()=&gt;rej(r.error);r.readAsDataURL(blob)});<br>}<br>function safeName(s){return String(s||&#39;&#39;).replace(/[^\w\- ]+/g,&#39;&#39;).trim().replace(/\s+/g,&#39;-&#39;)||&#39;QA-Evidence&#39;}<br>function stamp(){const d=new Date();const p=n=&gt;String(n).padStart(2,&#39;0&#39;);return `${d.getFullYear()}${p(d.getMonth()+1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`}<br>function fieldFor(num){return fields.find(f=&gt;f.num===num)}<br>function labelName(a){return (labels.find(l=&gt;l.id===a.label)||{}).name||a.name||(&#39;QA &#39;+a.label)}<br>function valueOf(a){<br> const f=fieldFor(a.label);<br> if(f&amp;&amp;f.mode===&#39;manual&#39;)return f.value||&#39;&#39;;<br> return a.text||&#39;&#39;;<br>}<br><br>// ---------- SCREEN CAPTURE ----------<br>async function startScreenCapture(){<br> if(!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia){<br>  alert(&#39;Screen capture is unavailable. Open this page in Chrome or Edge using HTTPS or localhost.&#39;);<br>  return;<br> }<br> try{<br>  stopScreenCapture(false);<br>  screenStream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:false});<br>  $(&#39;liveVideo&#39;).srcObject=screenStream;<br>  $(&#39;livePanel&#39;).style.display=&#39;block&#39;;<br>  $(&#39;captureStatus&#39;).textContent=&#39;Screen sharing is active. Click Take Screenshot to save the current frame.&#39;;<br>  screenStream.getVideoTracks()[0].addEventListener(&#39;ended&#39;,()=&gt;{stopScreenCapture()});<br>  await $(&#39;liveVideo&#39;).play();<br> }catch(error){<br>  if(error.name===&#39;NotAllowedError&#39;){<br>   $(&#39;captureStatus&#39;).textContent=&#39;Screen sharing was cancelled or permission was denied.&#39;;<br>  }else{<br>   $(&#39;captureStatus&#39;).textContent=&#39;Capture error: &#39;+error.message;<br>   console.error(error);<br>  }<br> }<br>}<br><br>function captureFrame(){<br> const video=$(&#39;liveVideo&#39;);<br> if(!screenStream || !video.videoWidth){<br>  alert(&#39;Start screen sharing first and wait for the preview.&#39;);<br>  return;<br> }<br> const canvas=document.createElement(&#39;canvas&#39;);<br> canvas.width=video.videoWidth;<br> canvas.height=video.videoHeight;<br> canvas.getContext(&#39;2d&#39;).drawImage(video,0,0,canvas.width,canvas.height);<br> canvas.toBlob(blob=&gt;{<br>  if(blob) addImageFromBlob(blob,`Screen Capture ${new Date().toLocaleString()}`);<br>  else alert(&#39;Could not capture this screen.&#39;);<br> },&#39;image/png&#39;);<br>}<br><br>function stopScreenCapture(updateStatus=true){<br> if(screenStream){<br>  screenStream.getTracks().forEach(track=&gt;track.stop());<br>  screenStream=null;<br> }<br> $(&#39;liveVideo&#39;).srcObject=null;<br> $(&#39;livePanel&#39;).style.display=&#39;none&#39;;<br> if(updateStatus) $(&#39;captureStatus&#39;).textContent=&#39;Screen capture stopped.&#39;;<br>}<br><br>// ---------- IMAGE UPLOAD AND PASTE ----------<br>$(&#39;fileInput&#39;).addEventListener(&#39;change&#39;,e=&gt;{<br> Array.from(e.target.files||[]).forEach(file=&gt;{<br>  if(file.type.startsWith(&#39;image/&#39;)) addImageFromBlob(file,file.name);<br> });<br> e.target.value=&#39;&#39;;<br>});<br><br>document.addEventListener(&#39;paste&#39;,e=&gt;{<br> if(e.target&amp;&amp;/^(INPUT|TEXTAREA)$/.test(e.target.tagName))return;<br> const item=Array.from(e.clipboardData?.items||[]).find(x=&gt;x.type.startsWith(&#39;image/&#39;));<br> if(item){<br>  const file=item.getAsFile();<br>  if(file) addImageFromBlob(file,`Pasted Screenshot ${Date.now()}`);<br> }<br>});<br><br>function makeItem(blob,name){<br> return new Promise((resolve,reject)=&gt;{<br>  const url=URL.createObjectURL(blob);<br>  const img=new Image();<br>  img.onload=()=&gt;resolve({img,url,blob,name,title:&#39;&#39;,include:true,alreadyMerged:false,selectedForMerge:true,width:img.naturalWidth,height:img.naturalHeight});<br>  img.onerror=()=&gt;{URL.revokeObjectURL(url);reject(new Error(&#39;Could not read image &#39;+name))};<br>  img.src=url;<br> });<br>}<br><br>function addImageFromBlob(blob,name){<br> makeItem(blob,name).then(item=&gt;{<br>  images.push(item);<br>  current=images.length-1;<br>  scheduleWorkspaceAutosave();<br>  showImage();<br>  renderImages();<br> }).catch(err=&gt;console.error(err));<br>}<br><br>// ---------- PAGE MANAGEMENT ----------<br>function deleteImage(index){<br> if(index&lt;0||index&gt;=images.length)return;<br> if(!confirm(`Delete &quot;${images[index].name}&quot; and its annotations?`))return;<br> const oldCurrent=current;<br> const item=images[index];<br> if(item.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(item.url);<br> images.splice(index,1);<br> scheduleWorkspaceAutosave();<br> annotations=annotations.filter(a=&gt;a.image!==index).map(a=&gt;({...a,image:a.image&gt;index?a.image-1:a.image}));<br> eisAttachments.forEach(att=&gt;{if(att.targetPage&gt;index)att.targetPage--;else if(att.targetPage&gt;=images.length)att.targetPage=Math.max(0,images.length-1);});<br> selected=null;<br> history=[];<br> if(!images.length)current=-1;<br> else if(oldCurrent&gt;index)current=oldCurrent-1;<br> else if(oldCurrent===index)current=Math.min(index,images.length-1);<br> else current=oldCurrent;<br> renderImages();<br> if(current&gt;=0)showImage();<br> else{<br>  $(&#39;stage&#39;).hidden=true;<br>  $(&#39;empty&#39;).hidden=false;<br>  updateImageStatus();<br> }<br> render();<br>}<br><br>function clearAllImagesSilently(){<br> images.forEach(i=&gt;{if(i.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(i.url)});<br> images=[];annotations=[];current=-1;selected=null;history=[];<br> $(&#39;stage&#39;).hidden=true;<br> $(&#39;empty&#39;).hidden=false;<br>}<br><br>function removeAllImages(){<br> if(!images.length)return;<br> if(!confirm(&#39;Delete all screenshots and annotations?&#39;))return;<br> clearAllImagesSilently();<br> updateImageStatus();<br> renderImages();<br> render();<br>}<br><br>function movePage(i,dir){<br> const j=i+dir;<br> if(j&lt;0||j&gt;=images.length)return;<br> [images[i],images[j]]=[images[j],images[i]];<br> annotations.forEach(a=&gt;{if(a.image===i)a.image=j;else if(a.image===j)a.image=i});<br> eisAttachments.forEach(att=&gt;{if(att.targetPage===i)att.targetPage=j;else if(att.targetPage===j)att.targetPage=i;});<br> if(current===i)current=j;else if(current===j)current=i;<br> scheduleWorkspaceAutosave();<br> history=[];<br> renderImages();<br> updateImageStatus();<br> render();<br>}<br><br>function setAllInclude(v){<br> images.forEach(it=&gt;it.include=v);<br> renderImages();<br>}<br><br>function autoAssignHeaders(){<br> if(!pageTitles.length)return alert(&#39;Add your page header titles in Config first.&#39;);<br> if(!images.length)return alert(&#39;Add screenshots first.&#39;);<br> const start=Math.max(1,parseInt($(&#39;startPage&#39;).value,10)||1);<br> images.forEach((it,i)=&gt;{<br>  const k=i-(start-1);<br>  if(k&lt;0){it.include=false;}<br>  else{it.title=pageTitles[k]||&#39;&#39;;it.include=true;}<br> });<br> renderImages();<br> updateImageStatus();<br> scheduleWorkspaceAutosave();<br>}<br><br>function renderImages(){<br> const list=$(&#39;screenshots&#39;);<br> list.innerHTML=&#39;&#39;;<br> $(&#39;imageCount&#39;).textContent=images.length+&#39; screenshots&#39;;<br> images.forEach((item,i)=&gt;{<br>  const row=document.createElement(&#39;div&#39;);<br>  row.className=&#39;screenshot-item&#39;+(i===current?&#39; active&#39;:&#39;&#39;);<br><br>  const top=document.createElement(&#39;div&#39;);top.className=&#39;shot-top&#39;;<br>  const img=document.createElement(&#39;img&#39;);img.src=item.url;<br>  const info=document.createElement(&#39;div&#39;);info.className=&#39;screenshot-info&#39;;<br>  const name=document.createElement(&#39;strong&#39;);name.textContent=`${i+1}. ${item.name}`;<br>  const size=document.createElement(&#39;span&#39;);size.textContent=`${item.width} × ${item.height}`;<br>  info.append(name,size);<br>  const up=document.createElement(&#39;button&#39;);up.className=&#39;mini&#39;;<br>  up.textContent=&#39;▲&#39;;up.title=&#39;Move page up&#39;;up.disabled=i===0;<br>  up.onclick=e=&gt;{e.stopPropagation();movePage(i,-1)};<br>  const dn=document.createElement(&#39;button&#39;);dn.className=&#39;mini&#39;;<br>  dn.textContent=&#39;▼&#39;;dn.title=&#39;Move page down&#39;;dn.disabled=i===images.length-1;<br>  dn.onclick=e=&gt;{e.stopPropagation();movePage(i,1)};<br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;delete-image danger&#39;;del.textContent=&#39;✕&#39;;del.title=&#39;Delete screenshot&#39;;<br>  del.onclick=e=&gt;{e.stopPropagation();deleteImage(i)};<br>  top.append(img,info,up,dn,del);<br><br>  if(!item.title&amp;&amp;pageTitles[i])item.title=pageTitles[i];<br>  const meta=document.createElement(&#39;div&#39;);meta.className=&#39;shot-meta&#39;;<br>  const lab=document.createElement(&#39;label&#39;);<br>  const chk=document.createElement(&#39;input&#39;);chk.type=&#39;checkbox&#39;;chk.checked=item.include!==false;<br>  chk.onchange=()=&gt;{item.include=chk.checked;scheduleWorkspaceAutosave()};<br>  lab.onclick=e=&gt;e.stopPropagation();<br>  lab.append(chk,document.createTextNode(&#39;In docs&#39;));<br>  const sel=document.createElement(&#39;select&#39;);<br>  const opts=[&#39;&#39;,...pageTitles];<br>  if(item.title&amp;&amp;!pageTitles.includes(item.title))opts.push(item.title);<br>  opts.forEach(t=&gt;{<br>   const o=document.createElement(&#39;option&#39;);o.value=t;o.textContent=t||&#39;— header —&#39;;<br>   if(t===(item.title||&#39;&#39;))o.selected=true;<br>   sel.appendChild(o);<br>  });<br>  sel.onclick=e=&gt;e.stopPropagation();<br>  sel.onchange=()=&gt;{item.title=sel.value;updateImageStatus();scheduleWorkspaceAutosave()};<br>  meta.append(lab,sel);<br><br>  row.append(top,meta);<br>  row.onclick=()=&gt;{current=i;showImage();renderImages()};<br>  list.appendChild(row);<br> });<br> renderMergeChecklist();<br> updateStats();<br> scheduleWorkspaceAutosave();<br>}<br><br>function updateImageStatus(){<br> if(current&lt;0||!images[current]){$(&#39;imageStatus&#39;).textContent=&#39;No active screenshot.&#39;;return}<br> const it=images[current];<br> $(&#39;imageStatus&#39;).textContent=`Working on page ${current+1} of ${images.length} · ${it.title||&#39;no header&#39;} · ${it.name} · ${it.width} × ${it.height}`;<br> if(typeof renderCurrentPageReceiptStatus===&#39;function&#39;)renderCurrentPageReceiptStatus();<br>}<br><br>function showImage(){<br> if(current&lt;0||!images[current])return;<br> const item=images[current];<br> $(&#39;stage&#39;).hidden=false;<br> $(&#39;empty&#39;).hidden=true;<br> base.onload=()=&gt;{<br>  overlay.width=item.width;<br>  overlay.height=item.height;<br>  render();<br> };<br> base.src=item.url;<br> updateImageStatus();<br> selected=null;<br> const resumeNum=nextSequentialLabelForPage(current);<br> if(resumeNum){<br>  ensureLabelCapacity(resumeNum);<br>  selectedLabel=resumeNum;<br> }<br> render();<br>}<br><br>// ---------- LABELS (PER-PAGE SEQUENCE + RESUME MEMORY) ----------<br>function drawLabels(){<br> $(&#39;labels&#39;).innerHTML=&#39;&#39;;<br> const usedOnCurrentPage=usedAnnotationNumbers(null,current);<br> labels.forEach(label=&gt;{<br>  const div=document.createElement(&#39;div&#39;);<br>  const alreadyUsed=usedOnCurrentPage.has(label.id);<br>  const manualField=fieldFor(label.id)?.mode===&#39;manual&#39;;<br>  const unavailable=alreadyUsed||manualField;<br>  div.className=&#39;label-item&#39;+(selectedLabel===label.id?&#39; active&#39;:&#39;&#39;)+(unavailable?&#39; used&#39;:&#39;&#39;)+(manualField?&#39; manual-label&#39;:&#39;&#39;);<br>  div.style.opacity=unavailable?&#39;.42&#39;:&#39;1&#39;;<br>  div.title=manualField?`#${label.id} is a manual-value field and cannot be used for OCR boxes`:alreadyUsed?`#${label.id} is already labeled on this page`:`Select label #${label.id} for this page`;<br>  div.style.borderLeft=`3px solid ${label.color}`;<br>  const number=document.createElement(&#39;strong&#39;);<br>  number.textContent=label.id;<br>  const name=document.createElement(&#39;span&#39;);<br>  name.textContent=label.name;<br>  div.append(number,name);<br>  div.onclick=()=&gt;{<br>   if(fieldFor(label.id)?.mode===&#39;manual&#39;){<br>    $(&#39;autoStatus&#39;).textContent=`#${label.id} is a manual-value field. Its value is shown in Extracted Data and cannot be selected for OCR.`;<br>    return;<br>   }<br>   if(usedAnnotationNumbers(null,current).has(label.id)){<br>    $(&#39;autoStatus&#39;).textContent=`#${label.id} is already used on Page ${current+1}. Choose an unused number on this page.`;<br>    return;<br>   }<br>   selectedLabel=label.id;<br>   $(&#39;labelName&#39;).value=label.name;<br>   $(&#39;labelColor&#39;).value=label.color;<br>   drawLabels();<br>  };<br>  $(&#39;labels&#39;).appendChild(div);<br> });<br> if(fieldFor(selectedLabel)?.mode===&#39;manual&#39;||usedOnCurrentPage.has(selectedLabel)){<br>  const next=nextSequentialLabelForPage(current);<br>  if(next){ensureLabelCapacity(next);selectedLabel=next;}<br> }<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(label){<br>  $(&#39;labelName&#39;).value=label.name;<br>  $(&#39;labelColor&#39;).value=label.color;<br> }<br> $(&#39;labelCount&#39;).value=labels.length;<br> updatePageTaskProgress();<br> updateStats();<br>}<br><br>function updatePageTaskProgress(){<br> const box=$(&#39;pageTaskProgress&#39;);<br> if(!box)return;<br> if(current&lt;0||!images[current]){<br>  box.innerHTML=&#39;&lt;strong&gt;Page Sequence:&lt;/strong&gt; Starts at #1 per page.&lt;br&gt;&lt;span class=&quot;small&quot;&gt;Select a page to see labeled boxes and continue where you left off.&lt;/span&gt;&#39;;<br>  return;<br> }<br> const curUsed=[...usedAnnotationNumbers(null,current)].sort((a,b)=&gt;a-b);<br> const nextNum=nextSequentialLabelForPage(current);<br> const curText=curUsed.length<br>  ? `Done on Page ${current+1}: &lt;b&gt;#${curUsed.join(&#39;, #&#39;)}&lt;/b&gt; · Next: &lt;b&gt;#${nextNum||&#39;—&#39;}&lt;/b&gt;`<br>  : `Page ${current+1} has 0 boxes yet · Starting at &lt;b&gt;#${nextNum||1}&lt;/b&gt;`;<br><br> const otherSummaries=[];<br> images.forEach((it,idx)=&gt;{<br>  if(idx===current)return;<br>  const nums=[...usedAnnotationNumbers(null,idx)].sort((a,b)=&gt;a-b);<br>  if(nums.length){<br>   const nextOther=nextSequentialLabelForPage(idx);<br>   otherSummaries.push(`Page ${idx+1} (${it.title||it.name}): &lt;b&gt;${nums.length} labeled&lt;/b&gt; (#${nums[0]}..#${nums[nums.length-1]}, next #${nextOther||&#39;—&#39;})`);<br>  }<br> });<br> const otherHtml=otherSummaries.length<br>  ? `&lt;div class=&quot;small&quot; style=&quot;margin-top:4px;border-top:1px solid var(--border);padding-top:4px&quot;&gt;Other pages progress:&lt;br&gt;• ${otherSummaries.join(&#39;&lt;br&gt;• &#39;)}&lt;/div&gt;`<br>  : `&lt;div class=&quot;small&quot; style=&quot;margin-top:2px&quot;&gt;Other pages: none labeled yet.&lt;/div&gt;`;<br><br> box.innerHTML=`&lt;strong&gt;Page ${current+1} Sequence:&lt;/strong&gt; ${curText}${otherHtml}`;<br>}<br><br>function applyLabelCount(){<br> let n=parseInt($(&#39;labelCount&#39;).value,10);<br> if(!n||n&lt;1)return alert(&#39;Enter a number from 1 to &#39;+MAX_LABELS+&#39;.&#39;);<br> n=Math.min(n,MAX_LABELS);<br> if(n&lt;labels.length){<br>  const used=annotations.some(a=&gt;a.label&gt;n);<br>  if(used&amp;&amp;!confirm(&#39;Some annotations use labels above &#39;+n+&#39;. They will keep their numbers but those labels will no longer be selectable. Continue?&#39;))return;<br> }<br> labels=makeLabels(n,labels);<br> if(selectedLabel&gt;n)selectedLabel=n;<br> drawLabels();<br> render();<br> persistConfig();<br>}<br><br>function saveLabel(){<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(!label)return;<br> if(!$(&#39;labelName&#39;).value.trim())return alert(&#39;Enter a label name.&#39;);<br> label.name=$(&#39;labelName&#39;).value.trim();<br> label.color=$(&#39;labelColor&#39;).value;<br> const f=fieldFor(label.id);<br> if(f){f.name=label.name;renderFields();}<br> drawLabels();<br> render();<br> persistConfig();<br>}<br><br>function resetLabels(){<br> if(!confirm(&#39;Reset all QA labels?&#39;))return;<br> labels=makeLabels(labels.length);<br> selectedLabel=1;<br> syncLabelsFromFields();<br> render();<br> persistConfig();<br>}<br><br>$(&#39;autoIncrement&#39;).addEventListener(&#39;change&#39;,()=&gt;{<br> if($(&#39;autoIncrement&#39;).checked){<br>  const next=nextSequentialLabel();<br>  if(next){ensureLabelCapacity(next);selectedLabel=next;drawLabels();}<br>  $(&#39;autoStatus&#39;).textContent=next?`ON: next OCR label is #${next}. Manual-value labels are disabled.`:&#39;No available OCR labels; increase the label count or change a field to Read by OCR.&#39;;<br> }else{<br>  $(&#39;autoStatus&#39;).textContent=&#39;OFF: manually select unused labels. Used numbers are blocked.&#39;;<br> }<br>});<br><br>// Annotation numbers reset per page (each page has its own 1..N sequence) and resume where left off.<br>function usedAnnotationNumbers(exceptId=null,pageIdx=current){<br> if(pageIdx&lt;0)return new Set();<br> return new Set(annotations.filter(a=&gt;a.image===pageIdx&amp;&amp;a.id!==exceptId).map(a=&gt;Number(a.label)));<br>}<br>function nextAvailableLabel(start=1,exceptId=null,pageIdx=current){<br> const used=usedAnnotationNumbers(exceptId,pageIdx);<br> let n=Math.max(1,Number(start)||1);<br> while((used.has(n)||fieldFor(n)?.mode===&#39;manual&#39;)&amp;&amp;n&lt;=MAX_LABELS)n++;<br> return n&lt;=MAX_LABELS?n:null;<br>}<br>function ensureLabelCapacity(n){<br> if(!n)return false;<br> if(n&gt;MAX_LABELS)return false;<br> if(n&gt;labels.length){<br>  labels=makeLabels(n,labels);<br>  $(&#39;labelCount&#39;).value=n;<br> }<br> return true;<br>}<br>function nextSequentialLabelForPage(pageIdx=current,exceptId=null){<br> const used=usedAnnotationNumbers(exceptId,pageIdx);<br> let candidate=1;<br> while(candidate&lt;=MAX_LABELS&amp;&amp;(used.has(candidate)||fieldFor(candidate)?.mode===&#39;manual&#39;))candidate++;<br> return candidate&lt;=MAX_LABELS?candidate:null;<br>}<br>function nextSequentialLabel(exceptId=null){<br> return nextSequentialLabelForPage(current,exceptId);<br>}<br>function selectNextAvailableLabel(){<br> const next=nextSequentialLabelForPage(current);<br> if(!next){<br>  $(&#39;autoStatus&#39;).textContent=&#39;All available labels on this page are used. Increase the label count to continue.&#39;;<br>  return false;<br> }<br> ensureLabelCapacity(next);<br> selectedLabel=next;<br> drawLabels();<br> const active=$(&#39;labels&#39;).querySelector(&#39;.label-item.active&#39;);<br> if(active)active.scrollIntoView({block:&#39;nearest&#39;});<br> $(&#39;autoStatus&#39;).textContent=`Page ${current+1} next sequence number: #${next}.`;<br> return true;<br>}<br>function autoIncrementLabel(){<br> if(!$(&#39;autoIncrement&#39;).checked)return;<br> selectNextAvailableLabel();<br>}<br><br>// ---------- FIELDS CONFIG ----------<br>function normField(f){<br> let n=parseInt(f.num,10);<br> if(!n||n&lt;1)n=1;<br> if(n&gt;MAX_LABELS)n=MAX_LABELS;<br> return{num:n,name:String(f.name??&#39;&#39;).trim(),mode:f.mode===&#39;manual&#39;?&#39;manual&#39;:&#39;ocr&#39;,value:String(f.value??&#39;&#39;)};<br>}<br><br>function parseFieldList(text){<br> const out=[];let bad=0;<br> text.split(/\r?\n/).forEach(raw=&gt;{<br>  const line=raw.trim();<br>  if(!line)return;<br>  let m;<br>  if(line.includes(&#39;|&#39;)){<br>   const p=line.split(&#39;|&#39;).map(s=&gt;s.trim());<br>   const n=parseInt(p[0],10);<br>   if(n&gt;0&amp;&amp;p[1]!==undefined){<br>    out.push(normField({num:n,name:p[1],mode:(p.length&gt;=3&amp;&amp;p.slice(2).join(&#39;|&#39;).trim())?&#39;manual&#39;:&#39;ocr&#39;,value:p.slice(2).join(&#39;|&#39;)}));<br>    return;<br>   }<br>  }<br>  if((m=line.match(/^(\d{1,3})(?!\d)\s*[.):=\-–\t]?\s*(.+)$/))){<br>   let name=m[2].trim(),value=&#39;&#39;,md=&#39;ocr&#39;;<br>   const tag=name.match(/\s*\[manual\]\s*$/i);<br>   if(tag){md=&#39;manual&#39;;name=name.slice(0,tag.index).trim();}<br>   const eq=name.indexOf(&#39;=&#39;);<br>   if(eq&gt;0){value=name.slice(eq+1).trim();name=name.slice(0,eq).trim();md=&#39;manual&#39;;}<br>   out.push(normField({num:+m[1],name,mode:md,value}));<br>  }else if((m=line.match(/^(.+?)\s*[:=\t]\s*(\d{1,3})$/))){<br>   out.push(normField({num:+m[2],name:m[1].trim(),mode:&#39;ocr&#39;,value:&#39;&#39;}));<br>  }else bad++;<br> });<br> return{list:out,bad};<br>}<br><br>function fieldsToText(list=fields){<br> return list.map(f=&gt;f.mode===&#39;manual&#39;?`${f.num} | ${f.name} | ${f.value}`:`${f.num} ${f.name}`).join(&#39;\n&#39;);<br>}<br><br>function applyFieldList(){<br> const {list,bad}=parseFieldList($(&#39;fieldsPaste&#39;).value);<br> if(!list.length){$(&#39;fieldsMsg&#39;).textContent=&#39;Nothing could be read. Use lines like &quot;2 Client Name&quot;.&#39;;return}<br> fields=list.sort((a,b)=&gt;a.num-b.num);<br> $(&#39;fieldsPaste&#39;).value=fieldsToText();<br> afterFieldsChange(true);<br> const manual=fields.filter(f=&gt;f.mode===&#39;manual&#39;).length;<br> $(&#39;fieldsMsg&#39;).textContent=`${fields.length} fields applied (${manual} manual).`+(bad?` ${bad} line(s) skipped.`:&#39;&#39;);<br>}<br><br>function addFieldRow(){<br> const next=fields.length?Math.min(MAX_LABELS,Math.max(...fields.map(f=&gt;f.num))+1):1;<br> fields.push(normField({num:next,name:&#39;&#39;,mode:&#39;ocr&#39;,value:&#39;&#39;}));<br> afterFieldsChange(true);<br>}<br><br>function syncLabelsFromFields(){<br> const max=Math.min(MAX_LABELS,Math.max(0,...fields.map(f=&gt;f.num)));<br> if(max&gt;labels.length)labels=makeLabels(max,labels);<br> fields.forEach(f=&gt;{<br>  if(f.num&gt;=1&amp;&amp;f.num&lt;=labels.length&amp;&amp;f.name)labels[f.num-1].name=f.name;<br> });<br> drawLabels();<br>}<br><br>function afterFieldsChange(rerenderFields){<br> syncLabelsFromFields();<br> renderAnnotationList();<br> renderExtracted();<br> drawLabels();<br> persistConfig();<br> if(rerenderFields)renderFields();<br>}<br><br>function renderFields(){<br> const body=$(&#39;fieldsBody&#39;);<br> body.innerHTML=&#39;&#39;;<br> fields.forEach((f,idx)=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  const td=()=&gt;document.createElement(&#39;td&#39;);<br>  const t1=td(),t2=td(),t3=td(),t4=td(),t5=td();<br><br>  const num=document.createElement(&#39;input&#39;);num.type=&#39;number&#39;;num.min=1;num.max=MAX_LABELS;num.value=f.num;<br>  num.onchange=()=&gt;{f.num=normField({num:num.value}).num;num.value=f.num;afterFieldsChange(false)};<br>  t1.appendChild(num);<br><br>  const name=document.createElement(&#39;input&#39;);name.type=&#39;text&#39;;name.value=f.name;name.placeholder=&#39;Field name&#39;;<br>  name.oninput=()=&gt;{f.name=name.value.trim();afterFieldsChange(false)};<br>  t2.appendChild(name);<br><br>  const sel=document.createElement(&#39;select&#39;);<br>  [[&#39;ocr&#39;,&#39;Read by OCR&#39;],[&#39;manual&#39;,&#39;Manual value&#39;]].forEach(([v,t])=&gt;{<br>   const o=document.createElement(&#39;option&#39;);o.value=v;o.textContent=t;if(f.mode===v)o.selected=true;sel.appendChild(o);<br>  });<br>  sel.onchange=()=&gt;{f.mode=sel.value;afterFieldsChange(true)};<br>  t3.appendChild(sel);<br><br>  const val=document.createElement(&#39;input&#39;);val.type=&#39;text&#39;;val.value=f.value;<br>  val.placeholder=f.mode===&#39;manual&#39;?&#39;Type the fixed value&#39;:&#39;(not used)&#39;;<br>  val.disabled=f.mode!==&#39;manual&#39;;<br>  val.oninput=()=&gt;{f.value=val.value;renderAnnotationList();renderExtracted();persistConfig()};<br>  t4.appendChild(val);<br><br>  const del=document.createElement(&#39;button&#39;);del.className=&#39;danger mini&#39;;del.textContent=&#39;✕&#39;;<br>  del.onclick=()=&gt;{fields.splice(idx,1);afterFieldsChange(true)};<br>  t5.appendChild(del);<br><br>  tr.append(t1,t2,t3,t4,t5);<br>  body.appendChild(tr);<br> });<br>}<br><br>// ---------- PAGE TITLES CONFIG ----------<br>$(&#39;pageTitlesText&#39;).addEventListener(&#39;input&#39;,()=&gt;{<br> pageTitles=$(&#39;pageTitlesText&#39;).value.split(/\r?\n/).map(s=&gt;s.trim()).filter(Boolean);<br> renderImages();<br> persistConfig();<br>});<br>$(&#39;projectName&#39;).addEventListener(&#39;input&#39;,persistConfig);<br>$(&#39;autoOcr&#39;).addEventListener(&#39;change&#39;,persistConfig);<br>$(&#39;ocrLang&#39;).addEventListener(&#39;change&#39;,()=&gt;{terminateWorker();persistConfig()});<br><br>function openConfig(){<br> const d=$(&#39;configPanel&#39;);<br> d.open=true;<br> d.scrollIntoView({behavior:&#39;smooth&#39;,block:&#39;start&#39;});<br>}<br><br>// ---------- CONFIG SAVE / LOAD ----------<br>function getConfig(){<br> return{<br>  projectName:$(&#39;projectName&#39;).value,<br>  pageTitles:pageTitles.slice(),<br>  fields:fields.map(f=&gt;({...f})),<br>  pageFields:Object.fromEntries(Object.entries(pageFields).map(([k,v])=&gt;[k,v.map(f=&gt;({...f}))])),<br>  labels:labels.map(l=&gt;({name:l.name,color:l.color})),<br>  autoOcr:$(&#39;autoOcr&#39;).checked,<br>  ocrLang:$(&#39;ocrLang&#39;).value.trim()||&#39;eng&#39;,<br>  eisFeeRules:eisFeeRules.map(r=&gt;({...r})),<br>  pageFeeRules:Object.fromEntries(Object.entries(pageFeeRules).map(([k,v])=&gt;[k,v.map(x=&gt;({...x}))])),<br>  eisTolerance:Number(eisTolerance)||0<br> };<br>}<br><br>function applyConfig(c){<br> if(!c||typeof c!==&#39;object&#39;)return;<br> if(typeof c.projectName===&#39;string&#39;)$(&#39;projectName&#39;).value=c.projectName;<br> pageTitles=Array.isArray(c.pageTitles)?c.pageTitles.map(String).filter(s=&gt;s.trim()):[];<br> fields=Array.isArray(c.fields)?c.fields.map(normField):[];<br> pageFields=c.pageFields&amp;&amp;typeof c.pageFields===&#39;object&#39;?Object.fromEntries(Object.entries(c.pageFields).map(([k,v])=&gt;[k,Array.isArray(v)?v.map(normField):[]])):{};<br> if(Array.isArray(c.labels)&amp;&amp;c.labels.length){<br>  labels=c.labels.slice(0,MAX_LABELS).map((l,i)=&gt;({id:i+1,name:String(l&amp;&amp;l.name||`QA ${i+1}`),color:(l&amp;&amp;l.color)||&#39;#ff4242&#39;}));<br> }<br> if(typeof c.autoOcr===&#39;boolean&#39;)$(&#39;autoOcr&#39;).checked=c.autoOcr;<br> if(typeof c.ocrLang===&#39;string&#39;&amp;&amp;c.ocrLang.trim()){$(&#39;ocrLang&#39;).value=c.ocrLang.trim();terminateWorker();}<br> if(Array.isArray(c.eisFeeRules))eisFeeRules=c.eisFeeRules.map(normEisFeeRule);<br> if(c.pageFeeRules&amp;&amp;typeof c.pageFeeRules===&#39;object&#39;)pageFeeRules=Object.fromEntries(Object.entries(c.pageFeeRules).map(([k,v])=&gt;[k,Array.isArray(v)?v.map(normPageFee):[]]));<br> if(typeof c.eisTolerance===&#39;number&#39;&amp;&amp;!Number.isNaN(c.eisTolerance)){eisTolerance=c.eisTolerance;if($(&#39;eisTolerance&#39;))$(&#39;eisTolerance&#39;).value=eisTolerance;}<br> if(selectedLabel&gt;labels.length)selectedLabel=labels.length;<br> $(&#39;pageTitlesText&#39;).value=pageTitles.join(&#39;\n&#39;);<br> $(&#39;fieldsPaste&#39;).value=fieldsToText();<br> renderFields();<br> syncLabelsFromFields();<br> renderImages();<br> renderAnnotationList();<br> renderExtracted();<br> persistConfig();<br>}<br><br>function persistConfig(){<br> try{localStorage.setItem(CONFIG_KEY,JSON.stringify(getConfig()))}catch(e){}<br> scheduleWorkspaceAutosave();<br>}<br><br>// Full workspace autosave uses IndexedDB because screenshots are usually too large for localStorage.<br>const WORKSPACE_DB=&#39;qa-screenshot-studio-workspace&#39;;<br>const WORKSPACE_STORE=&#39;projects&#39;;<br>let workspaceSaveTimer=null;<br>let workspaceDbPromise=null;<br>function openWorkspaceDB(){<br> if(workspaceDbPromise)return workspaceDbPromise;<br> workspaceDbPromise=new Promise((resolve,reject)=&gt;{<br>  if(!(&#39;indexedDB&#39; in window)){reject(new Error(&#39;IndexedDB is unavailable&#39;));return;}<br>  const req=indexedDB.open(WORKSPACE_DB,1);<br>  req.onupgradeneeded=()=&gt;{const db=req.result;if(!db.objectStoreNames.contains(WORKSPACE_STORE))db.createObjectStore(WORKSPACE_STORE)};<br>  req.onsuccess=()=&gt;resolve(req.result);<br>  req.onerror=()=&gt;reject(req.error||new Error(&#39;Could not open browser storage&#39;));<br> });<br> return workspaceDbPromise;<br>}<br>function scheduleWorkspaceAutosave(){<br> clearTimeout(workspaceSaveTimer);<br> workspaceSaveTimer=setTimeout(()=&gt;saveWorkspaceAuto(),650);<br>}<br>async function saveWorkspaceAuto(){<br> try{<br>  const db=await openWorkspaceDB();<br>  const snapshot={<br>   version:1,savedAt:new Date().toISOString(),<br>   config:getConfig(),projectName:$(&#39;projectName&#39;).value,<br>   selectedLabel,current,<br>   images:images.map(it=&gt;({name:it.name,title:it.title||&#39;&#39;,include:it.include!==false,alreadyMerged:!!it.alreadyMerged,selectedForMerge:it.selectedForMerge!==false,width:it.width,height:it.height,blob:it.blob})),<br>   annotations:annotations.map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:a.status})),<br>   activeEisAttachmentId,<br>   eisAttachments:eisAttachments.map(att=&gt;({<br>    id:att.id,name:att.name,mime:att.mime,targetPage:att.targetPage,<br>    isImage:!!att.isImage,isPdf:!!att.isPdf,rawText:att.rawText||&#39;&#39;,ocrStatus:att.ocrStatus===&#39;pending&#39;?&#39;&#39;:(att.ocrStatus||&#39;&#39;),<br>    blob:att.blob<br>   }))<br>  };<br>  await new Promise((resolve,reject)=&gt;{<br>   const tx=db.transaction(WORKSPACE_STORE,&#39;readwrite&#39;);<br>   tx.objectStore(WORKSPACE_STORE).put(snapshot,&#39;autosave&#39;);<br>   tx.oncomplete=resolve;tx.onerror=()=&gt;reject(tx.error||new Error(&#39;Auto-save failed&#39;));tx.onabort=()=&gt;reject(tx.error||new Error(&#39;Auto-save aborted&#39;));<br>  });<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;✓ Auto-saved &#39;+new Date().toLocaleTimeString();<br> }catch(err){<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;Auto-save unavailable: &#39;+err.message+&#39; · Use Save Project as backup.&#39;;<br> }<br>}<br>async function restoreWorkspaceAuto(){<br> try{<br>  const db=await openWorkspaceDB();<br>  const snapshot=await new Promise((resolve,reject)=&gt;{<br>   const tx=db.transaction(WORKSPACE_STORE,&#39;readonly&#39;);<br>   const req=tx.objectStore(WORKSPACE_STORE).get(&#39;autosave&#39;);<br>   req.onsuccess=()=&gt;resolve(req.result||null);req.onerror=()=&gt;reject(req.error);<br>  });<br>  if(!snapshot)return false;<br>  if(snapshot.config)applyConfig(snapshot.config);<br>  if(typeof snapshot.projectName===&#39;string&#39;)$(&#39;projectName&#39;).value=snapshot.projectName;<br>  clearAllImagesSilently();<br>  for(const saved of snapshot.images||[]){<br>   if(!saved.blob)continue;<br>   const item=await makeItem(saved.blob,saved.name||&#39;Image&#39;);<br>   item.title=saved.title||&#39;&#39;;item.include=saved.include!==false;item.alreadyMerged=!!saved.alreadyMerged;item.selectedForMerge=saved.selectedForMerge!==undefined?!!saved.selectedForMerge:!saved.alreadyMerged;<br>   images.push(item);<br>  }<br>  annotations=Array.isArray(snapshot.annotations)?snapshot.annotations.map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:(a.status||&#39;&#39;)})):[];<br>  selectedLabel=Number(snapshot.selectedLabel)||1;<br>  current=images.length?Math.max(0,Math.min(Number(snapshot.current)||0,images.length-1)):-1;<br>  clearEisAttachmentsSilently();<br>  for(const sAtt of snapshot.eisAttachments||[]){<br>   if(!sAtt.blob)continue;<br>   const url=URL.createObjectURL(sAtt.blob);<br>   eisAttachments.push({<br>    id:sAtt.id||(crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random())),<br>    name:sAtt.name||&#39;Receipt&#39;,<br>    mime:sAtt.mime||sAtt.blob.type||&#39;&#39;,<br>    targetPage:Math.max(0,Number(sAtt.targetPage)||0),<br>    blob:sAtt.blob,url,<br>    isImage:!!sAtt.isImage,isPdf:!!sAtt.isPdf||sAtt.mime===&#39;application/pdf&#39;||/\.pdf$/i.test(sAtt.name||&#39;&#39;),<br>    rawText:sAtt.rawText||&#39;&#39;,<br>    ocrStatus:sAtt.ocrStatus||&#39;&#39;<br>   });<br>  }<br>  activeEisAttachmentId=snapshot.activeEisAttachmentId||(eisAttachments[0]?.id||null);<br>  if(current&gt;=0)showImage();<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;✓ Restored last auto-saved workspace&#39;;<br>  return true;<br> }catch(err){<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;Could not restore auto-save: &#39;+err.message;<br>  return false;<br> }<br>}<br>function loadLocalConfig(){<br> try{<br>  const s=localStorage.getItem(CONFIG_KEY);<br>  if(s)applyConfig(JSON.parse(s));<br> }catch(e){}<br>}<br><br>function exportConfig(){<br> const data={app:&#39;QA Screenshot Studio&#39;,type:&#39;config&#39;,version:4,savedAt:new Date().toISOString(),config:getConfig()};<br> downloadBlob(new Blob([JSON.stringify(data,null,2)],{type:&#39;application/json&#39;}),`${safeName($(&#39;projectName&#39;).value)}-config.json`);<br>}<br><br>$(&#39;configFile&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const file=e.target.files&amp;&amp;e.target.files[0];<br> e.target.value=&#39;&#39;;<br> if(!file)return;<br> try{<br>  const obj=JSON.parse(await file.text());<br>  const c=obj.config||obj;<br>  if(!c||(!c.fields&amp;&amp;!c.pageTitles&amp;&amp;!c.labels))throw new Error(&#39;No config found in this file.&#39;);<br>  applyConfig(c);<br>  $(&#39;fieldsMsg&#39;).textContent=&#39;Config imported.&#39;;<br> }catch(err){alert(&#39;Could not import config: &#39;+err.message)}<br>});<br><br>// ---------- PROJECT SAVE / LOAD ----------<br>async function saveProject(){<br> try{<br>  const imgs=[];<br>  for(const it of images){<br>   imgs.push({name:it.name,title:it.title||&#39;&#39;,include:it.include!==false,alreadyMerged:!!it.alreadyMerged,selectedForMerge:it.selectedForMerge!==false,width:it.width,height:it.height,dataUrl:await blobToDataURL(it.blob)});<br>  }<br>  const data={<br>   app:&#39;QA Screenshot Studio&#39;,type:&#39;project&#39;,version:4,savedAt:new Date().toISOString(),<br>   projectName:$(&#39;projectName&#39;).value,<br>   config:getConfig(),<br>   selectedLabel,current,<br>   images:imgs,<br>   annotations:annotations.map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:a.status})),<br>   activeEisAttachmentId,<br>   eisAttachments:await Promise.all(eisAttachments.map(async att=&gt;({<br>    id:att.id,name:att.name,mime:att.mime,targetPage:att.targetPage,<br>    isImage:!!att.isImage,isPdf:!!att.isPdf,rawText:att.rawText||&#39;&#39;,ocrStatus:att.ocrStatus||&#39;&#39;,<br>    dataUrl:await blobToDataURL(att.blob)<br>   })))<br>  };<br>  downloadBlob(new Blob([JSON.stringify(data)],{type:&#39;application/json&#39;}),`${safeName($(&#39;projectName&#39;).value)}-${stamp()}.qaproject.json`);<br> }catch(err){alert(&#39;Could not save project: &#39;+err.message)}<br>}<br><br>$(&#39;projectFile&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const file=e.target.files&amp;&amp;e.target.files[0];<br> e.target.value=&#39;&#39;;<br> if(!file)return;<br> try{<br>  const data=JSON.parse(await file.text());<br>  if(!data||!Array.isArray(data.images))throw new Error(&#39;This is not a project file.&#39;);<br>  if((images.length||annotations.length)&amp;&amp;!confirm(&#39;Loading a project replaces the current screenshots and annotations. Continue?&#39;))return;<br>  clearAllImagesSilently();<br>  for(const s of data.images){<br>   const blob=await (await fetch(s.dataUrl)).blob();<br>   const it=await makeItem(blob,s.name||&#39;Image&#39;);<br>   it.title=s.title||&#39;&#39;;<br>   it.include=s.include!==false;<br>   it.alreadyMerged=!!s.alreadyMerged;<br>   it.selectedForMerge=s.selectedForMerge!==undefined?!!s.selectedForMerge:!s.alreadyMerged;<br>   images.push(it);<br>  }<br>  annotations=(Array.isArray(data.annotations)?data.annotations:[])<br>   .filter(a=&gt;a.image&gt;=0&amp;&amp;a.image&lt;images.length)<br>   .map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:(a.status||&#39;&#39;),text:a.text||&#39;&#39;}));<br>  if(data.config)applyConfig(data.config);<br>  clearEisAttachmentsSilently();<br>  if(Array.isArray(data.eisAttachments)){<br>   for(const sAtt of data.eisAttachments){<br>    if(!sAtt.dataUrl)continue;<br>    const blob=await (await fetch(sAtt.dataUrl)).blob();<br>    const url=URL.createObjectURL(blob);<br>    eisAttachments.push({<br>     id:sAtt.id||(crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random())),<br>     name:sAtt.name||&#39;Receipt&#39;,mime:sAtt.mime||blob.type||&#39;&#39;,<br>     targetPage:Math.max(0,Number(sAtt.targetPage)||0),<br>     blob,url,isImage:!!sAtt.isImage,isPdf:!!sAtt.isPdf||sAtt.mime===&#39;application/pdf&#39;||/\.pdf$/i.test(sAtt.name||&#39;&#39;),rawText:sAtt.rawText||&#39;&#39;,ocrStatus:sAtt.ocrStatus||&#39;&#39;<br>    });<br>   }<br>   activeEisAttachmentId=data.activeEisAttachmentId||(eisAttachments[0]?.id||null);<br>  }<br>  if(typeof data.projectName===&#39;string&#39;)$(&#39;projectName&#39;).value=data.projectName;<br>  if(data.selectedLabel&gt;=1&amp;&amp;data.selectedLabel&lt;=labels.length)selectedLabel=data.selectedLabel;<br>  current=images.length?Math.min(Math.max(0,parseInt(data.current,10)||0),images.length-1):-1;<br>  drawLabels();<br>  renderImages();<br>  if(current&gt;=0)showImage();else updateImageStatus();<br>  render();<br> }catch(err){alert(&#39;Could not load project: &#39;+err.message)}<br>});<br><br>// ---------- DRAW TOOLS ----------<br>function setMode(value){<br> mode=value;<br> $(&#39;boxTool&#39;).classList.toggle(&#39;active&#39;,value===&#39;box&#39;);<br> $(&#39;circleTool&#39;).classList.toggle(&#39;active&#39;,value===&#39;circle&#39;);<br> $(&#39;toolStatus&#39;).textContent=&#39;Current tool: &#39;+(value===&#39;box&#39;?&#39;Rectangle&#39;:&#39;Circle&#39;);<br>}<br><br>function pointerPosition(e){<br> const r=overlay.getBoundingClientRect();<br> return{x:(e.clientX-r.left)*overlay.width/r.width,y:(e.clientY-r.top)*overlay.height/r.height};<br>}<br><br>function annotationAtPoint(p){<br> const list=annotations.filter(a=&gt;a.image===current);<br> for(let i=list.length-1;i&gt;=0;i--){<br>  const a=list[i];<br>  if(p.x&gt;=a.x&amp;&amp;p.x&lt;=a.x+a.w&amp;&amp;p.y&gt;=a.y&amp;&amp;p.y&lt;=a.y+a.h)return a;<br> }<br> return null;<br>}<br>function isResizeHandle(a,p){<br> const size=Math.max(14,overlay.width/90);<br> return p.x&gt;=a.x+a.w-size&amp;&amp;p.x&lt;=a.x+a.w+size&amp;&amp;p.y&gt;=a.y+a.h-size&amp;&amp;p.y&lt;=a.y+a.h+size;<br>}<br>overlay.addEventListener(&#39;pointerdown&#39;,e=&gt;{<br> if(current&lt;0)return;<br> e.preventDefault();<br> const p=pointerPosition(e);<br> const hit=annotationAtPoint(p);<br> if(hit){<br>  selected=hit.id;<br>  history.push(JSON.stringify(annotations));<br>  drag={<br>   kind:isResizeHandle(hit,p)?&#39;resize&#39;:&#39;move&#39;,id:hit.id,<br>   startX:p.x,startY:p.y,origX:hit.x,origY:hit.y,origW:hit.w,origH:hit.h<br>  };<br>  render();<br>  overlay.setPointerCapture(e.pointerId);<br>  return;<br> }<br> history.push(JSON.stringify(annotations));<br> drag={kind:&#39;draw&#39;,startX:p.x,startY:p.y,x:p.x,y:p.y};<br> overlay.setPointerCapture(e.pointerId);<br>});<br><br>overlay.addEventListener(&#39;pointermove&#39;,e=&gt;{<br> if(!drag)return;<br> const p=pointerPosition(e);<br> if(drag.kind===&#39;move&#39;||drag.kind===&#39;resize&#39;){<br>  const a=annotations.find(x=&gt;x.id===drag.id);<br>  if(!a)return;<br>  const dx=p.x-drag.startX,dy=p.y-drag.startY;<br>  if(drag.kind===&#39;move&#39;){<br>   a.x=Math.max(0,Math.min(overlay.width-a.w,drag.origX+dx));<br>   a.y=Math.max(0,Math.min(overlay.height-a.h,drag.origY+dy));<br>  }else{<br>   a.w=Math.max(8,Math.min(overlay.width-a.x,drag.origW+dx));<br>   a.h=Math.max(8,Math.min(overlay.height-a.y,drag.origH+dy));<br>  }<br>  render();<br>  return;<br> }<br> drag.x=p.x;drag.y=p.y;<br> render(drag);<br>});<br><br>overlay.addEventListener(&#39;pointerup&#39;,e=&gt;{<br> if(!drag)return;<br> const p=pointerPosition(e);<br> if(drag.kind===&#39;move&#39;||drag.kind===&#39;resize&#39;){<br>  drag=null;render();scheduleWorkspaceAutosave();return;<br> }<br> drag.x=p.x;drag.y=p.y;<br> const x=Math.min(drag.startX,drag.x);<br> const y=Math.min(drag.startY,drag.y);<br> const w=Math.abs(drag.x-drag.startX);<br> const h=Math.abs(drag.y-drag.startY);<br> if(w&lt;3&amp;&amp;h&lt;3){<br>  history.pop();drag=null;render();return;<br> }<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(!label){drag=null;render();return}<br> if(usedAnnotationNumbers(null,current).has(label.id)){<br>  const next=nextSequentialLabelForPage(current);<br>  if(next){ensureLabelCapacity(next);selectedLabel=next;drawLabels();}<br>  drag=null;render();<br>  $(&#39;autoStatus&#39;).textContent=`#${label.id} is already used on Page ${current+1}. Selected next unused label #${next||&#39;—&#39;}.`;<br>  alert(`Label #${label.id} is already used on Page ${current+1}. Select the next unused number${next?&#39; (#&#39;+next+&#39;)&#39;:&#39;&#39;}.`);<br>  return;<br> }<br> const f=fieldFor(label.id);<br> const isManual=f&amp;&amp;f.mode===&#39;manual&#39;;<br> const doOcr=$(&#39;autoOcr&#39;).checked&amp;&amp;!isManual;<br> const a={<br>  id:crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random()),<br>  image:current,label:label.id,name:label.name,color:label.color,type:mode,x,y,w,h,<br>  text:&#39;&#39;,status:doOcr?&#39;pending&#39;:&#39;&#39;<br> };<br> annotations.push(a);<br> selected=a.id;<br> drag=null;<br> autoIncrementLabel();<br> render();<br> if(doOcr)queueOCR(a.id);<br>});<br><br>overlay.addEventListener(&#39;pointercancel&#39;,()=&gt;{drag=null;render()});<br><br>// ---------- ANNOTATION RENDERING ----------<br>function drawAnnotation(a,isSelected=false){<br> ctx.save();<br> ctx.strokeStyle=a.color;<br> ctx.fillStyle=a.color;<br> ctx.lineWidth=Math.max(3,overlay.width/500);<br> if(a.type===&#39;circle&#39;){<br>  const radius=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>  ctx.beginPath();<br>  ctx.arc(a.x+a.w/2,a.y+a.h/2,radius,0,Math.PI*2);<br>  ctx.stroke();<br>  ctx.fillStyle=a.color;<br>  ctx.font=`bold ${Math.max(14,radius)}px Arial`;<br>  ctx.textAlign=&#39;center&#39;;ctx.textBaseline=&#39;middle&#39;;<br>  ctx.fillText(String(a.label),a.x+a.w/2,a.y+a.h/2);<br> }else{<br>  ctx.strokeRect(a.x,a.y,a.w,a.h);<br>  const mw=Math.max(32,String(a.label).length*11+15);<br>  ctx.fillRect(a.x,Math.max(0,a.y-25),mw,25);<br>  ctx.fillStyle=&#39;white&#39;;<br>  ctx.font=&#39;bold 15px Arial&#39;;<br>  ctx.textAlign=&#39;center&#39;;ctx.textBaseline=&#39;middle&#39;;<br>  ctx.fillText(String(a.label),a.x+mw/2,Math.max(0,a.y-25)+12.5);<br> }<br> if(isSelected){<br>  ctx.setLineDash([7,5]);ctx.strokeStyle=&#39;white&#39;;ctx.lineWidth=2;<br>  if(a.type===&#39;circle&#39;){<br>   const r=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>   ctx.beginPath();ctx.arc(a.x+a.w/2,a.y+a.h/2,r+6,0,Math.PI*2);ctx.stroke();<br>  }else ctx.strokeRect(a.x-4,a.y-4,a.w+8,a.h+8);<br>  ctx.setLineDash([]);<br>  ctx.fillStyle=&#39;white&#39;;ctx.strokeStyle=&#39;#17233b&#39;;ctx.lineWidth=2;<br>  ctx.fillRect(a.x+a.w-7,a.y+a.h-7,14,14);<br>  ctx.strokeRect(a.x+a.w-7,a.y+a.h-7,14,14);<br> }<br> ctx.restore();<br>}<br><br>function render(preview=null){<br> if(!overlay.width||!overlay.height){renderAnnotationList();renderExtracted();updateStats();drawLabels();return}<br> ctx.clearRect(0,0,overlay.width,overlay.height);<br> annotations.filter(a=&gt;a.image===current).forEach(a=&gt;drawAnnotation(a,a.id===selected));<br> if(preview){<br>  const l=labels.find(x=&gt;x.id===selectedLabel);<br>  if(l){<br>   ctx.save();ctx.globalAlpha=.65;<br>   drawAnnotation({<br>    type:mode,x:Math.min(preview.startX,preview.x),<br>    y:Math.min(preview.startY,preview.y),<br>    w:Math.abs(preview.x-preview.startX),<br>    h:Math.abs(preview.y-preview.startY),<br>    label:l.id,color:l.color<br>   });<br>   ctx.restore();<br>  }<br>  return;<br> }<br> renderAnnotationList();<br> renderExtracted();<br> updateStats();<br> drawLabels();<br> scheduleWorkspaceAutosave();<br>}<br><br>function renderAnnotationList(){<br> const list=$(&#39;annotations&#39;);<br> list.innerHTML=&#39;&#39;;<br> const visible=annotations.filter(a=&gt;a.image===current);<br> $(&#39;annotationCount&#39;).textContent=visible.length+&#39; annotations&#39;;<br> visible.forEach(a=&gt;{<br>  const row=document.createElement(&#39;div&#39;);<br>  row.className=&#39;annotation-item&#39;+(a.id===selected?&#39; active&#39;:&#39;&#39;);<br>  const dot=document.createElement(&#39;span&#39;);<br>  dot.className=&#39;annotation-dot&#39;;<br>  dot.style.background=a.color;<br>  const text=document.createElement(&#39;span&#39;);<br>  const v=valueOf(a);<br>  text.textContent=`#${a.label} · ${labelName(a)}`+(v?` · ${v.length&gt;22?v.slice(0,22)+&#39;…&#39;:v}`:&#39;&#39;)+(a.confidence?` · ${a.confidence}%`:&#39;&#39;);<br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;danger&#39;;del.textContent=&#39;✕&#39;;<br>  del.onclick=e=&gt;{e.stopPropagation();deleteAnnotation(a.id)};<br>  row.append(dot,text,del);<br>  row.onclick=()=&gt;{selected=a.id;render()};<br>  list.appendChild(row);<br> });<br>}<br><br>function deleteAnnotation(id){<br> history.push(JSON.stringify(annotations));<br> annotations=annotations.filter(a=&gt;a.id!==id);<br> if(selected===id)selected=null;<br> render();<br>}<br><br>function deleteSelected(){<br> if(!selected)return alert(&#39;Select an annotation first.&#39;);<br> deleteAnnotation(selected);<br>}<br><br>function undo(){<br> if(!history.length)return alert(&#39;Nothing to undo.&#39;);<br> annotations=JSON.parse(history.pop()).map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:a.status}));<br> selected=null;<br> render();<br>}<br><br>function clearAnnotations(){<br> const count=annotations.filter(a=&gt;a.image===current).length;<br> if(!count)return;<br> if(!confirm(&#39;Clear annotations on this screenshot?&#39;))return;<br> history.push(JSON.stringify(annotations));<br> annotations=annotations.filter(a=&gt;a.image!==current);<br> selected=null;<br> render();<br>}<br><br>// ---------- EXTRACTED DATA TABLE ----------<br>function statusText(a,manual){<br> if(manual)return &#39;manual value&#39;;<br> if(a.status===&#39;pending&#39;)return &#39;reading…&#39;;<br> if(a.status===&#39;error&#39;)return &#39;OCR failed&#39;;<br> if(a.status===&#39;done&#39;)return a.text?&#39;read ✓&#39;:&#39;no text found&#39;;<br> return a.text?&#39;edited&#39;:&#39;&#39;;<br>}<br><br>function renderExtracted(){<br> const body=$(&#39;dataBody&#39;);<br> if(!body)return;<br> body.innerHTML=&#39;&#39;;<br> const rows=annotations.filter(a=&gt;a.image===current).sort((p,q)=&gt;p.label-q.label);<br> const annotationLabels=new Set(rows.map(a=&gt;Number(a.label)));<br> // Include manual config values even when the user has not drawn a box for that field.<br> const manualOnly=fields.filter(f=&gt;f.mode===&#39;manual&#39;&amp;&amp;!annotationLabels.has(Number(f.num)))<br>  .sort((a,b)=&gt;a.num-b.num);<br> const hasRows=rows.length&gt;0||manualOnly.length&gt;0;<br> $(&#39;dataEmpty&#39;).hidden=hasRows;<br> rows.forEach(a=&gt;{<br>  const f=fieldFor(a.label);<br>  const manual=f&amp;&amp;f.mode===&#39;manual&#39;;<br>  const tr=document.createElement(&#39;tr&#39;);<br>  if(a.id===selected)tr.className=&#39;sel&#39;;<br>  const c1=document.createElement(&#39;td&#39;);c1.textContent=&#39;#&#39;+a.label;<br>  const c2=document.createElement(&#39;td&#39;);c2.textContent=labelName(a);<br>  const c3=document.createElement(&#39;td&#39;);<br>  const inp=document.createElement(&#39;input&#39;);inp.type=&#39;text&#39;;<br>  inp.value=manual?(f.value||&#39;&#39;):(a.text||&#39;&#39;);<br>  inp.readOnly=!!manual;<br>  inp.dataset.val=a.id;<br>  inp.title=manual?&#39;Manual field: edit its value in Config&#39;:&#39;Edit if OCR got it wrong&#39;;<br>  inp.oninput=()=&gt;{a.text=inp.value;a.status=a.status===&#39;error&#39;?&#39;&#39;:a.status;renderAnnotationList()};<br>  c3.appendChild(inp);<br>  const c4=document.createElement(&#39;td&#39;);<br>  const st=document.createElement(&#39;span&#39;);st.className=&#39;small&#39;;st.dataset.stat=a.id;st.textContent=statusText(a,manual);<br>  c4.appendChild(st);<br>  if(!manual){<br>   const b=document.createElement(&#39;button&#39;);b.className=&#39;mini&#39;;b.textContent=&#39;OCR&#39;;b.style.marginLeft=&#39;6px&#39;;<br>   b.onclick=e=&gt;{e.stopPropagation();a.status=&#39;pending&#39;;updateRow(a);queueOCR(a.id)};<br>   c4.appendChild(b);<br>  }<br>  tr.append(c1,c2,c3,c4);<br>  tr.onclick=()=&gt;{selected=a.id;render()};<br>  body.appendChild(tr);<br> });<br> manualOnly.forEach(f=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  tr.className=&#39;manual-data-row&#39;;<br>  const c1=document.createElement(&#39;td&#39;);c1.textContent=&#39;#&#39;+f.num;<br>  const c2=document.createElement(&#39;td&#39;);c2.textContent=f.name||(&#39;QA &#39;+f.num);<br>  const c3=document.createElement(&#39;td&#39;);<br>  const inp=document.createElement(&#39;input&#39;);inp.type=&#39;text&#39;;inp.value=f.value||&#39;&#39;;inp.readOnly=true;<br>  inp.title=&#39;Manual value — update it in Config&#39;;<br>  c3.appendChild(inp);<br>  const c4=document.createElement(&#39;td&#39;);<br>  const st=document.createElement(&#39;span&#39;);st.className=&#39;small&#39;;st.textContent=&#39;manual value · no OCR&#39;;<br>  c4.appendChild(st);<br>  tr.append(c1,c2,c3,c4);<br>  body.appendChild(tr);<br> });<br>}<br><br>function updateRow(a){<br> const inp=document.querySelector(`[data-val=&quot;${a.id}&quot;]`);<br> const st=document.querySelector(`[data-stat=&quot;${a.id}&quot;]`);<br> if(inp&amp;&amp;st){<br>  const f=fieldFor(a.label);<br>  const manual=f&amp;&amp;f.mode===&#39;manual&#39;;<br>  if(!manual)inp.value=a.text||&#39;&#39;;<br>  st.textContent=statusText(a,manual);<br> }else renderExtracted();<br> renderAnnotationList();<br> if($(&#39;eisModal&#39;)?.classList.contains(&#39;open&#39;))renderEisModal();<br>}<br><br>function reOcrPage(){<br> let n=0;<br> annotations.filter(a=&gt;a.image===current).forEach(a=&gt;{<br>  const f=fieldFor(a.label);<br>  if(f&amp;&amp;f.mode===&#39;manual&#39;)return;<br>  a.status=&#39;pending&#39;;n++;<br>  queueOCR(a.id);<br> });<br> renderExtracted();<br> $(&#39;dataMsg&#39;).textContent=n?`Reading ${n} box(es)…`:&#39;No OCR boxes on this page.&#39;;<br>}<br><br>function pageFieldList(idx){return Object.prototype.hasOwnProperty.call(pageFields,String(idx))?pageFields[String(idx)]:fields;}<br>function applyCurrentPageFields(){<br> if(current&lt;0)return alert(&#39;Select a Main Page first.&#39;);<br> const parsed=parseFieldList($(&#39;pageFieldsPaste&#39;).value);<br> if(!parsed.list.length)return alert(&#39;Enter fields using: 1 | Client Name |&#39;);<br> pageFields[String(current)]=parsed.list.sort((a,b)=&gt;a.num-b.num);<br> $(&#39;pageFieldsStatus&#39;).textContent=`${parsed.list.length} fields saved for Page ${current+1}.`;<br> renderExtracted();renderEisModal();scheduleWorkspaceAutosave();persistConfig();<br>}<br>function copyGlobalFieldsToPage(){<br> if(current&lt;0)return alert(&#39;Select a Main Page first.&#39;);<br> pageFields[String(current)]=fields.map(f=&gt;({...f}));<br> $(&#39;pageFieldsPaste&#39;).value=fieldsToText(pageFields[String(current)]);<br> $(&#39;pageFieldsStatus&#39;).textContent=`Copied ${fields.length} global fields to Page ${current+1}.`;<br> renderExtracted();renderEisModal();scheduleWorkspaceAutosave();persistConfig();<br>}<br>function clearCurrentPageFields(){<br> if(current&lt;0)return;delete pageFields[String(current)];$(&#39;pageFieldsPaste&#39;).value=&#39;&#39;;<br> $(&#39;pageFieldsStatus&#39;).textContent=`Page ${current+1} now uses global fields.`;<br> renderExtracted();renderEisModal();scheduleWorkspaceAutosave();persistConfig();<br>}<br>function refreshPageFieldsEditor(){<br> const has=current&gt;=0&amp;&amp;Object.prototype.hasOwnProperty.call(pageFields,String(current));<br> $(&#39;pageFieldsPaste&#39;).value=has?fieldsToText(pageFields[String(current)]):&#39;&#39;;<br> $(&#39;pageFieldsStatus&#39;).textContent=current&lt;0?&#39;No page selected.&#39;:has?`Custom fields for Page ${current+1} (${pageFields[String(current)].length}).`:`Page ${current+1} uses global fields.`;<br>}<br>function extractedRows(idx){<br> const pageAnnotations=annotations.filter(a=&gt;a.image===idx).sort((p,q)=&gt;p.label-q.label);<br> const rows=pageAnnotations.map(a=&gt;[String(a.label),labelName(a),valueOf(a)]);<br> const present=new Set(pageAnnotations.map(a=&gt;Number(a.label)));<br> pageFieldList(idx).filter(f=&gt;f.mode===&#39;manual&#39;&amp;&amp;!present.has(Number(f.num)))<br>  .sort((a,b)=&gt;a.num-b.num)<br>  .forEach(f=&gt;rows.push([String(f.num),f.name||(&#39;QA &#39;+f.num),f.value||&#39;&#39;]));<br> return rows.sort((a,b)=&gt;Number(a[0])-Number(b[0]));<br>}<br>function copyExtracted(all){<br> const clean=s=&gt;String(s??&#39;&#39;).replace(/[\t\r\n]+/g,&#39; &#39;);<br> const lines=[];<br> if(all){<br>  lines.push([&#39;Page&#39;,&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;].join(&#39;\t&#39;));<br>  images.forEach((it,i)=&gt;extractedRows(i).forEach(r=&gt;lines.push([it.title||it.name,...r].map(clean).join(&#39;\t&#39;))));<br> }else{<br>  lines.push([&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;].join(&#39;\t&#39;));<br>  extractedRows(current).forEach(r=&gt;lines.push(r.map(clean).join(&#39;\t&#39;)));<br> }<br> const text=lines.join(&#39;\n&#39;);<br> const done=()=&gt;{$(&#39;dataMsg&#39;).textContent=&#39;Copied to clipboard.&#39;};<br> const fallback=()=&gt;{<br>  const t=document.createElement(&#39;textarea&#39;);t.value=text;document.body.appendChild(t);t.select();<br>  try{document.execCommand(&#39;copy&#39;);done()}catch(e){$(&#39;dataMsg&#39;).textContent=&#39;Copy failed.&#39;}<br>  t.remove();<br> };<br> if(navigator.clipboard&amp;&amp;navigator.clipboard.writeText)navigator.clipboard.writeText(text).then(done).catch(fallback);<br> else fallback();<br>}<br><br>// ---------- OCR ----------<br>let ocrWorker=null,ocrWorkerLang=&#39;&#39;,ocrChain=Promise.resolve();<br><br>function terminateWorker(){<br> if(ocrWorker){try{ocrWorker.terminate()}catch(e){}ocrWorker=null;}<br>}<br><br>async function waitForTesseract(timeout=20000){<br> const started=Date.now();<br> while(!window.Tesseract&amp;&amp;Date.now()-started&lt;timeout){<br>  await new Promise(resolve=&gt;setTimeout(resolve,150));<br> }<br> if(!window.Tesseract)throw new Error(&#39;OCR library did not load. Check your internet connection, then reload this page.&#39;);<br> return window.Tesseract;<br>}<br><br>async function getWorker(){<br> const lang=$(&#39;ocrLang&#39;).value.trim()||&#39;eng&#39;;<br> if(ocrWorker&amp;&amp;ocrWorkerLang===lang)return ocrWorker;<br> terminateWorker();<br> const engine=await waitForTesseract();<br> $(&#39;ocrStatus&#39;).textContent=&#39;Loading OCR language data…&#39;;<br> ocrWorker=await engine.createWorker(lang,1,{logger:m=&gt;{<br>  if(m.status){<br>   const pct=typeof m.progress===&#39;number&#39;?` ${Math.round(m.progress*100)}%`:&#39;&#39;;<br>   $(&#39;ocrStatus&#39;).textContent=&#39;OCR: &#39;+m.status+pct;<br>  }<br> }});<br> ocrWorkerLang=lang;<br> try{<br>  await ocrWorker.setParameters({<br>   preserve_interword_spaces:&#39;1&#39;,<br>   user_defined_dpi:&#39;300&#39;,<br>   tessedit_do_invert:&#39;0&#39;<br>  });<br> }catch(e){}<br> $(&#39;ocrStatus&#39;).textContent=&#39;OCR engine ready.&#39;;<br> return ocrWorker;<br>}<br><br>function cropAnnotation(a){<br> const item=images[a.image];<br> if(!item)throw new Error(&#39;The screenshot for this box no longer exists.&#39;);<br> const pad=Math.max(3,Math.round(Math.min(a.w,a.h)*.06));<br> const sx=Math.max(0,Math.floor(a.x)-pad),sy=Math.max(0,Math.floor(a.y)-pad);<br> const ex=Math.min(item.width,Math.ceil(a.x+a.w)+pad);<br> const ey=Math.min(item.height,Math.ceil(a.y+a.h)+pad);<br> const sw=Math.max(1,ex-sx),sh=Math.max(1,ey-sy);<br> // Upscale small text substantially; keep large screenshots within reasonable memory use.<br> const scale=Math.min(5,Math.max(2,Math.ceil(260/Math.max(1,sh))));<br> const c=document.createElement(&#39;canvas&#39;);<br> c.width=Math.max(1,Math.round(sw*scale)+32);<br> c.height=Math.max(1,Math.round(sh*scale)+32);<br> const g=c.getContext(&#39;2d&#39;,{willReadFrequently:true});<br> g.fillStyle=&#39;#fff&#39;;g.fillRect(0,0,c.width,c.height);<br> g.imageSmoothingEnabled=true;g.imageSmoothingQuality=&#39;high&#39;;<br> g.drawImage(item.img,sx,sy,sw,sh,16,16,sw*scale,sh*scale);<br><br> // Analyze only the actual crop, not the white padding.<br> const imageData=g.getImageData(16,16,Math.max(1,Math.round(sw*scale)),Math.max(1,Math.round(sh*scale)));<br> const px=imageData.data;<br> let total=0,min=255,max=0;<br> const histogram=new Uint32Array(256);<br> for(let i=0;i&lt;px.length;i+=4){<br>  const lum=Math.round(.299*px[i]+.587*px[i+1]+.114*px[i+2]);<br>  total+=lum;min=Math.min(min,lum);max=Math.max(max,lum);histogram[lum]++;<br> }<br> const count=px.length/4,avg=count?total/count:255;<br> // Contrast stretch, grayscale and invert dark UI captures where the text is light.<br> const invert=avg&lt;125;<br> const range=Math.max(35,max-min);<br> for(let i=0;i&lt;px.length;i+=4){<br>  let lum=.299*px[i]+.587*px[i+1]+.114*px[i+2];<br>  lum=(lum-min)*255/range;<br>  lum=invert?255-lum:lum;<br>  px[i]=px[i+1]=px[i+2]=Math.max(0,Math.min(255,lum));<br> }<br> g.putImageData(imageData,16,16);<br><br> // Create an adaptive-ish binary variant using a histogram-derived threshold.<br> const gray=g.getImageData(16,16,Math.max(1,Math.round(sw*scale)),Math.max(1,Math.round(sh*scale)));<br> const h=gray.data;<br> let sum=0,n=0;<br> for(let i=0;i&lt;h.length;i+=4){sum+=h[i];n++;}<br> const mean=n?sum/n:180;<br> const threshold=Math.max(90,Math.min(205,mean-8));<br> for(let i=0;i&lt;h.length;i+=4){<br>  const v=h[i]&gt;threshold?255:0;<br>  h[i]=h[i+1]=h[i+2]=v;<br> }<br> const binary=document.createElement(&#39;canvas&#39;);<br> binary.width=c.width;binary.height=c.height;<br> const bg=binary.getContext(&#39;2d&#39;);<br> bg.fillStyle=&#39;#fff&#39;;bg.fillRect(0,0,binary.width,binary.height);<br> bg.putImageData(gray,16,16);<br> return{canvas:c,binary,singleLine:sh&lt;100&amp;&amp;sw/Math.max(1,sh)&gt;2.2};<br>}<br><br>function queueOCR(id){<br> ocrChain=ocrChain.then(()=&gt;runOCR(id)).catch(err=&gt;{<br>  console.error(&#39;OCR queue error:&#39;,err);<br>  $(&#39;ocrStatus&#39;).textContent=&#39;OCR queue error: &#39;+(err.message||err);<br> });<br>}<br><br>async function runOCR(id){<br> const a=annotations.find(x=&gt;x.id===id);<br> if(!a||!images[a.image])return;<br> try{<br>  const worker=await getWorker();<br>  const {canvas,binary,singleLine}=cropAnnotation(a);<br>  const engine=window.Tesseract;<br>  const psm=singleLine?engine.PSM.SINGLE_LINE:engine.PSM.SINGLE_BLOCK;<br>  let best=null;<br>  // Compare enhanced grayscale and thresholded variants; retain the higher-confidence read.<br>  const enlarged=document.createElement(&#39;canvas&#39;);<br>  enlarged.width=Math.max(canvas.width,Math.round(canvas.width*1.6));enlarged.height=Math.max(canvas.height,Math.round(canvas.height*1.6));<br>  const ex=enlarged.getContext(&#39;2d&#39;);ex.imageSmoothingEnabled=true;ex.imageSmoothingQuality=&#39;high&#39;;ex.fillStyle=&#39;#fff&#39;;ex.fillRect(0,0,enlarged.width,enlarged.height);ex.drawImage(canvas,0,0,enlarged.width,enlarged.height);<br>  const candidates=[canvas,binary,enlarged],modes=[psm,engine.PSM.SINGLE_BLOCK,engine.PSM.SPARSE_TEXT];<br>  for(let ci=0;ci&lt;candidates.length;ci++){<br>   const candidate=candidates[ci];<br>   try{<br>    await worker.setParameters({tessedit_pageseg_mode:modes[ci],preserve_interword_spaces:&#39;1&#39;,user_defined_dpi:&#39;300&#39;});<br>    const result=await worker.recognize(candidate);<br>    const data=result.data||{};<br>    const textValue=String(data.text||&#39;&#39;).replace(/[\t\r\n]+/g,&#39; &#39;).replace(/\s{2,}/g,&#39; &#39;).trim();<br>    const confidence=Number(data.confidence)||0;<br>    const score=confidence+(textValue?Math.min(8,textValue.length*.15):0);<br>    if(!best||score&gt;best.score)best={text:textValue,confidence,score};<br>   }catch(candidateError){console.warn(&#39;OCR preprocessing pass failed:&#39;,candidateError);}<br>  }<br>  const cur=annotations.find(x=&gt;x.id===id);<br>  if(!cur)return;<br>  cur.text=best?best.text:&#39;&#39;;<br>  cur.confidence=best?Math.round(best.confidence):0;<br>  cur.status=&#39;done&#39;;<br>  $(&#39;ocrStatus&#39;).textContent=best?`OCR complete · confidence ${cur.confidence}%`:&#39;OCR complete · no text found&#39;;<br>  updateRow(cur);<br> }catch(err){<br>  console.error(err);<br>  const cur=annotations.find(x=&gt;x.id===id);<br>  if(cur){cur.status=&#39;error&#39;;updateRow(cur);}<br>  $(&#39;ocrStatus&#39;).textContent=&#39;OCR error: &#39;+(err.message||err);<br> }<br>}<br><br>// ---------- SELECTIVE MERGE IMAGES ----------<br>function onExcludeMergedToggle(){<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> if(exclude){<br>  images.forEach(it=&gt;{if(it.alreadyMerged)it.selectedForMerge=false;});<br> }<br> renderMergeChecklist();<br> scheduleWorkspaceAutosave();<br>}<br><br>function selectMergeCandidates(mode){<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> images.forEach(it=&gt;{<br>  if(mode===&#39;none&#39;)it.selectedForMerge=false;<br>  else if(mode===&#39;unmerged&#39;)it.selectedForMerge=!it.alreadyMerged;<br>  else if(mode===&#39;all&#39;)it.selectedForMerge=exclude?!it.alreadyMerged:true;<br> });<br> renderMergeChecklist();<br> scheduleWorkspaceAutosave();<br>}<br><br>function resetMergedHistory(){<br> images.forEach(it=&gt;{it.alreadyMerged=false;});<br> renderMergeChecklist();<br> scheduleWorkspaceAutosave();<br> $(&#39;mergeSelectionStatus&#39;).textContent=&#39;Merged flags cleared. All images can be selected again.&#39;;<br>}<br><br>function renderMergeChecklist(){<br> const list=$(&#39;mergeChecklist&#39;);<br> const status=$(&#39;mergeSelectionStatus&#39;);<br> if(!list)return;<br> list.innerHTML=&#39;&#39;;<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> if(!images.length){<br>  list.innerHTML=&#39;&lt;div class=&quot;small&quot; style=&quot;padding:4px&quot;&gt;No images loaded yet.&lt;/div&gt;&#39;;<br>  if(status)status.textContent=&#39;0 image(s) selected for merge.&#39;;<br>  return;<br> }<br> let count=0;<br> images.forEach((it,i)=&gt;{<br>  if(exclude&amp;&amp;it.alreadyMerged)it.selectedForMerge=false;<br>  if(it.selectedForMerge)count++;<br>  const row=document.createElement(&#39;label&#39;);<br>  row.className=&#39;merge-item&#39;+(it.alreadyMerged?&#39; merged-before&#39;:&#39;&#39;);<br>  const chk=document.createElement(&#39;input&#39;);<br>  chk.type=&#39;checkbox&#39;;<br>  chk.checked=!!it.selectedForMerge;<br>  chk.disabled=!!(exclude&amp;&amp;it.alreadyMerged);<br>  chk.onchange=()=&gt;{<br>   it.selectedForMerge=chk.checked;<br>   renderMergeChecklist();<br>   scheduleWorkspaceAutosave();<br>  };<br>  const txt=document.createElement(&#39;span&#39;);<br>  txt.style.cssText=&#39;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap&#39;;<br>  txt.textContent=`Page ${i+1}: ${it.title||it.name}`;<br>  row.append(chk,txt);<br>  if(it.alreadyMerged){<br>   const tag=document.createElement(&#39;span&#39;);<br>   tag.className=&#39;tag-merged&#39;;<br>   tag.textContent=&#39;Merged&#39;;<br>   tag.title=&#39;This source image was already used in a previous merge&#39;;<br>   row.appendChild(tag);<br>  }<br>  list.appendChild(row);<br> });<br> if(status)status.textContent=`${count} of ${images.length} image(s) ticked for merge.`;<br>}<br><br>function mergeImages(direction){<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> const selectedPairs=images.map((it,idx)=&gt;({it,idx}))<br>  .filter(({it})=&gt;it.selectedForMerge&amp;&amp;!(exclude&amp;&amp;it.alreadyMerged));<br> if(selectedPairs.length&lt;2){<br>  return alert(&#39;Tick at least two eligible images in the Merge Images checklist.&#39;);<br> }<br> const source=selectedPairs.map(p=&gt;p.it);<br> const canvas=document.createElement(&#39;canvas&#39;);<br> const c=canvas.getContext(&#39;2d&#39;);<br> if(direction===&#39;vertical&#39;){<br>  canvas.width=Math.max(...source.map(x=&gt;x.width));<br>  canvas.height=source.reduce((n,x)=&gt;n+x.height,0);<br>  let y=0;<br>  source.forEach(x=&gt;{c.drawImage(x.img,0,y);y+=x.height;});<br> }else{<br>  canvas.width=source.reduce((n,x)=&gt;n+x.width,0);<br>  canvas.height=Math.max(...source.map(x=&gt;x.height));<br>  let x=0;<br>  source.forEach(i=&gt;{c.drawImage(i.img,x,0);x+=i.width;});<br> }<br> const mergedPageLabels=selectedPairs.map(p=&gt;`P${p.idx+1}`).join(&#39;+&#39;);<br> const title=source[0].title||pageTitles[0]||$(&#39;projectName&#39;).value.trim()||&#39;Merged Evidence&#39;;<br> canvas.toBlob(async blob=&gt;{<br>  if(!blob)return alert(&#39;Could not merge the screenshots. The combined image may be too large.&#39;);<br>  try{<br>   source.forEach(srcItem=&gt;{<br>    srcItem.alreadyMerged=true;<br>    srcItem.selectedForMerge=false;<br>   });<br>   const merged=await makeItem(blob,`Merged (${mergedPageLabels}) ${direction} ${stamp()}`);<br>   merged.title=`${title} [${mergedPageLabels}]`;<br>   merged.include=true;<br>   merged.alreadyMerged=false;<br>   merged.selectedForMerge=false;<br>   annotations.forEach(a=&gt;{a.image+=1;});<br>   images.unshift(merged);<br>   current=0;selected=null;history=[];<br>   showImage();renderImages();render();<br>   $(&#39;imageStatus&#39;).textContent=`Page 1 of ${images.length} · ${merged.title} · merged ${source.length} selected screenshot(s)`;<br>   $(&#39;dataMsg&#39;).textContent=`Merged ${mergedPageLabels} into Page 1. Those source images are now flagged &quot;Merged&quot; and excluded from future merges unless unchecked/reset.`;<br>   persistConfig();<br>  }catch(err){console.error(err);alert(&#39;Merge failed: &#39;+err.message);}<br> },&#39;image/png&#39;);<br>}<br><br>// ---------- REPORTS VIEWER, SAVE, DOWNLOAD &amp; PRINT ----------<br>function openReportsModal(){<br> const modal=$(&#39;reportsModal&#39;);<br> if(!modal)return;<br> renderReportsModal();<br> modal.classList.add(&#39;open&#39;);<br>}<br>function closeReportsModal(){<br> const modal=$(&#39;reportsModal&#39;);<br> if(modal)modal.classList.remove(&#39;open&#39;);<br>}<br>function buildReportData(){<br> const projName=$(&#39;projectName&#39;).value.trim()||&#39;QA Evidence&#39;;<br> const generatedAt=new Date().toLocaleString();<br> const pages=images.map((it,idx)=&gt;{<br>  const pageAnns=annotations.filter(a=&gt;a.image===idx).sort((a,b)=&gt;a.label-b.label);<br>  const rows=extractedRows(idx).map(r=&gt;{<br>   const ann=pageAnns.find(a=&gt;Number(a.label)===Number(r[0]));<br>   const f=fieldFor(Number(r[0]));<br>   const isManual=f&amp;&amp;f.mode===&#39;manual&#39;;<br>   const status=isManual?&#39;Manual&#39;:(ann?(ann.status===&#39;done&#39;?&#39;OCR Verified&#39;:(ann.status===&#39;error&#39;?&#39;OCR Error&#39;:&#39;Edited/Pending&#39;)):&#39;Manual&#39;);<br>   return{num:r[0],field:r[1],value:r[2],status,confidence:ann&amp;&amp;ann.confidence?ann.confidence+&#39;%&#39;:&#39;—&#39;};<br>  });<br>  return{<br>   pageNum:idx+1,<br>   name:it.name,<br>   title:it.title||pageTitles[idx]||it.name,<br>   include:it.include!==false,<br>   alreadyMerged:!!it.alreadyMerged,<br>   width:it.width,<br>   height:it.height,<br>   boxCount:pageAnns.length,<br>   rows<br>  };<br> });<br> const totalExtracted=pages.reduce((s,p)=&gt;s+p.rows.length,0);<br> return{projName,generatedAt,pages,totalPages:images.length,totalBoxes:annotations.length,totalExtracted};<br>}<br>function renderReportsModal(){<br> const body=$(&#39;reportsModalBody&#39;);<br> if(!body)return;<br> const rep=buildReportData();<br> const showThumbs=$(&#39;reportIncludeThumbs&#39;)?.checked;<br> $(&#39;reportSubtitle&#39;).textContent=`${rep.projName} · Generated ${rep.generatedAt}`;<br> if(!rep.pages.length){<br>  body.innerHTML=&#39;&lt;div class=&quot;empty&quot;&gt;&lt;strong&gt;No screenshots or report data yet&lt;/strong&gt;&lt;div&gt;Capture or upload images and label fields to generate reports.&lt;/div&gt;&lt;/div&gt;&#39;;<br>  return;<br> }<br> let html=`<br>  &lt;div class=&quot;report-summary-grid&quot;&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.totalPages}&lt;/strong&gt;&lt;span&gt;Total Pages&lt;/span&gt;&lt;/div&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.totalBoxes}&lt;/strong&gt;&lt;span&gt;Labeled Boxes&lt;/span&gt;&lt;/div&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.totalExtracted}&lt;/strong&gt;&lt;span&gt;Total Data Rows&lt;/span&gt;&lt;/div&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.pages.filter(p=&gt;p.include).length}&lt;/strong&gt;&lt;span&gt;Pages Included in Docs&lt;/span&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br> `;<br> rep.pages.forEach((p,idx)=&gt;{<br>  let thumbHtml=&#39;&#39;;<br>  if(showThumbs){<br>   const c=createExportCanvas(idx);<br>   if(c){<br>    const scaled=scaleCanvas(c,720);<br>    thumbHtml=`&lt;img class=&quot;report-thumb&quot; src=&quot;${scaled.toDataURL(&#39;image/png&#39;)}&quot; alt=&quot;Page ${p.pageNum}&quot;&gt;`;<br>   }<br>  }<br>  const rowsHtml=p.rows.length<br>   ? `&lt;table class=&quot;data-table&quot;&gt;&lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:65px&quot;&gt;#&lt;/th&gt;&lt;th style=&quot;width:28%&quot;&gt;Field Name&lt;/th&gt;&lt;th&gt;Extracted / Manual Value&lt;/th&gt;&lt;th style=&quot;width:120px&quot;&gt;Source&lt;/th&gt;&lt;th style=&quot;width:80px&quot;&gt;Conf.&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;${p.rows.map(r=&gt;`&lt;tr&gt;&lt;td&gt;#${xesc(r.num)}&lt;/td&gt;&lt;td&gt;${xesc(r.field)}&lt;/td&gt;&lt;td&gt;${xesc(r.value)}&lt;/td&gt;&lt;td&gt;${xesc(r.status)}&lt;/td&gt;&lt;td&gt;${xesc(r.confidence)}&lt;/td&gt;&lt;/tr&gt;`).join(&#39;&#39;)}&lt;/tbody&gt;&lt;/table&gt;`<br>   : `&lt;div class=&quot;small&quot;&gt;No labeled fields on this page.&lt;/div&gt;`;<br>  html+=`<br>   &lt;div class=&quot;report-page-card&quot;&gt;<br>    &lt;div class=&quot;report-page-head&quot;&gt;<br>     &lt;div&gt;&lt;strong&gt;Page ${p.pageNum}: ${xesc(p.title)}&lt;/strong&gt; &lt;span class=&quot;small&quot;&gt;(${xesc(p.name)} · ${p.width}×${p.height})&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&quot;small&quot;&gt;${p.boxCount} box(es) · ${p.include?&#39;In Docs&#39;:&#39;Excluded from Docs&#39;}${p.alreadyMerged?&#39; · Merged Source&#39;:&#39;&#39;}&lt;/div&gt;<br>    &lt;/div&gt;<br>    ${rowsHtml}<br>    ${thumbHtml}<br>   &lt;/div&gt;<br>  `;<br> });<br> body.innerHTML=html;<br>}<br>function downloadReportCSV(){<br> const rep=buildReportData();<br> const escCsv=v=&gt;`&quot;${String(v??&#39;&#39;).replace(/&quot;/g,&#39;&quot;&quot;&#39;)}&quot;`;<br> const lines=[[&#39;Page #&#39;,&#39;Page Header&#39;,&#39;File Name&#39;,&#39;In Docs&#39;,&#39;Label #&#39;,&#39;Field Name&#39;,&#39;Value&#39;,&#39;Source&#39;,&#39;Confidence&#39;].map(escCsv).join(&#39;,&#39;)];<br> rep.pages.forEach(p=&gt;{<br>  if(!p.rows.length){<br>   lines.push([p.pageNum,p.title,p.name,p.include?&#39;Yes&#39;:&#39;No&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;No annotations&#39;,&#39;&#39;].map(escCsv).join(&#39;,&#39;));<br>  }else{<br>   p.rows.forEach(r=&gt;{<br>    lines.push([p.pageNum,p.title,p.name,p.include?&#39;Yes&#39;:&#39;No&#39;,r.num,r.field,r.value,r.status,r.confidence].map(escCsv).join(&#39;,&#39;));<br>   });<br>  }<br> });<br> const blob=new Blob([&#39;\uFEFF&#39;+lines.join(&#39;\r\n&#39;)],{type:&#39;text/csv;charset=utf-8&#39;});<br> downloadBlob(blob,`${safeName(rep.projName)}-Report-${stamp()}.csv`);<br>}<br>function downloadReportHTML(){<br> const rep=buildReportData();<br> const showThumbs=$(&#39;reportIncludeThumbs&#39;)?.checked;<br> let sections=&#39;&#39;;<br> rep.pages.forEach((p,idx)=&gt;{<br>  let imgTag=&#39;&#39;;<br>  if(showThumbs){<br>   const c=createExportCanvas(idx);<br>   if(c){<br>    const scaled=scaleCanvas(c,1100);<br>    imgTag=`&lt;div style=&quot;margin-top:10px&quot;&gt;&lt;img src=&quot;${scaled.toDataURL(&#39;image/png&#39;)}&quot; style=&quot;max-width:100%;border:1px solid #cbd5e1;border-radius:6px&quot;&gt;&lt;/div&gt;`;<br>   }<br>  }<br>  const tbl=p.rows.length<br>   ? `&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:60px&quot;&gt;#&lt;/th&gt;&lt;th style=&quot;width:28%&quot;&gt;Field&lt;/th&gt;&lt;th&gt;Value&lt;/th&gt;&lt;th style=&quot;width:120px&quot;&gt;Source&lt;/th&gt;&lt;th style=&quot;width:80px&quot;&gt;Conf.&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;${p.rows.map(r=&gt;`&lt;tr&gt;&lt;td&gt;#${xesc(r.num)}&lt;/td&gt;&lt;td&gt;${xesc(r.field)}&lt;/td&gt;&lt;td&gt;${xesc(r.value)}&lt;/td&gt;&lt;td&gt;${xesc(r.status)}&lt;/td&gt;&lt;td&gt;${xesc(r.confidence)}&lt;/td&gt;&lt;/tr&gt;`).join(&#39;&#39;)}&lt;/tbody&gt;&lt;/table&gt;`<br>   : `&lt;p style=&quot;color:#64748b;font-size:13px&quot;&gt;No labeled fields on this page.&lt;/p&gt;`;<br>  sections+=`&lt;section class=&quot;card&quot;&gt;&lt;h2&gt;Page ${p.pageNum}: ${xesc(p.title)}&lt;/h2&gt;&lt;div class=&quot;meta&quot;&gt;File: ${xesc(p.name)} · Dimensions: ${p.width}×${p.height} · Boxes: ${p.boxCount}&lt;/div&gt;${tbl}${imgTag}&lt;/section&gt;`;<br> });<br> const doc=`&lt;!DOCTYPE html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;UTF-8&quot;&gt;&lt;title&gt;${xesc(rep.projName)} - QA Report&lt;/title&gt;&lt;style&gt;body{font-family:Arial,sans-serif;background:#f8fafc;color:#0f172a;margin:24px}h1{margin:0 0 4px}.sub{color:#475569;font-size:13px;margin-bottom:18px}.kpis{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:18px}.kpi{background:#fff;border:1px solid #cbd5e1;border-radius:8px;padding:10px 14px;min-width:130px}.kpi strong{display:block;font-size:20px}.card{background:#fff;border:1px solid #cbd5e1;border-radius:10px;padding:16px;margin-bottom:16px;page-break-inside:avoid}h2{margin:0 0 4px;font-size:16px}.meta{color:#64748b;font-size:12px;margin-bottom:10px}table{width:100%;border-collapse:collapse;font-size:13px}th,td{border:1px solid #cbd5e1;padding:7px 9px;text-align:left}th{background:#e2e8f0}@media print{body{background:#fff;margin:10px}}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;${xesc(rep.projName)} — QA Report&lt;/h1&gt;&lt;div class=&quot;sub&quot;&gt;Generated ${xesc(rep.generatedAt)}&lt;/div&gt;&lt;div class=&quot;kpis&quot;&gt;&lt;div class=&quot;kpi&quot;&gt;&lt;strong&gt;${rep.totalPages}&lt;/strong&gt;&lt;span&gt;Pages&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;kpi&quot;&gt;&lt;strong&gt;${rep.totalBoxes}&lt;/strong&gt;&lt;span&gt;Labeled Boxes&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;kpi&quot;&gt;&lt;strong&gt;${rep.totalExtracted}&lt;/strong&gt;&lt;span&gt;Extracted Rows&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;${sections}&lt;/body&gt;&lt;/html&gt;`;<br> downloadBlob(new Blob([doc],{type:&#39;text/html;charset=utf-8&#39;}),`${safeName(rep.projName)}-Report-${stamp()}.html`);<br>}<br>function printReport(){<br> renderReportsModal();<br> window.print();<br>}<br><br>// ---------- PNG EXPORT ----------<br>function drawExportAnnotation(c,a,width){<br> c.save();c.strokeStyle=a.color;c.fillStyle=a.color;<br> c.lineWidth=Math.max(3,width/500);<br> if(a.type===&#39;circle&#39;){<br>  const r=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>  c.beginPath();c.arc(a.x+a.w/2,a.y+a.h/2,r,0,Math.PI*2);c.stroke();<br>  c.font=`bold ${Math.max(14,r)}px Arial`;<br>  c.textAlign=&#39;center&#39;;c.textBaseline=&#39;middle&#39;;<br>  c.fillText(String(a.label),a.x+a.w/2,a.y+a.h/2);<br> }else{<br>  c.strokeRect(a.x,a.y,a.w,a.h);<br>  const mw=Math.max(32,String(a.label).length*11+15);<br>  c.fillRect(a.x,Math.max(0,a.y-25),mw,25);<br>  c.fillStyle=&#39;white&#39;;c.font=&#39;bold 15px Arial&#39;;<br>  c.textAlign=&#39;center&#39;;c.textBaseline=&#39;middle&#39;;<br>  c.fillText(String(a.label),a.x+mw/2,Math.max(0,a.y-25)+12.5);<br> }<br> c.restore();<br>}<br><br>function createExportCanvas(index){<br> const item=images[index];if(!item)return null;<br> const canvas=document.createElement(&#39;canvas&#39;);<br> canvas.width=item.width;canvas.height=item.height;<br> const c=canvas.getContext(&#39;2d&#39;);<br> c.drawImage(item.img,0,0);<br> annotations.filter(a=&gt;a.image===index).forEach(a=&gt;drawExportAnnotation(c,a,item.width));<br> return canvas;<br>}<br><br>function downloadCanvas(canvas,name){<br> canvas.toBlob(blob=&gt;{<br>  if(!blob)return alert(&#39;Could not export image. It may be too large.&#39;);<br>  downloadBlob(blob,name);<br> },&#39;image/png&#39;);<br>}<br><br>function exportPNG(){<br> if(current&lt;0)return alert(&#39;Load a screenshot first.&#39;);<br> const canvas=createExportCanvas(current);<br> if(canvas)downloadCanvas(canvas,`QA-Evidence-${Date.now()}.png`);<br>}<br><br>function exportAllPNG(){<br> if(!images.length)return alert(&#39;No screenshots to export.&#39;);<br> images.forEach((item,i)=&gt;{<br>  const canvas=createExportCanvas(i);<br>  if(canvas)downloadCanvas(canvas,`QA-Evidence-${i+1}.png`);<br> });<br>}<br><br>// ---------- DOCX EXPORT (no external library) ----------<br>// ZIP-BEGIN<br>const crcTable=(()=&gt;{const t=new Uint32Array(256);for(let n=0;n&lt;256;n++){let c=n;for(let k=0;k&lt;8;k++)c=c&amp;1?0xEDB88320^(c&gt;&gt;&gt;1):c&gt;&gt;&gt;1;t[n]=c&gt;&gt;&gt;0}return t})();<br>function crc32(buf){let c=0xFFFFFFFF;for(let i=0;i&lt;buf.length;i++)c=crcTable[(c^buf[i])&amp;255]^(c&gt;&gt;&gt;8);return (c^0xFFFFFFFF)&gt;&gt;&gt;0}<br>function makeZip(files,mime){<br> const enc=new TextEncoder();<br> const chunks=[],central=[];let offset=0;<br> files.forEach(f=&gt;{<br>  const nameB=enc.encode(f.name);<br>  const crc=crc32(f.data),size=f.data.length;<br>  const lh=new DataView(new ArrayBuffer(30));<br>  lh.setUint32(0,0x04034b50,true);lh.setUint16(4,20,true);lh.setUint16(6,0x0800,true);lh.setUint16(8,0,true);<br>  lh.setUint16(10,0,true);lh.setUint16(12,0x21,true);<br>  lh.setUint32(14,crc,true);lh.setUint32(18,size,true);lh.setUint32(22,size,true);<br>  lh.setUint16(26,nameB.length,true);lh.setUint16(28,0,true);<br>  chunks.push(new Uint8Array(lh.buffer),nameB,f.data);<br>  const ch=new DataView(new ArrayBuffer(46));<br>  ch.setUint32(0,0x02014b50,true);ch.setUint16(4,20,true);ch.setUint16(6,20,true);ch.setUint16(8,0x0800,true);ch.setUint16(10,0,true);<br>  ch.setUint16(12,0,true);ch.setUint16(14,0x21,true);<br>  ch.setUint32(16,crc,true);ch.setUint32(20,size,true);ch.setUint32(24,size,true);<br>  ch.setUint16(28,nameB.length,true);ch.setUint16(30,0,true);ch.setUint16(32,0,true);ch.setUint16(34,0,true);ch.setUint16(36,0,true);<br>  ch.setUint32(38,0,true);ch.setUint32(42,offset,true);<br>  central.push(new Uint8Array(ch.buffer),nameB);<br>  offset+=30+nameB.length+size;<br> });<br> const cdSize=central.reduce((n,c)=&gt;n+c.length,0);<br> const end=new DataView(new ArrayBuffer(22));<br> end.setUint32(0,0x06054b50,true);end.setUint16(4,0,true);end.setUint16(6,0,true);<br> end.setUint16(8,files.length,true);end.setUint16(10,files.length,true);<br> end.setUint32(12,cdSize,true);end.setUint32(16,offset,true);end.setUint16(20,0,true);<br> return new Blob([...chunks,...central,new Uint8Array(end.buffer)],{type:mime||&#39;application/zip&#39;});<br>}<br>// ZIP-END<br><br>const xesc=s=&gt;String(s??&#39;&#39;).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,&#39;&#39;).replace(/&amp;/g,&#39;&amp;amp;&#39;).replace(/&lt;/g,&#39;&amp;lt;&#39;).replace(/&gt;/g,&#39;&amp;gt;&#39;).replace(/&quot;/g,&#39;&amp;quot;&#39;);<br>function wRun(t,o={}){<br> return `&lt;w:r&gt;&lt;w:rPr&gt;${o.b?&#39;&lt;w:b/&gt;&#39;:&#39;&#39;}${o.color?`&lt;w:color w:val=&quot;${o.color}&quot;/&gt;`:&#39;&#39;}${o.sz?`&lt;w:sz w:val=&quot;${o.sz}&quot;/&gt;&lt;w:szCs w:val=&quot;${o.sz}&quot;/&gt;`:&#39;&#39;}&lt;/w:rPr&gt;&lt;w:t xml:space=&quot;preserve&quot;&gt;${xesc(t)}&lt;/w:t&gt;&lt;/w:r&gt;`;<br>}<br>function wPara(inner,ppr=&#39;&#39;){return `&lt;w:p&gt;${ppr?`&lt;w:pPr&gt;${ppr}&lt;/w:pPr&gt;`:&#39;&#39;}${inner}&lt;/w:p&gt;`}<br>function wTable(rows){<br> const W=[900,3000,6180];<br> const bd=[&#39;top&#39;,&#39;left&#39;,&#39;bottom&#39;,&#39;right&#39;,&#39;insideH&#39;,&#39;insideV&#39;].map(s=&gt;`&lt;w:${s} w:val=&quot;single&quot; w:sz=&quot;4&quot; w:space=&quot;0&quot; w:color=&quot;999999&quot;/&gt;`).join(&#39;&#39;);<br> let x=`&lt;w:tbl&gt;&lt;w:tblPr&gt;&lt;w:tblW w:w=&quot;10080&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:tblBorders&gt;${bd}&lt;/w:tblBorders&gt;&lt;w:tblLayout w:type=&quot;fixed&quot;/&gt;&lt;w:tblCellMar&gt;&lt;w:top w:w=&quot;40&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:left w:w=&quot;100&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:bottom w:w=&quot;40&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:right w:w=&quot;100&quot; w:type=&quot;dxa&quot;/&gt;&lt;/w:tblCellMar&gt;&lt;/w:tblPr&gt;&lt;w:tblGrid&gt;${W.map(w=&gt;`&lt;w:gridCol w:w=&quot;${w}&quot;/&gt;`).join(&#39;&#39;)}&lt;/w:tblGrid&gt;`;<br> rows.forEach((r,ri)=&gt;{<br>  x+=`&lt;w:tr&gt;${ri===0?&#39;&lt;w:trPr&gt;&lt;w:tblHeader/&gt;&lt;/w:trPr&gt;&#39;:&#39;&#39;}`;<br>  r.forEach((c,ci)=&gt;{<br>   x+=`&lt;w:tc&gt;&lt;w:tcPr&gt;&lt;w:tcW w:w=&quot;${W[ci]}&quot; w:type=&quot;dxa&quot;/&gt;${ri===0?&#39;&lt;w:shd w:val=&quot;clear&quot; w:color=&quot;auto&quot; w:fill=&quot;D9E2F3&quot;/&gt;&#39;:&#39;&#39;}&lt;/w:tcPr&gt;${wPara(wRun(c,{b:ri===0}))}&lt;/w:tc&gt;`;<br>  });<br>  x+=&#39;&lt;/w:tr&gt;&#39;;<br> });<br> return x+&#39;&lt;/w:tbl&gt;&#39;;<br>}<br>function wImage(n,rid,cx,cy){<br> return `&lt;w:p&gt;&lt;w:pPr&gt;&lt;w:spacing w:after=&quot;120&quot;/&gt;&lt;/w:pPr&gt;&lt;w:r&gt;&lt;w:drawing&gt;&lt;wp:inline distT=&quot;0&quot; distB=&quot;0&quot; distL=&quot;0&quot; distR=&quot;0&quot;&gt;&lt;wp:extent cx=&quot;${cx}&quot; cy=&quot;${cy}&quot;/&gt;&lt;wp:docPr id=&quot;${n}&quot; name=&quot;Picture ${n}&quot;/&gt;&lt;a:graphic&gt;&lt;a:graphicData uri=&quot;http://schemas.openxmlformats.org/drawingml/2006/picture&quot;&gt;&lt;pic:pic&gt;&lt;pic:nvPicPr&gt;&lt;pic:cNvPr id=&quot;${n}&quot; name=&quot;image${n}.png&quot;/&gt;&lt;pic:cNvPicPr/&gt;&lt;/pic:nvPicPr&gt;&lt;pic:blipFill&gt;&lt;a:blip r:embed=&quot;${rid}&quot;/&gt;&lt;a:stretch&gt;&lt;a:fillRect/&gt;&lt;/a:stretch&gt;&lt;/pic:blipFill&gt;&lt;pic:spPr&gt;&lt;a:xfrm&gt;&lt;a:off x=&quot;0&quot; y=&quot;0&quot;/&gt;&lt;a:ext cx=&quot;${cx}&quot; cy=&quot;${cy}&quot;/&gt;&lt;/a:xfrm&gt;&lt;a:prstGeom prst=&quot;rect&quot;&gt;&lt;a:avLst/&gt;&lt;/a:prstGeom&gt;&lt;/pic:spPr&gt;&lt;/pic:pic&gt;&lt;/a:graphicData&gt;&lt;/a:graphic&gt;&lt;/wp:inline&gt;&lt;/w:drawing&gt;&lt;/w:r&gt;&lt;/w:p&gt;`;<br>}<br>function scaleCanvas(src,maxW){<br> if(src.width&lt;=maxW)return src;<br> const k=maxW/src.width;<br> const c=document.createElement(&#39;canvas&#39;);<br> c.width=maxW;c.height=Math.round(src.height*k);<br> const g=c.getContext(&#39;2d&#39;);g.imageSmoothingQuality=&#39;high&#39;;<br> g.drawImage(src,0,0,c.width,c.height);<br> return c;<br>}<br><br>async function exportDocx(){<br> const sel=images.map((it,i)=&gt;({it,i})).filter(x=&gt;x.it.include!==false);<br> if(!sel.length)return alert(&#39;No pages are ticked &quot;In docs&quot;. Tick at least one page.&#39;);<br> if(annotations.some(a=&gt;a.status===&#39;pending&#39;)&amp;&amp;!confirm(&#39;OCR is still reading some boxes. Export anyway?&#39;))return;<br> const withImg=$(&#39;docImages&#39;).checked,withTable=$(&#39;docTables&#39;).checked;<br> const projName=$(&#39;projectName&#39;).value.trim()||&#39;QA Evidence&#39;;<br> const enc=new TextEncoder();<br> const files=[],rels=[];<br> let body=&#39;&#39;,n=0;<br><br> body+=wPara(wRun(projName,{b:1,sz:44}),&#39;&lt;w:spacing w:after=&quot;120&quot;/&gt;&#39;);<br> body+=wPara(wRun(`Generated ${new Date().toLocaleString()} · ${sel.length} page(s)`,{sz:20,color:&#39;666666&#39;}),&#39;&lt;w:spacing w:after=&quot;240&quot;/&gt;&#39;);<br> const manual=fields.filter(f=&gt;f.mode===&#39;manual&#39;);<br> if(manual.length){<br>  body+=wPara(wRun(&#39;Manual fields&#39;,{b:1,sz:28}),&#39;&lt;w:keepNext/&gt;&lt;w:spacing w:before=&quot;120&quot; w:after=&quot;120&quot;/&gt;&#39;);<br>  body+=wTable([[&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;],...manual.map(f=&gt;[&#39;#&#39;+f.num,f.name,f.value])]);<br> }<br><br> for(const {it,i} of sel){<br>  body+=wPara(wRun(it.title||pageTitles[i]||it.name,{b:1,sz:32}),`${i===sel[0].i?&#39;&#39;:&#39;&lt;w:pageBreakBefore/&gt;&#39;}&lt;w:keepNext/&gt;&lt;w:spacing w:after=&quot;60&quot;/&gt;&lt;w:outlineLvl w:val=&quot;0&quot;/&gt;`);<br>  body+=wPara(wRun(`Page ${i+1} · ${it.name}`,{sz:18,color:&#39;777777&#39;}),&#39;&lt;w:keepNext/&gt;&lt;w:spacing w:after=&quot;120&quot;/&gt;&#39;);<br>  if(withImg){<br>   n++;<br>   const canvas=scaleCanvas(createExportCanvas(i),1800);<br>   const blob=await new Promise(r=&gt;canvas.toBlob(r,&#39;image/png&#39;));<br>   if(!blob)return alert(&#39;Could not render page &#39;+(i+1)+&#39; for the docs file.&#39;);<br>   const data=new Uint8Array(await blob.arrayBuffer());<br>   files.push({name:`word/media/image${n}.png`,data});<br>   rels.push(`&lt;Relationship Id=&quot;rId${n+10}&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/image&quot; Target=&quot;media/image${n}.png&quot;/&gt;`);<br>   let cx=canvas.width*9525,cy=canvas.height*9525;<br>   const k=Math.min(1,6400800/cx,5943600/cy);<br>   cx=Math.round(cx*k);cy=Math.round(cy*k);<br>   body+=wImage(n,`rId${n+10}`,cx,cy);<br>  }<br>  if(withTable){<br>   const rows=extractedRows(i);<br>   if(rows.length)body+=wTable([[&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;],...rows.map(r=&gt;[&#39;#&#39;+r[0],r[1],r[2]])]);<br>   else body+=wPara(wRun(&#39;No annotations on this page.&#39;,{sz:20,color:&#39;777777&#39;}));<br>  }<br> }<br><br> const NS=&#39;xmlns:w=&quot;http://schemas.openxmlformats.org/wordprocessingml/2006/main&quot; xmlns:r=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships&quot; xmlns:wp=&quot;http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing&quot; xmlns:a=&quot;http://schemas.openxmlformats.org/drawingml/2006/main&quot; xmlns:pic=&quot;http://schemas.openxmlformats.org/drawingml/2006/picture&quot;&#39;;<br> const head=&#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;&#39;;<br> const docXml=`${head}&lt;w:document ${NS}&gt;&lt;w:body&gt;${body}&lt;w:p/&gt;&lt;w:sectPr&gt;&lt;w:pgSz w:w=&quot;12240&quot; w:h=&quot;15840&quot;/&gt;&lt;w:pgMar w:top=&quot;1080&quot; w:right=&quot;1080&quot; w:bottom=&quot;1080&quot; w:left=&quot;1080&quot; w:header=&quot;720&quot; w:footer=&quot;720&quot; w:gutter=&quot;0&quot;/&gt;&lt;/w:sectPr&gt;&lt;/w:body&gt;&lt;/w:document&gt;`;<br> const stylesXml=`${head}&lt;w:styles xmlns:w=&quot;http://schemas.openxmlformats.org/wordprocessingml/2006/main&quot;&gt;&lt;w:docDefaults&gt;&lt;w:rPrDefault&gt;&lt;w:rPr&gt;&lt;w:rFonts w:ascii=&quot;Calibri&quot; w:hAnsi=&quot;Calibri&quot; w:cs=&quot;Calibri&quot;/&gt;&lt;w:sz w:val=&quot;22&quot;/&gt;&lt;w:szCs w:val=&quot;22&quot;/&gt;&lt;/w:rPr&gt;&lt;/w:rPrDefault&gt;&lt;w:pPrDefault&gt;&lt;w:pPr&gt;&lt;w:spacing w:after=&quot;0&quot; w:line=&quot;259&quot; w:lineRule=&quot;auto&quot;/&gt;&lt;/w:pPr&gt;&lt;/w:pPrDefault&gt;&lt;/w:docDefaults&gt;&lt;/w:styles&gt;`;<br> const ctypes=`${head}&lt;Types xmlns=&quot;http://schemas.openxmlformats.org/package/2006/content-types&quot;&gt;&lt;Default Extension=&quot;rels&quot; ContentType=&quot;application/vnd.openxmlformats-package.relationships+xml&quot;/&gt;&lt;Default Extension=&quot;xml&quot; ContentType=&quot;application/xml&quot;/&gt;&lt;Default Extension=&quot;png&quot; ContentType=&quot;image/png&quot;/&gt;&lt;Override PartName=&quot;/word/document.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml&quot;/&gt;&lt;Override PartName=&quot;/word/styles.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml&quot;/&gt;&lt;/Types&gt;`;<br> const rootRels=`${head}&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;&lt;Relationship Id=&quot;rId1&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument&quot; Target=&quot;word/document.xml&quot;/&gt;&lt;/Relationships&gt;`;<br> const docRels=`${head}&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;&lt;Relationship Id=&quot;rId1&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles&quot; Target=&quot;styles.xml&quot;/&gt;${rels.join(&#39;&#39;)}&lt;/Relationships&gt;`;<br><br> const all=[<br>  {name:&#39;[Content_Types].xml&#39;,data:enc.encode(ctypes)},<br>  {name:&#39;_rels/.rels&#39;,data:enc.encode(rootRels)},<br>  {name:&#39;word/document.xml&#39;,data:enc.encode(docXml)},<br>  {name:&#39;word/styles.xml&#39;,data:enc.encode(stylesXml)},<br>  {name:&#39;word/_rels/document.xml.rels&#39;,data:enc.encode(docRels)},<br>  ...files<br> ];<br> const blob=makeZip(all,&#39;application/vnd.openxmlformats-officedocument.wordprocessingml.document&#39;);<br> downloadBlob(blob,`${safeName(projName)}-${stamp()}.docx`);<br>}<br><br>function updateStats(){<br> $(&#39;statImages&#39;).textContent=images.length;<br> $(&#39;statAnnotations&#39;).textContent=annotations.length;<br> $(&#39;statLabels&#39;).textContent=labels.length;<br>}<br><br>$(&#39;pageTitlesText&#39;).addEventListener(&#39;input&#39;,()=&gt;{<br> pageTitles=$(&#39;pageTitlesText&#39;).value.split(/\\r?\\n/).map(x=&gt;x.trim()).filter(Boolean);<br> images.forEach((it,i)=&gt;{if(pageTitles[i])it.title=pageTitles[i];});<br> renderImages();persistConfig();<br>});<br>$(&#39;projectName&#39;).addEventListener(&#39;input&#39;,persistConfig);<br><br>// ---------- EIS VALIDATION (PER-PAGE SLOTS, ALL MAIN FIELDS READY &amp; ENHANCED OCR) ----------<br>let pendingEisTargetPage = null;<br><br>function normEisFeeRule(r){<br> return{<br>  id:r.id||(crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random())),<br>  fieldNum:Math.max(1,Math.min(MAX_LABELS,parseInt(r.fieldNum,10)||1)),<br>  name:String(r.name||&#39;&#39;).trim(),<br>  aliases:String(r.aliases||&#39;&#39;).trim(),<br>  expected:String(r.expected??r.thirdRowExpected??&#39;&#39;).trim(),<br>  ruleType:[&#39;name_and_3rd_row&#39;,&#39;match_page&#39;,&#39;exact&#39;,&#39;present&#39;].includes(r.ruleType)?r.ruleType:&#39;match_page&#39;,<br>  enabled:r.enabled!==false<br> };<br>}<br><br>function normPageFee(f,idx=0){<br> return{<br>  id:f.id||(crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random())),<br>  feeIndex:Math.max(1,parseInt(f.feeIndex,10)||idx+1),<br>  nameFieldNum:Math.max(1,Math.min(50,parseInt(f.nameFieldNum,10)||1)),<br>  name:String(f.name||&#39;&#39;).trim(),<br>  amountFieldNum:Math.max(1,Math.min(50,parseInt(f.amountFieldNum,10)||2)),<br>  amountExpected:String(f.amountExpected??&#39;&#39;).trim(),<br>  codeFieldNum:Math.max(1,Math.min(50,parseInt(f.codeFieldNum,10)||3)),<br>  codeExpected:String(f.codeExpected??&#39;&#39;).trim(),<br>  enabled:f.enabled!==false<br> };<br>}<br>function pageFeeList(pageIdx){return pageFeeRules[String(pageIdx)]||[];}<br>function selectedFeePage(){<br> const v=parseInt($(&#39;pageFeePageSelect&#39;)?.value,10);<br> return Number.isFinite(v)?v:Math.max(0,activePageFeeEditor||0);<br>}<br>function populatePageFeePageSelect(){<br> const sel=$(&#39;pageFeePageSelect&#39;);if(!sel)return;<br> const old=selectedFeePage();<br> sel.innerHTML=&#39;&#39;;<br> images.forEach((im,i)=&gt;{const o=document.createElement(&#39;option&#39;);o.value=String(i);o.textContent=`Page ${i+1}: ${im.title||im.name||&#39;Main Page&#39;}`;sel.appendChild(o);});<br> if(!images.length){const o=document.createElement(&#39;option&#39;);o.value=&#39;0&#39;;o.textContent=&#39;No Main Pages loaded&#39;;sel.appendChild(o);sel.disabled=true;}<br> else{sel.disabled=false;sel.value=String(Math.min(old,images.length-1));}<br> activePageFeeEditor=selectedFeePage();<br>}<br>function renderPageFeeEditor(){<br> const sel=$(&#39;pageFeePageSelect&#39;),body=$(&#39;pageFeeRowsBody&#39;);if(!body)return;<br> activePageFeeEditor=selectedFeePage();<br> const list=pageFeeList(activePageFeeEditor);body.innerHTML=&#39;&#39;;<br> const usedNums=[];list.forEach(f=&gt;usedNums.push(f.nameFieldNum,f.amountFieldNum,f.codeFieldNum));<br> const duplicates=usedNums.filter((n,i)=&gt;usedNums.indexOf(n)!==i);<br> const mainNums=pageFieldList(activePageFeeEditor).map(f=&gt;Number(f.num));<br> const overlaps=[...new Set(usedNums.filter(n=&gt;{const f=pageFieldList(activePageFeeEditor).find(x=&gt;Number(x.num)===Number(n));return f&amp;&amp;!/fee|charge|tax|cwt|withholding/i.test(f.name||&#39;&#39;);}))];<br> const conflictText=[duplicates.length?`Duplicate fee field numbers: ${[...new Set(duplicates)].join(&#39;, &#39;)}`:&#39;&#39;,overlaps.length?`Overlap with Main Page fields: ${overlaps.join(&#39;, &#39;)}`:&#39;&#39;].filter(Boolean).join(&#39; · &#39;);<br> $(&#39;pageFeeEditorStatus&#39;).textContent=images.length?`Page ${activePageFeeEditor+1}: ${list.length} fee(s) configured. Each fee occupies three numbered fields within 1–50. CWT may be printed with only name + amount; its code is optional and negative amounts are treated by absolute value.${conflictText?&#39; ⚠ &#39;+conflictText:&#39; No field-number conflicts detected.&#39;}`:&#39;Add Main Page screenshots first.&#39;;<br> list.forEach((fee,i)=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  const cell=(value,kind,placeholder,change)=&gt;{const td=document.createElement(&#39;td&#39;);const inp=document.createElement(&#39;input&#39;);inp.type=kind;inp.value=value??&#39;&#39;;inp.placeholder=placeholder||&#39;&#39;;if(kind===&#39;number&#39;){inp.min=1;inp.max=50;}inp.onchange=()=&gt;{change(inp.value);persistConfig();renderEisModal();};if(kind===&#39;text&#39;)inp.oninput=()=&gt;{change(inp.value);persistConfig();};td.appendChild(inp);tr.appendChild(td);};<br>  const idx=document.createElement(&#39;td&#39;);idx.textContent=String(i+1);tr.appendChild(idx);<br>  cell(fee.nameFieldNum,&#39;number&#39;,&#39;1&#39;,v=&gt;fee.nameFieldNum=Math.max(1,Math.min(50,parseInt(v,10)||1)));<br>  cell(fee.name,&#39;text&#39;,&#39;Fee name&#39;,v=&gt;fee.name=v);<br>  cell(fee.amountFieldNum,&#39;number&#39;,&#39;2&#39;,v=&gt;fee.amountFieldNum=Math.max(1,Math.min(50,parseInt(v,10)||2)));<br>  cell(fee.amountExpected,&#39;text&#39;,&#39;Leave blank for dynamic amount&#39;,v=&gt;fee.amountExpected=v);<br>  cell(fee.codeFieldNum,&#39;number&#39;,&#39;3&#39;,v=&gt;fee.codeFieldNum=Math.max(1,Math.min(50,parseInt(v,10)||3)));<br>  cell(fee.codeExpected,&#39;text&#39;,&#39;e.g. NC / IC / CWT&#39;,v=&gt;fee.codeExpected=v);<br>  const td=document.createElement(&#39;td&#39;);const del=document.createElement(&#39;button&#39;);del.className=&#39;mini danger&#39;;del.textContent=&#39;✕&#39;;del.onclick=()=&gt;{list.splice(i,1);persistConfig();renderPageFeeEditor();renderEisModal();};td.appendChild(del);tr.appendChild(td);<br>  body.appendChild(tr);<br> });<br>}<br>function nextAvailableFeeFieldBlock(pageIdx,list=pageFeeList(pageIdx)){<br> const used=new Set(list.flatMap(f=&gt;[f.nameFieldNum,f.amountFieldNum,f.codeFieldNum]));<br> const nonFeeMainNums=new Set(pageFieldList(pageIdx).filter(f=&gt;!/fee|charge|tax|cwt|withholding/i.test(f.name||&#39;&#39;)).map(f=&gt;Number(f.num)));<br> const nonFeeAnnotationNums=new Set(annotations.filter(a=&gt;a.image===pageIdx).filter(a=&gt;{const f=pageFieldList(pageIdx).find(x=&gt;Number(x.num)===Number(a.label));return f&amp;&amp;!/fee|charge|tax|cwt|withholding/i.test(f.name||&#39;&#39;);}).map(a=&gt;Number(a.label)));<br> let start=1;<br> while(start&lt;=48&amp;&amp;(used.has(start)||used.has(start+1)||used.has(start+2)||[start,start+1,start+2].some(n=&gt;nonFeeMainNums.has(n)||nonFeeAnnotationNums.has(n))))start++;<br> return start&lt;=48?{nameFieldNum:start,amountFieldNum:start+1,codeFieldNum:start+2}:null;<br>}<br>function addPageFee(){<br> if(!images.length)return alert(&#39;Add Main Page screenshots first.&#39;);<br> const idx=selectedFeePage(),list=pageFeeList(idx);<br> if(!pageFeeRules[String(idx)])pageFeeRules[String(idx)]=list;<br> const nums=nextAvailableFeeFieldBlock(idx,list);<br> if(!nums)return alert(&#39;No free consecutive three-field block remains in fields 1–50 on this page. Reassign field numbers or remove unused fields first.&#39;);<br> list.push(normPageFee({feeIndex:list.length+1,...nums,name:&#39;&#39;,amountExpected:&#39;&#39;,codeExpected:&#39;&#39;},list.length));<br> pageFeeRules[String(idx)]=list;persistConfig();renderPageFeeEditor();renderEisModal();<br>}<br><br>function copyPageFeesToNext(){<br> const idx=selectedFeePage();if(idx+1&gt;=images.length)return alert(&#39;There is no next Main Page.&#39;);<br> pageFeeRules[String(idx+1)]=pageFeeList(idx).map((f,i)=&gt;normPageFee({...f,id:undefined,feeIndex:i+1},i));<br> persistConfig();populatePageFeePageSelect();$(&#39;pageFeePageSelect&#39;).value=String(idx+1);renderPageFeeEditor();renderEisModal();<br>}<br><br>function clearEisAttachmentsSilently(){<br> eisAttachments.forEach(att=&gt;{if(att.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(att.url);});<br> eisAttachments=[];<br> activeEisAttachmentId=null;<br>}<br><br>function renderCurrentPageReceiptStatus(){<br> const host=$(&#39;currentPageReceiptStatus&#39;);if(!host)return;<br> if(current&lt;0){host.textContent=&#39;Receipt validation: select a Main Page.&#39;;return;}<br> const att=eisAttachments.find(x=&gt;x.targetPage===current);<br> if(!att){host.textContent=`Receipt validation: no original receipt attached to Page ${current+1}.`;return;}<br> const ev=evaluateEisAttachment(att);<br> host.textContent=`Receipt validation — Page ${current+1}: ${ev.overall} · ${ev.passCount} PASS · ${ev.failCount} FAIL · ${ev.pendingCount} pending. Open Receipt Validation to inspect details.`;<br>}<br><br>function openEisForCurrentPage(){<br> if(current&lt;0)return alert(&#39;Select a Main Page first.&#39;);<br> openEisModal(&#39;validate&#39;);<br> const att=eisAttachments.find(x=&gt;x.targetPage===current);<br> if(att)activeEisAttachmentId=att.id;<br> renderEisModal();<br> const card=$(&#39;eisAttachmentsList&#39;)?.children?.[current];<br> if(card)card.scrollIntoView({behavior:&#39;smooth&#39;,block:&#39;center&#39;});<br>}<br><br>function openEisModal(tab=&#39;validate&#39;){<br> const modal=$(&#39;eisModal&#39;);<br> if(!modal)return;<br> syncMainFieldsIntoEisRules(false);<br> switchEisTab(tab);<br> renderEisModal();<br> modal.classList.add(&#39;open&#39;);<br>}<br><br>function closeEisModal(){<br> const modal=$(&#39;eisModal&#39;);<br> if(modal)modal.classList.remove(&#39;open&#39;);<br>}<br><br>function switchEisTab(tab){<br> eisActiveTab=tab===&#39;config&#39;?&#39;config&#39;:&#39;validate&#39;;<br> $(&#39;eisViewValidate&#39;).style.display=eisActiveTab===&#39;validate&#39;?&#39;block&#39;:&#39;none&#39;;<br> $(&#39;eisViewConfig&#39;).style.display=eisActiveTab===&#39;config&#39;?&#39;block&#39;:&#39;none&#39;;<br> $(&#39;eisTabValidateBtn&#39;).classList.toggle(&#39;active&#39;,eisActiveTab===&#39;validate&#39;);<br> $(&#39;eisTabConfigBtn&#39;).classList.toggle(&#39;active&#39;,eisActiveTab===&#39;config&#39;);<br> if(eisActiveTab===&#39;config&#39;){populatePageFeePageSelect();renderPageFeeEditor();renderEisFeesTable();}<br> else renderEisModal();<br>}<br><br>function toggleEisConfigPanel(){<br> switchEisTab(eisActiveTab===&#39;config&#39;?&#39;validate&#39;:&#39;config&#39;);<br>}<br><br>// Automatically ensures all Main Config fields are ready for EIS validation without duplicating existing rules<br>function syncMainFieldsIntoEisRules(showToast=true){<br> let added=0;<br> fields.forEach(f=&gt;{<br>  if(!f.name)return;<br>  const exists=eisFeeRules.some(r=&gt;Number(r.fieldNum)===Number(f.num)||r.name.toLowerCase()===f.name.toLowerCase());<br>  if(!exists){<br>   const isThreeRowFee=/fee&#39;?s?\s*\d+\s*charge/i.test(f.name);<br>   eisFeeRules.push(normEisFeeRule({<br>    fieldNum:f.num,<br>    name:f.name,<br>    aliases:f.name,<br>    expected:f.mode===&#39;manual&#39;?f.value:&#39;&#39;,<br>    ruleType:isThreeRowFee?&#39;name_and_3rd_row&#39;:&#39;match_page&#39;,<br>    enabled:true<br>   }));<br>   added++;<br>  }<br> });<br> eisFeeRules.sort((a,b)=&gt;a.fieldNum-b.fieldNum);<br> if(showToast&amp;&amp;$(&#39;eisFeesMsg&#39;)){<br>  $(&#39;eisFeesMsg&#39;).textContent=added?`Synced ${added} field(s) from Main Config.`:&#39;All Main Config fields are already synced and ready.&#39;;<br> }<br> return added;<br>}<br><br>function ensureDefaultEisFeeRules(){<br> syncMainFieldsIntoEisRules(false);<br>}<br><br>function importFeesFromMainConfig(){<br> if(!fields.length)return alert(&#39;No fields configured in the main Config panel yet.&#39;);<br> syncMainFieldsIntoEisRules(true);<br> onEisConfigChanged();<br>}<br><br>function addEisFeeRow(){<br> const nextNum=eisFeeRules.length?Math.min(MAX_LABELS,Math.max(...eisFeeRules.map(r=&gt;r.fieldNum))+1):1;<br> eisFeeRules.push(normEisFeeRule({fieldNum:nextNum,name:&#39;&#39;,aliases:&#39;&#39;,expected:&#39;&#39;,ruleType:&#39;match_page&#39;,enabled:true}));<br> onEisConfigChanged();<br>}<br><br>function applyEisFeesPaste(){<br> const raw=$(&#39;eisFeesPaste&#39;).value.trim();<br> if(!raw)return;<br> const pageIdx=selectedFeePage();<br> const lines=raw.split(/\r?\n/).map(x=&gt;x.trim());<br> const blocks=raw.split(/\r?\n\s*\r?\n+/).map(b=&gt;b.split(/\r?\n/).map(x=&gt;x.trim()).filter(Boolean)).filter(b=&gt;b.length);<br> const feeBlocks=[];<br> const looksMoney=v=&gt;parseMoneyValue(v)!==null&amp;&amp;/^[₱$€£¥]?\s*-?\(?[\d,]+(?:\.\d{1,2})?\)?\s*$/.test(String(v||&#39;&#39;).trim());<br> const isCode=v=&gt;/^(NC|IC|CWT)$/i.test(String(v||&#39;&#39;).trim());<br><br> // Preferred format: blank-line-separated fee blocks. Each block is Name / Amount / optional Code.<br> if(blocks.length&gt;1||(!lines.some(x=&gt;x.includes(&#39;|&#39;))&amp;&amp;lines.length&gt;=2)){<br>  if(blocks.length&gt;1){<br>   blocks.forEach(b=&gt;{if(b.length&gt;=2&amp;&amp;looksMoney(b[1]))feeBlocks.push({name:b[0],amount:b[1],code:b[2]||(/\bcwt\b/i.test(b[0])?&#39;CWT&#39;:&#39;&#39;)});});<br>  }else{<br>   // Also accept the same three-line pattern without blank separators; CWT may use only two lines.<br>   let i=0;<br>   while(i&lt;lines.length){<br>    const name=lines[i],amount=lines[i+1];<br>    if(name&amp;&amp;amount&amp;&amp;looksMoney(amount)){<br>     let code=&#39;&#39;;<br>     if(lines[i+2]&amp;&amp;isCode(lines[i+2])){code=lines[i+2];i+=3;}<br>     else{if(/\bcwt\b|creditable withholding tax|withholding tax/i.test(name))code=&#39;CWT&#39;;i+=2;}<br>     feeBlocks.push({name,amount,code});<br>    }else i++;<br>   }<br>  }<br> }<br><br> if(feeBlocks.length){<br>  if(!images.length)return alert(&#39;Add Main Page screenshots before configuring page-specific fees.&#39;);<br>  const next=[];<br>  for(let i=0;i&lt;feeBlocks.length;i++){<br>   const nums=nextAvailableFeeFieldBlock(pageIdx,next);<br>   if(!nums){$(&#39;eisFeesMsg&#39;).textContent=&#39;Only &#39;+next.length+&#39; fee(s) fit in the available 1–50 field numbers. Free up field numbers and try again.&#39;;return;}<br>   const b=feeBlocks[i];<br>   next.push(normPageFee({feeIndex:i+1,...nums,name:b.name,amountExpected:b.amount,codeExpected:b.code||&#39;&#39;},i));<br>  }<br>  pageFeeRules[String(pageIdx)]=next;<br>  persistConfig();populatePageFeePageSelect();$(&#39;pageFeePageSelect&#39;).value=String(pageIdx);renderPageFeeEditor();renderEisModal();<br>  $(&#39;eisFeesMsg&#39;).textContent=`Applied ${next.length} fee(s) to Page ${pageIdx+1}. Each fee received 3 field numbers; pasted amounts are expected values. Other pages were not changed.`;<br>  return;<br> }<br><br> // Legacy numbered / pipe format remains available for non-fee field rules.<br> const parsed=[];<br> lines.filter(Boolean).forEach(line=&gt;{<br>  if(line.includes(&#39;|&#39;)){<br>   const p=line.split(&#39;|&#39;).map(x=&gt;x.trim()),num=parseInt(p[0],10);<br>   if(num&gt;0&amp;&amp;p[1])parsed.push(normEisFeeRule({fieldNum:num,name:p[1],expected:p[2]||&#39;&#39;,ruleType:[&#39;name_and_3rd_row&#39;,&#39;match_page&#39;,&#39;exact&#39;,&#39;present&#39;].includes(p[3])?p[3]:&#39;match_page&#39;,aliases:p[4]||p[1],enabled:true}));<br>  }else{<br>   const m=line.match(/^(\d{1,3})[.):=\-\s]+(.+)$/);<br>   if(m){let name=m[2].trim(),expected=&#39;&#39;;const eq=name.indexOf(&#39;=&#39;);if(eq&gt;0){expected=name.slice(eq+1).trim();name=name.slice(0,eq).trim();}parsed.push(normEisFeeRule({fieldNum:parseInt(m[1],10),name,aliases:name,expected,ruleType:&#39;match_page&#39;,enabled:true}));}<br>  }<br> });<br> if(!parsed.length){$(&#39;eisFeesMsg&#39;).textContent=&#39;Could not parse. Paste blocks as Fee Name / Amount / optional Code, or use Field# | Field Name | Expected | match_page.&#39;;return;}<br> parsed.forEach(nr=&gt;{const idx=eisFeeRules.findIndex(r=&gt;r.name.toLowerCase()===nr.name.toLowerCase()||Number(r.fieldNum)===Number(nr.fieldNum));if(idx&gt;=0)eisFeeRules[idx]=nr;else eisFeeRules.push(nr);});<br> eisFeeRules.sort((a,b)=&gt;a.fieldNum-b.fieldNum);onEisConfigChanged();<br> $(&#39;eisFeesMsg&#39;).textContent=`Applied ${parsed.length} shared field rule(s).`;<br>}<br><br>function onEisConfigChanged(){<br> eisTolerance=Math.max(0,parseFloat($(&#39;eisTolerance&#39;)?.value)||0);<br> $(&#39;eisFeeRuleCount&#39;).textContent=eisFeeRules.filter(r=&gt;r.enabled).length;<br> populatePageFeePageSelect();<br> renderPageFeeEditor();<br> renderEisFeesTable();<br> renderEisModal();<br> persistConfig();<br>}<br><br>function renderEisFeesTable(){<br> const body=$(&#39;eisFeesBody&#39;);<br> if(!body)return;<br> body.innerHTML=&#39;&#39;;<br> $(&#39;eisFeeRuleCount&#39;).textContent=eisFeeRules.filter(r=&gt;r.enabled).length;<br> eisFeeRules.forEach((r,idx)=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  const td=()=&gt;document.createElement(&#39;td&#39;);<br>  const c1=td(),c2=td(),c3=td(),c4=td(),c5=td(),c6=td(),c7=td();<br><br>  const numInp=document.createElement(&#39;input&#39;);<br>  numInp.type=&#39;number&#39;;numInp.min=1;numInp.max=MAX_LABELS;numInp.value=r.fieldNum;<br>  numInp.onchange=()=&gt;{r.fieldNum=Math.max(1,Math.min(MAX_LABELS,parseInt(numInp.value,10)||1));onEisConfigChanged();};<br>  c1.appendChild(numInp);<br><br>  const nameInp=document.createElement(&#39;input&#39;);<br>  nameInp.type=&#39;text&#39;;nameInp.value=r.name;nameInp.placeholder=&quot;e.g. fee&#39;s 1 charge or Client Name&quot;;<br>  nameInp.oninput=()=&gt;{r.name=nameInp.value;persistConfig();renderEisModal();};<br>  c2.appendChild(nameInp);<br><br>  const aliasInp=document.createElement(&#39;input&#39;);<br>  aliasInp.type=&#39;text&#39;;aliasInp.value=r.aliases;aliasInp.placeholder=&#39;Optional alternate names&#39;;<br>  aliasInp.oninput=()=&gt;{r.aliases=aliasInp.value;persistConfig();renderEisModal();};<br>  c3.appendChild(aliasInp);<br><br>  const expInp=document.createElement(&#39;input&#39;);<br>  expInp.type=&#39;text&#39;;expInp.value=r.expected;expInp.placeholder=&#39;Optional expected or 3rd row code&#39;;<br>  expInp.oninput=()=&gt;{r.expected=expInp.value;persistConfig();renderEisModal();};<br>  c4.appendChild(expInp);<br><br>  const sel=document.createElement(&#39;select&#39;);<br>  [<br>   [&#39;match_page&#39;,&#39;Match Main Page &amp; EIS&#39;],<br>   [&#39;name_and_3rd_row&#39;,&#39;Fee Name + 3rd Row (Dynamic Amt)&#39;],<br>   [&#39;exact&#39;,&#39;Exact Expected Value&#39;],<br>   [&#39;present&#39;,&#39;Present in Receipt&#39;]<br>  ].forEach(([v,lbl])=&gt;{<br>   const o=document.createElement(&#39;option&#39;);o.value=v;o.textContent=lbl;if(r.ruleType===v)o.selected=true;sel.appendChild(o);<br>  });<br>  sel.onchange=()=&gt;{r.ruleType=sel.value;onEisConfigChanged();};<br>  c5.appendChild(sel);<br><br>  const chk=document.createElement(&#39;input&#39;);<br>  chk.type=&#39;checkbox&#39;;chk.checked=r.enabled!==false;<br>  chk.onchange=()=&gt;{r.enabled=chk.checked;onEisConfigChanged();};<br>  c6.style.textAlign=&#39;center&#39;;<br>  c6.appendChild(chk);<br><br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;danger mini&#39;;del.textContent=&#39;✕&#39;;<br>  del.onclick=()=&gt;{eisFeeRules.splice(idx,1);onEisConfigChanged();};<br>  c7.appendChild(del);<br><br>  tr.append(c1,c2,c3,c4,c5,c6,c7);<br>  body.appendChild(tr);<br> });<br>}<br><br>function exportEisFeesConfig(){<br> const payload={app:&#39;QA Screenshot Studio - EIS Fees Config&#39;,version:4,savedAt:new Date().toISOString(),eisTolerance,eisFeeRules,pageFeeRules};<br> downloadBlob(new Blob([JSON.stringify(payload,null,2)],{type:&#39;application/json&#39;}),`${safeName($(&#39;projectName&#39;).value)}-EIS-Fees-Config.json`);<br>}<br><br>$(&#39;eisFeesConfigFile&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const file=e.target.files&amp;&amp;e.target.files[0];<br> e.target.value=&#39;&#39;;<br> if(!file)return;<br> try{<br>  const obj=JSON.parse(await file.text());<br>  if(!Array.isArray(obj.eisFeeRules))throw new Error(&#39;No eisFeeRules array found in JSON.&#39;);<br>  eisFeeRules=obj.eisFeeRules.map(normEisFeeRule);<br>  if(obj.pageFeeRules&amp;&amp;typeof obj.pageFeeRules===&#39;object&#39;)pageFeeRules=Object.fromEntries(Object.entries(obj.pageFeeRules).map(([k,v])=&gt;[k,Array.isArray(v)?v.map(normPageFee):[]]));<br>  if(typeof obj.eisTolerance===&#39;number&#39;){eisTolerance=obj.eisTolerance;$(&#39;eisTolerance&#39;).value=eisTolerance;}<br>  onEisConfigChanged();<br>  populatePageFeePageSelect();renderPageFeeEditor();<br>  $(&#39;eisFeesMsg&#39;).textContent=`Imported ${eisFeeRules.length} shared rule(s) and page-specific fee configurations.`;<br> }catch(err){alert(&#39;Could not import EIS Fees Config: &#39;+err.message);}<br>});<br><br>function populateEisTargetPageSelect(){<br> // Kept for backward-compatibility; per-page slots now directly mirror Main Pages 1..N<br>}<br><br>function triggerBulkEisAttach(){<br> if(!images.length){<br>  return alert(&#39;Load or capture at least one Main Page first so receipts can map per page.&#39;);<br> }<br> $(&#39;eisFileInput&#39;).click();<br>}<br><br>function triggerSinglePageEisAttach(pageIdx){<br> pendingEisTargetPage=pageIdx;<br> $(&#39;eisSinglePageFileInput&#39;).click();<br>}<br><br>$(&#39;eisSinglePageFileInput&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const file=e.target.files&amp;&amp;e.target.files[0];<br> e.target.value=&#39;&#39;;<br> const targetIdx=pendingEisTargetPage;<br> pendingEisTargetPage=null;<br> if(!file||targetIdx===null||targetIdx&lt;0)return;<br> syncMainFieldsIntoEisRules(false);<br> await attachEisFileForPage(file,targetIdx);<br>});<br><br>$(&#39;eisFileInput&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const files=Array.from(e.target.files||[]);<br> e.target.value=&#39;&#39;;<br> if(!files.length)return;<br> if(!images.length)return alert(&#39;Add screenshots in the Main Workspace first.&#39;);<br> syncMainFieldsIntoEisRules(false);<br><br> // Map files to unattached pages first in sequential page order (Page 1, Page 2, ...)<br> let startIdx=0;<br> const firstEmpty=images.findIndex((_,idx)=&gt;!eisAttachments.some(a=&gt;a.targetPage===idx));<br> if(firstEmpty&gt;=0)startIdx=firstEmpty;<br><br> for(let i=0;i&lt;files.length;i++){<br>  const targetIdx=Math.min(images.length-1,startIdx+i);<br>  await attachEisFileForPage(files[i],targetIdx);<br> }<br>});<br><br>async function attachEisFileForPage(file,targetPageIdx){<br> const isPdf=file.type===&#39;application/pdf&#39;||/\.pdf$/i.test(file.name);<br> const isImage=file.type.startsWith(&#39;image/&#39;)||/\.(png|jpe?g|webp|bmp|gif)$/i.test(file.name);<br> const url=URL.createObjectURL(file);<br> let rawText=&#39;&#39;;<br> let ocrStatus=&#39;&#39;;<br> if(!isImage&amp;&amp;!isPdf){<br>  try{<br>   rawText=await file.text();<br>   ocrStatus=&#39;parsed&#39;;<br>  }catch(err){<br>   rawText=&#39;&#39;;<br>   ocrStatus=&#39;error&#39;;<br>  }<br> }else{<br>  ocrStatus=&#39;pending&#39;;<br> }<br><br> // Replace any existing attachment assigned to this exact Main Page slot so it stays 1-to-1 per page<br> const existingIdx=eisAttachments.findIndex(x=&gt;x.targetPage===targetPageIdx);<br> if(existingIdx&gt;=0){<br>  const old=eisAttachments[existingIdx];<br>  if(old.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(old.url);<br>  eisAttachments.splice(existingIdx,1);<br> }<br><br> const att={<br>  id:crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random()),<br>  name:file.name,<br>  mime:file.type||&#39;&#39;,<br>  targetPage:targetPageIdx,<br>  blob:file,<br>  url,<br>  isImage,isPdf,<br>  rawText,<br>  ocrStatus<br> };<br> eisAttachments.push(att);<br> eisAttachments.sort((a,b)=&gt;a.targetPage-b.targetPage);<br> activeEisAttachmentId=att.id;<br> scheduleWorkspaceAutosave();<br> renderEisModal();<br> if(isImage){<br>  await runEisAttachmentOCR(att.id);<br> }else if(isPdf){<br>  await runEisPdfOCR(att.id);<br> }<br>}<br><br>// High-accuracy image preprocessing for full-page EIS screenshots/documents<br>function preprocessEisImageForOCR(imgEl){<br> const w=imgEl.naturalWidth||imgEl.width;<br> const h=imgEl.naturalHeight||imgEl.height;<br> // Upscale smaller captures to at least ~2200px on the longest side for crisp small text &amp; codes (NC/IC)<br> const maxDim=Math.max(w,h);<br> const scale=maxDim&lt;2200?Math.min(3,Math.max(1.5,2400/Math.max(1,maxDim))):1.25;<br> const cw=Math.round(w*scale)+40;<br> const ch=Math.round(h*scale)+40;<br><br> const grayCanvas=document.createElement(&#39;canvas&#39;);<br> grayCanvas.width=cw;grayCanvas.height=ch;<br> const g=grayCanvas.getContext(&#39;2d&#39;,{willReadFrequently:true});<br> g.fillStyle=&#39;#ffffff&#39;;<br> g.fillRect(0,0,cw,ch);<br> g.imageSmoothingEnabled=true;<br> g.imageSmoothingQuality=&#39;high&#39;;<br> g.drawImage(imgEl,20,20,Math.round(w*scale),Math.round(h*scale));<br><br> const imgData=g.getImageData(20,20,Math.round(w*scale),Math.round(h*scale));<br> const px=imgData.data;<br> let sum=0,min=255,max=0;<br> const count=px.length/4;<br> for(let i=0;i&lt;px.length;i+=4){<br>  const lum=Math.round(0.299*px[i]+0.587*px[i+1]+0.114*px[i+2]);<br>  sum+=lum;<br>  if(lum&lt;min)min=lum;<br>  if(lum&gt;max)max=lum;<br> }<br> const avg=count?sum/count:255;<br> const invert=avg&lt;118; // Handle dark-mode screenshots automatically<br> const range=Math.max(40,max-min);<br><br> for(let i=0;i&lt;px.length;i+=4){<br>  let lum=0.299*px[i]+0.587*px[i+1]+0.114*px[i+2];<br>  lum=(lum-min)*255/range;<br>  if(invert)lum=255-lum;<br>  // Gentle contrast S-curve to sharpen thin characters<br>  lum=lum&lt;128?(lum*lum)/128:255-((255-lum)*(255-lum))/128;<br>  const v=Math.max(0,Math.min(255,Math.round(lum)));<br>  px[i]=px[i+1]=px[i+2]=v;<br> }<br> g.putImageData(imgData,20,20);<br><br> // Create a clean high-contrast binarized version for tabular/receipt text<br> const binCanvas=document.createElement(&#39;canvas&#39;);<br> binCanvas.width=cw;binCanvas.height=ch;<br> const bg=binCanvas.getContext(&#39;2d&#39;,{willReadFrequently:true});<br> bg.fillStyle=&#39;#ffffff&#39;;<br> bg.fillRect(0,0,cw,ch);<br> const binData=g.getImageData(20,20,Math.round(w*scale),Math.round(h*scale));<br> const bpx=binData.data;<br> const thresh=invert?165:175;<br> for(let i=0;i&lt;bpx.length;i+=4){<br>  const v=bpx[i]&gt;thresh?255:0;<br>  bpx[i]=bpx[i+1]=bpx[i+2]=v;<br> }<br> bg.putImageData(binData,20,20);<br><br> return{grayCanvas,binCanvas};<br>}<br><br>function loadHtmlImage(url){<br> return new Promise((resolve,reject)=&gt;{<br>  const im=new Image();<br>  im.onload=()=&gt;resolve(im);<br>  im.onerror=()=&gt;reject(new Error(&#39;Could not decode EIS image&#39;));<br>  im.src=url;<br> });<br>}<br><br>function cleanOcrOutputLines(raw){<br> return String(raw||&#39;&#39;)<br>  .replace(/[\u2018\u2019]/g,&quot;&#39;&quot;)<br>  .replace(/[\u201C\u201D]/g,&#39;&quot;&#39;)<br>  .split(/\r?\n/)<br>  .map(line=&gt;line.replace(/[ \t]{2,}/g,&#39; &#39;).trim())<br>  .filter(Boolean)<br>  .join(&#39;\n&#39;);<br>}<br><br>async function runEisAttachmentOCR(attId){<br> const att=eisAttachments.find(x=&gt;x.id===attId);<br> if(!att||!att.isImage)return;<br> att.ocrStatus=&#39;pending&#39;;<br> renderEisModal();<br> try{<br>  const worker=await getWorker();<br>  const imgEl=await loadHtmlImage(att.url);<br>  const {grayCanvas,binCanvas}=preprocessEisImageForOCR(imgEl);<br>  const engine=window.Tesseract;<br><br>  // Pass 1: Enhanced grayscale with PSM.AUTO (preserves multi-row and column reading order)<br>  await worker.setParameters({<br>   tessedit_pageseg_mode:engine.PSM.AUTO,<br>   preserve_interword_spaces:&#39;1&#39;,<br>   user_defined_dpi:&#39;300&#39;<br>  });<br>  const res1=await worker.recognize(grayCanvas);<br>  const text1=cleanOcrOutputLines(res1?.data?.text||&#39;&#39;);<br>  const conf1=Number(res1?.data?.confidence)||0;<br><br>  // Pass 2: Binarized high-contrast image with PSM.SPARSE_TEXT or AUTO if Pass 1 confidence is low or short<br>  let bestText=text1;<br>  let bestConf=conf1;<br>  if(conf1&lt;82||text1.length&lt;25){<br>   try{<br>    await worker.setParameters({<br>     tessedit_pageseg_mode:engine.PSM.AUTO,<br>     preserve_interword_spaces:&#39;1&#39;,<br>     user_defined_dpi:&#39;300&#39;<br>    });<br>    const res2=await worker.recognize(binCanvas);<br>    const text2=cleanOcrOutputLines(res2?.data?.text||&#39;&#39;);<br>    const conf2=Number(res2?.data?.confidence)||0;<br>    if(text2.length&gt;0&amp;&amp;(conf2&gt;bestConf+2||(bestText.length&lt;15&amp;&amp;text2.length&gt;bestText.length))){<br>     bestText=text2;<br>     bestConf=conf2;<br>    }<br>   }catch(e2){console.warn(&#39;EIS secondary OCR pass skipped:&#39;,e2);}<br>  }<br><br>  att.rawText=bestText;<br>  att.ocrConfidence=Math.round(bestConf);<br>  att.ocrStatus=&#39;done&#39;;<br> }catch(err){<br>  console.error(&#39;EIS OCR error:&#39;,err);<br>  att.ocrStatus=&#39;error&#39;;<br> }<br> scheduleWorkspaceAutosave();<br> renderEisModal();<br>}<br><br>async function runEisPdfOCR(attId){<br> const att=eisAttachments.find(x=&gt;x.id===attId);if(!att||!att.isPdf)return;<br> att.ocrStatus=&#39;pending&#39;;renderEisModal();<br> try{<br>  const started=Date.now();while(!window.pdfjsLib&amp;&amp;Date.now()-started&lt;15000)await new Promise(r=&gt;setTimeout(r,100));<br>  if(!window.pdfjsLib)throw new Error(&#39;PDF reader did not load. Check internet and reload.&#39;);<br>  const pdf=await window.pdfjsLib.getDocument({data:await att.blob.arrayBuffer()}).promise,worker=await getWorker(),pages=[];<br>  for(let n=1;n&lt;=pdf.numPages;n++){<br>   const page=await pdf.getPage(n),vp=page.getViewport({scale:2.2}),c=document.createElement(&#39;canvas&#39;);<br>   c.width=Math.ceil(vp.width);c.height=Math.ceil(vp.height);<br>   await page.render({canvasContext:c.getContext(&#39;2d&#39;),viewport:vp}).promise;<br>   const r=await worker.recognize(c);pages.push(`--- PDF PAGE ${n} ---\n${cleanOcrOutputLines(r?.data?.text||&#39;&#39;)}`);<br>   $(&#39;ocrStatus&#39;).textContent=`EIS PDF OCR: page ${n}/${pdf.numPages}`;<br>  }<br>  att.rawText=pages.join(&#39;\n\n&#39;);att.ocrStatus=&#39;done&#39;;<br> }catch(e){console.error(e);att.ocrStatus=&#39;error&#39;;att.rawText=`PDF OCR ERROR: ${e.message}`;}<br> scheduleWorkspaceAutosave();renderEisModal();<br>}<br>function reOcrActiveEisAttachment(){<br> if(!activeEisAttachmentId)return alert(&#39;Select an attached receipt first.&#39;);<br> const att=eisAttachments.find(x=&gt;x.id===activeEisAttachmentId);<br> if(!att)return alert(&#39;The selected receipt is no longer attached.&#39;);<br> if(att.isImage)runEisAttachmentOCR(att.id);<br> else if(att.isPdf)runEisPdfOCR(att.id);<br> else alert(&#39;This is a text/data attachment. Edit the extracted text directly.&#39;);<br>}<br><br>function onEisRawTextEdited(){<br> const att=eisAttachments.find(x=&gt;x.id===activeEisAttachmentId);<br> if(!att)return;<br> att.rawText=$(&#39;eisAttachmentRawText&#39;).value;<br> scheduleWorkspaceAutosave();<br> renderEisModal(true);<br>}<br><br>function deleteEisAttachment(attId){<br> const idx=eisAttachments.findIndex(x=&gt;x.id===attId);<br> if(idx&lt;0)return;<br> const att=eisAttachments[idx];<br> if(att.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(att.url);<br> eisAttachments.splice(idx,1);<br> if(activeEisAttachmentId===attId){<br>  activeEisAttachmentId=eisAttachments[0]?.id||null;<br> }<br> scheduleWorkspaceAutosave();<br> renderEisModal();<br>}<br><br>function getMainPageFieldValue(pageIdx,fieldNum){<br> if(pageIdx&lt;0||pageIdx&gt;=images.length)return &#39;&#39;;<br> const ann=annotations.find(a=&gt;a.image===pageIdx&amp;&amp;Number(a.label)===Number(fieldNum));<br> if(ann){const v=String(valueOf(ann)||&#39;&#39;).trim();if(v)return v;}<br> const pageField=pageFieldList(pageIdx).find(f=&gt;Number(f.num)===Number(fieldNum));<br> if(pageField&amp;&amp;pageField.mode===&#39;manual&#39;&amp;&amp;String(pageField.value||&#39;&#39;).trim())return String(pageField.value).trim();<br> const globalField=fieldFor(Number(fieldNum));<br> if(globalField&amp;&amp;globalField.mode===&#39;manual&#39;)return String(globalField.value||&#39;&#39;).trim();<br> return &#39;&#39;;<br>}<br><br>// Builds the complete list of fields ready for validation on a target page:<br>// Combines all Main Config fields + any annotations drawn on that Main Page + any custom EIS Fees Config rules<br>function getReadyRulesForPage(pageIdx){<br> const map=new Map();<br><br> // 1. Add all enabled rules from EIS Fees Config<br> eisFeeRules.filter(r=&gt;r.enabled!==false).forEach(r=&gt;{<br>  map.set(`${r.fieldNum}::${r.name.toLowerCase()}`,{...r});<br> });<br><br> // 2. Ensure every Main Config field is included &amp; ready<br> pageFieldList(pageIdx).forEach(f=&gt;{<br>  if(!f.name)return;<br>  const keyByNum=[...map.values()].find(x=&gt;Number(x.fieldNum)===Number(f.num));<br>  if(!keyByNum){<br>   const isThreeRowFee=/fee&#39;?s?\s*\d+\s*charge/i.test(f.name);<br>   map.set(`${f.num}::${f.name.toLowerCase()}`,normEisFeeRule({<br>    fieldNum:f.num,<br>    name:f.name,<br>    aliases:f.name,<br>    expected:f.mode===&#39;manual&#39;?f.value:&#39;&#39;,<br>    ruleType:isThreeRowFee?&#39;name_and_3rd_row&#39;:&#39;match_page&#39;,<br>    enabled:true<br>   }));<br>  }<br> });<br><br> // 3. Ensure any annotated box on this specific Main Page is also included &amp; ready<br> annotations.filter(a=&gt;a.image===pageIdx).forEach(a=&gt;{<br>  if(pageFeeList(pageIdx).some(pf=&gt;[pf.nameFieldNum,pf.amountFieldNum,pf.codeFieldNum].includes(Number(a.label))))return;<br>  const existing=[...map.values()].find(x=&gt;Number(x.fieldNum)===Number(a.label));<br>  if(!existing){<br>   const nm=labelName(a);<br>   const isThreeRowFee=/fee&#39;?s?\s*\d+\s*charge/i.test(nm);<br>   map.set(`${a.label}::${nm.toLowerCase()}`,normEisFeeRule({<br>    fieldNum:a.label,<br>    name:nm,<br>    aliases:nm,<br>    expected:&#39;&#39;,<br>    ruleType:isThreeRowFee?&#39;name_and_3rd_row&#39;:&#39;match_page&#39;,<br>    enabled:true<br>   }));<br>  }<br> });<br><br> // Add only this page&#39;s fee definitions. Each fee maps to three numbered fields:<br> // nameFieldNum (label), amountFieldNum (dynamic amount), codeFieldNum (code/tag).<br> pageFeeList(pageIdx).filter(f=&gt;f.enabled!==false).forEach(f=&gt;{<br>  const rule=normEisFeeRule({fieldNum:f.nameFieldNum,name:f.name,aliases:f.name,expected:f.codeExpected,ruleType:&#39;name_and_3rd_row&#39;,enabled:true});<br>  rule.feeAmountFieldNum=f.amountFieldNum;rule.feeCodeFieldNum=f.codeFieldNum;rule.feeAmountExpected=f.amountExpected;rule.feeIndex=f.feeIndex;rule.isPageFee=true;<br>  // Replace any generic rule on this fee&#39;s three field numbers; the page fee is the authoritative definition.<br>  for(const [k,v] of [...map.entries()])if([f.nameFieldNum,f.amountFieldNum,f.codeFieldNum].includes(Number(v.fieldNum)))map.delete(k);<br>  map.set(`pagefee-${f.id}`,rule);<br> });<br><br> // Current page field definitions override shared fee defaults, except page-specific fee slots.<br> pageFieldList(pageIdx).forEach(f=&gt;{<br>  if(pageFeeList(pageIdx).some(pf=&gt;[pf.nameFieldNum,pf.amountFieldNum,pf.codeFieldNum].includes(Number(f.num))))return;<br>  if(!f.name)return;<br>  const prior=[...map.values()].find(x=&gt;Number(x.fieldNum)===Number(f.num));<br>  if(prior)map.delete(`${prior.fieldNum}::${prior.name.toLowerCase()}`);<br>  const rule=normEisFeeRule({fieldNum:f.num,name:f.name,aliases:f.name,expected:f.mode===&#39;manual&#39;?f.value:(prior?.expected||&#39;&#39;),ruleType:prior?.ruleType||(/fee|charge|tax|cwt/i.test(f.name)?&#39;name_and_3rd_row&#39;:&#39;match_page&#39;),enabled:true});<br>  map.set(`${rule.fieldNum}::${rule.name.toLowerCase()}`,rule);<br> });<br> return [...map.values()].sort((a,b)=&gt;a.fieldNum-b.fieldNum);<br>}<br><br>function parseNumericToken(str){<br> if(str===null||str===undefined)return null;<br> const cleaned=String(str).replace(/[,₱$€£¥\s]/g,&#39;&#39;);<br> const m=cleaned.match(/-?\d+(?:\.\d+)?/);<br> return m?parseFloat(m[0]):null;<br>}<br><br>function normalizeTextToken(s){<br> return String(s??&#39;&#39;).replace(/[\u2018\u2019]/g,&quot;&#39;&quot;).replace(/\s+/g,&#39; &#39;).trim();<br>}<br><br>function valuesMatch(valA,valB,tol=0.01){<br> const a=normalizeTextToken(valA);<br> const b=normalizeTextToken(valB);<br> if(!a||!b)return false;<br> if(a.toLowerCase()===b.toLowerCase())return true;<br> const na=parseNumericToken(a);<br> const nb=parseNumericToken(b);<br> if(na!==null&amp;&amp;nb!==null){<br>  return Math.abs(na-nb)&lt;=(Number(tol)||0);<br> }<br> return b.toLowerCase().includes(a.toLowerCase())||a.toLowerCase().includes(b.toLowerCase());<br>}<br><br>// Extracts both:<br>// - 3-row fee blocks (Row 1 = Fee Name, Row 2 = Dynamic Amount, Row 3 = Code/Tag e.g. NC / IC)<br>// - Standard Main Page field values (same-line &quot;Label: Value&quot;, next-line value, or direct value match)<br>function extractFieldFromEisText(rawText,rule,mainPageVal){<br> const text=String(rawText||&#39;&#39;);<br> if(!text.trim())return{foundName:&#39;&#39;,dynamicAmount:&#39;&#39;,thirdRowValue:&#39;&#39;,matchedValue:&#39;&#39;};<br><br> const candidates=[rule.name,...String(rule.aliases||&#39;&#39;).split(&#39;,&#39;)]<br>  .map(s=&gt;normalizeTextToken(s)).filter(Boolean);<br> const lines=text.split(/\r?\n/).map(l=&gt;normalizeTextToken(l)).filter(Boolean);<br><br> // 1. Check 3-row block or label-based match<br> for(const key of candidates){<br>  const kl=key.toLowerCase();<br>  const escKey=key.replace(/[.*+?^${}()|[\]\\]/g,&#39;\\$&amp;&#39;);<br><br>  // Same-line &quot;Label : Value&quot; or &quot;Label = Value&quot;<br>  const sameLineRe=new RegExp(`^${escKey}\\s*[:=\\-–|]\\s*(.+)$`,&#39;i&#39;);<br>  for(let i=0;i&lt;lines.length;i++){<br>   const sm=lines[i].match(sameLineRe);<br>   if(sm&amp;&amp;sm[1]&amp;&amp;sm[1].trim()){<br>    const v=sm[1].trim();<br>    return{foundName:key,dynamicAmount:&#39;&#39;,thirdRowValue:v,matchedValue:v};<br>   }<br>  }<br><br>  // Row-by-row lookup where line[i] matches Fee/Field Name<br>  for(let i=0;i&lt;lines.length;i++){<br>   const lineLow=lines[i].toLowerCase();<br>   if(lineLow===kl||lineLow.includes(kl)){<br>    const inlineParts=lines[i].split(/\s*[|\t,;]\s*/).map(x=&gt;x.trim()).filter(Boolean);<br>    if(inlineParts.length&gt;=3 &amp;&amp; inlineParts[0].toLowerCase().includes(kl)){<br>     return{foundName:inlineParts[0],dynamicAmount:inlineParts[1],thirdRowValue:inlineParts[2],matchedValue:inlineParts[2]};<br>    }<br>    const row2=lines[i+1]||&#39;&#39;;<br>    const row3=lines[i+2]||&#39;&#39;;<br>    if(rule.ruleType===&#39;name_and_3rd_row&#39;){<br>     // CWT is commonly printed as a two-line item (CWT, then amount).<br>     // Do not accidentally treat the next fee&#39;s name as its code row.<br>     const isCwtName=/\bcwt\b|creditable withholding tax|withholding tax/i.test(lines[i]);<br>     const row3LooksLikeCode=/^(NC|IC|CWT)$/i.test(normalizeTextToken(row3));<br>     const codeValue=row3LooksLikeCode?row3:(isCwtName?&#39;CWT&#39;:&#39;&#39;);<br>     return{foundName:lines[i],dynamicAmount:row2,thirdRowValue:codeValue,matchedValue:codeValue};<br>    }<br>    // For standard Main Page fields, check if remainder on same line or next line holds the value<br>    const remainder=lines[i].replace(new RegExp(escKey,&#39;i&#39;),&#39;&#39;).replace(/^[\s:=\-–|]+/,&#39;&#39;).trim();<br>    const val=remainder||row2||lines[i];<br>    return{foundName:lines[i],dynamicAmount:&#39;&#39;,thirdRowValue:val,matchedValue:val};<br>   }<br>  }<br><br>  // JSON / XML key-value lookup<br>  const jsonRe=new RegExp(`[&quot;&#39;]?${escKey}[&quot;&#39;]?\\s*[:=]\\s*[&quot;&#39;]?([^&quot;&#39;,\\r\\n}&lt;]+)`,&#39;i&#39;);<br>  const jm=text.match(jsonRe);<br>  if(jm&amp;&amp;jm[1]&amp;&amp;jm[1].trim()){<br>   const v=jm[1].trim();<br>   return{foundName:key,dynamicAmount:&#39;&#39;,thirdRowValue:v,matchedValue:v};<br>  }<br> }<br><br> // 2. Direct value search for standard Main Page fields (when EIS shows the value directly without repeating the field label)<br> if(rule.ruleType!==&#39;name_and_3rd_row&#39;){<br>  const target=normalizeTextToken(mainPageVal||rule.expected);<br>  if(target){<br>   const tl=target.toLowerCase();<br>   const hitLine=lines.find(l=&gt;l.toLowerCase()===tl||l.toLowerCase().includes(tl));<br>   if(hitLine){<br>    return{foundName:rule.name,dynamicAmount:&#39;&#39;,thirdRowValue:target,matchedValue:target};<br>   }<br>   const targetNum=parseNumericToken(target);<br>   if(targetNum!==null){<br>    for(const l of lines){<br>     const tokens=l.match(/-?\d[\d,]*(?:\.\d+)?/g)||[];<br>     for(const tok of tokens){<br>      const n=parseNumericToken(tok);<br>      if(n!==null&amp;&amp;Math.abs(n-targetNum)&lt;=(Number(eisTolerance)||0)){<br>       return{foundName:rule.name,dynamicAmount:&#39;&#39;,thirdRowValue:tok,matchedValue:tok};<br>      }<br>     }<br>    }<br>   }<br>  }<br> }<br><br> return{foundName:&#39;&#39;,dynamicAmount:&#39;&#39;,thirdRowValue:&#39;&#39;,matchedValue:&#39;&#39;};<br>}<br><br>function evaluateEisAttachment(att){<br> const activeRules=getReadyRulesForPage(att.targetPage);<br> const results=activeRules.map(rule=&gt;{<br>  const mainVal=getMainPageFieldValue(att.targetPage,rule.fieldNum);<br>  const block=extractFieldFromEisText(att.rawText,rule,mainVal);<br>  const expVal=normalizeTextToken(rule.expected);<br>  let pass=false,reason=&#39;&#39;,status=&#39;FAIL&#39;;<br><br>  if(att.ocrStatus===&#39;pending&#39;||(!String(att.rawText||&#39;&#39;).trim()&amp;&amp;att.ocrStatus!==&#39;error&#39;)){<br>   return{rule,mainVal,expVal,eisName:&#39;Reading…&#39;,eisAmount:&#39;…&#39;,eisThirdRow:&#39;…&#39;,status:&#39;PENDING&#39;,reason:&#39;Receipt OCR is still running or the receipt text is not ready.&#39;};<br>  }<br>  if(att.ocrStatus===&#39;error&#39;){<br>   return{rule,mainVal,expVal,eisName:&#39;&#39;,eisAmount:&#39;&#39;,eisThirdRow:&#39;&#39;,status:&#39;PENDING&#39;,reason:&#39;Receipt could not be read. Re-OCR or edit the extracted receipt text.&#39;};<br>  }<br><br>  if(rule.ruleType===&#39;name_and_3rd_row&#39;){<br>   const isCwtFee=/\bcwt\b|creditable withholding tax|withholding tax/i.test(rule.name||&#39;&#39;);<br>   const amountFieldVal=rule.isPageFee?getMainPageFieldValue(att.targetPage,rule.feeAmountFieldNum):&#39;&#39;;<br>   const codeFieldVal=rule.isPageFee?getMainPageFieldValue(att.targetPage,rule.feeCodeFieldNum):&#39;&#39;;<br>   const targetCode=normalizeTextToken(codeFieldVal||rule.codeExpected||expVal||(isCwtFee?&#39;CWT&#39;:&#39;&#39;));<br>   const amountExpected=normalizeTextToken(amountFieldVal||rule.feeAmountExpected||&#39;&#39;);<br>   const rawAmountFound=normalizeTextToken(block.dynamicAmount||&#39;&#39;);<br>   const parsedAmount=parseMoneyValue(rawAmountFound);<br>   const amountFound=parsedAmount===null?&#39;&#39;:String(isCwtFee?Math.abs(parsedAmount):parsedAmount);<br>   const expectedAmountNum=amountExpected?parseMoneyValue(amountExpected):null;<br>   const foundAmountNum=amountFound?parseMoneyValue(amountFound):null;<br>   const comparableExpected=isCwtFee&amp;&amp;expectedAmountNum!==null?Math.abs(expectedAmountNum):expectedAmountNum;<br>   const amountOk=Boolean(amountFound)&amp;&amp;(!amountExpected||(comparableExpected!==null&amp;&amp;foundAmountNum!==null&amp;&amp;Math.abs(comparableExpected-foundAmountNum)&lt;=(Number(eisTolerance)||0)));<br>   const codeFound=normalizeTextToken(block.thirdRowValue||&#39;&#39;);<br>   const codeRequired=!isCwtFee||Boolean(targetCode);<br>   const codeConfigured=Boolean(targetCode);<br>   const codeOk=codeConfigured&amp;&amp;Boolean(codeFound)&amp;&amp;codeFound.toLowerCase()===targetCode.toLowerCase();<br>   const nameOk=Boolean(block.foundName);<br>   const setupPending=nameOk&amp;&amp;amountOk&amp;&amp;!codeConfigured&amp;&amp;!isCwtFee;<br>   pass=nameOk&amp;&amp;amountOk&amp;&amp;(isCwtFee&amp;&amp;!codeConfigured?true:codeOk);<br>   if(!nameOk)reason=`Fee name &quot;${rule.name}&quot; was not found in this receipt.`;<br>   else if(!amountFound)reason=`Fee amount is missing (Main Page Field #${rule.feeAmountFieldNum||&#39;—&#39;}).`;<br>   else if(!amountOk)reason=`Receipt amount ${amountFound} does not match Main Page / expected amount ${amountExpected}.`;<br>   else if(setupPending)reason=`Fee name and amount found, but configure or capture the expected fee code in Main Page Field #${rule.feeCodeFieldNum||&#39;—&#39;} before this fee can PASS.`;<br>   else if(!codeOk&amp;&amp;!isCwtFee)reason=`Receipt code &quot;${codeFound||&#39;missing&#39;}&quot; does not match Main Page / expected code &quot;${targetCode}&quot;.`;<br>   else reason=`Fee name, amount${amountExpected?&#39; (matched Main Page)&#39;:&#39; (present; dynamic)&#39;}, and ${codeConfigured?&#39;code&#39;:&#39;CWT identity&#39;} validated${isCwtFee?&#39;; CWT uses absolute amount and is deducted&#39;:&#39;&#39;}.`;<br>   return{rule,mainVal,expVal,eisName:block.foundName,eisAmount:rawAmountFound,eisThirdRow:codeFound,status:setupPending?&#39;PENDING&#39;:(pass?&#39;PASS&#39;:&#39;FAIL&#39;),reason,amountFieldVal,codeFieldVal,amountFound};<br>  }<br><br>  if(rule.ruleType===&#39;present&#39;){<br>   pass=Boolean(block.foundName||block.matchedValue);<br>   reason=pass?`&quot;${rule.name}&quot; found in receipt.`:`&quot;${rule.name}&quot; not found in receipt.`;<br>  }else if(rule.ruleType===&#39;exact&#39;){<br>   const eisCheckVal=block.matchedValue||block.thirdRowValue;<br>   if(!expVal){pass=false;reason=&#39;No Expected Value is configured.&#39;;}<br>   else{<br>    const mainOk=mainVal?valuesMatch(mainVal,expVal,eisTolerance):true;<br>    const eisOk=valuesMatch(eisCheckVal,expVal,eisTolerance);<br>    pass=mainOk&amp;&amp;eisOk;<br>    reason=pass?`Exact expected value matched (${expVal}).`:!eisCheckVal?`Missing in receipt (expected ${expVal}).`:!eisOk?`Receipt value &quot;${eisCheckVal}&quot; does not match expected &quot;${expVal}&quot;.`:`Main Page value &quot;${mainVal}&quot; does not match expected &quot;${expVal}&quot;.`;<br>   }<br>  }else{<br>   const eisCheckVal=block.matchedValue||block.thirdRowValue;<br>   const reference=mainVal||expVal;<br>   if(!reference){<br>    pass=Boolean(block.foundName&amp;&amp;eisCheckVal);<br>    reason=pass?`Field &quot;${rule.name}&quot; was found in receipt; no fixed Main Page value was configured.`:`No Main Page value or matching receipt field was found for &quot;${rule.name}&quot;.`;<br>   }else if(!eisCheckVal){pass=false;reason=`&quot;${reference}&quot; was not found in receipt for &quot;${rule.name}&quot;.`;}<br>   else{<br>    pass=valuesMatch(reference,eisCheckVal,eisTolerance)&amp;&amp;(!expVal||valuesMatch(expVal,eisCheckVal,eisTolerance));<br>    reason=pass?`Main Page and receipt values match (${eisCheckVal}).`:`Mismatch: Main Page &quot;${reference}&quot; vs receipt &quot;${eisCheckVal}&quot;.`;<br>   }<br>  }<br>  return{rule,mainVal,expVal,eisName:block.foundName,eisAmount:block.dynamicAmount,eisThirdRow:block.matchedValue||block.thirdRowValue,status:pass?&#39;PASS&#39;:&#39;FAIL&#39;,reason};<br> });<br> const passCount=results.filter(x=&gt;x.status===&#39;PASS&#39;).length;<br> const failCount=results.filter(x=&gt;x.status===&#39;FAIL&#39;).length;<br> const pendingCount=results.filter(x=&gt;x.status===&#39;PENDING&#39;).length;<br> const overall=pendingCount?&#39;PENDING&#39;:(!results.length?&#39;NO FIELDS&#39;:(failCount===0?&#39;PASS&#39;:&#39;FAIL&#39;));<br> return{results,passCount,failCount,pendingCount,overall};<br>}<br><br>function target3dSafe(v){return Boolean(String(v||&#39;&#39;).trim());}<br><br>function parseMoneyValue(raw){<br> const n=String(raw??&#39;&#39;).replace(/[₱,$\s]/g,&#39;&#39;).replace(/\(([^)]+)\)/,&#39;-$1&#39;);<br> const m=n.match(/-?\d+(?:,\d{3})*(?:\.\d{1,2})?/);<br> return m?Number(m[0].replace(/,/g,&#39;&#39;)):null;<br>}<br>function calculateReceiptFees(raw){<br> const lines=String(raw||&#39;&#39;).split(/\r?\n/).map(x=&gt;x.trim()).filter(Boolean);<br> const fees=[];let gross=0,cwt=0;const used=new Set();<br> for(let i=0;i&lt;lines.length;i++){<br>  if(used.has(i))continue;<br>  let label=&#39;&#39;,amount=null,amountLine=-1;<br>  const same=lines[i].match(/^(.{2,100}?)\s*[:=|]\s*(?:₱\s*)?(-?\(?[\d,]+(?:\.\d{1,2})?\)?)/);<br>  if(same){label=same[1].trim();amount=parseMoneyValue(same[2]);amountLine=i;}<br>  else if(/fee|charge|tax|withholding|cwt|service/i.test(lines[i])){<br>   const next=lines[i+1]||&#39;&#39;;<br>   if(parseMoneyValue(next)!==null){label=lines[i];amount=parseMoneyValue(next);amountLine=i+1;}<br>  }<br>  if(!label||amount===null)continue;<br>  const isCwt=/\bcwt\b|creditable withholding tax|withholding tax/i.test(label);<br>  fees.push({label,amount,isCwt,absoluteAmount:Math.abs(amount),sourceLine:i+1});<br>  if(amountLine&gt;=0)used.add(amountLine);<br>  if(isCwt)cwt+=Math.abs(amount);else gross+=amount;<br> }<br> return{fees,gross,cwt,net:gross-cwt};<br>}<br><br>function renderReceiptFinancialSummary(att){<br> const host=$(&#39;eisFinancialSummaryBody&#39;);if(!host)return;<br> const r=calculateReceiptFees(att?.rawText||&#39;&#39;);<br> if(!r.fees.length){host.textContent=&#39;No fee amounts confidently detected. Review/edit OCR text; calculation updates automatically.&#39;;return;}<br> const money=n=&gt;&#39;₱&#39;+Number(n||0).toLocaleString(&#39;en-PH&#39;,{minimumFractionDigits:2,maximumFractionDigits:2});<br> host.innerHTML=`&lt;div class=&quot;fin-grid&quot;&gt;&lt;div class=&quot;fin-cell&quot;&gt;Gross fees&lt;strong&gt;${money(r.gross)}&lt;/strong&gt;&lt;/div&gt;&lt;div class=&quot;fin-cell&quot;&gt;Less: CWT&lt;strong&gt;− ${money(r.cwt)}&lt;/strong&gt;&lt;/div&gt;&lt;div class=&quot;fin-cell&quot;&gt;Net total&lt;strong&gt;${money(r.net)}&lt;/strong&gt;&lt;/div&gt;&lt;div class=&quot;fin-cell&quot;&gt;Fee lines&lt;strong&gt;${r.fees.length}&lt;/strong&gt;&lt;/div&gt;&lt;/div&gt;&lt;table class=&quot;data-table&quot; style=&quot;margin-top:9px&quot;&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Fee&lt;/th&gt;&lt;th&gt;Amount&lt;/th&gt;&lt;th&gt;Treatment&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;${r.fees.map(f=&gt;`&lt;tr&gt;&lt;td&gt;${xesc(f.label)}&lt;/td&gt;&lt;td&gt;${money(f.amount)}&lt;/td&gt;&lt;td&gt;${f.isCwt?&#39;Deduct from total&#39;:&#39;Add to gross&#39;}&lt;/td&gt;&lt;/tr&gt;`).join(&#39;&#39;)}&lt;/tbody&gt;&lt;/table&gt;`;<br>}<br>function runAllEisValidations(){<br> syncMainFieldsIntoEisRules(false);<br> renderEisModal();<br>}<br><br>function renderEisModal(skipTextareaOverwrite=false){<br> if(!$(&#39;eisModal&#39;))return;<br> $(&#39;eisFeeRuleCount&#39;).textContent=eisFeeRules.filter(r=&gt;r.enabled).length;<br><br> const attList=$(&#39;eisAttachmentsList&#39;);<br> $(&#39;eisAttListCount&#39;).textContent=eisAttachments.length;<br> if($(&#39;eisMainPageTotalCount&#39;))$(&#39;eisMainPageTotalCount&#39;).textContent=images.length;<br> attList.innerHTML=&#39;&#39;;<br><br> let totalChecks=0,totalPass=0,totalFail=0;<br> const summaryBody=$(&#39;eisAllSummaryBody&#39;);<br> summaryBody.innerHTML=&#39;&#39;;<br><br> if(!images.length){<br>  attList.innerHTML=&#39;&lt;div class=&quot;small&quot;&gt;No pages loaded in the Main Workspace yet. Capture or upload screenshots in the main screen first.&lt;/div&gt;&#39;;<br> }else{<br>  // Render one dedicated EIS attachment slot per Main Page (Page 1, Page 2, ...)<br>  images.forEach((imgIt,pIdx)=&gt;{<br>   const att=eisAttachments.find(a=&gt;a.targetPage===pIdx)||null;<br>   const readyRules=getReadyRulesForPage(pIdx);<br>   const pageTitle=imgIt.title||imgIt.name;<br><br>   const card=document.createElement(&#39;div&#39;);<br>   card.className=&#39;eis-att-item&#39;;<br>   if(att&amp;&amp;att.id===activeEisAttachmentId)card.style.borderColor=&#39;var(--accent)&#39;;<br>   if(att)card.onclick=()=&gt;{activeEisAttachmentId=att.id;renderEisModal();};<br><br>   const head=document.createElement(&#39;div&#39;);<br>   head.className=&#39;eis-att-head&#39;;<br>   const title=document.createElement(&#39;strong&#39;);<br>   title.style.cssText=&#39;font-size:12px;max-width:215px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap&#39;;<br>   title.textContent=`Page ${pIdx+1}: ${pageTitle}`;<br><br>   const badge=document.createElement(&#39;span&#39;);<br>   if(!att){<br>    badge.className=&#39;badge-warn&#39;;<br>    badge.textContent=&#39;NO EIS FILE&#39;;<br>   }else{<br>    const ev=evaluateEisAttachment(att);<br>    totalChecks+=ev.results.length;<br>    totalPass+=ev.passCount;<br>    totalFail+=ev.failCount;<br>    badge.className=ev.overall===&#39;PASS&#39;?&#39;badge-pass&#39;:(ev.overall===&#39;FAIL&#39;?&#39;badge-fail&#39;:&#39;badge-warn&#39;);<br>    badge.textContent=`${ev.overall} (${ev.passCount}/${ev.results.length})`;<br>   }<br>   head.append(title,badge);<br><br>   const subRow=document.createElement(&#39;div&#39;);<br>   subRow.style.cssText=&#39;display:flex;align-items:center;justify-content:space-between;gap:6px;margin-top:6px&#39;;<br>   subRow.onclick=e=&gt;e.stopPropagation();<br><br>   const infoSpan=document.createElement(&#39;span&#39;);<br>   infoSpan.className=&#39;small&#39;;<br>   infoSpan.style.cssText=&#39;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1&#39;;<br>   infoSpan.textContent=att<br>    ? `📎 ${att.name} · ${readyRules.length} field(s) ready`<br>    : `${readyRules.length} field(s) ready · Waiting for receipt`;<br><br>   const btnGroup=document.createElement(&#39;div&#39;);<br>   btnGroup.style.cssText=&#39;display:flex;gap:4px;flex-shrink:0&#39;;<br>   const attachBtn=document.createElement(&#39;button&#39;);<br>   attachBtn.className=att?&#39;mini&#39;:&#39;mini primary&#39;;<br>   attachBtn.textContent=att?&#39;Replace&#39;:&#39;📎 Attach EIS&#39;;<br>   attachBtn.onclick=()=&gt;triggerSinglePageEisAttach(pIdx);<br>   btnGroup.appendChild(attachBtn);<br><br>   if(att){<br>    const delBtn=document.createElement(&#39;button&#39;);<br>    delBtn.className=&#39;mini danger&#39;;<br>    delBtn.textContent=&#39;✕&#39;;<br>    delBtn.title=&#39;Remove receipt from this page&#39;;<br>    delBtn.onclick=()=&gt;deleteEisAttachment(att.id);<br>    btnGroup.appendChild(delBtn);<br>   }<br>   subRow.append(infoSpan,btnGroup);<br>   card.append(head,subRow);<br><br>   if(att&amp;&amp;att.isImage&amp;&amp;att.url){<br>    const prev=document.createElement(&#39;img&#39;);<br>    prev.className=&#39;eis-att-preview&#39;;<br>    prev.src=att.url;<br>    card.appendChild(prev);<br>   }<br>   attList.appendChild(card);<br><br>   // Add row to All Pages Validation Summary table<br>   const sTr=document.createElement(&#39;tr&#39;);<br>   if(att&amp;&amp;att.id===activeEisAttachmentId)sTr.className=&#39;sel&#39;;<br>   sTr.style.cursor=&#39;pointer&#39;;<br>   if(att){<br>    const ev=evaluateEisAttachment(att);<br>    sTr.onclick=()=&gt;{activeEisAttachmentId=att.id;renderEisModal();};<br>    sTr.innerHTML=`<br>     &lt;td&gt;&lt;strong&gt;${xesc(att.name)}&lt;/strong&gt;&lt;/td&gt;<br>     &lt;td&gt;Page ${pIdx+1} (${xesc(pageTitle)})&lt;/td&gt;<br>     &lt;td&gt;${ev.passCount} / ${ev.results.length}&lt;/td&gt;<br>     &lt;td&gt;&lt;span class=&quot;${ev.overall===&#39;PASS&#39;?&#39;badge-pass&#39;:(ev.overall===&#39;FAIL&#39;?&#39;badge-fail&#39;:&#39;badge-warn&#39;)}&quot;&gt;${ev.overall}&lt;/span&gt;&lt;/td&gt;<br>     &lt;td&gt;&lt;button class=&quot;mini&quot;&gt;Inspect&lt;/button&gt;&lt;/td&gt;<br>    `;<br>   }else{<br>    sTr.onclick=()=&gt;triggerSinglePageEisAttach(pIdx);<br>    sTr.innerHTML=`<br>     &lt;td class=&quot;small&quot;&gt;&lt;em&gt;Not attached yet&lt;/em&gt;&lt;/td&gt;<br>     &lt;td&gt;Page ${pIdx+1} (${xesc(pageTitle)})&lt;/td&gt;<br>     &lt;td&gt;0 / ${readyRules.length}&lt;/td&gt;<br>     &lt;td&gt;&lt;span class=&quot;badge-warn&quot;&gt;PENDING FILE&lt;/span&gt;&lt;/td&gt;<br>     &lt;td&gt;&lt;button class=&quot;mini primary&quot;&gt;📎 Attach&lt;/button&gt;&lt;/td&gt;<br>    `;<br>   }<br>   summaryBody.appendChild(sTr);<br>  });<br> }<br><br> $(&#39;eisKpiAttachments&#39;).textContent=eisAttachments.length;<br> $(&#39;eisKpiChecks&#39;).textContent=totalChecks;<br> $(&#39;eisKpiPass&#39;).textContent=totalPass;<br> $(&#39;eisKpiFail&#39;).textContent=totalFail;<br> $(&#39;eisGlobalSummary&#39;).textContent=`${eisAttachments.length}/${images.length} page(s) attached · ${totalPass} PASS · ${totalFail} FAIL · Auto-saved`;<br> renderCurrentPageReceiptStatus();<br><br> const activeAtt=eisAttachments.find(x=&gt;x.id===activeEisAttachmentId)||eisAttachments[0]||null;<br> const compBody=$(&#39;eisComparisonBody&#39;);<br> compBody.innerHTML=&#39;&#39;;<br><br> if(!activeAtt){<br>  $(&#39;eisManualTextWrap&#39;).style.display=&#39;none&#39;;<br>  $(&#39;eisComparisonEmpty&#39;).hidden=false;<br>  $(&#39;eisActiveCompareInfo&#39;).textContent=&#39;Attach a receipt to any Main Page slot on the left — all fields on that page are ready to validate immediately.&#39;;<br>  return;<br> }<br><br> activeEisAttachmentId=activeAtt.id;<br> $(&#39;eisManualTextWrap&#39;).style.display=&#39;block&#39;;<br> if(!skipTextareaOverwrite&amp;&amp;$(&#39;eisAttachmentRawText&#39;)){<br>  $(&#39;eisAttachmentRawText&#39;).value=activeAtt.rawText||&#39;&#39;;<br> }<br> const targetPageObj=images[activeAtt.targetPage];<br> const confNote=activeAtt.ocrConfidence?` · OCR confidence: ${activeAtt.ocrConfidence}%`:&#39;&#39;;<br> $(&#39;eisActiveCompareInfo&#39;).innerHTML=`Validating &lt;b&gt;${xesc(activeAtt.name)}&lt;/b&gt; against &lt;b&gt;Page ${activeAtt.targetPage+1}${targetPageObj?&#39; (&#39;+xesc(targetPageObj.title||targetPageObj.name)+&#39;)&#39;:&#39;&#39;}&lt;/b&gt;${confNote}`;<br><br> renderReceiptFinancialSummary(activeAtt);<br> const activeEval=evaluateEisAttachment(activeAtt);<br> $(&#39;eisComparisonEmpty&#39;).hidden=activeEval.results.length&gt;0;<br><br> activeEval.results.forEach(item=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  const badgeHtml=item.status===&#39;PASS&#39;<br>   ?&#39;&lt;span class=&quot;badge-pass&quot;&gt;PASS&lt;/span&gt;&#39;<br>   :(item.status===&#39;FAIL&#39;?&#39;&lt;span class=&quot;badge-fail&quot;&gt;FAIL&lt;/span&gt;&#39;:&#39;&lt;span class=&quot;badge-warn&quot;&gt;PENDING&lt;/span&gt;&#39;);<br>  const modeLabel=item.rule.isPageFee?&#39;3-Field Fee&#39;:(item.rule.ruleType===&#39;name_and_3rd_row&#39;?&#39;3-Row Fee&#39;:&#39;Main Field&#39;);<br>  const amtDisplay=item.eisAmount ? `${xesc(item.eisAmount)} &lt;span class=&quot;small&quot;&gt;(receipt)&lt;/span&gt;` : &#39;—&#39;;<br>  const mainDisplay=item.mainVal||(item.expVal?`${item.expVal} (config)`:&#39;—&#39;);<br>  tr.innerHTML=`<br>   &lt;td&gt;${item.rule.isPageFee?`#${item.rule.fieldNum} / #${item.rule.feeAmountFieldNum} / #${item.rule.feeCodeFieldNum}`:`#${item.rule.fieldNum}`}&lt;/td&gt;<br>   &lt;td&gt;&lt;strong&gt;${xesc(item.rule.name)}&lt;/strong&gt;&lt;/td&gt;<br>   &lt;td class=&quot;small&quot;&gt;${modeLabel}&lt;/td&gt;<br>   &lt;td&gt;${xesc(mainDisplay)}&lt;/td&gt;<br>   &lt;td&gt;${xesc(item.eisName||&#39;—&#39;)}&lt;/td&gt;<br>   &lt;td&gt;${amtDisplay}&lt;/td&gt;<br>   &lt;td&gt;&lt;strong&gt;${xesc(item.eisThirdRow||&#39;—&#39;)}&lt;/strong&gt;&lt;/td&gt;<br>   &lt;td&gt;${badgeHtml}&lt;/td&gt;<br>   &lt;td class=&quot;small&quot;&gt;${xesc(item.reason)}&lt;/td&gt;<br>  `;<br>  compBody.appendChild(tr);<br> });<br>}<br><br>function downloadEisReportCSV(){<br> if(!eisAttachments.length)return alert(&#39;No EIS attachments to export yet.&#39;);<br> const escCsv=v=&gt;`&quot;${String(v??&#39;&#39;).replace(/&quot;/g,&#39;&quot;&quot;&#39;)}&quot;`;<br> const lines=[[&#39;Attached Receipt&#39;,&#39;Target Page #&#39;,&#39;Target Page Name&#39;,&#39;Name Field #&#39;,&#39;Amount Field #&#39;,&#39;Code Field #&#39;,&#39;Field / Fee Name&#39;,&#39;Rule Mode&#39;,&#39;Main Page Value&#39;,&#39;EIS Found / Row 1&#39;,&#39;EIS Row 2 (Amount)&#39;,&#39;Receipt Code / Value&#39;,&#39;Result&#39;,&#39;Details&#39;].map(escCsv).join(&#39;,&#39;)];<br> eisAttachments.forEach(att=&gt;{<br>  const pName=images[att.targetPage]?(images[att.targetPage].title||images[att.targetPage].name):&#39;&#39;;<br>  const ev=evaluateEisAttachment(att);<br>  ev.results.forEach(r=&gt;{<br>   lines.push([att.name,att.targetPage+1,pName,r.rule.fieldNum,r.rule.feeAmountFieldNum||&#39;&#39;,r.rule.feeCodeFieldNum||&#39;&#39;,r.rule.name,r.rule.ruleType,r.mainVal||r.expVal,r.eisName,r.eisAmount,r.eisThirdRow,r.status,r.reason].map(escCsv).join(&#39;,&#39;));<br>  });<br> });<br> const blob=new Blob([&#39;\uFEFF&#39;+lines.join(&#39;\r\n&#39;)],{type:&#39;text/csv;charset=utf-8&#39;});<br> downloadBlob(blob,`${safeName($(&#39;projectName&#39;).value)}-EIS-Validation-${stamp()}.csv`);<br>}<br><br>// ---------- INITIALIZE ----------<br>(async function initializeStudio(){<br> loadLocalConfig();<br> const restored=await restoreWorkspaceAuto();<br> drawLabels();<br> renderFields();<br> renderImages();<br> renderMergeChecklist();<br> ensureDefaultEisFeeRules();<br> populateEisTargetPageSelect();<br> renderEisFeesTable();<br> renderEisModal();<br> if(current&gt;=0)showImage();else render();<br> updateStats();<br> if(!restored)scheduleWorkspaceAutosave();<br>})();<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48af39e27413" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QA Screenshot & Screen Capture Studio]]></title>
            <link>https://medium.com/@barabonajansen/qa-screenshot-screen-capture-studio-0127147d1c9e?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0127147d1c9e</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 03:38:58 GMT</pubDate>
            <atom:updated>2026-11-17T03:38:58.402Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;QA Screenshot &amp; Screen Capture Studio&lt;/title&gt;<br>&lt;script async src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br>&lt;style&gt;<br>:root {<br>  --bg:#0b1020;--panel:#121a2d;--panel2:#192640;<br>  --border:#2b3b57;--text:#eaf0ff;--muted:#91a0ba;<br>  --accent:#6d8cff;--danger:#ff6477;--green:#31c48d;<br>}<br>*{box-sizing:border-box}<br>body{margin:0;background:var(--bg);color:var(--text);font:14px Arial,sans-serif}<br>button,input,textarea,select{font:inherit}<br>button{padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--panel2);color:var(--text);cursor:pointer}<br>button:hover{border-color:var(--accent)}<br>button:disabled{opacity:.45;cursor:not-allowed}<br>.primary{background:var(--accent);border-color:var(--accent);color:white}<br>.danger{color:#ff9ba6;border-color:#783b49}<br>.success{color:#75e3b5;border-color:#286b55}<br>.mini{padding:3px 7px;font-size:11px}<br>header{padding:17px 21px;background:#10182a;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}<br>h1{font-size:20px;margin:0}<br>h4{margin:12px 0 6px;font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}<br>header p{font-size:12px;color:var(--muted);margin:5px 0 0}<br>.app{display:grid;grid-template-columns:290px minmax(0,1fr) 270px;min-height:calc(100vh - 75px)}<br>.sidebar,.rightbar{padding:15px;background:var(--panel);overflow-y:auto}<br>.sidebar{border-right:1px solid var(--border)}<br>.rightbar{border-left:1px solid var(--border)}<br>.workspace{padding:16px;min-width:0}<br>.section{margin-bottom:22px}<br>.section h3{font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin:0 0 12px}<br>.panel{background:var(--panel);border:1px solid var(--border);border-radius:11px;padding:13px;margin-bottom:14px}<br>.panel-title{font-weight:bold;margin-bottom:12px}<br>details.panel&gt;summary{cursor:pointer;font-weight:bold}<br>.toolbar{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:10px;align-items:center}<br>.toolbar button.active{background:var(--accent);border-color:var(--accent)}<br>.small{font-size:11px;color:var(--muted);line-height:1.6}<br>input[type=text],input[type=number]{width:100%;background:#0c1425;border:1px solid var(--border);border-radius:7px;color:white;padding:9px}<br>textarea{width:100%;background:#0c1425;border:1px solid var(--border);border-radius:7px;color:white;padding:9px;font:12px/1.5 Consolas,monospace;resize:vertical}<br>select{background:#0c1425;border:1px solid var(--border);border-radius:6px;color:white;padding:5px;font-size:11px}<br>input[type=color]{width:42px;height:35px;border:0;background:transparent}<br>input[type=checkbox]{accent-color:var(--accent)}<br>.label-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;max-height:340px;overflow-y:auto;padding-right:3px}<br>.label-item{padding:7px 3px;border:1px solid var(--border);border-radius:7px;text-align:center;background:#0d1628;cursor:pointer;overflow:hidden}<br>.label-item.active{outline:2px solid var(--accent);background:#25365b}.label-item.used{cursor:not-allowed;filter:grayscale(.45)}<br>.label-item strong,.label-item span{display:block}<br>.label-item span{font-size:10px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}<br>.edit-label{display:flex;gap:7px;margin-top:9px}<br>.edit-label input[type=text]{flex:1;min-width:0}<br>.count-row{display:flex;gap:7px;margin:10px 0}<br>.count-row input{flex:1;min-width:0}<br>.toggle-row{display:flex;align-items:center;gap:8px;margin:12px 0;cursor:pointer}<br>.screenshot-list,.annotation-list{display:flex;flex-direction:column;gap:8px}<br>.screenshot-item{display:flex;flex-direction:column;gap:6px;padding:7px;border:1px solid var(--border);border-radius:8px;background:#0d1628;cursor:pointer}<br>.screenshot-item.active{border-color:var(--accent);background:#14213c}<br>.shot-top{display:flex;align-items:center;gap:6px}<br>.shot-meta{display:flex;align-items:center;gap:6px}<br>.shot-meta label{font-size:10px;color:var(--muted);display:flex;align-items:center;gap:3px;white-space:nowrap;cursor:pointer}<br>.shot-meta select{flex:1;min-width:0}<br>.screenshot-item img{width:55px;height:44px;object-fit:contain;background:#080d18}<br>.screenshot-info{flex:1;min-width:0}<br>.screenshot-info strong{display:block;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}<br>.screenshot-info span{font-size:10px;color:var(--muted)}<br>.delete-image{padding:5px 7px;font-size:11px}<br>.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px}<br>.stat{background:var(--panel);border:1px solid var(--border);padding:11px;border-radius:8px}<br>.stat strong{display:block;font-size:19px}<br>.stat span{font-size:11px;color:var(--muted)}<br>.stage-wrap{background:#080d18;border:1px dashed #35435e;border-radius:9px;min-height:350px;padding:12px;overflow:auto;display:flex;justify-content:center;align-items:flex-start}<br>.stage{position:relative;display:inline-block;line-height:0;max-width:100%}<br>#base{display:block;max-width:100%;height:auto;user-select:none}<br>#overlay{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:crosshair}<br>.empty{text-align:center;color:var(--muted);padding:100px 15px;line-height:1.8}<br>.annotation-item{display:flex;align-items:center;gap:8px;padding:8px;border:1px solid var(--border);border-radius:7px;background:#0d1628;cursor:pointer;font-size:11px}<br>.annotation-item.active{border-color:var(--accent)}<br>.annotation-dot{width:12px;height:12px;border-radius:50%;flex-shrink:0}<br>.annotation-item span:nth-child(2){flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}<br>.annotation-item button{padding:4px 6px}<br>.preview-video{display:block;width:100%;max-height:420px;background:#05080e;object-fit:contain;border-radius:8px}<br>.capture-status{padding:9px;border:1px solid var(--border);border-radius:8px;margin:8px 0;color:var(--muted);font-size:11px}<br>#livePanel{display:none}<br>.cfg-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:12px}<br>table.data-table{width:100%;border-collapse:collapse;font-size:12px}<br>.data-table th,.data-table td{border:1px solid var(--border);padding:6px 8px;text-align:left;vertical-align:middle}<br>.data-table th{background:#192640;font-size:11px;color:var(--muted)}<br>.data-table input[type=text],.data-table input[type=number]{padding:6px}<br>.data-table tr.sel td{background:#1a2848}<br>@media(max-width:1100px){.app{grid-template-columns:260px minmax(0,1fr)}.rightbar{grid-column:1/-1;border-left:0;border-top:1px solid var(--border)}}<br>@media(max-width:800px){.cfg-grid{grid-template-columns:1fr}}<br>@media(max-width:700px){.app{display:block}.sidebar,.rightbar{border:0;border-bottom:1px solid var(--border)}}<br><br>.annotation-edit-handle{cursor:nwse-resize}<br>#autosaveStatus{color:var(--green);font-size:12px}<br>.merge-list{max-height:175px;overflow-y:auto;border:1px solid var(--border);border-radius:8px;background:#0d1628;padding:6px;display:flex;flex-direction:column;gap:5px;margin:8px 0}<br>.merge-item{display:flex;align-items:center;gap:6px;font-size:11px;padding:4px 6px;border-radius:6px;background:#101b31;cursor:pointer}<br>.merge-item.merged-before{opacity:.68;border-left:2px solid #f59e0b}<br>.merge-item span.tag-merged{font-size:9px;padding:1px 5px;border-radius:4px;background:#3b2d14;color:#fbbf24;margin-left:auto;white-space:nowrap}<br>.page-progress-box{background:#0d1628;border:1px solid var(--border);border-radius:8px;padding:8px 10px;margin:8px 0;font-size:11px;line-height:1.5}<br>.page-progress-box strong{color:#93c5fd}<br>.modal-backdrop{position:fixed;inset:0;background:rgba(4,8,18,.82);z-index:9999;display:none;align-items:center;justify-content:center;padding:18px}<br>.modal-backdrop.open{display:flex}<br>.modal-card{background:var(--panel);border:1px solid var(--border);border-radius:12px;width:min(1080px,96vw);max-height:90vh;display:flex;flex-direction:column;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.65)}<br>.modal-head{padding:14px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;background:#10182a}<br>.modal-head h2{margin:0;font-size:17px}<br>.modal-body{padding:16px 18px;overflow-y:auto;flex:1}<br>.report-summary-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:14px}<br>.report-kpi{background:#0d1628;border:1px solid var(--border);border-radius:8px;padding:10px}<br>.report-kpi strong{display:block;font-size:18px}<br>.report-kpi span{font-size:11px;color:var(--muted)}<br>.report-page-card{background:#0d1628;border:1px solid var(--border);border-radius:9px;padding:12px;margin-bottom:14px}<br>.report-page-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;flex-wrap:wrap}<br>.report-thumb{max-width:260px;max-height:150px;border:1px solid var(--border);border-radius:6px;margin-top:8px;display:block}<br>@media print{<br> body&gt;*:not(#reportsModal){display:none!important}<br> #reportsModal{position:static!important;display:block!important;background:white!important;padding:0!important}<br> #reportsModal .modal-card{width:100%!important;max-height:none!important;border:0!important;box-shadow:none!important;background:white!important;color:#111!important}<br> #reportsModal .modal-head button,#reportsModal .no-print{display:none!important}<br> #reportsModal .report-page-card,#reportsModal .report-kpi{background:white!important;border:1px solid #ccc!important;color:#111!important;break-inside:avoid}<br> #reportsModal .data-table th{background:#eef2f7!important;color:#111!important}<br> #reportsModal .data-table td,#reportsModal .data-table th{border:1px solid #bbb!important;color:#111!important}<br>}<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;header&gt;<br> &lt;div&gt;<br>  &lt;h1&gt;QA Screenshot &amp; Screen Capture Studio&lt;/h1&gt;<br>  &lt;p&gt;Windows screen capture · QA evidence · Annotations · OCR by number · Docs export&lt;/p&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;toolbar&quot;&gt;<br>  &lt;button class=&quot;primary&quot; onclick=&quot;startScreenCapture()&quot;&gt;▣ Capture Screen&lt;/button&gt;<br>  &lt;button onclick=&quot;document.getElementById(&#39;fileInput&#39;).click()&quot;&gt;＋ Upload Images&lt;/button&gt;<br>  &lt;button onclick=&quot;openConfig()&quot;&gt;⚙ Config&lt;/button&gt;<br>  &lt;button onclick=&quot;openReportsModal()&quot;&gt;📊 View Reports&lt;/button&gt;<br>  &lt;button class=&quot;success&quot; onclick=&quot;exportDocx()&quot;&gt;⬇ Download Docs&lt;/button&gt;<br>  &lt;button onclick=&quot;saveProject()&quot;&gt;💾 Save Project&lt;/button&gt;<br>  &lt;button onclick=&quot;document.getElementById(&#39;projectFile&#39;).click()&quot;&gt;📂 Load Project&lt;/button&gt;<br> &lt;/div&gt;<br>&lt;/header&gt;<br><br>&lt;input type=&quot;file&quot; id=&quot;fileInput&quot; accept=&quot;image/*&quot; multiple hidden&gt;<br>&lt;input type=&quot;file&quot; id=&quot;projectFile&quot; accept=&quot;.json,application/json&quot; hidden&gt;<br>&lt;input type=&quot;file&quot; id=&quot;configFile&quot; accept=&quot;.json,application/json&quot; hidden&gt;<br><br>&lt;div class=&quot;app&quot;&gt;<br>&lt;aside class=&quot;sidebar&quot;&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Windows Screen Capture&lt;/h3&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;startScreenCapture()&quot;&gt;Choose Screen / Window / Tab&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;<br>   The next dialog lets you select your entire screen, an application window, or a browser tab.<br>  &lt;/div&gt;<br>  &lt;div id=&quot;captureStatus&quot; class=&quot;capture-status&quot;&gt;Screen capture is not active.&lt;/div&gt;<br>  &lt;div id=&quot;livePanel&quot;&gt;<br>   &lt;video id=&quot;liveVideo&quot; class=&quot;preview-video&quot; autoplay muted playsinline&gt;&lt;/video&gt;<br>   &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;captureFrame()&quot;&gt;Take Screenshot&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;stopScreenCapture()&quot;&gt;Stop Sharing&lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Pages &amp;amp; Docs&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;imageCount&quot;&gt;0 screenshots&lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;Click a page to work on it. Tick &quot;In docs&quot; and pick a header for each page. Use ▲▼ to reorder.&lt;/div&gt;<br>  &lt;div class=&quot;screenshot-list&quot; id=&quot;screenshots&quot; style=&quot;margin-top:8px&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; style=&quot;margin-top:12px&quot;&gt;Auto-assign headers from the config list, starting at page<br>   &lt;input type=&quot;number&quot; id=&quot;startPage&quot; value=&quot;1&quot; min=&quot;1&quot; style=&quot;width:62px;display:inline-block;padding:4px&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;autoAssignHeaders()&quot;&gt;Auto-assign headers&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;setAllInclude(true)&quot;&gt;All in docs&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;setAllInclude(false)&quot;&gt;None&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;label class=&quot;small&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;docImages&quot; checked&gt; Screenshots&lt;/label&gt;<br>   &lt;label class=&quot;small&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;docTables&quot; checked&gt; Data tables&lt;/label&gt;<br>  &lt;/div&gt;<br>  &lt;button class=&quot;primary&quot; style=&quot;width:100%&quot; onclick=&quot;exportDocx()&quot;&gt;⬇ Download Docs (.docx)&lt;/button&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Merge Images&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;Tick the images you want to merge:&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;selectMergeCandidates(&#39;unmerged&#39;)&quot;&gt;Select Unmerged&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;selectMergeCandidates(&#39;all&#39;)&quot;&gt;Select All&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;selectMergeCandidates(&#39;none&#39;)&quot;&gt;Clear&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;label class=&quot;toggle-row&quot; style=&quot;margin:6px 0;font-size:11px&quot;&gt;<br>   &lt;input type=&quot;checkbox&quot; id=&quot;excludePreviouslyMerged&quot; checked onchange=&quot;onExcludeMergedToggle()&quot;&gt;<br>   Exclude previously merged images<br>  &lt;/label&gt;<br>  &lt;div id=&quot;mergeChecklist&quot; class=&quot;merge-list&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;mergeSelectionStatus&quot;&gt;0 image(s) selected for merge.&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:6px&quot;&gt;<br>   &lt;button onclick=&quot;mergeImages(&#39;vertical&#39;)&quot;&gt;Vertical&lt;/button&gt;<br>   &lt;button onclick=&quot;mergeImages(&#39;horizontal&#39;)&quot;&gt;Horizontal&lt;/button&gt;<br>   &lt;button class=&quot;mini&quot; onclick=&quot;resetMergedHistory()&quot; title=&quot;Allow previously merged images to be merged again&quot;&gt;Reset Merged&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;button class=&quot;danger&quot; onclick=&quot;removeAllImages()&quot;&gt;Delete All Images&lt;/button&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;QA Labels&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;Number of labels (1–999)&lt;/div&gt;<br>  &lt;div class=&quot;count-row&quot;&gt;<br>   &lt;input type=&quot;number&quot; id=&quot;labelCount&quot; min=&quot;1&quot; max=&quot;999&quot; value=&quot;200&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;applyLabelCount()&quot;&gt;Apply&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;label class=&quot;toggle-row&quot;&gt;<br>   &lt;input type=&quot;checkbox&quot; id=&quot;autoIncrement&quot;&gt;<br>   Auto-increment labels<br>  &lt;/label&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;autoStatus&quot;&gt;OFF: manually select labels.&lt;/div&gt;<br>  &lt;div class=&quot;page-progress-box&quot; id=&quot;pageTaskProgress&quot;&gt;<br>   &lt;strong&gt;Page Sequence:&lt;/strong&gt; Starts at #1 per page.&lt;br&gt;<br>   &lt;span class=&quot;small&quot;&gt;Select a page to see labeled boxes and continue where you left off.&lt;/span&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;label-grid&quot; id=&quot;labels&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;edit-label&quot;&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;labelName&quot; placeholder=&quot;Label name&quot;&gt;<br>   &lt;input type=&quot;color&quot; id=&quot;labelColor&quot; value=&quot;#ff4242&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;saveLabel()&quot;&gt;Save Label&lt;/button&gt;<br>   &lt;button onclick=&quot;resetLabels()&quot;&gt;Reset&lt;/button&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br><br>&lt;/aside&gt;<br><br>&lt;main class=&quot;workspace&quot;&gt;<br> &lt;div class=&quot;stats&quot;&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statImages&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Screenshots&lt;/span&gt;&lt;/div&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statAnnotations&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Annotations&lt;/span&gt;&lt;/div&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statLabels&quot;&gt;200&lt;/strong&gt;&lt;span&gt;QA Labels&lt;/span&gt;&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;details class=&quot;panel&quot; id=&quot;configPanel&quot;&gt;<br>  &lt;summary&gt;⚙ Config — page headers, numbered fields, OCR, project files&lt;/summary&gt;<br><br>  &lt;div class=&quot;cfg-grid&quot;&gt;<br>   &lt;div&gt;<br>    &lt;h4&gt;Project name&lt;/h4&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;projectName&quot; value=&quot;QA Evidence&quot;&gt;<br>    &lt;h4&gt;Page header titles (one per line)&lt;/h4&gt;<br>    &lt;textarea id=&quot;pageTitlesText&quot; rows=&quot;9&quot; placeholder=&quot;Login Page&amp;#10;Dashboard&amp;#10;Client Details&amp;#10;Payment Page&quot;&gt;&lt;/textarea&gt;<br>    &lt;div class=&quot;small&quot;&gt;Each page can be given one of these as its header in the docs file.&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div&gt;<br>    &lt;h4&gt;Paste field list (number + name)&lt;/h4&gt;<br>    &lt;textarea id=&quot;fieldsPaste&quot; rows=&quot;9&quot; placeholder=&quot;1 | Dynamic Value | my manual value&amp;#10;2 Client Name&amp;#10;3 Invoice Number&amp;#10;4. Total Amount&amp;#10;Address = 5&quot;&gt;&lt;/textarea&gt;<br>    &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>     &lt;button class=&quot;primary&quot; onclick=&quot;applyFieldList()&quot;&gt;Apply list&lt;/button&gt;<br>     &lt;button onclick=&quot;addFieldRow()&quot;&gt;+ Add field&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;small&quot;&gt;<br>     One field per line: &lt;b&gt;2 Client Name&lt;/b&gt;, &lt;b&gt;2. Client Name&lt;/b&gt;, &lt;b&gt;2: Client Name&lt;/b&gt; or &lt;b&gt;Client Name = 2&lt;/b&gt;.&lt;br&gt;<br>     Manual field (fixed value, no OCR): &lt;b&gt;1 | Dynamic Value | your value&lt;/b&gt; or &lt;b&gt;1 Dynamic Value = your value&lt;/b&gt;.<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;h4&gt;Fields (number → name)&lt;/h4&gt;<br>  &lt;table class=&quot;data-table&quot;&gt;<br>   &lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:80px&quot;&gt;#&lt;/th&gt;&lt;th&gt;Field name&lt;/th&gt;&lt;th style=&quot;width:115px&quot;&gt;Type&lt;/th&gt;&lt;th&gt;Manual value&lt;/th&gt;&lt;th style=&quot;width:44px&quot;&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>   &lt;tbody id=&quot;fieldsBody&quot;&gt;&lt;/tbody&gt;<br>  &lt;/table&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;fieldsMsg&quot;&gt;No fields yet. Paste a list above.&lt;/div&gt;<br><br>  &lt;h4&gt;OCR&lt;/h4&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;label class=&quot;small&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;autoOcr&quot; checked&gt; Auto-read text when a box is drawn&lt;/label&gt;<br>   &lt;span class=&quot;small&quot;&gt;Language:&lt;/span&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;ocrLang&quot; value=&quot;eng&quot; style=&quot;width:120px;padding:6px&quot; title=&quot;Tesseract language code, e.g. eng, eng+fra&quot;&gt;<br>   &lt;span class=&quot;small&quot; id=&quot;ocrStatus&quot;&gt;OCR engine loads on first use.&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;h4&gt;Files&lt;/h4&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;success&quot; onclick=&quot;saveProject()&quot;&gt;💾 Save Project (all + config)&lt;/button&gt;<br>   &lt;button onclick=&quot;document.getElementById(&#39;projectFile&#39;).click()&quot;&gt;📂 Load Project&lt;/button&gt;<br>   &lt;button onclick=&quot;exportConfig()&quot;&gt;Export Config JSON&lt;/button&gt;<br>   &lt;button onclick=&quot;document.getElementById(&#39;configFile&#39;).click()&quot;&gt;Import Config JSON&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;Config, images, annotations and page order are saved automatically in this browser using local storage (IndexedDB). They should return when you reopen this same browser and file location.&lt;/div&gt;<br>  &lt;div id=&quot;autosaveStatus&quot; class=&quot;small&quot;&gt;Auto-save is ready.&lt;/div&gt;<br> &lt;/details&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Annotation Tools&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button id=&quot;boxTool&quot; class=&quot;active&quot; onclick=&quot;setMode(&#39;box&#39;)&quot;&gt;▢ Rectangle&lt;/button&gt;<br>   &lt;button id=&quot;circleTool&quot; onclick=&quot;setMode(&#39;circle&#39;)&quot;&gt;◯ Circle&lt;/button&gt;<br>   &lt;button onclick=&quot;undo()&quot;&gt;↶ Undo&lt;/button&gt;<br>   &lt;button class=&quot;danger&quot; onclick=&quot;deleteSelected()&quot;&gt;Delete Selected&lt;/button&gt;<br>   &lt;button class=&quot;danger&quot; onclick=&quot;clearAnnotations()&quot;&gt;Clear Annotations&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;exportPNG()&quot;&gt;Export Current PNG&lt;/button&gt;<br>   &lt;button onclick=&quot;exportAllPNG()&quot;&gt;Export All PNG&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;toolStatus&quot;&gt;Current tool: Rectangle · Select a box to move it; drag its bottom-right handle to resize.&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Screenshot Workspace&lt;/div&gt;<br>  &lt;div class=&quot;stage-wrap&quot;&gt;<br>   &lt;div id=&quot;empty&quot; class=&quot;empty&quot;&gt;<br>    &lt;div style=&quot;font-size:40px&quot;&gt;▣&lt;/div&gt;<br>    &lt;strong&gt;No screenshot loaded&lt;/strong&gt;<br>    &lt;div&gt;Capture your Windows screen or upload an image.&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div id=&quot;stage&quot; class=&quot;stage&quot; hidden&gt;<br>    &lt;img id=&quot;base&quot; alt=&quot;Screenshot&quot;&gt;<br>    &lt;canvas id=&quot;overlay&quot;&gt;&lt;/canvas&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;imageStatus&quot; style=&quot;margin-top:9px&quot;&gt;No active screenshot.&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Extracted Data (current page)&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button onclick=&quot;reOcrPage()&quot;&gt;Re-read all boxes (OCR)&lt;/button&gt;<br>   &lt;button onclick=&quot;copyExtracted(false)&quot;&gt;Copy page as TSV&lt;/button&gt;<br>   &lt;button onclick=&quot;copyExtracted(true)&quot;&gt;Copy all pages as TSV&lt;/button&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;openReportsModal()&quot;&gt;📊 All Reports / Save / Print&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;table class=&quot;data-table&quot;&gt;<br>   &lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:60px&quot;&gt;#&lt;/th&gt;&lt;th style=&quot;width:30%&quot;&gt;Field&lt;/th&gt;&lt;th&gt;Value (editable)&lt;/th&gt;&lt;th style=&quot;width:150px&quot;&gt;Status&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>   &lt;tbody id=&quot;dataBody&quot;&gt;&lt;/tbody&gt;<br>  &lt;/table&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;dataEmpty&quot;&gt;No extracted data yet. Manual-value fields from Config appear here automatically; OCR fields appear after you draw a box.&lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;dataMsg&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/main&gt;<br><br>&lt;aside class=&quot;rightbar&quot;&gt;<br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Annotation History&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;annotationCount&quot;&gt;0 annotations&lt;/div&gt;<br>  &lt;div class=&quot;annotation-list&quot; id=&quot;annotations&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;How to use&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;<br>   1. Capture or upload pages.&lt;br&gt;&lt;br&gt;<br>   2. Open ⚙ Config: add page header titles and paste your numbered field list (e.g. &lt;b&gt;2 Client Name&lt;/b&gt;).&lt;br&gt;&lt;br&gt;<br>   3. Click a page to work on it, assign its header, tick &quot;In docs&quot;.&lt;br&gt;&lt;br&gt;<br>   4. Select a label number, then draw a box. The text inside is read automatically and appears under Extracted Data. Manual fields use the value from Config.&lt;br&gt;&lt;br&gt;<br>   5. Turn on auto-increment to move to the next number after each box.&lt;br&gt;&lt;br&gt;<br>   6. Download Docs (.docx) or Save Project (.json).<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/aside&gt;<br>&lt;/div&gt;<br><br>&lt;div id=&quot;reportsModal&quot; class=&quot;modal-backdrop&quot; onclick=&quot;if(event.target===this)closeReportsModal()&quot;&gt;<br> &lt;div class=&quot;modal-card&quot;&gt;<br>  &lt;div class=&quot;modal-head&quot;&gt;<br>   &lt;div&gt;<br>    &lt;h2&gt;📊 QA Evidence &amp;amp; Extraction Reports&lt;/h2&gt;<br>    &lt;div class=&quot;small&quot; id=&quot;reportSubtitle&quot;&gt;Complete summary across all pages&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div class=&quot;toolbar no-print&quot; style=&quot;margin:0&quot;&gt;<br>    &lt;label class=&quot;small&quot; style=&quot;display:flex;align-items:center;gap:4px&quot;&gt;<br>     &lt;input type=&quot;checkbox&quot; id=&quot;reportIncludeThumbs&quot; checked onchange=&quot;renderReportsModal()&quot;&gt; Include annotated images<br>    &lt;/label&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;downloadReportHTML()&quot;&gt;⬇ Save HTML Report&lt;/button&gt;<br>    &lt;button onclick=&quot;downloadReportCSV()&quot;&gt;⬇ Download CSV&lt;/button&gt;<br>    &lt;button class=&quot;success&quot; onclick=&quot;exportDocx()&quot;&gt;⬇ Download DOCX&lt;/button&gt;<br>    &lt;button onclick=&quot;printReport()&quot;&gt;🖨 Print / Save PDF&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;closeReportsModal()&quot;&gt;✕ Close&lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;modal-body&quot; id=&quot;reportsModalBody&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;script&gt;<br>const $ = id =&gt; document.getElementById(id);<br>const DEFAULT_LABEL_COUNT=200;<br>const MAX_LABELS=999;<br>const CONFIG_KEY=&#39;qaStudioConfig_v2&#39;;<br><br>let images=[];<br>let current=-1;<br>function makeLabels(n,old=[]){<br> return Array.from({length:n},(_,i)=&gt;old[i]||{id:i+1,name:`QA ${i+1}`,color:&#39;#ff4242&#39;});<br>}<br>let labels=makeLabels(DEFAULT_LABEL_COUNT);<br>let selectedLabel=1;<br>let mode=&#39;box&#39;;<br>let annotations=[];<br>let selected=null;<br>let drag=null;<br>let history=[];<br>let screenStream=null;<br>let pageTitles=[];<br>let fields=[];   // {num,name,mode:&#39;ocr&#39;|&#39;manual&#39;,value}<br><br>const base=$(&#39;base&#39;);<br>const overlay=$(&#39;overlay&#39;);<br>const ctx=overlay.getContext(&#39;2d&#39;);<br><br>// ---------- helpers ----------<br>function downloadBlob(blob,name){<br> const url=URL.createObjectURL(blob);<br> const link=document.createElement(&#39;a&#39;);<br> link.href=url;link.download=name;link.click();<br> setTimeout(()=&gt;URL.revokeObjectURL(url),2000);<br>}<br>function blobToDataURL(blob){<br> return new Promise((res,rej)=&gt;{const r=new FileReader();r.onload=()=&gt;res(r.result);r.onerror=()=&gt;rej(r.error);r.readAsDataURL(blob)});<br>}<br>function safeName(s){return String(s||&#39;&#39;).replace(/[^\w\- ]+/g,&#39;&#39;).trim().replace(/\s+/g,&#39;-&#39;)||&#39;QA-Evidence&#39;}<br>function stamp(){const d=new Date();const p=n=&gt;String(n).padStart(2,&#39;0&#39;);return `${d.getFullYear()}${p(d.getMonth()+1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`}<br>function fieldFor(num){return fields.find(f=&gt;f.num===num)}<br>function labelName(a){return (labels.find(l=&gt;l.id===a.label)||{}).name||a.name||(&#39;QA &#39;+a.label)}<br>function valueOf(a){<br> const f=fieldFor(a.label);<br> if(f&amp;&amp;f.mode===&#39;manual&#39;)return f.value||&#39;&#39;;<br> return a.text||&#39;&#39;;<br>}<br><br>// ---------- SCREEN CAPTURE ----------<br>async function startScreenCapture(){<br> if(!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia){<br>  alert(&#39;Screen capture is unavailable. Open this page in Chrome or Edge using HTTPS or localhost.&#39;);<br>  return;<br> }<br> try{<br>  stopScreenCapture(false);<br>  screenStream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:false});<br>  $(&#39;liveVideo&#39;).srcObject=screenStream;<br>  $(&#39;livePanel&#39;).style.display=&#39;block&#39;;<br>  $(&#39;captureStatus&#39;).textContent=&#39;Screen sharing is active. Click Take Screenshot to save the current frame.&#39;;<br>  screenStream.getVideoTracks()[0].addEventListener(&#39;ended&#39;,()=&gt;{stopScreenCapture()});<br>  await $(&#39;liveVideo&#39;).play();<br> }catch(error){<br>  if(error.name===&#39;NotAllowedError&#39;){<br>   $(&#39;captureStatus&#39;).textContent=&#39;Screen sharing was cancelled or permission was denied.&#39;;<br>  }else{<br>   $(&#39;captureStatus&#39;).textContent=&#39;Capture error: &#39;+error.message;<br>   console.error(error);<br>  }<br> }<br>}<br><br>function captureFrame(){<br> const video=$(&#39;liveVideo&#39;);<br> if(!screenStream || !video.videoWidth){<br>  alert(&#39;Start screen sharing first and wait for the preview.&#39;);<br>  return;<br> }<br> const canvas=document.createElement(&#39;canvas&#39;);<br> canvas.width=video.videoWidth;<br> canvas.height=video.videoHeight;<br> canvas.getContext(&#39;2d&#39;).drawImage(video,0,0,canvas.width,canvas.height);<br> canvas.toBlob(blob=&gt;{<br>  if(blob) addImageFromBlob(blob,`Screen Capture ${new Date().toLocaleString()}`);<br>  else alert(&#39;Could not capture this screen.&#39;);<br> },&#39;image/png&#39;);<br>}<br><br>function stopScreenCapture(updateStatus=true){<br> if(screenStream){<br>  screenStream.getTracks().forEach(track=&gt;track.stop());<br>  screenStream=null;<br> }<br> $(&#39;liveVideo&#39;).srcObject=null;<br> $(&#39;livePanel&#39;).style.display=&#39;none&#39;;<br> if(updateStatus) $(&#39;captureStatus&#39;).textContent=&#39;Screen capture stopped.&#39;;<br>}<br><br>// ---------- IMAGE UPLOAD AND PASTE ----------<br>$(&#39;fileInput&#39;).addEventListener(&#39;change&#39;,e=&gt;{<br> Array.from(e.target.files||[]).forEach(file=&gt;{<br>  if(file.type.startsWith(&#39;image/&#39;)) addImageFromBlob(file,file.name);<br> });<br> e.target.value=&#39;&#39;;<br>});<br><br>document.addEventListener(&#39;paste&#39;,e=&gt;{<br> if(e.target&amp;&amp;/^(INPUT|TEXTAREA)$/.test(e.target.tagName))return;<br> const item=Array.from(e.clipboardData?.items||[]).find(x=&gt;x.type.startsWith(&#39;image/&#39;));<br> if(item){<br>  const file=item.getAsFile();<br>  if(file) addImageFromBlob(file,`Pasted Screenshot ${Date.now()}`);<br> }<br>});<br><br>function makeItem(blob,name){<br> return new Promise((resolve,reject)=&gt;{<br>  const url=URL.createObjectURL(blob);<br>  const img=new Image();<br>  img.onload=()=&gt;resolve({img,url,blob,name,title:&#39;&#39;,include:true,alreadyMerged:false,selectedForMerge:true,width:img.naturalWidth,height:img.naturalHeight});<br>  img.onerror=()=&gt;{URL.revokeObjectURL(url);reject(new Error(&#39;Could not read image &#39;+name))};<br>  img.src=url;<br> });<br>}<br><br>function addImageFromBlob(blob,name){<br> makeItem(blob,name).then(item=&gt;{<br>  images.push(item);<br>  current=images.length-1;<br>  scheduleWorkspaceAutosave();<br>  showImage();<br>  renderImages();<br> }).catch(err=&gt;console.error(err));<br>}<br><br>// ---------- PAGE MANAGEMENT ----------<br>function deleteImage(index){<br> if(index&lt;0||index&gt;=images.length)return;<br> if(!confirm(`Delete &quot;${images[index].name}&quot; and its annotations?`))return;<br> const oldCurrent=current;<br> const item=images[index];<br> if(item.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(item.url);<br> images.splice(index,1);<br> scheduleWorkspaceAutosave();<br> annotations=annotations.filter(a=&gt;a.image!==index).map(a=&gt;({...a,image:a.image&gt;index?a.image-1:a.image}));<br> selected=null;<br> history=[];<br> if(!images.length)current=-1;<br> else if(oldCurrent&gt;index)current=oldCurrent-1;<br> else if(oldCurrent===index)current=Math.min(index,images.length-1);<br> else current=oldCurrent;<br> renderImages();<br> if(current&gt;=0)showImage();<br> else{<br>  $(&#39;stage&#39;).hidden=true;<br>  $(&#39;empty&#39;).hidden=false;<br>  updateImageStatus();<br> }<br> render();<br>}<br><br>function clearAllImagesSilently(){<br> images.forEach(i=&gt;{if(i.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(i.url)});<br> images=[];annotations=[];current=-1;selected=null;history=[];<br> $(&#39;stage&#39;).hidden=true;<br> $(&#39;empty&#39;).hidden=false;<br>}<br><br>function removeAllImages(){<br> if(!images.length)return;<br> if(!confirm(&#39;Delete all screenshots and annotations?&#39;))return;<br> clearAllImagesSilently();<br> updateImageStatus();<br> renderImages();<br> render();<br>}<br><br>function movePage(i,dir){<br> const j=i+dir;<br> if(j&lt;0||j&gt;=images.length)return;<br> [images[i],images[j]]=[images[j],images[i]];<br> annotations.forEach(a=&gt;{if(a.image===i)a.image=j;else if(a.image===j)a.image=i});<br> if(current===i)current=j;else if(current===j)current=i;<br> scheduleWorkspaceAutosave();<br> history=[];<br> renderImages();<br> updateImageStatus();<br> render();<br>}<br><br>function setAllInclude(v){<br> images.forEach(it=&gt;it.include=v);<br> renderImages();<br>}<br><br>function autoAssignHeaders(){<br> if(!pageTitles.length)return alert(&#39;Add your page header titles in Config first.&#39;);<br> if(!images.length)return alert(&#39;Add screenshots first.&#39;);<br> const start=Math.max(1,parseInt($(&#39;startPage&#39;).value,10)||1);<br> images.forEach((it,i)=&gt;{<br>  const k=i-(start-1);<br>  if(k&lt;0){it.include=false;}<br>  else{it.title=pageTitles[k]||&#39;&#39;;it.include=true;}<br> });<br> renderImages();<br> updateImageStatus();<br> scheduleWorkspaceAutosave();<br>}<br><br>function renderImages(){<br> const list=$(&#39;screenshots&#39;);<br> list.innerHTML=&#39;&#39;;<br> $(&#39;imageCount&#39;).textContent=images.length+&#39; screenshots&#39;;<br> images.forEach((item,i)=&gt;{<br>  const row=document.createElement(&#39;div&#39;);<br>  row.className=&#39;screenshot-item&#39;+(i===current?&#39; active&#39;:&#39;&#39;);<br><br>  const top=document.createElement(&#39;div&#39;);top.className=&#39;shot-top&#39;;<br>  const img=document.createElement(&#39;img&#39;);img.src=item.url;<br>  const info=document.createElement(&#39;div&#39;);info.className=&#39;screenshot-info&#39;;<br>  const name=document.createElement(&#39;strong&#39;);name.textContent=`${i+1}. ${item.name}`;<br>  const size=document.createElement(&#39;span&#39;);size.textContent=`${item.width} × ${item.height}`;<br>  info.append(name,size);<br>  const up=document.createElement(&#39;button&#39;);up.className=&#39;mini&#39;;<br>  up.textContent=&#39;▲&#39;;up.title=&#39;Move page up&#39;;up.disabled=i===0;<br>  up.onclick=e=&gt;{e.stopPropagation();movePage(i,-1)};<br>  const dn=document.createElement(&#39;button&#39;);dn.className=&#39;mini&#39;;<br>  dn.textContent=&#39;▼&#39;;dn.title=&#39;Move page down&#39;;dn.disabled=i===images.length-1;<br>  dn.onclick=e=&gt;{e.stopPropagation();movePage(i,1)};<br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;delete-image danger&#39;;del.textContent=&#39;✕&#39;;del.title=&#39;Delete screenshot&#39;;<br>  del.onclick=e=&gt;{e.stopPropagation();deleteImage(i)};<br>  top.append(img,info,up,dn,del);<br><br>  if(!item.title&amp;&amp;pageTitles[i])item.title=pageTitles[i];<br>  const meta=document.createElement(&#39;div&#39;);meta.className=&#39;shot-meta&#39;;<br>  const lab=document.createElement(&#39;label&#39;);<br>  const chk=document.createElement(&#39;input&#39;);chk.type=&#39;checkbox&#39;;chk.checked=item.include!==false;<br>  chk.onchange=()=&gt;{item.include=chk.checked;scheduleWorkspaceAutosave()};<br>  lab.onclick=e=&gt;e.stopPropagation();<br>  lab.append(chk,document.createTextNode(&#39;In docs&#39;));<br>  const sel=document.createElement(&#39;select&#39;);<br>  const opts=[&#39;&#39;,...pageTitles];<br>  if(item.title&amp;&amp;!pageTitles.includes(item.title))opts.push(item.title);<br>  opts.forEach(t=&gt;{<br>   const o=document.createElement(&#39;option&#39;);o.value=t;o.textContent=t||&#39;— header —&#39;;<br>   if(t===(item.title||&#39;&#39;))o.selected=true;<br>   sel.appendChild(o);<br>  });<br>  sel.onclick=e=&gt;e.stopPropagation();<br>  sel.onchange=()=&gt;{item.title=sel.value;updateImageStatus();scheduleWorkspaceAutosave()};<br>  meta.append(lab,sel);<br><br>  row.append(top,meta);<br>  row.onclick=()=&gt;{current=i;showImage();renderImages()};<br>  list.appendChild(row);<br> });<br> renderMergeChecklist();<br> updateStats();<br> scheduleWorkspaceAutosave();<br>}<br><br>function updateImageStatus(){<br> if(current&lt;0||!images[current]){$(&#39;imageStatus&#39;).textContent=&#39;No active screenshot.&#39;;return}<br> const it=images[current];<br> $(&#39;imageStatus&#39;).textContent=`Working on page ${current+1} of ${images.length} · ${it.title||&#39;no header&#39;} · ${it.name} · ${it.width} × ${it.height}`;<br>}<br><br>function showImage(){<br> if(current&lt;0||!images[current])return;<br> const item=images[current];<br> $(&#39;stage&#39;).hidden=false;<br> $(&#39;empty&#39;).hidden=true;<br> base.onload=()=&gt;{<br>  overlay.width=item.width;<br>  overlay.height=item.height;<br>  render();<br> };<br> base.src=item.url;<br> updateImageStatus();<br> selected=null;<br> const resumeNum=nextSequentialLabelForPage(current);<br> if(resumeNum){<br>  ensureLabelCapacity(resumeNum);<br>  selectedLabel=resumeNum;<br> }<br> render();<br>}<br><br>// ---------- LABELS (PER-PAGE SEQUENCE + RESUME MEMORY) ----------<br>function drawLabels(){<br> $(&#39;labels&#39;).innerHTML=&#39;&#39;;<br> const usedOnCurrentPage=usedAnnotationNumbers(null,current);<br> labels.forEach(label=&gt;{<br>  const div=document.createElement(&#39;div&#39;);<br>  const alreadyUsed=usedOnCurrentPage.has(label.id);<br>  const manualField=fieldFor(label.id)?.mode===&#39;manual&#39;;<br>  const unavailable=alreadyUsed||manualField;<br>  div.className=&#39;label-item&#39;+(selectedLabel===label.id?&#39; active&#39;:&#39;&#39;)+(unavailable?&#39; used&#39;:&#39;&#39;)+(manualField?&#39; manual-label&#39;:&#39;&#39;);<br>  div.style.opacity=unavailable?&#39;.42&#39;:&#39;1&#39;;<br>  div.title=manualField?`#${label.id} is a manual-value field and cannot be used for OCR boxes`:alreadyUsed?`#${label.id} is already labeled on this page`:`Select label #${label.id} for this page`;<br>  div.style.borderLeft=`3px solid ${label.color}`;<br>  const number=document.createElement(&#39;strong&#39;);<br>  number.textContent=label.id;<br>  const name=document.createElement(&#39;span&#39;);<br>  name.textContent=label.name;<br>  div.append(number,name);<br>  div.onclick=()=&gt;{<br>   if(fieldFor(label.id)?.mode===&#39;manual&#39;){<br>    $(&#39;autoStatus&#39;).textContent=`#${label.id} is a manual-value field. Its value is shown in Extracted Data and cannot be selected for OCR.`;<br>    return;<br>   }<br>   if(usedAnnotationNumbers(null,current).has(label.id)){<br>    $(&#39;autoStatus&#39;).textContent=`#${label.id} is already used on Page ${current+1}. Choose an unused number on this page.`;<br>    return;<br>   }<br>   selectedLabel=label.id;<br>   $(&#39;labelName&#39;).value=label.name;<br>   $(&#39;labelColor&#39;).value=label.color;<br>   drawLabels();<br>  };<br>  $(&#39;labels&#39;).appendChild(div);<br> });<br> if(fieldFor(selectedLabel)?.mode===&#39;manual&#39;||usedOnCurrentPage.has(selectedLabel)){<br>  const next=nextSequentialLabelForPage(current);<br>  if(next){ensureLabelCapacity(next);selectedLabel=next;}<br> }<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(label){<br>  $(&#39;labelName&#39;).value=label.name;<br>  $(&#39;labelColor&#39;).value=label.color;<br> }<br> $(&#39;labelCount&#39;).value=labels.length;<br> updatePageTaskProgress();<br> updateStats();<br>}<br><br>function updatePageTaskProgress(){<br> const box=$(&#39;pageTaskProgress&#39;);<br> if(!box)return;<br> if(current&lt;0||!images[current]){<br>  box.innerHTML=&#39;&lt;strong&gt;Page Sequence:&lt;/strong&gt; Starts at #1 per page.&lt;br&gt;&lt;span class=&quot;small&quot;&gt;Select a page to see labeled boxes and continue where you left off.&lt;/span&gt;&#39;;<br>  return;<br> }<br> const curUsed=[...usedAnnotationNumbers(null,current)].sort((a,b)=&gt;a-b);<br> const nextNum=nextSequentialLabelForPage(current);<br> const curText=curUsed.length<br>  ? `Done on Page ${current+1}: &lt;b&gt;#${curUsed.join(&#39;, #&#39;)}&lt;/b&gt; · Next: &lt;b&gt;#${nextNum||&#39;—&#39;}&lt;/b&gt;`<br>  : `Page ${current+1} has 0 boxes yet · Starting at &lt;b&gt;#${nextNum||1}&lt;/b&gt;`;<br><br> const otherSummaries=[];<br> images.forEach((it,idx)=&gt;{<br>  if(idx===current)return;<br>  const nums=[...usedAnnotationNumbers(null,idx)].sort((a,b)=&gt;a-b);<br>  if(nums.length){<br>   const nextOther=nextSequentialLabelForPage(idx);<br>   otherSummaries.push(`Page ${idx+1} (${it.title||it.name}): &lt;b&gt;${nums.length} labeled&lt;/b&gt; (#${nums[0]}..#${nums[nums.length-1]}, next #${nextOther||&#39;—&#39;})`);<br>  }<br> });<br> const otherHtml=otherSummaries.length<br>  ? `&lt;div class=&quot;small&quot; style=&quot;margin-top:4px;border-top:1px solid var(--border);padding-top:4px&quot;&gt;Other pages progress:&lt;br&gt;• ${otherSummaries.join(&#39;&lt;br&gt;• &#39;)}&lt;/div&gt;`<br>  : `&lt;div class=&quot;small&quot; style=&quot;margin-top:2px&quot;&gt;Other pages: none labeled yet.&lt;/div&gt;`;<br><br> box.innerHTML=`&lt;strong&gt;Page ${current+1} Sequence:&lt;/strong&gt; ${curText}${otherHtml}`;<br>}<br><br>function applyLabelCount(){<br> let n=parseInt($(&#39;labelCount&#39;).value,10);<br> if(!n||n&lt;1)return alert(&#39;Enter a number from 1 to &#39;+MAX_LABELS+&#39;.&#39;);<br> n=Math.min(n,MAX_LABELS);<br> if(n&lt;labels.length){<br>  const used=annotations.some(a=&gt;a.label&gt;n);<br>  if(used&amp;&amp;!confirm(&#39;Some annotations use labels above &#39;+n+&#39;. They will keep their numbers but those labels will no longer be selectable. Continue?&#39;))return;<br> }<br> labels=makeLabels(n,labels);<br> if(selectedLabel&gt;n)selectedLabel=n;<br> drawLabels();<br> render();<br> persistConfig();<br>}<br><br>function saveLabel(){<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(!label)return;<br> if(!$(&#39;labelName&#39;).value.trim())return alert(&#39;Enter a label name.&#39;);<br> label.name=$(&#39;labelName&#39;).value.trim();<br> label.color=$(&#39;labelColor&#39;).value;<br> const f=fieldFor(label.id);<br> if(f){f.name=label.name;renderFields();}<br> drawLabels();<br> render();<br> persistConfig();<br>}<br><br>function resetLabels(){<br> if(!confirm(&#39;Reset all QA labels?&#39;))return;<br> labels=makeLabels(labels.length);<br> selectedLabel=1;<br> syncLabelsFromFields();<br> render();<br> persistConfig();<br>}<br><br>$(&#39;autoIncrement&#39;).addEventListener(&#39;change&#39;,()=&gt;{<br> if($(&#39;autoIncrement&#39;).checked){<br>  const next=nextSequentialLabel();<br>  if(next){ensureLabelCapacity(next);selectedLabel=next;drawLabels();}<br>  $(&#39;autoStatus&#39;).textContent=next?`ON: next OCR label is #${next}. Manual-value labels are disabled.`:&#39;No available OCR labels; increase the label count or change a field to Read by OCR.&#39;;<br> }else{<br>  $(&#39;autoStatus&#39;).textContent=&#39;OFF: manually select unused labels. Used numbers are blocked.&#39;;<br> }<br>});<br><br>// Annotation numbers reset per page (each page has its own 1..N sequence) and resume where left off.<br>function usedAnnotationNumbers(exceptId=null,pageIdx=current){<br> if(pageIdx&lt;0)return new Set();<br> return new Set(annotations.filter(a=&gt;a.image===pageIdx&amp;&amp;a.id!==exceptId).map(a=&gt;Number(a.label)));<br>}<br>function nextAvailableLabel(start=1,exceptId=null,pageIdx=current){<br> const used=usedAnnotationNumbers(exceptId,pageIdx);<br> let n=Math.max(1,Number(start)||1);<br> while((used.has(n)||fieldFor(n)?.mode===&#39;manual&#39;)&amp;&amp;n&lt;=MAX_LABELS)n++;<br> return n&lt;=MAX_LABELS?n:null;<br>}<br>function ensureLabelCapacity(n){<br> if(!n)return false;<br> if(n&gt;MAX_LABELS)return false;<br> if(n&gt;labels.length){<br>  labels=makeLabels(n,labels);<br>  $(&#39;labelCount&#39;).value=n;<br> }<br> return true;<br>}<br>function nextSequentialLabelForPage(pageIdx=current,exceptId=null){<br> const used=usedAnnotationNumbers(exceptId,pageIdx);<br> let candidate=1;<br> while(candidate&lt;=MAX_LABELS&amp;&amp;(used.has(candidate)||fieldFor(candidate)?.mode===&#39;manual&#39;))candidate++;<br> return candidate&lt;=MAX_LABELS?candidate:null;<br>}<br>function nextSequentialLabel(exceptId=null){<br> return nextSequentialLabelForPage(current,exceptId);<br>}<br>function selectNextAvailableLabel(){<br> const next=nextSequentialLabelForPage(current);<br> if(!next){<br>  $(&#39;autoStatus&#39;).textContent=&#39;All available labels on this page are used. Increase the label count to continue.&#39;;<br>  return false;<br> }<br> ensureLabelCapacity(next);<br> selectedLabel=next;<br> drawLabels();<br> const active=$(&#39;labels&#39;).querySelector(&#39;.label-item.active&#39;);<br> if(active)active.scrollIntoView({block:&#39;nearest&#39;});<br> $(&#39;autoStatus&#39;).textContent=`Page ${current+1} next sequence number: #${next}.`;<br> return true;<br>}<br>function autoIncrementLabel(){<br> if(!$(&#39;autoIncrement&#39;).checked)return;<br> selectNextAvailableLabel();<br>}<br><br>// ---------- FIELDS CONFIG ----------<br>function normField(f){<br> let n=parseInt(f.num,10);<br> if(!n||n&lt;1)n=1;<br> if(n&gt;MAX_LABELS)n=MAX_LABELS;<br> return{num:n,name:String(f.name??&#39;&#39;).trim(),mode:f.mode===&#39;manual&#39;?&#39;manual&#39;:&#39;ocr&#39;,value:String(f.value??&#39;&#39;)};<br>}<br><br>function parseFieldList(text){<br> const out=[];let bad=0;<br> text.split(/\r?\n/).forEach(raw=&gt;{<br>  const line=raw.trim();<br>  if(!line)return;<br>  let m;<br>  if(line.includes(&#39;|&#39;)){<br>   const p=line.split(&#39;|&#39;).map(s=&gt;s.trim());<br>   const n=parseInt(p[0],10);<br>   if(n&gt;0&amp;&amp;p[1]!==undefined){<br>    out.push(normField({num:n,name:p[1],mode:p.length&gt;=3?&#39;manual&#39;:&#39;ocr&#39;,value:p.slice(2).join(&#39;|&#39;)}));<br>    return;<br>   }<br>  }<br>  if((m=line.match(/^(\d{1,3})(?!\d)\s*[.):=\-–\t]?\s*(.+)$/))){<br>   let name=m[2].trim(),value=&#39;&#39;,md=&#39;ocr&#39;;<br>   const tag=name.match(/\s*\[manual\]\s*$/i);<br>   if(tag){md=&#39;manual&#39;;name=name.slice(0,tag.index).trim();}<br>   const eq=name.indexOf(&#39;=&#39;);<br>   if(eq&gt;0){value=name.slice(eq+1).trim();name=name.slice(0,eq).trim();md=&#39;manual&#39;;}<br>   out.push(normField({num:+m[1],name,mode:md,value}));<br>  }else if((m=line.match(/^(.+?)\s*[:=\t]\s*(\d{1,3})$/))){<br>   out.push(normField({num:+m[2],name:m[1].trim(),mode:&#39;ocr&#39;,value:&#39;&#39;}));<br>  }else bad++;<br> });<br> return{list:out,bad};<br>}<br><br>function fieldsToText(){<br> return fields.map(f=&gt;f.mode===&#39;manual&#39;?`${f.num} | ${f.name} | ${f.value}`:`${f.num} ${f.name}`).join(&#39;\n&#39;);<br>}<br><br>function applyFieldList(){<br> const {list,bad}=parseFieldList($(&#39;fieldsPaste&#39;).value);<br> if(!list.length){$(&#39;fieldsMsg&#39;).textContent=&#39;Nothing could be read. Use lines like &quot;2 Client Name&quot;.&#39;;return}<br> fields=list.sort((a,b)=&gt;a.num-b.num);<br> $(&#39;fieldsPaste&#39;).value=fieldsToText();<br> afterFieldsChange(true);<br> const manual=fields.filter(f=&gt;f.mode===&#39;manual&#39;).length;<br> $(&#39;fieldsMsg&#39;).textContent=`${fields.length} fields applied (${manual} manual).`+(bad?` ${bad} line(s) skipped.`:&#39;&#39;);<br>}<br><br>function addFieldRow(){<br> const next=fields.length?Math.min(MAX_LABELS,Math.max(...fields.map(f=&gt;f.num))+1):1;<br> fields.push(normField({num:next,name:&#39;&#39;,mode:&#39;ocr&#39;,value:&#39;&#39;}));<br> afterFieldsChange(true);<br>}<br><br>function syncLabelsFromFields(){<br> const max=Math.min(MAX_LABELS,Math.max(0,...fields.map(f=&gt;f.num)));<br> if(max&gt;labels.length)labels=makeLabels(max,labels);<br> fields.forEach(f=&gt;{<br>  if(f.num&gt;=1&amp;&amp;f.num&lt;=labels.length&amp;&amp;f.name)labels[f.num-1].name=f.name;<br> });<br> drawLabels();<br>}<br><br>function afterFieldsChange(rerenderFields){<br> syncLabelsFromFields();<br> renderAnnotationList();<br> renderExtracted();<br> drawLabels();<br> persistConfig();<br> if(rerenderFields)renderFields();<br>}<br><br>function renderFields(){<br> const body=$(&#39;fieldsBody&#39;);<br> body.innerHTML=&#39;&#39;;<br> fields.forEach((f,idx)=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  const td=()=&gt;document.createElement(&#39;td&#39;);<br>  const t1=td(),t2=td(),t3=td(),t4=td(),t5=td();<br><br>  const num=document.createElement(&#39;input&#39;);num.type=&#39;number&#39;;num.min=1;num.max=MAX_LABELS;num.value=f.num;<br>  num.onchange=()=&gt;{f.num=normField({num:num.value}).num;num.value=f.num;afterFieldsChange(false)};<br>  t1.appendChild(num);<br><br>  const name=document.createElement(&#39;input&#39;);name.type=&#39;text&#39;;name.value=f.name;name.placeholder=&#39;Field name&#39;;<br>  name.oninput=()=&gt;{f.name=name.value.trim();afterFieldsChange(false)};<br>  t2.appendChild(name);<br><br>  const sel=document.createElement(&#39;select&#39;);<br>  [[&#39;ocr&#39;,&#39;Read by OCR&#39;],[&#39;manual&#39;,&#39;Manual value&#39;]].forEach(([v,t])=&gt;{<br>   const o=document.createElement(&#39;option&#39;);o.value=v;o.textContent=t;if(f.mode===v)o.selected=true;sel.appendChild(o);<br>  });<br>  sel.onchange=()=&gt;{f.mode=sel.value;afterFieldsChange(true)};<br>  t3.appendChild(sel);<br><br>  const val=document.createElement(&#39;input&#39;);val.type=&#39;text&#39;;val.value=f.value;<br>  val.placeholder=f.mode===&#39;manual&#39;?&#39;Type the fixed value&#39;:&#39;(not used)&#39;;<br>  val.disabled=f.mode!==&#39;manual&#39;;<br>  val.oninput=()=&gt;{f.value=val.value;renderAnnotationList();renderExtracted();persistConfig()};<br>  t4.appendChild(val);<br><br>  const del=document.createElement(&#39;button&#39;);del.className=&#39;danger mini&#39;;del.textContent=&#39;✕&#39;;<br>  del.onclick=()=&gt;{fields.splice(idx,1);afterFieldsChange(true)};<br>  t5.appendChild(del);<br><br>  tr.append(t1,t2,t3,t4,t5);<br>  body.appendChild(tr);<br> });<br>}<br><br>// ---------- PAGE TITLES CONFIG ----------<br>$(&#39;pageTitlesText&#39;).addEventListener(&#39;input&#39;,()=&gt;{<br> pageTitles=$(&#39;pageTitlesText&#39;).value.split(/\r?\n/).map(s=&gt;s.trim()).filter(Boolean);<br> renderImages();<br> persistConfig();<br>});<br>$(&#39;projectName&#39;).addEventListener(&#39;input&#39;,persistConfig);<br>$(&#39;autoOcr&#39;).addEventListener(&#39;change&#39;,persistConfig);<br>$(&#39;ocrLang&#39;).addEventListener(&#39;change&#39;,()=&gt;{terminateWorker();persistConfig()});<br><br>function openConfig(){<br> const d=$(&#39;configPanel&#39;);<br> d.open=true;<br> d.scrollIntoView({behavior:&#39;smooth&#39;,block:&#39;start&#39;});<br>}<br><br>// ---------- CONFIG SAVE / LOAD ----------<br>function getConfig(){<br> return{<br>  projectName:$(&#39;projectName&#39;).value,<br>  pageTitles:pageTitles.slice(),<br>  fields:fields.map(f=&gt;({...f})),<br>  labels:labels.map(l=&gt;({name:l.name,color:l.color})),<br>  autoOcr:$(&#39;autoOcr&#39;).checked,<br>  ocrLang:$(&#39;ocrLang&#39;).value.trim()||&#39;eng&#39;<br> };<br>}<br><br>function applyConfig(c){<br> if(!c||typeof c!==&#39;object&#39;)return;<br> if(typeof c.projectName===&#39;string&#39;)$(&#39;projectName&#39;).value=c.projectName;<br> pageTitles=Array.isArray(c.pageTitles)?c.pageTitles.map(String).filter(s=&gt;s.trim()):[];<br> fields=Array.isArray(c.fields)?c.fields.map(normField):[];<br> if(Array.isArray(c.labels)&amp;&amp;c.labels.length){<br>  labels=c.labels.slice(0,MAX_LABELS).map((l,i)=&gt;({id:i+1,name:String(l&amp;&amp;l.name||`QA ${i+1}`),color:(l&amp;&amp;l.color)||&#39;#ff4242&#39;}));<br> }<br> if(typeof c.autoOcr===&#39;boolean&#39;)$(&#39;autoOcr&#39;).checked=c.autoOcr;<br> if(typeof c.ocrLang===&#39;string&#39;&amp;&amp;c.ocrLang.trim()){$(&#39;ocrLang&#39;).value=c.ocrLang.trim();terminateWorker();}<br> if(selectedLabel&gt;labels.length)selectedLabel=labels.length;<br> $(&#39;pageTitlesText&#39;).value=pageTitles.join(&#39;\n&#39;);<br> $(&#39;fieldsPaste&#39;).value=fieldsToText();<br> renderFields();<br> syncLabelsFromFields();<br> renderImages();<br> renderAnnotationList();<br> renderExtracted();<br> persistConfig();<br>}<br><br>function persistConfig(){<br> try{localStorage.setItem(CONFIG_KEY,JSON.stringify(getConfig()))}catch(e){}<br> scheduleWorkspaceAutosave();<br>}<br><br>// Full workspace autosave uses IndexedDB because screenshots are usually too large for localStorage.<br>const WORKSPACE_DB=&#39;qa-screenshot-studio-workspace&#39;;<br>const WORKSPACE_STORE=&#39;projects&#39;;<br>let workspaceSaveTimer=null;<br>let workspaceDbPromise=null;<br>function openWorkspaceDB(){<br> if(workspaceDbPromise)return workspaceDbPromise;<br> workspaceDbPromise=new Promise((resolve,reject)=&gt;{<br>  if(!(&#39;indexedDB&#39; in window)){reject(new Error(&#39;IndexedDB is unavailable&#39;));return;}<br>  const req=indexedDB.open(WORKSPACE_DB,1);<br>  req.onupgradeneeded=()=&gt;{const db=req.result;if(!db.objectStoreNames.contains(WORKSPACE_STORE))db.createObjectStore(WORKSPACE_STORE)};<br>  req.onsuccess=()=&gt;resolve(req.result);<br>  req.onerror=()=&gt;reject(req.error||new Error(&#39;Could not open browser storage&#39;));<br> });<br> return workspaceDbPromise;<br>}<br>function scheduleWorkspaceAutosave(){<br> clearTimeout(workspaceSaveTimer);<br> workspaceSaveTimer=setTimeout(()=&gt;saveWorkspaceAuto(),650);<br>}<br>async function saveWorkspaceAuto(){<br> try{<br>  const db=await openWorkspaceDB();<br>  const snapshot={<br>   version:1,savedAt:new Date().toISOString(),<br>   config:getConfig(),projectName:$(&#39;projectName&#39;).value,<br>   selectedLabel,current,<br>   images:images.map(it=&gt;({name:it.name,title:it.title||&#39;&#39;,include:it.include!==false,alreadyMerged:!!it.alreadyMerged,selectedForMerge:it.selectedForMerge!==false,width:it.width,height:it.height,blob:it.blob})),<br>   annotations:annotations.map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:a.status}))<br>  };<br>  await new Promise((resolve,reject)=&gt;{<br>   const tx=db.transaction(WORKSPACE_STORE,&#39;readwrite&#39;);<br>   tx.objectStore(WORKSPACE_STORE).put(snapshot,&#39;autosave&#39;);<br>   tx.oncomplete=resolve;tx.onerror=()=&gt;reject(tx.error||new Error(&#39;Auto-save failed&#39;));tx.onabort=()=&gt;reject(tx.error||new Error(&#39;Auto-save aborted&#39;));<br>  });<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;✓ Auto-saved &#39;+new Date().toLocaleTimeString();<br> }catch(err){<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;Auto-save unavailable: &#39;+err.message+&#39; · Use Save Project as backup.&#39;;<br> }<br>}<br>async function restoreWorkspaceAuto(){<br> try{<br>  const db=await openWorkspaceDB();<br>  const snapshot=await new Promise((resolve,reject)=&gt;{<br>   const tx=db.transaction(WORKSPACE_STORE,&#39;readonly&#39;);<br>   const req=tx.objectStore(WORKSPACE_STORE).get(&#39;autosave&#39;);<br>   req.onsuccess=()=&gt;resolve(req.result||null);req.onerror=()=&gt;reject(req.error);<br>  });<br>  if(!snapshot)return false;<br>  if(snapshot.config)applyConfig(snapshot.config);<br>  if(typeof snapshot.projectName===&#39;string&#39;)$(&#39;projectName&#39;).value=snapshot.projectName;<br>  clearAllImagesSilently();<br>  for(const saved of snapshot.images||[]){<br>   if(!saved.blob)continue;<br>   const item=await makeItem(saved.blob,saved.name||&#39;Image&#39;);<br>   item.title=saved.title||&#39;&#39;;item.include=saved.include!==false;item.alreadyMerged=!!saved.alreadyMerged;item.selectedForMerge=saved.selectedForMerge!==undefined?!!saved.selectedForMerge:!saved.alreadyMerged;<br>   images.push(item);<br>  }<br>  annotations=Array.isArray(snapshot.annotations)?snapshot.annotations.map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:(a.status||&#39;&#39;)})):[];<br>  selectedLabel=Number(snapshot.selectedLabel)||1;<br>  current=images.length?Math.max(0,Math.min(Number(snapshot.current)||0,images.length-1)):-1;<br>  if(current&gt;=0)showImage();<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;✓ Restored last auto-saved workspace&#39;;<br>  return true;<br> }catch(err){<br>  const el=$(&#39;autosaveStatus&#39;);if(el)el.textContent=&#39;Could not restore auto-save: &#39;+err.message;<br>  return false;<br> }<br>}<br>function loadLocalConfig(){<br> try{<br>  const s=localStorage.getItem(CONFIG_KEY);<br>  if(s)applyConfig(JSON.parse(s));<br> }catch(e){}<br>}<br><br>function exportConfig(){<br> const data={app:&#39;QA Screenshot Studio&#39;,type:&#39;config&#39;,version:2,savedAt:new Date().toISOString(),config:getConfig()};<br> downloadBlob(new Blob([JSON.stringify(data,null,2)],{type:&#39;application/json&#39;}),`${safeName($(&#39;projectName&#39;).value)}-config.json`);<br>}<br><br>$(&#39;configFile&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const file=e.target.files&amp;&amp;e.target.files[0];<br> e.target.value=&#39;&#39;;<br> if(!file)return;<br> try{<br>  const obj=JSON.parse(await file.text());<br>  const c=obj.config||obj;<br>  if(!c||(!c.fields&amp;&amp;!c.pageTitles&amp;&amp;!c.labels))throw new Error(&#39;No config found in this file.&#39;);<br>  applyConfig(c);<br>  $(&#39;fieldsMsg&#39;).textContent=&#39;Config imported.&#39;;<br> }catch(err){alert(&#39;Could not import config: &#39;+err.message)}<br>});<br><br>// ---------- PROJECT SAVE / LOAD ----------<br>async function saveProject(){<br> try{<br>  const imgs=[];<br>  for(const it of images){<br>   imgs.push({name:it.name,title:it.title||&#39;&#39;,include:it.include!==false,alreadyMerged:!!it.alreadyMerged,selectedForMerge:it.selectedForMerge!==false,width:it.width,height:it.height,dataUrl:await blobToDataURL(it.blob)});<br>  }<br>  const data={<br>   app:&#39;QA Screenshot Studio&#39;,type:&#39;project&#39;,version:2,savedAt:new Date().toISOString(),<br>   projectName:$(&#39;projectName&#39;).value,<br>   config:getConfig(),<br>   selectedLabel,current,<br>   images:imgs,<br>   annotations:annotations.map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:a.status}))<br>  };<br>  downloadBlob(new Blob([JSON.stringify(data)],{type:&#39;application/json&#39;}),`${safeName($(&#39;projectName&#39;).value)}-${stamp()}.qaproject.json`);<br> }catch(err){alert(&#39;Could not save project: &#39;+err.message)}<br>}<br><br>$(&#39;projectFile&#39;).addEventListener(&#39;change&#39;,async e=&gt;{<br> const file=e.target.files&amp;&amp;e.target.files[0];<br> e.target.value=&#39;&#39;;<br> if(!file)return;<br> try{<br>  const data=JSON.parse(await file.text());<br>  if(!data||!Array.isArray(data.images))throw new Error(&#39;This is not a project file.&#39;);<br>  if((images.length||annotations.length)&amp;&amp;!confirm(&#39;Loading a project replaces the current screenshots and annotations. Continue?&#39;))return;<br>  clearAllImagesSilently();<br>  for(const s of data.images){<br>   const blob=await (await fetch(s.dataUrl)).blob();<br>   const it=await makeItem(blob,s.name||&#39;Image&#39;);<br>   it.title=s.title||&#39;&#39;;<br>   it.include=s.include!==false;<br>   it.alreadyMerged=!!s.alreadyMerged;<br>   it.selectedForMerge=s.selectedForMerge!==undefined?!!s.selectedForMerge:!s.alreadyMerged;<br>   images.push(it);<br>  }<br>  annotations=(Array.isArray(data.annotations)?data.annotations:[])<br>   .filter(a=&gt;a.image&gt;=0&amp;&amp;a.image&lt;images.length)<br>   .map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:(a.status||&#39;&#39;),text:a.text||&#39;&#39;}));<br>  if(data.config)applyConfig(data.config);<br>  if(typeof data.projectName===&#39;string&#39;)$(&#39;projectName&#39;).value=data.projectName;<br>  if(data.selectedLabel&gt;=1&amp;&amp;data.selectedLabel&lt;=labels.length)selectedLabel=data.selectedLabel;<br>  current=images.length?Math.min(Math.max(0,parseInt(data.current,10)||0),images.length-1):-1;<br>  drawLabels();<br>  renderImages();<br>  if(current&gt;=0)showImage();else updateImageStatus();<br>  render();<br> }catch(err){alert(&#39;Could not load project: &#39;+err.message)}<br>});<br><br>// ---------- DRAW TOOLS ----------<br>function setMode(value){<br> mode=value;<br> $(&#39;boxTool&#39;).classList.toggle(&#39;active&#39;,value===&#39;box&#39;);<br> $(&#39;circleTool&#39;).classList.toggle(&#39;active&#39;,value===&#39;circle&#39;);<br> $(&#39;toolStatus&#39;).textContent=&#39;Current tool: &#39;+(value===&#39;box&#39;?&#39;Rectangle&#39;:&#39;Circle&#39;);<br>}<br><br>function pointerPosition(e){<br> const r=overlay.getBoundingClientRect();<br> return{x:(e.clientX-r.left)*overlay.width/r.width,y:(e.clientY-r.top)*overlay.height/r.height};<br>}<br><br>function annotationAtPoint(p){<br> const list=annotations.filter(a=&gt;a.image===current);<br> for(let i=list.length-1;i&gt;=0;i--){<br>  const a=list[i];<br>  if(p.x&gt;=a.x&amp;&amp;p.x&lt;=a.x+a.w&amp;&amp;p.y&gt;=a.y&amp;&amp;p.y&lt;=a.y+a.h)return a;<br> }<br> return null;<br>}<br>function isResizeHandle(a,p){<br> const size=Math.max(14,overlay.width/90);<br> return p.x&gt;=a.x+a.w-size&amp;&amp;p.x&lt;=a.x+a.w+size&amp;&amp;p.y&gt;=a.y+a.h-size&amp;&amp;p.y&lt;=a.y+a.h+size;<br>}<br>overlay.addEventListener(&#39;pointerdown&#39;,e=&gt;{<br> if(current&lt;0)return;<br> e.preventDefault();<br> const p=pointerPosition(e);<br> const hit=annotationAtPoint(p);<br> if(hit){<br>  selected=hit.id;<br>  history.push(JSON.stringify(annotations));<br>  drag={<br>   kind:isResizeHandle(hit,p)?&#39;resize&#39;:&#39;move&#39;,id:hit.id,<br>   startX:p.x,startY:p.y,origX:hit.x,origY:hit.y,origW:hit.w,origH:hit.h<br>  };<br>  render();<br>  overlay.setPointerCapture(e.pointerId);<br>  return;<br> }<br> history.push(JSON.stringify(annotations));<br> drag={kind:&#39;draw&#39;,startX:p.x,startY:p.y,x:p.x,y:p.y};<br> overlay.setPointerCapture(e.pointerId);<br>});<br><br>overlay.addEventListener(&#39;pointermove&#39;,e=&gt;{<br> if(!drag)return;<br> const p=pointerPosition(e);<br> if(drag.kind===&#39;move&#39;||drag.kind===&#39;resize&#39;){<br>  const a=annotations.find(x=&gt;x.id===drag.id);<br>  if(!a)return;<br>  const dx=p.x-drag.startX,dy=p.y-drag.startY;<br>  if(drag.kind===&#39;move&#39;){<br>   a.x=Math.max(0,Math.min(overlay.width-a.w,drag.origX+dx));<br>   a.y=Math.max(0,Math.min(overlay.height-a.h,drag.origY+dy));<br>  }else{<br>   a.w=Math.max(8,Math.min(overlay.width-a.x,drag.origW+dx));<br>   a.h=Math.max(8,Math.min(overlay.height-a.y,drag.origH+dy));<br>  }<br>  render();<br>  return;<br> }<br> drag.x=p.x;drag.y=p.y;<br> render(drag);<br>});<br><br>overlay.addEventListener(&#39;pointerup&#39;,e=&gt;{<br> if(!drag)return;<br> const p=pointerPosition(e);<br> if(drag.kind===&#39;move&#39;||drag.kind===&#39;resize&#39;){<br>  drag=null;render();scheduleWorkspaceAutosave();return;<br> }<br> drag.x=p.x;drag.y=p.y;<br> const x=Math.min(drag.startX,drag.x);<br> const y=Math.min(drag.startY,drag.y);<br> const w=Math.abs(drag.x-drag.startX);<br> const h=Math.abs(drag.y-drag.startY);<br> if(w&lt;3&amp;&amp;h&lt;3){<br>  history.pop();drag=null;render();return;<br> }<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(!label){drag=null;render();return}<br> if(usedAnnotationNumbers(null,current).has(label.id)){<br>  const next=nextSequentialLabelForPage(current);<br>  if(next){ensureLabelCapacity(next);selectedLabel=next;drawLabels();}<br>  drag=null;render();<br>  $(&#39;autoStatus&#39;).textContent=`#${label.id} is already used on Page ${current+1}. Selected next unused label #${next||&#39;—&#39;}.`;<br>  alert(`Label #${label.id} is already used on Page ${current+1}. Select the next unused number${next?&#39; (#&#39;+next+&#39;)&#39;:&#39;&#39;}.`);<br>  return;<br> }<br> const f=fieldFor(label.id);<br> const isManual=f&amp;&amp;f.mode===&#39;manual&#39;;<br> const doOcr=$(&#39;autoOcr&#39;).checked&amp;&amp;!isManual;<br> const a={<br>  id:crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random()),<br>  image:current,label:label.id,name:label.name,color:label.color,type:mode,x,y,w,h,<br>  text:&#39;&#39;,status:doOcr?&#39;pending&#39;:&#39;&#39;<br> };<br> annotations.push(a);<br> selected=a.id;<br> drag=null;<br> autoIncrementLabel();<br> render();<br> if(doOcr)queueOCR(a.id);<br>});<br><br>overlay.addEventListener(&#39;pointercancel&#39;,()=&gt;{drag=null;render()});<br><br>// ---------- ANNOTATION RENDERING ----------<br>function drawAnnotation(a,isSelected=false){<br> ctx.save();<br> ctx.strokeStyle=a.color;<br> ctx.fillStyle=a.color;<br> ctx.lineWidth=Math.max(3,overlay.width/500);<br> if(a.type===&#39;circle&#39;){<br>  const radius=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>  ctx.beginPath();<br>  ctx.arc(a.x+a.w/2,a.y+a.h/2,radius,0,Math.PI*2);<br>  ctx.stroke();<br>  ctx.fillStyle=a.color;<br>  ctx.font=`bold ${Math.max(14,radius)}px Arial`;<br>  ctx.textAlign=&#39;center&#39;;ctx.textBaseline=&#39;middle&#39;;<br>  ctx.fillText(String(a.label),a.x+a.w/2,a.y+a.h/2);<br> }else{<br>  ctx.strokeRect(a.x,a.y,a.w,a.h);<br>  const mw=Math.max(32,String(a.label).length*11+15);<br>  ctx.fillRect(a.x,Math.max(0,a.y-25),mw,25);<br>  ctx.fillStyle=&#39;white&#39;;<br>  ctx.font=&#39;bold 15px Arial&#39;;<br>  ctx.textAlign=&#39;center&#39;;ctx.textBaseline=&#39;middle&#39;;<br>  ctx.fillText(String(a.label),a.x+mw/2,Math.max(0,a.y-25)+12.5);<br> }<br> if(isSelected){<br>  ctx.setLineDash([7,5]);ctx.strokeStyle=&#39;white&#39;;ctx.lineWidth=2;<br>  if(a.type===&#39;circle&#39;){<br>   const r=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>   ctx.beginPath();ctx.arc(a.x+a.w/2,a.y+a.h/2,r+6,0,Math.PI*2);ctx.stroke();<br>  }else ctx.strokeRect(a.x-4,a.y-4,a.w+8,a.h+8);<br>  ctx.setLineDash([]);<br>  ctx.fillStyle=&#39;white&#39;;ctx.strokeStyle=&#39;#17233b&#39;;ctx.lineWidth=2;<br>  ctx.fillRect(a.x+a.w-7,a.y+a.h-7,14,14);<br>  ctx.strokeRect(a.x+a.w-7,a.y+a.h-7,14,14);<br> }<br> ctx.restore();<br>}<br><br>function render(preview=null){<br> if(!overlay.width||!overlay.height){renderAnnotationList();renderExtracted();updateStats();drawLabels();return}<br> ctx.clearRect(0,0,overlay.width,overlay.height);<br> annotations.filter(a=&gt;a.image===current).forEach(a=&gt;drawAnnotation(a,a.id===selected));<br> if(preview){<br>  const l=labels.find(x=&gt;x.id===selectedLabel);<br>  if(l){<br>   ctx.save();ctx.globalAlpha=.65;<br>   drawAnnotation({<br>    type:mode,x:Math.min(preview.startX,preview.x),<br>    y:Math.min(preview.startY,preview.y),<br>    w:Math.abs(preview.x-preview.startX),<br>    h:Math.abs(preview.y-preview.startY),<br>    label:l.id,color:l.color<br>   });<br>   ctx.restore();<br>  }<br>  return;<br> }<br> renderAnnotationList();<br> renderExtracted();<br> updateStats();<br> drawLabels();<br> scheduleWorkspaceAutosave();<br>}<br><br>function renderAnnotationList(){<br> const list=$(&#39;annotations&#39;);<br> list.innerHTML=&#39;&#39;;<br> const visible=annotations.filter(a=&gt;a.image===current);<br> $(&#39;annotationCount&#39;).textContent=visible.length+&#39; annotations&#39;;<br> visible.forEach(a=&gt;{<br>  const row=document.createElement(&#39;div&#39;);<br>  row.className=&#39;annotation-item&#39;+(a.id===selected?&#39; active&#39;:&#39;&#39;);<br>  const dot=document.createElement(&#39;span&#39;);<br>  dot.className=&#39;annotation-dot&#39;;<br>  dot.style.background=a.color;<br>  const text=document.createElement(&#39;span&#39;);<br>  const v=valueOf(a);<br>  text.textContent=`#${a.label} · ${labelName(a)}`+(v?` · ${v.length&gt;22?v.slice(0,22)+&#39;…&#39;:v}`:&#39;&#39;)+(a.confidence?` · ${a.confidence}%`:&#39;&#39;);<br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;danger&#39;;del.textContent=&#39;✕&#39;;<br>  del.onclick=e=&gt;{e.stopPropagation();deleteAnnotation(a.id)};<br>  row.append(dot,text,del);<br>  row.onclick=()=&gt;{selected=a.id;render()};<br>  list.appendChild(row);<br> });<br>}<br><br>function deleteAnnotation(id){<br> history.push(JSON.stringify(annotations));<br> annotations=annotations.filter(a=&gt;a.id!==id);<br> if(selected===id)selected=null;<br> render();<br>}<br><br>function deleteSelected(){<br> if(!selected)return alert(&#39;Select an annotation first.&#39;);<br> deleteAnnotation(selected);<br>}<br><br>function undo(){<br> if(!history.length)return alert(&#39;Nothing to undo.&#39;);<br> annotations=JSON.parse(history.pop()).map(a=&gt;({...a,status:a.status===&#39;pending&#39;?&#39;&#39;:a.status}));<br> selected=null;<br> render();<br>}<br><br>function clearAnnotations(){<br> const count=annotations.filter(a=&gt;a.image===current).length;<br> if(!count)return;<br> if(!confirm(&#39;Clear annotations on this screenshot?&#39;))return;<br> history.push(JSON.stringify(annotations));<br> annotations=annotations.filter(a=&gt;a.image!==current);<br> selected=null;<br> render();<br>}<br><br>// ---------- EXTRACTED DATA TABLE ----------<br>function statusText(a,manual){<br> if(manual)return &#39;manual value&#39;;<br> if(a.status===&#39;pending&#39;)return &#39;reading…&#39;;<br> if(a.status===&#39;error&#39;)return &#39;OCR failed&#39;;<br> if(a.status===&#39;done&#39;)return a.text?&#39;read ✓&#39;:&#39;no text found&#39;;<br> return a.text?&#39;edited&#39;:&#39;&#39;;<br>}<br><br>function renderExtracted(){<br> const body=$(&#39;dataBody&#39;);<br> if(!body)return;<br> body.innerHTML=&#39;&#39;;<br> const rows=annotations.filter(a=&gt;a.image===current).sort((p,q)=&gt;p.label-q.label);<br> const annotationLabels=new Set(rows.map(a=&gt;Number(a.label)));<br> // Include manual config values even when the user has not drawn a box for that field.<br> const manualOnly=fields.filter(f=&gt;f.mode===&#39;manual&#39;&amp;&amp;!annotationLabels.has(Number(f.num)))<br>  .sort((a,b)=&gt;a.num-b.num);<br> const hasRows=rows.length&gt;0||manualOnly.length&gt;0;<br> $(&#39;dataEmpty&#39;).hidden=hasRows;<br> rows.forEach(a=&gt;{<br>  const f=fieldFor(a.label);<br>  const manual=f&amp;&amp;f.mode===&#39;manual&#39;;<br>  const tr=document.createElement(&#39;tr&#39;);<br>  if(a.id===selected)tr.className=&#39;sel&#39;;<br>  const c1=document.createElement(&#39;td&#39;);c1.textContent=&#39;#&#39;+a.label;<br>  const c2=document.createElement(&#39;td&#39;);c2.textContent=labelName(a);<br>  const c3=document.createElement(&#39;td&#39;);<br>  const inp=document.createElement(&#39;input&#39;);inp.type=&#39;text&#39;;<br>  inp.value=manual?(f.value||&#39;&#39;):(a.text||&#39;&#39;);<br>  inp.readOnly=!!manual;<br>  inp.dataset.val=a.id;<br>  inp.title=manual?&#39;Manual field: edit its value in Config&#39;:&#39;Edit if OCR got it wrong&#39;;<br>  inp.oninput=()=&gt;{a.text=inp.value;a.status=a.status===&#39;error&#39;?&#39;&#39;:a.status;renderAnnotationList()};<br>  c3.appendChild(inp);<br>  const c4=document.createElement(&#39;td&#39;);<br>  const st=document.createElement(&#39;span&#39;);st.className=&#39;small&#39;;st.dataset.stat=a.id;st.textContent=statusText(a,manual);<br>  c4.appendChild(st);<br>  if(!manual){<br>   const b=document.createElement(&#39;button&#39;);b.className=&#39;mini&#39;;b.textContent=&#39;OCR&#39;;b.style.marginLeft=&#39;6px&#39;;<br>   b.onclick=e=&gt;{e.stopPropagation();a.status=&#39;pending&#39;;updateRow(a);queueOCR(a.id)};<br>   c4.appendChild(b);<br>  }<br>  tr.append(c1,c2,c3,c4);<br>  tr.onclick=()=&gt;{selected=a.id;render()};<br>  body.appendChild(tr);<br> });<br> manualOnly.forEach(f=&gt;{<br>  const tr=document.createElement(&#39;tr&#39;);<br>  tr.className=&#39;manual-data-row&#39;;<br>  const c1=document.createElement(&#39;td&#39;);c1.textContent=&#39;#&#39;+f.num;<br>  const c2=document.createElement(&#39;td&#39;);c2.textContent=f.name||(&#39;QA &#39;+f.num);<br>  const c3=document.createElement(&#39;td&#39;);<br>  const inp=document.createElement(&#39;input&#39;);inp.type=&#39;text&#39;;inp.value=f.value||&#39;&#39;;inp.readOnly=true;<br>  inp.title=&#39;Manual value — update it in Config&#39;;<br>  c3.appendChild(inp);<br>  const c4=document.createElement(&#39;td&#39;);<br>  const st=document.createElement(&#39;span&#39;);st.className=&#39;small&#39;;st.textContent=&#39;manual value · no OCR&#39;;<br>  c4.appendChild(st);<br>  tr.append(c1,c2,c3,c4);<br>  body.appendChild(tr);<br> });<br>}<br><br>function updateRow(a){<br> const inp=document.querySelector(`[data-val=&quot;${a.id}&quot;]`);<br> const st=document.querySelector(`[data-stat=&quot;${a.id}&quot;]`);<br> if(inp&amp;&amp;st){<br>  const f=fieldFor(a.label);<br>  const manual=f&amp;&amp;f.mode===&#39;manual&#39;;<br>  if(!manual)inp.value=a.text||&#39;&#39;;<br>  st.textContent=statusText(a,manual);<br> }else renderExtracted();<br> renderAnnotationList();<br>}<br><br>function reOcrPage(){<br> let n=0;<br> annotations.filter(a=&gt;a.image===current).forEach(a=&gt;{<br>  const f=fieldFor(a.label);<br>  if(f&amp;&amp;f.mode===&#39;manual&#39;)return;<br>  a.status=&#39;pending&#39;;n++;<br>  queueOCR(a.id);<br> });<br> renderExtracted();<br> $(&#39;dataMsg&#39;).textContent=n?`Reading ${n} box(es)…`:&#39;No OCR boxes on this page.&#39;;<br>}<br><br>function extractedRows(idx){<br> const pageAnnotations=annotations.filter(a=&gt;a.image===idx).sort((p,q)=&gt;p.label-q.label);<br> const rows=pageAnnotations.map(a=&gt;[String(a.label),labelName(a),valueOf(a)]);<br> const present=new Set(pageAnnotations.map(a=&gt;Number(a.label)));<br> fields.filter(f=&gt;f.mode===&#39;manual&#39;&amp;&amp;!present.has(Number(f.num)))<br>  .sort((a,b)=&gt;a.num-b.num)<br>  .forEach(f=&gt;rows.push([String(f.num),f.name||(&#39;QA &#39;+f.num),f.value||&#39;&#39;]));<br> return rows.sort((a,b)=&gt;Number(a[0])-Number(b[0]));<br>}<br>function copyExtracted(all){<br> const clean=s=&gt;String(s??&#39;&#39;).replace(/[\t\r\n]+/g,&#39; &#39;);<br> const lines=[];<br> if(all){<br>  lines.push([&#39;Page&#39;,&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;].join(&#39;\t&#39;));<br>  images.forEach((it,i)=&gt;extractedRows(i).forEach(r=&gt;lines.push([it.title||it.name,...r].map(clean).join(&#39;\t&#39;))));<br> }else{<br>  lines.push([&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;].join(&#39;\t&#39;));<br>  extractedRows(current).forEach(r=&gt;lines.push(r.map(clean).join(&#39;\t&#39;)));<br> }<br> const text=lines.join(&#39;\n&#39;);<br> const done=()=&gt;{$(&#39;dataMsg&#39;).textContent=&#39;Copied to clipboard.&#39;};<br> const fallback=()=&gt;{<br>  const t=document.createElement(&#39;textarea&#39;);t.value=text;document.body.appendChild(t);t.select();<br>  try{document.execCommand(&#39;copy&#39;);done()}catch(e){$(&#39;dataMsg&#39;).textContent=&#39;Copy failed.&#39;}<br>  t.remove();<br> };<br> if(navigator.clipboard&amp;&amp;navigator.clipboard.writeText)navigator.clipboard.writeText(text).then(done).catch(fallback);<br> else fallback();<br>}<br><br>// ---------- OCR ----------<br>let ocrWorker=null,ocrWorkerLang=&#39;&#39;,ocrChain=Promise.resolve();<br><br>function terminateWorker(){<br> if(ocrWorker){try{ocrWorker.terminate()}catch(e){}ocrWorker=null;}<br>}<br><br>async function waitForTesseract(timeout=20000){<br> const started=Date.now();<br> while(!window.Tesseract&amp;&amp;Date.now()-started&lt;timeout){<br>  await new Promise(resolve=&gt;setTimeout(resolve,150));<br> }<br> if(!window.Tesseract)throw new Error(&#39;OCR library did not load. Check your internet connection, then reload this page.&#39;);<br> return window.Tesseract;<br>}<br><br>async function getWorker(){<br> const lang=$(&#39;ocrLang&#39;).value.trim()||&#39;eng&#39;;<br> if(ocrWorker&amp;&amp;ocrWorkerLang===lang)return ocrWorker;<br> terminateWorker();<br> const engine=await waitForTesseract();<br> $(&#39;ocrStatus&#39;).textContent=&#39;Loading OCR language data…&#39;;<br> ocrWorker=await engine.createWorker(lang,1,{logger:m=&gt;{<br>  if(m.status){<br>   const pct=typeof m.progress===&#39;number&#39;?` ${Math.round(m.progress*100)}%`:&#39;&#39;;<br>   $(&#39;ocrStatus&#39;).textContent=&#39;OCR: &#39;+m.status+pct;<br>  }<br> }});<br> ocrWorkerLang=lang;<br> try{<br>  await ocrWorker.setParameters({<br>   preserve_interword_spaces:&#39;1&#39;,<br>   user_defined_dpi:&#39;300&#39;,<br>   tessedit_do_invert:&#39;0&#39;<br>  });<br> }catch(e){}<br> $(&#39;ocrStatus&#39;).textContent=&#39;OCR engine ready.&#39;;<br> return ocrWorker;<br>}<br><br>function cropAnnotation(a){<br> const item=images[a.image];<br> if(!item)throw new Error(&#39;The screenshot for this box no longer exists.&#39;);<br> const pad=Math.max(3,Math.round(Math.min(a.w,a.h)*.06));<br> const sx=Math.max(0,Math.floor(a.x)-pad),sy=Math.max(0,Math.floor(a.y)-pad);<br> const ex=Math.min(item.width,Math.ceil(a.x+a.w)+pad);<br> const ey=Math.min(item.height,Math.ceil(a.y+a.h)+pad);<br> const sw=Math.max(1,ex-sx),sh=Math.max(1,ey-sy);<br> // Upscale small text substantially; keep large screenshots within reasonable memory use.<br> const scale=Math.min(5,Math.max(2,Math.ceil(260/Math.max(1,sh))));<br> const c=document.createElement(&#39;canvas&#39;);<br> c.width=Math.max(1,Math.round(sw*scale)+32);<br> c.height=Math.max(1,Math.round(sh*scale)+32);<br> const g=c.getContext(&#39;2d&#39;,{willReadFrequently:true});<br> g.fillStyle=&#39;#fff&#39;;g.fillRect(0,0,c.width,c.height);<br> g.imageSmoothingEnabled=true;g.imageSmoothingQuality=&#39;high&#39;;<br> g.drawImage(item.img,sx,sy,sw,sh,16,16,sw*scale,sh*scale);<br><br> // Analyze only the actual crop, not the white padding.<br> const imageData=g.getImageData(16,16,Math.max(1,Math.round(sw*scale)),Math.max(1,Math.round(sh*scale)));<br> const px=imageData.data;<br> let total=0,min=255,max=0;<br> const histogram=new Uint32Array(256);<br> for(let i=0;i&lt;px.length;i+=4){<br>  const lum=Math.round(.299*px[i]+.587*px[i+1]+.114*px[i+2]);<br>  total+=lum;min=Math.min(min,lum);max=Math.max(max,lum);histogram[lum]++;<br> }<br> const count=px.length/4,avg=count?total/count:255;<br> // Contrast stretch, grayscale and invert dark UI captures where the text is light.<br> const invert=avg&lt;125;<br> const range=Math.max(35,max-min);<br> for(let i=0;i&lt;px.length;i+=4){<br>  let lum=.299*px[i]+.587*px[i+1]+.114*px[i+2];<br>  lum=(lum-min)*255/range;<br>  lum=invert?255-lum:lum;<br>  px[i]=px[i+1]=px[i+2]=Math.max(0,Math.min(255,lum));<br> }<br> g.putImageData(imageData,16,16);<br><br> // Create an adaptive-ish binary variant using a histogram-derived threshold.<br> const gray=g.getImageData(16,16,Math.max(1,Math.round(sw*scale)),Math.max(1,Math.round(sh*scale)));<br> const h=gray.data;<br> let sum=0,n=0;<br> for(let i=0;i&lt;h.length;i+=4){sum+=h[i];n++;}<br> const mean=n?sum/n:180;<br> const threshold=Math.max(90,Math.min(205,mean-8));<br> for(let i=0;i&lt;h.length;i+=4){<br>  const v=h[i]&gt;threshold?255:0;<br>  h[i]=h[i+1]=h[i+2]=v;<br> }<br> const binary=document.createElement(&#39;canvas&#39;);<br> binary.width=c.width;binary.height=c.height;<br> const bg=binary.getContext(&#39;2d&#39;);<br> bg.fillStyle=&#39;#fff&#39;;bg.fillRect(0,0,binary.width,binary.height);<br> bg.putImageData(gray,16,16);<br> return{canvas:c,binary,singleLine:sh&lt;100&amp;&amp;sw/Math.max(1,sh)&gt;2.2};<br>}<br><br>function queueOCR(id){<br> ocrChain=ocrChain.then(()=&gt;runOCR(id)).catch(err=&gt;{<br>  console.error(&#39;OCR queue error:&#39;,err);<br>  $(&#39;ocrStatus&#39;).textContent=&#39;OCR queue error: &#39;+(err.message||err);<br> });<br>}<br><br>async function runOCR(id){<br> const a=annotations.find(x=&gt;x.id===id);<br> if(!a||!images[a.image])return;<br> try{<br>  const worker=await getWorker();<br>  const {canvas,binary,singleLine}=cropAnnotation(a);<br>  const engine=window.Tesseract;<br>  const psm=singleLine?engine.PSM.SINGLE_LINE:engine.PSM.SINGLE_BLOCK;<br>  let best=null;<br>  // Compare enhanced grayscale and thresholded variants; retain the higher-confidence read.<br>  for(const candidate of [canvas,binary]){<br>   try{<br>    await worker.setParameters({tessedit_pageseg_mode:psm,preserve_interword_spaces:&#39;1&#39;});<br>    const result=await worker.recognize(candidate);<br>    const data=result.data||{};<br>    const textValue=String(data.text||&#39;&#39;).replace(/[\t\r\n]+/g,&#39; &#39;).replace(/\s{2,}/g,&#39; &#39;).trim();<br>    const confidence=Number(data.confidence)||0;<br>    const score=confidence+(textValue?Math.min(8,textValue.length*.15):0);<br>    if(!best||score&gt;best.score)best={text:textValue,confidence,score};<br>   }catch(candidateError){console.warn(&#39;OCR preprocessing pass failed:&#39;,candidateError);}<br>  }<br>  const cur=annotations.find(x=&gt;x.id===id);<br>  if(!cur)return;<br>  cur.text=best?best.text:&#39;&#39;;<br>  cur.confidence=best?Math.round(best.confidence):0;<br>  cur.status=&#39;done&#39;;<br>  $(&#39;ocrStatus&#39;).textContent=best?`OCR complete · confidence ${cur.confidence}%`:&#39;OCR complete · no text found&#39;;<br>  updateRow(cur);<br> }catch(err){<br>  console.error(err);<br>  const cur=annotations.find(x=&gt;x.id===id);<br>  if(cur){cur.status=&#39;error&#39;;updateRow(cur);}<br>  $(&#39;ocrStatus&#39;).textContent=&#39;OCR error: &#39;+(err.message||err);<br> }<br>}<br><br>// ---------- SELECTIVE MERGE IMAGES ----------<br>function onExcludeMergedToggle(){<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> if(exclude){<br>  images.forEach(it=&gt;{if(it.alreadyMerged)it.selectedForMerge=false;});<br> }<br> renderMergeChecklist();<br> scheduleWorkspaceAutosave();<br>}<br><br>function selectMergeCandidates(mode){<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> images.forEach(it=&gt;{<br>  if(mode===&#39;none&#39;)it.selectedForMerge=false;<br>  else if(mode===&#39;unmerged&#39;)it.selectedForMerge=!it.alreadyMerged;<br>  else if(mode===&#39;all&#39;)it.selectedForMerge=exclude?!it.alreadyMerged:true;<br> });<br> renderMergeChecklist();<br> scheduleWorkspaceAutosave();<br>}<br><br>function resetMergedHistory(){<br> images.forEach(it=&gt;{it.alreadyMerged=false;});<br> renderMergeChecklist();<br> scheduleWorkspaceAutosave();<br> $(&#39;mergeSelectionStatus&#39;).textContent=&#39;Merged flags cleared. All images can be selected again.&#39;;<br>}<br><br>function renderMergeChecklist(){<br> const list=$(&#39;mergeChecklist&#39;);<br> const status=$(&#39;mergeSelectionStatus&#39;);<br> if(!list)return;<br> list.innerHTML=&#39;&#39;;<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> if(!images.length){<br>  list.innerHTML=&#39;&lt;div class=&quot;small&quot; style=&quot;padding:4px&quot;&gt;No images loaded yet.&lt;/div&gt;&#39;;<br>  if(status)status.textContent=&#39;0 image(s) selected for merge.&#39;;<br>  return;<br> }<br> let count=0;<br> images.forEach((it,i)=&gt;{<br>  if(exclude&amp;&amp;it.alreadyMerged)it.selectedForMerge=false;<br>  if(it.selectedForMerge)count++;<br>  const row=document.createElement(&#39;label&#39;);<br>  row.className=&#39;merge-item&#39;+(it.alreadyMerged?&#39; merged-before&#39;:&#39;&#39;);<br>  const chk=document.createElement(&#39;input&#39;);<br>  chk.type=&#39;checkbox&#39;;<br>  chk.checked=!!it.selectedForMerge;<br>  chk.disabled=!!(exclude&amp;&amp;it.alreadyMerged);<br>  chk.onchange=()=&gt;{<br>   it.selectedForMerge=chk.checked;<br>   renderMergeChecklist();<br>   scheduleWorkspaceAutosave();<br>  };<br>  const txt=document.createElement(&#39;span&#39;);<br>  txt.style.cssText=&#39;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap&#39;;<br>  txt.textContent=`Page ${i+1}: ${it.title||it.name}`;<br>  row.append(chk,txt);<br>  if(it.alreadyMerged){<br>   const tag=document.createElement(&#39;span&#39;);<br>   tag.className=&#39;tag-merged&#39;;<br>   tag.textContent=&#39;Merged&#39;;<br>   tag.title=&#39;This source image was already used in a previous merge&#39;;<br>   row.appendChild(tag);<br>  }<br>  list.appendChild(row);<br> });<br> if(status)status.textContent=`${count} of ${images.length} image(s) ticked for merge.`;<br>}<br><br>function mergeImages(direction){<br> const exclude=$(&#39;excludePreviouslyMerged&#39;)?.checked;<br> const selectedPairs=images.map((it,idx)=&gt;({it,idx}))<br>  .filter(({it})=&gt;it.selectedForMerge&amp;&amp;!(exclude&amp;&amp;it.alreadyMerged));<br> if(selectedPairs.length&lt;2){<br>  return alert(&#39;Tick at least two eligible images in the Merge Images checklist.&#39;);<br> }<br> const source=selectedPairs.map(p=&gt;p.it);<br> const canvas=document.createElement(&#39;canvas&#39;);<br> const c=canvas.getContext(&#39;2d&#39;);<br> if(direction===&#39;vertical&#39;){<br>  canvas.width=Math.max(...source.map(x=&gt;x.width));<br>  canvas.height=source.reduce((n,x)=&gt;n+x.height,0);<br>  let y=0;<br>  source.forEach(x=&gt;{c.drawImage(x.img,0,y);y+=x.height;});<br> }else{<br>  canvas.width=source.reduce((n,x)=&gt;n+x.width,0);<br>  canvas.height=Math.max(...source.map(x=&gt;x.height));<br>  let x=0;<br>  source.forEach(i=&gt;{c.drawImage(i.img,x,0);x+=i.width;});<br> }<br> const mergedPageLabels=selectedPairs.map(p=&gt;`P${p.idx+1}`).join(&#39;+&#39;);<br> const title=source[0].title||pageTitles[0]||$(&#39;projectName&#39;).value.trim()||&#39;Merged Evidence&#39;;<br> canvas.toBlob(async blob=&gt;{<br>  if(!blob)return alert(&#39;Could not merge the screenshots. The combined image may be too large.&#39;);<br>  try{<br>   source.forEach(srcItem=&gt;{<br>    srcItem.alreadyMerged=true;<br>    srcItem.selectedForMerge=false;<br>   });<br>   const merged=await makeItem(blob,`Merged (${mergedPageLabels}) ${direction} ${stamp()}`);<br>   merged.title=`${title} [${mergedPageLabels}]`;<br>   merged.include=true;<br>   merged.alreadyMerged=false;<br>   merged.selectedForMerge=false;<br>   annotations.forEach(a=&gt;{a.image+=1;});<br>   images.unshift(merged);<br>   current=0;selected=null;history=[];<br>   showImage();renderImages();render();<br>   $(&#39;imageStatus&#39;).textContent=`Page 1 of ${images.length} · ${merged.title} · merged ${source.length} selected screenshot(s)`;<br>   $(&#39;dataMsg&#39;).textContent=`Merged ${mergedPageLabels} into Page 1. Those source images are now flagged &quot;Merged&quot; and excluded from future merges unless unchecked/reset.`;<br>   persistConfig();<br>  }catch(err){console.error(err);alert(&#39;Merge failed: &#39;+err.message);}<br> },&#39;image/png&#39;);<br>}<br><br>// ---------- REPORTS VIEWER, SAVE, DOWNLOAD &amp; PRINT ----------<br>function openReportsModal(){<br> const modal=$(&#39;reportsModal&#39;);<br> if(!modal)return;<br> renderReportsModal();<br> modal.classList.add(&#39;open&#39;);<br>}<br>function closeReportsModal(){<br> const modal=$(&#39;reportsModal&#39;);<br> if(modal)modal.classList.remove(&#39;open&#39;);<br>}<br>function buildReportData(){<br> const projName=$(&#39;projectName&#39;).value.trim()||&#39;QA Evidence&#39;;<br> const generatedAt=new Date().toLocaleString();<br> const pages=images.map((it,idx)=&gt;{<br>  const pageAnns=annotations.filter(a=&gt;a.image===idx).sort((a,b)=&gt;a.label-b.label);<br>  const rows=extractedRows(idx).map(r=&gt;{<br>   const ann=pageAnns.find(a=&gt;Number(a.label)===Number(r[0]));<br>   const f=fieldFor(Number(r[0]));<br>   const isManual=f&amp;&amp;f.mode===&#39;manual&#39;;<br>   const status=isManual?&#39;Manual&#39;:(ann?(ann.status===&#39;done&#39;?&#39;OCR Verified&#39;:(ann.status===&#39;error&#39;?&#39;OCR Error&#39;:&#39;Edited/Pending&#39;)):&#39;Manual&#39;);<br>   return{num:r[0],field:r[1],value:r[2],status,confidence:ann&amp;&amp;ann.confidence?ann.confidence+&#39;%&#39;:&#39;—&#39;};<br>  });<br>  return{<br>   pageNum:idx+1,<br>   name:it.name,<br>   title:it.title||pageTitles[idx]||it.name,<br>   include:it.include!==false,<br>   alreadyMerged:!!it.alreadyMerged,<br>   width:it.width,<br>   height:it.height,<br>   boxCount:pageAnns.length,<br>   rows<br>  };<br> });<br> const totalExtracted=pages.reduce((s,p)=&gt;s+p.rows.length,0);<br> return{projName,generatedAt,pages,totalPages:images.length,totalBoxes:annotations.length,totalExtracted};<br>}<br>function renderReportsModal(){<br> const body=$(&#39;reportsModalBody&#39;);<br> if(!body)return;<br> const rep=buildReportData();<br> const showThumbs=$(&#39;reportIncludeThumbs&#39;)?.checked;<br> $(&#39;reportSubtitle&#39;).textContent=`${rep.projName} · Generated ${rep.generatedAt}`;<br> if(!rep.pages.length){<br>  body.innerHTML=&#39;&lt;div class=&quot;empty&quot;&gt;&lt;strong&gt;No screenshots or report data yet&lt;/strong&gt;&lt;div&gt;Capture or upload images and label fields to generate reports.&lt;/div&gt;&lt;/div&gt;&#39;;<br>  return;<br> }<br> let html=`<br>  &lt;div class=&quot;report-summary-grid&quot;&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.totalPages}&lt;/strong&gt;&lt;span&gt;Total Pages&lt;/span&gt;&lt;/div&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.totalBoxes}&lt;/strong&gt;&lt;span&gt;Labeled Boxes&lt;/span&gt;&lt;/div&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.totalExtracted}&lt;/strong&gt;&lt;span&gt;Total Data Rows&lt;/span&gt;&lt;/div&gt;<br>   &lt;div class=&quot;report-kpi&quot;&gt;&lt;strong&gt;${rep.pages.filter(p=&gt;p.include).length}&lt;/strong&gt;&lt;span&gt;Pages Included in Docs&lt;/span&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br> `;<br> rep.pages.forEach((p,idx)=&gt;{<br>  let thumbHtml=&#39;&#39;;<br>  if(showThumbs){<br>   const c=createExportCanvas(idx);<br>   if(c){<br>    const scaled=scaleCanvas(c,720);<br>    thumbHtml=`&lt;img class=&quot;report-thumb&quot; src=&quot;${scaled.toDataURL(&#39;image/png&#39;)}&quot; alt=&quot;Page ${p.pageNum}&quot;&gt;`;<br>   }<br>  }<br>  const rowsHtml=p.rows.length<br>   ? `&lt;table class=&quot;data-table&quot;&gt;&lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:65px&quot;&gt;#&lt;/th&gt;&lt;th style=&quot;width:28%&quot;&gt;Field Name&lt;/th&gt;&lt;th&gt;Extracted / Manual Value&lt;/th&gt;&lt;th style=&quot;width:120px&quot;&gt;Source&lt;/th&gt;&lt;th style=&quot;width:80px&quot;&gt;Conf.&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;${p.rows.map(r=&gt;`&lt;tr&gt;&lt;td&gt;#${xesc(r.num)}&lt;/td&gt;&lt;td&gt;${xesc(r.field)}&lt;/td&gt;&lt;td&gt;${xesc(r.value)}&lt;/td&gt;&lt;td&gt;${xesc(r.status)}&lt;/td&gt;&lt;td&gt;${xesc(r.confidence)}&lt;/td&gt;&lt;/tr&gt;`).join(&#39;&#39;)}&lt;/tbody&gt;&lt;/table&gt;`<br>   : `&lt;div class=&quot;small&quot;&gt;No labeled fields on this page.&lt;/div&gt;`;<br>  html+=`<br>   &lt;div class=&quot;report-page-card&quot;&gt;<br>    &lt;div class=&quot;report-page-head&quot;&gt;<br>     &lt;div&gt;&lt;strong&gt;Page ${p.pageNum}: ${xesc(p.title)}&lt;/strong&gt; &lt;span class=&quot;small&quot;&gt;(${xesc(p.name)} · ${p.width}×${p.height})&lt;/span&gt;&lt;/div&gt;<br>     &lt;div class=&quot;small&quot;&gt;${p.boxCount} box(es) · ${p.include?&#39;In Docs&#39;:&#39;Excluded from Docs&#39;}${p.alreadyMerged?&#39; · Merged Source&#39;:&#39;&#39;}&lt;/div&gt;<br>    &lt;/div&gt;<br>    ${rowsHtml}<br>    ${thumbHtml}<br>   &lt;/div&gt;<br>  `;<br> });<br> body.innerHTML=html;<br>}<br>function downloadReportCSV(){<br> const rep=buildReportData();<br> const escCsv=v=&gt;`&quot;${String(v??&#39;&#39;).replace(/&quot;/g,&#39;&quot;&quot;&#39;)}&quot;`;<br> const lines=[[&#39;Page #&#39;,&#39;Page Header&#39;,&#39;File Name&#39;,&#39;In Docs&#39;,&#39;Label #&#39;,&#39;Field Name&#39;,&#39;Value&#39;,&#39;Source&#39;,&#39;Confidence&#39;].map(escCsv).join(&#39;,&#39;)];<br> rep.pages.forEach(p=&gt;{<br>  if(!p.rows.length){<br>   lines.push([p.pageNum,p.title,p.name,p.include?&#39;Yes&#39;:&#39;No&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;No annotations&#39;,&#39;&#39;].map(escCsv).join(&#39;,&#39;));<br>  }else{<br>   p.rows.forEach(r=&gt;{<br>    lines.push([p.pageNum,p.title,p.name,p.include?&#39;Yes&#39;:&#39;No&#39;,r.num,r.field,r.value,r.status,r.confidence].map(escCsv).join(&#39;,&#39;));<br>   });<br>  }<br> });<br> const blob=new Blob([&#39;\uFEFF&#39;+lines.join(&#39;\r\n&#39;)],{type:&#39;text/csv;charset=utf-8&#39;});<br> downloadBlob(blob,`${safeName(rep.projName)}-Report-${stamp()}.csv`);<br>}<br>function downloadReportHTML(){<br> const rep=buildReportData();<br> const showThumbs=$(&#39;reportIncludeThumbs&#39;)?.checked;<br> let sections=&#39;&#39;;<br> rep.pages.forEach((p,idx)=&gt;{<br>  let imgTag=&#39;&#39;;<br>  if(showThumbs){<br>   const c=createExportCanvas(idx);<br>   if(c){<br>    const scaled=scaleCanvas(c,1100);<br>    imgTag=`&lt;div style=&quot;margin-top:10px&quot;&gt;&lt;img src=&quot;${scaled.toDataURL(&#39;image/png&#39;)}&quot; style=&quot;max-width:100%;border:1px solid #cbd5e1;border-radius:6px&quot;&gt;&lt;/div&gt;`;<br>   }<br>  }<br>  const tbl=p.rows.length<br>   ? `&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th style=&quot;width:60px&quot;&gt;#&lt;/th&gt;&lt;th style=&quot;width:28%&quot;&gt;Field&lt;/th&gt;&lt;th&gt;Value&lt;/th&gt;&lt;th style=&quot;width:120px&quot;&gt;Source&lt;/th&gt;&lt;th style=&quot;width:80px&quot;&gt;Conf.&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;${p.rows.map(r=&gt;`&lt;tr&gt;&lt;td&gt;#${xesc(r.num)}&lt;/td&gt;&lt;td&gt;${xesc(r.field)}&lt;/td&gt;&lt;td&gt;${xesc(r.value)}&lt;/td&gt;&lt;td&gt;${xesc(r.status)}&lt;/td&gt;&lt;td&gt;${xesc(r.confidence)}&lt;/td&gt;&lt;/tr&gt;`).join(&#39;&#39;)}&lt;/tbody&gt;&lt;/table&gt;`<br>   : `&lt;p style=&quot;color:#64748b;font-size:13px&quot;&gt;No labeled fields on this page.&lt;/p&gt;`;<br>  sections+=`&lt;section class=&quot;card&quot;&gt;&lt;h2&gt;Page ${p.pageNum}: ${xesc(p.title)}&lt;/h2&gt;&lt;div class=&quot;meta&quot;&gt;File: ${xesc(p.name)} · Dimensions: ${p.width}×${p.height} · Boxes: ${p.boxCount}&lt;/div&gt;${tbl}${imgTag}&lt;/section&gt;`;<br> });<br> const doc=`&lt;!DOCTYPE html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;UTF-8&quot;&gt;&lt;title&gt;${xesc(rep.projName)} - QA Report&lt;/title&gt;&lt;style&gt;body{font-family:Arial,sans-serif;background:#f8fafc;color:#0f172a;margin:24px}h1{margin:0 0 4px}.sub{color:#475569;font-size:13px;margin-bottom:18px}.kpis{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:18px}.kpi{background:#fff;border:1px solid #cbd5e1;border-radius:8px;padding:10px 14px;min-width:130px}.kpi strong{display:block;font-size:20px}.card{background:#fff;border:1px solid #cbd5e1;border-radius:10px;padding:16px;margin-bottom:16px;page-break-inside:avoid}h2{margin:0 0 4px;font-size:16px}.meta{color:#64748b;font-size:12px;margin-bottom:10px}table{width:100%;border-collapse:collapse;font-size:13px}th,td{border:1px solid #cbd5e1;padding:7px 9px;text-align:left}th{background:#e2e8f0}@media print{body{background:#fff;margin:10px}}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;${xesc(rep.projName)} — QA Report&lt;/h1&gt;&lt;div class=&quot;sub&quot;&gt;Generated ${xesc(rep.generatedAt)}&lt;/div&gt;&lt;div class=&quot;kpis&quot;&gt;&lt;div class=&quot;kpi&quot;&gt;&lt;strong&gt;${rep.totalPages}&lt;/strong&gt;&lt;span&gt;Pages&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;kpi&quot;&gt;&lt;strong&gt;${rep.totalBoxes}&lt;/strong&gt;&lt;span&gt;Labeled Boxes&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;kpi&quot;&gt;&lt;strong&gt;${rep.totalExtracted}&lt;/strong&gt;&lt;span&gt;Extracted Rows&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;${sections}&lt;/body&gt;&lt;/html&gt;`;<br> downloadBlob(new Blob([doc],{type:&#39;text/html;charset=utf-8&#39;}),`${safeName(rep.projName)}-Report-${stamp()}.html`);<br>}<br>function printReport(){<br> renderReportsModal();<br> window.print();<br>}<br><br>// ---------- PNG EXPORT ----------<br>function drawExportAnnotation(c,a,width){<br> c.save();c.strokeStyle=a.color;c.fillStyle=a.color;<br> c.lineWidth=Math.max(3,width/500);<br> if(a.type===&#39;circle&#39;){<br>  const r=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>  c.beginPath();c.arc(a.x+a.w/2,a.y+a.h/2,r,0,Math.PI*2);c.stroke();<br>  c.font=`bold ${Math.max(14,r)}px Arial`;<br>  c.textAlign=&#39;center&#39;;c.textBaseline=&#39;middle&#39;;<br>  c.fillText(String(a.label),a.x+a.w/2,a.y+a.h/2);<br> }else{<br>  c.strokeRect(a.x,a.y,a.w,a.h);<br>  const mw=Math.max(32,String(a.label).length*11+15);<br>  c.fillRect(a.x,Math.max(0,a.y-25),mw,25);<br>  c.fillStyle=&#39;white&#39;;c.font=&#39;bold 15px Arial&#39;;<br>  c.textAlign=&#39;center&#39;;c.textBaseline=&#39;middle&#39;;<br>  c.fillText(String(a.label),a.x+mw/2,Math.max(0,a.y-25)+12.5);<br> }<br> c.restore();<br>}<br><br>function createExportCanvas(index){<br> const item=images[index];if(!item)return null;<br> const canvas=document.createElement(&#39;canvas&#39;);<br> canvas.width=item.width;canvas.height=item.height;<br> const c=canvas.getContext(&#39;2d&#39;);<br> c.drawImage(item.img,0,0);<br> annotations.filter(a=&gt;a.image===index).forEach(a=&gt;drawExportAnnotation(c,a,item.width));<br> return canvas;<br>}<br><br>function downloadCanvas(canvas,name){<br> canvas.toBlob(blob=&gt;{<br>  if(!blob)return alert(&#39;Could not export image. It may be too large.&#39;);<br>  downloadBlob(blob,name);<br> },&#39;image/png&#39;);<br>}<br><br>function exportPNG(){<br> if(current&lt;0)return alert(&#39;Load a screenshot first.&#39;);<br> const canvas=createExportCanvas(current);<br> if(canvas)downloadCanvas(canvas,`QA-Evidence-${Date.now()}.png`);<br>}<br><br>function exportAllPNG(){<br> if(!images.length)return alert(&#39;No screenshots to export.&#39;);<br> images.forEach((item,i)=&gt;{<br>  const canvas=createExportCanvas(i);<br>  if(canvas)downloadCanvas(canvas,`QA-Evidence-${i+1}.png`);<br> });<br>}<br><br>// ---------- DOCX EXPORT (no external library) ----------<br>// ZIP-BEGIN<br>const crcTable=(()=&gt;{const t=new Uint32Array(256);for(let n=0;n&lt;256;n++){let c=n;for(let k=0;k&lt;8;k++)c=c&amp;1?0xEDB88320^(c&gt;&gt;&gt;1):c&gt;&gt;&gt;1;t[n]=c&gt;&gt;&gt;0}return t})();<br>function crc32(buf){let c=0xFFFFFFFF;for(let i=0;i&lt;buf.length;i++)c=crcTable[(c^buf[i])&amp;255]^(c&gt;&gt;&gt;8);return (c^0xFFFFFFFF)&gt;&gt;&gt;0}<br>function makeZip(files,mime){<br> const enc=new TextEncoder();<br> const chunks=[],central=[];let offset=0;<br> files.forEach(f=&gt;{<br>  const nameB=enc.encode(f.name);<br>  const crc=crc32(f.data),size=f.data.length;<br>  const lh=new DataView(new ArrayBuffer(30));<br>  lh.setUint32(0,0x04034b50,true);lh.setUint16(4,20,true);lh.setUint16(6,0x0800,true);lh.setUint16(8,0,true);<br>  lh.setUint16(10,0,true);lh.setUint16(12,0x21,true);<br>  lh.setUint32(14,crc,true);lh.setUint32(18,size,true);lh.setUint32(22,size,true);<br>  lh.setUint16(26,nameB.length,true);lh.setUint16(28,0,true);<br>  chunks.push(new Uint8Array(lh.buffer),nameB,f.data);<br>  const ch=new DataView(new ArrayBuffer(46));<br>  ch.setUint32(0,0x02014b50,true);ch.setUint16(4,20,true);ch.setUint16(6,20,true);ch.setUint16(8,0x0800,true);ch.setUint16(10,0,true);<br>  ch.setUint16(12,0,true);ch.setUint16(14,0x21,true);<br>  ch.setUint32(16,crc,true);ch.setUint32(20,size,true);ch.setUint32(24,size,true);<br>  ch.setUint16(28,nameB.length,true);ch.setUint16(30,0,true);ch.setUint16(32,0,true);ch.setUint16(34,0,true);ch.setUint16(36,0,true);<br>  ch.setUint32(38,0,true);ch.setUint32(42,offset,true);<br>  central.push(new Uint8Array(ch.buffer),nameB);<br>  offset+=30+nameB.length+size;<br> });<br> const cdSize=central.reduce((n,c)=&gt;n+c.length,0);<br> const end=new DataView(new ArrayBuffer(22));<br> end.setUint32(0,0x06054b50,true);end.setUint16(4,0,true);end.setUint16(6,0,true);<br> end.setUint16(8,files.length,true);end.setUint16(10,files.length,true);<br> end.setUint32(12,cdSize,true);end.setUint32(16,offset,true);end.setUint16(20,0,true);<br> return new Blob([...chunks,...central,new Uint8Array(end.buffer)],{type:mime||&#39;application/zip&#39;});<br>}<br>// ZIP-END<br><br>const xesc=s=&gt;String(s??&#39;&#39;).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,&#39;&#39;).replace(/&amp;/g,&#39;&amp;amp;&#39;).replace(/&lt;/g,&#39;&amp;lt;&#39;).replace(/&gt;/g,&#39;&amp;gt;&#39;).replace(/&quot;/g,&#39;&amp;quot;&#39;);<br>function wRun(t,o={}){<br> return `&lt;w:r&gt;&lt;w:rPr&gt;${o.b?&#39;&lt;w:b/&gt;&#39;:&#39;&#39;}${o.color?`&lt;w:color w:val=&quot;${o.color}&quot;/&gt;`:&#39;&#39;}${o.sz?`&lt;w:sz w:val=&quot;${o.sz}&quot;/&gt;&lt;w:szCs w:val=&quot;${o.sz}&quot;/&gt;`:&#39;&#39;}&lt;/w:rPr&gt;&lt;w:t xml:space=&quot;preserve&quot;&gt;${xesc(t)}&lt;/w:t&gt;&lt;/w:r&gt;`;<br>}<br>function wPara(inner,ppr=&#39;&#39;){return `&lt;w:p&gt;${ppr?`&lt;w:pPr&gt;${ppr}&lt;/w:pPr&gt;`:&#39;&#39;}${inner}&lt;/w:p&gt;`}<br>function wTable(rows){<br> const W=[900,3000,6180];<br> const bd=[&#39;top&#39;,&#39;left&#39;,&#39;bottom&#39;,&#39;right&#39;,&#39;insideH&#39;,&#39;insideV&#39;].map(s=&gt;`&lt;w:${s} w:val=&quot;single&quot; w:sz=&quot;4&quot; w:space=&quot;0&quot; w:color=&quot;999999&quot;/&gt;`).join(&#39;&#39;);<br> let x=`&lt;w:tbl&gt;&lt;w:tblPr&gt;&lt;w:tblW w:w=&quot;10080&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:tblBorders&gt;${bd}&lt;/w:tblBorders&gt;&lt;w:tblLayout w:type=&quot;fixed&quot;/&gt;&lt;w:tblCellMar&gt;&lt;w:top w:w=&quot;40&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:left w:w=&quot;100&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:bottom w:w=&quot;40&quot; w:type=&quot;dxa&quot;/&gt;&lt;w:right w:w=&quot;100&quot; w:type=&quot;dxa&quot;/&gt;&lt;/w:tblCellMar&gt;&lt;/w:tblPr&gt;&lt;w:tblGrid&gt;${W.map(w=&gt;`&lt;w:gridCol w:w=&quot;${w}&quot;/&gt;`).join(&#39;&#39;)}&lt;/w:tblGrid&gt;`;<br> rows.forEach((r,ri)=&gt;{<br>  x+=`&lt;w:tr&gt;${ri===0?&#39;&lt;w:trPr&gt;&lt;w:tblHeader/&gt;&lt;/w:trPr&gt;&#39;:&#39;&#39;}`;<br>  r.forEach((c,ci)=&gt;{<br>   x+=`&lt;w:tc&gt;&lt;w:tcPr&gt;&lt;w:tcW w:w=&quot;${W[ci]}&quot; w:type=&quot;dxa&quot;/&gt;${ri===0?&#39;&lt;w:shd w:val=&quot;clear&quot; w:color=&quot;auto&quot; w:fill=&quot;D9E2F3&quot;/&gt;&#39;:&#39;&#39;}&lt;/w:tcPr&gt;${wPara(wRun(c,{b:ri===0}))}&lt;/w:tc&gt;`;<br>  });<br>  x+=&#39;&lt;/w:tr&gt;&#39;;<br> });<br> return x+&#39;&lt;/w:tbl&gt;&#39;;<br>}<br>function wImage(n,rid,cx,cy){<br> return `&lt;w:p&gt;&lt;w:pPr&gt;&lt;w:spacing w:after=&quot;120&quot;/&gt;&lt;/w:pPr&gt;&lt;w:r&gt;&lt;w:drawing&gt;&lt;wp:inline distT=&quot;0&quot; distB=&quot;0&quot; distL=&quot;0&quot; distR=&quot;0&quot;&gt;&lt;wp:extent cx=&quot;${cx}&quot; cy=&quot;${cy}&quot;/&gt;&lt;wp:docPr id=&quot;${n}&quot; name=&quot;Picture ${n}&quot;/&gt;&lt;a:graphic&gt;&lt;a:graphicData uri=&quot;http://schemas.openxmlformats.org/drawingml/2006/picture&quot;&gt;&lt;pic:pic&gt;&lt;pic:nvPicPr&gt;&lt;pic:cNvPr id=&quot;${n}&quot; name=&quot;image${n}.png&quot;/&gt;&lt;pic:cNvPicPr/&gt;&lt;/pic:nvPicPr&gt;&lt;pic:blipFill&gt;&lt;a:blip r:embed=&quot;${rid}&quot;/&gt;&lt;a:stretch&gt;&lt;a:fillRect/&gt;&lt;/a:stretch&gt;&lt;/pic:blipFill&gt;&lt;pic:spPr&gt;&lt;a:xfrm&gt;&lt;a:off x=&quot;0&quot; y=&quot;0&quot;/&gt;&lt;a:ext cx=&quot;${cx}&quot; cy=&quot;${cy}&quot;/&gt;&lt;/a:xfrm&gt;&lt;a:prstGeom prst=&quot;rect&quot;&gt;&lt;a:avLst/&gt;&lt;/a:prstGeom&gt;&lt;/pic:spPr&gt;&lt;/pic:pic&gt;&lt;/a:graphicData&gt;&lt;/a:graphic&gt;&lt;/wp:inline&gt;&lt;/w:drawing&gt;&lt;/w:r&gt;&lt;/w:p&gt;`;<br>}<br>function scaleCanvas(src,maxW){<br> if(src.width&lt;=maxW)return src;<br> const k=maxW/src.width;<br> const c=document.createElement(&#39;canvas&#39;);<br> c.width=maxW;c.height=Math.round(src.height*k);<br> const g=c.getContext(&#39;2d&#39;);g.imageSmoothingQuality=&#39;high&#39;;<br> g.drawImage(src,0,0,c.width,c.height);<br> return c;<br>}<br><br>async function exportDocx(){<br> const sel=images.map((it,i)=&gt;({it,i})).filter(x=&gt;x.it.include!==false);<br> if(!sel.length)return alert(&#39;No pages are ticked &quot;In docs&quot;. Tick at least one page.&#39;);<br> if(annotations.some(a=&gt;a.status===&#39;pending&#39;)&amp;&amp;!confirm(&#39;OCR is still reading some boxes. Export anyway?&#39;))return;<br> const withImg=$(&#39;docImages&#39;).checked,withTable=$(&#39;docTables&#39;).checked;<br> const projName=$(&#39;projectName&#39;).value.trim()||&#39;QA Evidence&#39;;<br> const enc=new TextEncoder();<br> const files=[],rels=[];<br> let body=&#39;&#39;,n=0;<br><br> body+=wPara(wRun(projName,{b:1,sz:44}),&#39;&lt;w:spacing w:after=&quot;120&quot;/&gt;&#39;);<br> body+=wPara(wRun(`Generated ${new Date().toLocaleString()} · ${sel.length} page(s)`,{sz:20,color:&#39;666666&#39;}),&#39;&lt;w:spacing w:after=&quot;240&quot;/&gt;&#39;);<br> const manual=fields.filter(f=&gt;f.mode===&#39;manual&#39;);<br> if(manual.length){<br>  body+=wPara(wRun(&#39;Manual fields&#39;,{b:1,sz:28}),&#39;&lt;w:keepNext/&gt;&lt;w:spacing w:before=&quot;120&quot; w:after=&quot;120&quot;/&gt;&#39;);<br>  body+=wTable([[&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;],...manual.map(f=&gt;[&#39;#&#39;+f.num,f.name,f.value])]);<br> }<br><br> for(const {it,i} of sel){<br>  body+=wPara(wRun(it.title||pageTitles[i]||it.name,{b:1,sz:32}),`${i===sel[0].i?&#39;&#39;:&#39;&lt;w:pageBreakBefore/&gt;&#39;}&lt;w:keepNext/&gt;&lt;w:spacing w:after=&quot;60&quot;/&gt;&lt;w:outlineLvl w:val=&quot;0&quot;/&gt;`);<br>  body+=wPara(wRun(`Page ${i+1} · ${it.name}`,{sz:18,color:&#39;777777&#39;}),&#39;&lt;w:keepNext/&gt;&lt;w:spacing w:after=&quot;120&quot;/&gt;&#39;);<br>  if(withImg){<br>   n++;<br>   const canvas=scaleCanvas(createExportCanvas(i),1800);<br>   const blob=await new Promise(r=&gt;canvas.toBlob(r,&#39;image/png&#39;));<br>   if(!blob)return alert(&#39;Could not render page &#39;+(i+1)+&#39; for the docs file.&#39;);<br>   const data=new Uint8Array(await blob.arrayBuffer());<br>   files.push({name:`word/media/image${n}.png`,data});<br>   rels.push(`&lt;Relationship Id=&quot;rId${n+10}&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/image&quot; Target=&quot;media/image${n}.png&quot;/&gt;`);<br>   let cx=canvas.width*9525,cy=canvas.height*9525;<br>   const k=Math.min(1,6400800/cx,5943600/cy);<br>   cx=Math.round(cx*k);cy=Math.round(cy*k);<br>   body+=wImage(n,`rId${n+10}`,cx,cy);<br>  }<br>  if(withTable){<br>   const rows=extractedRows(i);<br>   if(rows.length)body+=wTable([[&#39;#&#39;,&#39;Field&#39;,&#39;Value&#39;],...rows.map(r=&gt;[&#39;#&#39;+r[0],r[1],r[2]])]);<br>   else body+=wPara(wRun(&#39;No annotations on this page.&#39;,{sz:20,color:&#39;777777&#39;}));<br>  }<br> }<br><br> const NS=&#39;xmlns:w=&quot;http://schemas.openxmlformats.org/wordprocessingml/2006/main&quot; xmlns:r=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships&quot; xmlns:wp=&quot;http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing&quot; xmlns:a=&quot;http://schemas.openxmlformats.org/drawingml/2006/main&quot; xmlns:pic=&quot;http://schemas.openxmlformats.org/drawingml/2006/picture&quot;&#39;;<br> const head=&#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;&#39;;<br> const docXml=`${head}&lt;w:document ${NS}&gt;&lt;w:body&gt;${body}&lt;w:p/&gt;&lt;w:sectPr&gt;&lt;w:pgSz w:w=&quot;12240&quot; w:h=&quot;15840&quot;/&gt;&lt;w:pgMar w:top=&quot;1080&quot; w:right=&quot;1080&quot; w:bottom=&quot;1080&quot; w:left=&quot;1080&quot; w:header=&quot;720&quot; w:footer=&quot;720&quot; w:gutter=&quot;0&quot;/&gt;&lt;/w:sectPr&gt;&lt;/w:body&gt;&lt;/w:document&gt;`;<br> const stylesXml=`${head}&lt;w:styles xmlns:w=&quot;http://schemas.openxmlformats.org/wordprocessingml/2006/main&quot;&gt;&lt;w:docDefaults&gt;&lt;w:rPrDefault&gt;&lt;w:rPr&gt;&lt;w:rFonts w:ascii=&quot;Calibri&quot; w:hAnsi=&quot;Calibri&quot; w:cs=&quot;Calibri&quot;/&gt;&lt;w:sz w:val=&quot;22&quot;/&gt;&lt;w:szCs w:val=&quot;22&quot;/&gt;&lt;/w:rPr&gt;&lt;/w:rPrDefault&gt;&lt;w:pPrDefault&gt;&lt;w:pPr&gt;&lt;w:spacing w:after=&quot;0&quot; w:line=&quot;259&quot; w:lineRule=&quot;auto&quot;/&gt;&lt;/w:pPr&gt;&lt;/w:pPrDefault&gt;&lt;/w:docDefaults&gt;&lt;/w:styles&gt;`;<br> const ctypes=`${head}&lt;Types xmlns=&quot;http://schemas.openxmlformats.org/package/2006/content-types&quot;&gt;&lt;Default Extension=&quot;rels&quot; ContentType=&quot;application/vnd.openxmlformats-package.relationships+xml&quot;/&gt;&lt;Default Extension=&quot;xml&quot; ContentType=&quot;application/xml&quot;/&gt;&lt;Default Extension=&quot;png&quot; ContentType=&quot;image/png&quot;/&gt;&lt;Override PartName=&quot;/word/document.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml&quot;/&gt;&lt;Override PartName=&quot;/word/styles.xml&quot; ContentType=&quot;application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml&quot;/&gt;&lt;/Types&gt;`;<br> const rootRels=`${head}&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;&lt;Relationship Id=&quot;rId1&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument&quot; Target=&quot;word/document.xml&quot;/&gt;&lt;/Relationships&gt;`;<br> const docRels=`${head}&lt;Relationships xmlns=&quot;http://schemas.openxmlformats.org/package/2006/relationships&quot;&gt;&lt;Relationship Id=&quot;rId1&quot; Type=&quot;http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles&quot; Target=&quot;styles.xml&quot;/&gt;${rels.join(&#39;&#39;)}&lt;/Relationships&gt;`;<br><br> const all=[<br>  {name:&#39;[Content_Types].xml&#39;,data:enc.encode(ctypes)},<br>  {name:&#39;_rels/.rels&#39;,data:enc.encode(rootRels)},<br>  {name:&#39;word/document.xml&#39;,data:enc.encode(docXml)},<br>  {name:&#39;word/styles.xml&#39;,data:enc.encode(stylesXml)},<br>  {name:&#39;word/_rels/document.xml.rels&#39;,data:enc.encode(docRels)},<br>  ...files<br> ];<br> const blob=makeZip(all,&#39;application/vnd.openxmlformats-officedocument.wordprocessingml.document&#39;);<br> downloadBlob(blob,`${safeName(projName)}-${stamp()}.docx`);<br>}<br><br>function updateStats(){<br> $(&#39;statImages&#39;).textContent=images.length;<br> $(&#39;statAnnotations&#39;).textContent=annotations.length;<br> $(&#39;statLabels&#39;).textContent=labels.length;<br>}<br><br>$(&#39;pageTitlesText&#39;).addEventListener(&#39;input&#39;,()=&gt;{<br> pageTitles=$(&#39;pageTitlesText&#39;).value.split(/\\r?\\n/).map(x=&gt;x.trim()).filter(Boolean);<br> images.forEach((it,i)=&gt;{if(pageTitles[i])it.title=pageTitles[i];});<br> renderImages();persistConfig();<br>});<br>$(&#39;projectName&#39;).addEventListener(&#39;input&#39;,persistConfig);<br>// ---------- INITIALIZE ----------<br>(async function initializeStudio(){<br> loadLocalConfig();<br> const restored=await restoreWorkspaceAuto();<br> drawLabels();<br> renderFields();<br> renderImages();<br> renderMergeChecklist();<br> if(current&gt;=0)showImage();else render();<br> updateStats();<br> if(!restored)scheduleWorkspaceAutosave();<br>})();<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0127147d1c9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VisualQA ProInteractive Box & Config Studio]]></title>
            <link>https://medium.com/@barabonajansen/visualqa-prointeractive-box-config-studio-f0f727a6439e?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f727a6439e</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 10:36:47 GMT</pubDate>
            <atom:updated>2026-11-14T10:36:47.964Z</atom:updated>
            <content:encoded><![CDATA[<pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;VisualQA Pro — Interactive Box Editor &amp; Config Studio&lt;/title&gt;<br>    <br>    &lt;!-- Libraries via CDN --&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/lucide@latest&quot;&gt;&lt;/script&gt;<br><br>    &lt;style&gt;<br>        :root {<br>            --bg-dark: #0f172a;<br>            --bg-panel: #1e293b;<br>            --bg-card: #273548;<br>            --border-color: #334155;<br>            --text-main: #f8fafc;<br>            --text-muted: #94a3b8;<br>            --primary: #3b82f6;<br>            --primary-hover: #2563eb;<br>            --success: #10b981;<br>            --danger: #ef4444;<br>            --warning: #f59e0b;<br>            --accent-purple: #8b5cf6;<br>        }<br><br>        * {<br>            box-sizing: border-box;<br>            margin: 0;<br>            padding: 0;<br>            font-family: &#39;Inter&#39;, -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Roboto, sans-serif;<br>        }<br><br>        body {<br>            background-color: var(--bg-dark);<br>            color: var(--text-main);<br>            height: 100vh;<br>            display: flex;<br>            flex-direction: column;<br>            overflow: hidden;<br>        }<br><br>        header {<br>            height: 58px;<br>            background-color: var(--bg-panel);<br>            border-bottom: 1px solid var(--border-color);<br>            display: flex;<br>            align-items: center;<br>            justify-content: space-between;<br>            padding: 0 20px;<br>            z-index: 20;<br>        }<br><br>        .brand {<br>            display: flex;<br>            align-items: center;<br>            gap: 10px;<br>            font-weight: 700;<br>            font-size: 1.1rem;<br>        }<br><br>        .brand-badge {<br>            background: linear-gradient(135deg, var(--primary), var(--accent-purple));<br>            padding: 4px 8px;<br>            border-radius: 6px;<br>            font-size: 0.75rem;<br>            text-transform: uppercase;<br>        }<br><br>        .toolbar-actions {<br>            display: flex;<br>            align-items: center;<br>            gap: 8px;<br>        }<br><br>        button, .btn {<br>            background-color: var(--bg-card);<br>            color: var(--text-main);<br>            border: 1px solid var(--border-color);<br>            padding: 7px 12px;<br>            border-radius: 6px;<br>            font-size: 0.82rem;<br>            font-weight: 500;<br>            cursor: pointer;<br>            display: inline-flex;<br>            align-items: center;<br>            gap: 6px;<br>            transition: all 0.15s ease;<br>        }<br><br>        button:hover { background-color: #334155; border-color: #475569; }<br>        button.primary { background-color: var(--primary); border-color: var(--primary); color: white; }<br>        button.primary:hover { background-color: var(--primary-hover); }<br>        button.success { background-color: rgba(16, 185, 129, 0.15); border-color: var(--success); color: #34d399; }<br>        button.danger-btn { background-color: rgba(239, 68, 68, 0.15); border-color: rgba(239, 68, 68, 0.4); color: #fca5a5; }<br>        button.danger-btn:hover { background-color: rgba(239, 68, 68, 0.3); color: #fff; }<br>        button.active-tool { background-color: var(--primary); border-color: #60a5fa; box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3); }<br><br>        .workspace {<br>            display: grid;<br>            grid-template-columns: 270px 1fr 455px;<br>            flex: 1;<br>            overflow: hidden;<br>        }<br><br>        .sidebar-left {<br>            background-color: var(--bg-panel);<br>            border-right: 1px solid var(--border-color);<br>            display: flex;<br>            flex-direction: column;<br>            overflow: hidden;<br>        }<br><br>        .panel-header {<br>            padding: 12px 14px;<br>            border-bottom: 1px solid var(--border-color);<br>            display: flex;<br>            justify-content: space-between;<br>            align-items: center;<br>            font-size: 0.84rem;<br>            font-weight: 600;<br>            text-transform: uppercase;<br>            color: var(--text-muted);<br>            gap: 6px;<br>        }<br><br>        .upload-zone {<br>            padding: 12px;<br>            border-bottom: 1px solid var(--border-color);<br>            display: flex;<br>            flex-direction: column;<br>            gap: 8px;<br>        }<br><br>        .option-tabs {<br>            display: grid;<br>            grid-template-columns: 1fr 1fr;<br>            gap: 4px;<br>            background: var(--bg-dark);<br>            padding: 4px;<br>            border-radius: 6px;<br>        }<br><br>        .option-tab {<br>            text-align: center;<br>            padding: 6px;<br>            font-size: 0.75rem;<br>            border-radius: 4px;<br>            cursor: pointer;<br>            color: var(--text-muted);<br>            border: none;<br>            background: transparent;<br>        }<br><br>        .option-tab.active { background: var(--bg-card); color: var(--text-main); font-weight: 600; }<br><br>        .sheet-list {<br>            flex: 1;<br>            overflow-y: auto;<br>            padding: 8px;<br>            display: flex;<br>            flex-direction: column;<br>            gap: 6px;<br>        }<br><br>        .sheet-item {<br>            background-color: var(--bg-card);<br>            border: 1px solid var(--border-color);<br>            border-radius: 8px;<br>            padding: 10px;<br>            cursor: pointer;<br>            transition: all 0.15s;<br>            display: flex;<br>            flex-direction: column;<br>            gap: 6px;<br>        }<br><br>        .sheet-item:hover { border-color: #64748b; }<br>        .sheet-item.selected { border-color: var(--primary); background-color: rgba(59, 130, 246, 0.12); }<br><br>        .sheet-item-top {<br>            display: flex;<br>            justify-content: space-between;<br>            align-items: center;<br>            gap: 6px;<br>        }<br><br>        .index-badge {<br>            background: var(--primary);<br>            color: white;<br>            font-size: 0.72rem;<br>            font-weight: 700;<br>            padding: 2px 7px;<br>            border-radius: 4px;<br>            white-space: nowrap;<br>        }<br><br>        .sheet-title-input {<br>            background: transparent;<br>            border: 1px solid transparent;<br>            color: var(--text-main);<br>            font-size: 0.85rem;<br>            font-weight: 600;<br>            width: 100%;<br>            padding: 2px 4px;<br>            border-radius: 4px;<br>        }<br><br>        .sheet-title-input:focus { outline: none; background: var(--bg-dark); border-color: var(--primary); }<br><br>        .sheet-meta {<br>            display: flex;<br>            justify-content: space-between;<br>            align-items: center;<br>            font-size: 0.74rem;<br>            color: var(--text-muted);<br>        }<br><br>        .canvas-workspace {<br>            display: flex;<br>            flex-direction: column;<br>            background-color: #090d16;<br>            overflow: hidden;<br>        }<br><br>        .canvas-toolbar {<br>            background-color: var(--bg-panel);<br>            border-bottom: 1px solid var(--border-color);<br>            padding: 8px 14px;<br>            display: flex;<br>            flex-wrap: wrap;<br>            align-items: center;<br>            justify-content: space-between;<br>            gap: 8px;<br>        }<br><br>        .tool-group { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }<br><br>        .dual-canvas-container {<br>            flex: 1;<br>            display: grid;<br>            grid-template-columns: 1fr 1fr;<br>            gap: 2px;<br>            background-color: var(--border-color);<br>            overflow: hidden;<br>        }<br><br>        .image-pane {<br>            background-color: #0b1120;<br>            display: flex;<br>            flex-direction: column;<br>            overflow: hidden;<br>            position: relative;<br>        }<br><br>        .pane-header {<br>            background-color: rgba(30, 41, 59, 0.95);<br>            padding: 8px 12px;<br>            border-bottom: 1px solid var(--border-color);<br>            display: flex;<br>            justify-content: space-between;<br>            align-items: center;<br>            font-size: 0.8rem;<br>            font-weight: 600;<br>            z-index: 5;<br>        }<br><br>        .pane-scroll {<br>            flex: 1;<br>            overflow: auto;<br>            display: flex;<br>            padding: 24px;<br>            position: relative;<br>            background-image: radial-gradient(#1e293b 1.2px, transparent 1.2px);<br>            background-size: 20px 20px;<br>        }<br><br>        .canvas-wrapper {<br>            margin: auto;<br>            position: relative;<br>            display: flex;<br>            align-items: center;<br>            justify-content: center;<br>            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.8);<br>            border: 1px solid #334155;<br>            background: #0f172a;<br>            flex-shrink: 0;<br>        }<br><br>        canvas { display: block; cursor: crosshair; }<br><br>        .empty-state {<br>            position: absolute;<br>            inset: 0;<br>            display: flex;<br>            flex-direction: column;<br>            align-items: center;<br>            justify-content: center;<br>            color: var(--text-muted);<br>            text-align: center;<br>            padding: 20px;<br>            pointer-events: none;<br>            background: #0b1120;<br>        }<br><br>        .sidebar-right {<br>            background-color: var(--bg-panel);<br>            border-left: 1px solid var(--border-color);<br>            display: flex;<br>            flex-direction: column;<br>            overflow: hidden;<br>        }<br><br>        .summary-bar {<br>            display: grid;<br>            grid-template-columns: repeat(3, 1fr);<br>            gap: 8px;<br>            padding: 10px 12px;<br>            background-color: var(--bg-dark);<br>            border-bottom: 1px solid var(--border-color);<br>        }<br><br>        .stat-box { background: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 6px; padding: 6px; text-align: center; }<br>        .stat-val { font-size: 1.2rem; font-weight: 700; }<br>        .stat-label { font-size: 0.68rem; color: var(--text-muted); text-transform: uppercase; }<br><br>        .requirements-list {<br>            flex: 1;<br>            overflow-y: auto;<br>            padding: 12px;<br>            display: flex;<br>            flex-direction: column;<br>            gap: 10px;<br>        }<br><br>        .req-card {<br>            background-color: var(--bg-card);<br>            border: 1px solid var(--border-color);<br>            border-radius: 8px;<br>            padding: 10px;<br>            display: flex;<br>            flex-direction: column;<br>            gap: 8px;<br>            transition: border-color 0.15s;<br>        }<br><br>        .req-card.selected { border-color: var(--warning); box-shadow: 0 0 0 1px var(--warning); }<br><br>        .req-card-header { display: flex; align-items: center; justify-content: space-between; gap: 5px; }<br>        .req-num-input {<br>            background: var(--accent-purple);<br>            color: white;<br>            font-weight: 700;<br>            font-size: 0.78rem;<br>            width: 40px;<br>            text-align: center;<br>            border: none;<br>            padding: 4px;<br>            border-radius: 4px;<br>        }<br>        .req-name-input { flex: 1; background: var(--bg-dark); border: 1px solid var(--border-color); color: var(--text-main); padding: 4px 8px; border-radius: 4px; font-size: 0.82rem; font-weight: 600; min-width: 90px; }<br><br>        .template-select {<br>            background: var(--bg-dark);<br>            border: 1px solid var(--border-color);<br>            color: var(--text-muted);<br>            font-size: 0.74rem;<br>            padding: 4px 6px;<br>            border-radius: 4px;<br>            cursor: pointer;<br>            max-width: 115px;<br>        }<br>        .template-select:hover { color: var(--text-main); border-color: var(--primary); }<br><br>        .comparison-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }<br>        .val-box { background: var(--bg-dark); border: 1px solid var(--border-color); border-radius: 6px; padding: 6px 8px; }<br>        .val-label { font-size: 0.68rem; text-transform: uppercase; color: var(--text-muted); display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }<br>        .val-label-actions { display: flex; align-items: center; gap: 4px; }<br>        .mini-icon-btn {<br>            background: transparent;<br>            border: 1px solid transparent;<br>            color: var(--text-muted);<br>            padding: 1px 4px;<br>            font-size: 0.68rem;<br>            border-radius: 3px;<br>            cursor: pointer;<br>        }<br>        .mini-icon-btn:hover { background: #1e293b; color: var(--text-main); border-color: #475569; }<br>        .mini-icon-btn.del:hover { color: #f87171; border-color: rgba(239,68,68,0.4); }<br><br>        .val-input { width: 100%; background: transparent; border: none; color: var(--text-main); font-size: 0.82rem; font-family: monospace; resize: vertical; min-height: 36px; }<br>        .val-input:focus { outline: 1px solid var(--primary); border-radius: 3px; }<br><br>        .req-footer { display: flex; justify-content: space-between; align-items: center; font-size: 0.74rem; padding-top: 5px; border-top: 1px solid rgba(255,255,255,0.06); }<br>        .status-pill { padding: 2px 7px; border-radius: 99px; font-size: 0.68rem; font-weight: 700; text-transform: uppercase; }<br>        .status-pass { background: rgba(16, 185, 129, 0.2); color: #34d399; }<br>        .status-fail { background: rgba(239, 68, 68, 0.2); color: #f87171; }<br>        .status-pending { background: rgba(148, 163, 184, 0.2); color: #cbd5e1; }<br><br>        #toast {<br>            position: fixed; bottom: 20px; right: 20px; background: var(--bg-panel); border: 1px solid var(--primary);<br>            color: var(--text-main); padding: 12px 18px; border-radius: 8px; box-shadow: 0 10px 25px rgba(0,0,0,0.5);<br>            font-size: 0.85rem; display: none; align-items: center; gap: 10px; z-index: 100;<br>        }<br>        .spinner { width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.2); border-top-color: var(--primary); border-radius: 50%; animation: spin 0.8s linear infinite; }<br>        @keyframes spin { to { transform: rotate(360deg); } }<br><br>        .modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.75); display: none; align-items: center; justify-content: center; z-index: 50; }<br>        .modal { background: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 12px; width: 85%; max-width: 900px; max-height: 85vh; display: flex; flex-direction: column; overflow: hidden; }<br>        .modal-header { padding: 16px 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }<br>        .modal-body { padding: 20px; overflow-y: auto; }<br>        <br>        table.report-table, table.config-table { width: 100%; border-collapse: collapse; font-size: 0.83rem; }<br>        table.report-table th, table.report-table td, table.config-table th, table.config-table td { border: 1px solid var(--border-color); padding: 8px 10px; text-align: left; }<br>        table.report-table th, table.config-table th { background: var(--bg-dark); color: var(--text-muted); }<br>        <br>        .cfg-input {<br>            width: 100%;<br>            background: var(--bg-dark);<br>            border: 1px solid var(--border-color);<br>            color: var(--text-main);<br>            padding: 6px 8px;<br>            border-radius: 4px;<br>            font-size: 0.83rem;<br>        }<br>        .cfg-input:focus { outline: none; border-color: var(--primary); }<br><br>        input[type=&quot;file&quot;] { display: none; }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>    &lt;header&gt;<br>        &lt;div class=&quot;brand&quot;&gt;<br>            &lt;i data-lucide=&quot;scan-eye&quot; style=&quot;color: #60a5fa;&quot;&gt;&lt;/i&gt;<br>            &lt;span&gt;VisualQA Pro&lt;/span&gt;<br>            &lt;span class=&quot;brand-badge&quot;&gt;Interactive Box &amp; Config Studio&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;toolbar-actions&quot;&gt;<br>            &lt;button onclick=&quot;document.getElementById(&#39;importJsonInput&#39;).click()&quot;&gt;&lt;i data-lucide=&quot;folder-open&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Import JSON&lt;/button&gt;<br>            &lt;input type=&quot;file&quot; id=&quot;importJsonInput&quot; accept=&quot;.json&quot; onchange=&quot;importProjectJSON(event)&quot;&gt;<br>            &lt;button onclick=&quot;exportProjectJSON()&quot;&gt;&lt;i data-lucide=&quot;save&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Save Project JSON&lt;/button&gt;<br>            &lt;button class=&quot;success&quot; onclick=&quot;openReportModal()&quot;&gt;&lt;i data-lucide=&quot;file-spreadsheet&quot; size=&quot;15&quot;&gt;&lt;/i&gt; QA Report &amp; CSV&lt;/button&gt;<br>        &lt;/div&gt;<br>    &lt;/header&gt;<br><br>    &lt;div class=&quot;workspace&quot;&gt;<br>        &lt;aside class=&quot;sidebar-left&quot;&gt;<br>            &lt;div class=&quot;panel-header&quot;&gt;<br>                &lt;span&gt;1. Requirement Sheets&lt;/span&gt;<br>                &lt;span id=&quot;sheetCountBadge&quot; style=&quot;color: var(--primary);&quot;&gt;0 Items&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;upload-zone&quot;&gt;<br>                &lt;div class=&quot;option-tabs&quot;&gt;<br>                    &lt;button class=&quot;option-tab active&quot; id=&quot;tabOpt1&quot; onclick=&quot;switchUploadMode(1)&quot;&gt;Option 1: Docs/PDF&lt;/button&gt;<br>                    &lt;button class=&quot;option-tab&quot; id=&quot;tabOpt2&quot; onclick=&quot;switchUploadMode(2)&quot;&gt;Option 2: Batch Images&lt;/button&gt;<br>                &lt;/div&gt;<br>                &lt;div id=&quot;opt1Panel&quot;&gt;<br>                    &lt;button class=&quot;primary&quot; style=&quot;width: 100%; justify-content: center;&quot; onclick=&quot;document.getElementById(&#39;docUploadInput&#39;).click()&quot;&gt;<br>                        &lt;i data-lucide=&quot;file-text&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Upload DOCX or PDF<br>                    &lt;/button&gt;<br>                    &lt;input type=&quot;file&quot; id=&quot;docUploadInput&quot; accept=&quot;.docx,.pdf&quot; onchange=&quot;handleDocOrPdfUpload(event)&quot;&gt;<br>                &lt;/div&gt;<br>                &lt;div id=&quot;opt2Panel&quot; style=&quot;display: none;&quot;&gt;<br>                    &lt;button class=&quot;primary&quot; style=&quot;width: 100%; justify-content: center;&quot; onclick=&quot;document.getElementById(&#39;batchOrigImagesInput&#39;).click()&quot;&gt;<br>                        &lt;i data-lucide=&quot;images&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Upload Orig Images (70+)<br>                    &lt;/button&gt;<br>                    &lt;input type=&quot;file&quot; id=&quot;batchOrigImagesInput&quot; accept=&quot;image/*&quot; multiple onchange=&quot;handleBatchOrigImages(event)&quot;&gt;<br>                &lt;/div&gt;<br>                &lt;button style=&quot;width: 100%; justify-content: center; font-size: 0.76rem;&quot; onclick=&quot;addBlankSheet()&quot;&gt;<br>                    &lt;i data-lucide=&quot;plus&quot; size=&quot;14&quot;&gt;&lt;/i&gt; Add Manual Sheet<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;sheet-list&quot; id=&quot;sheetList&quot;&gt;&lt;/div&gt;<br>        &lt;/aside&gt;<br><br>        &lt;main class=&quot;canvas-workspace&quot;&gt;<br>            &lt;div class=&quot;canvas-toolbar&quot;&gt;<br>                &lt;div class=&quot;tool-group&quot;&gt;<br>                    &lt;button id=&quot;toolDrawBox&quot; class=&quot;active-tool&quot; onclick=&quot;setTool(&#39;draw&#39;)&quot; title=&quot;Draw new box or re-draw selected box&quot;&gt;&lt;i data-lucide=&quot;box-select&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Draw Box&lt;/button&gt;<br>                    &lt;button id=&quot;toolSelect&quot; onclick=&quot;setTool(&#39;select&#39;)&quot; title=&quot;Click &amp; drag any box or corner handle to move/resize&quot;&gt;&lt;i data-lucide=&quot;move&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Edit / Move Box&lt;/button&gt;<br>                    &lt;button onclick=&quot;autoDetectRedBoxesCurrent()&quot; style=&quot;border-color: #ef4444; color: #fca5a5;&quot; title=&quot;Detect red numbered boxes on current sheet&quot;&gt;<br>                        &lt;i data-lucide=&quot;scan&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Detect Red Boxes (Sheet)<br>                    &lt;/button&gt;<br>                    &lt;button onclick=&quot;autoDetectRedBoxesAllSheets()&quot; style=&quot;border-color: #f87171; background: rgba(239,68,68,0.12); color: #fecaca;&quot; title=&quot;Detect red boxes across all sheets&quot;&gt;<br>                        &lt;i data-lucide=&quot;layers&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Detect All Sheets<br>                    &lt;/button&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;tool-group&quot;&gt;<br>                    &lt;button onclick=&quot;lockDevBoxesToAllSheets()&quot; class=&quot;primary&quot; title=&quot;Lock &amp; copy Developing Output fixed box positions to ALL sheets&quot;&gt;<br>                        &lt;i data-lucide=&quot;lock&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Lock Output Boxes to All<br>                    &lt;/button&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;tool-group&quot;&gt;<br>                    &lt;button onclick=&quot;fitImagesToView()&quot;&gt;&lt;i data-lucide=&quot;maximize-2&quot; size=&quot;14&quot;&gt;&lt;/i&gt; Fit&lt;/button&gt;<br>                    &lt;button onclick=&quot;changeZoom(-0.15)&quot;&gt;&lt;i data-lucide=&quot;zoom-out&quot; size=&quot;14&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                    &lt;span id=&quot;zoomLabel&quot; style=&quot;font-size: 0.78rem; min-width: 42px; text-align: center;&quot;&gt;100%&lt;/span&gt;<br>                    &lt;button onclick=&quot;changeZoom(0.15)&quot;&gt;&lt;i data-lucide=&quot;zoom-in&quot; size=&quot;14&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;dual-canvas-container&quot;&gt;<br>                &lt;div class=&quot;image-pane&quot;&gt;<br>                    &lt;div class=&quot;pane-header&quot;&gt;<br>                        &lt;span style=&quot;color: #60a5fa;&quot;&gt;&lt;i data-lucide=&quot;file-check-2&quot; size=&quot;14&quot;&gt;&lt;/i&gt; ORIGINAL REQUIREMENT IMAGE (RED BOXES)&lt;/span&gt;<br>                        &lt;div&gt;<br>                            &lt;button style=&quot;padding: 3px 8px; font-size: 0.74rem;&quot; onclick=&quot;document.getElementById(&#39;singleOrigUpload&#39;).click()&quot;&gt;Replace&lt;/button&gt;<br>                            &lt;input type=&quot;file&quot; id=&quot;singleOrigUpload&quot; accept=&quot;image/*&quot; onchange=&quot;replaceCurrentImage(&#39;orig&#39;, event)&quot;&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;pane-scroll&quot; id=&quot;origScrollPane&quot;&gt;<br>                        &lt;div class=&quot;canvas-wrapper&quot; id=&quot;origWrapper&quot;&gt;&lt;canvas id=&quot;origCanvas&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>                        &lt;div class=&quot;empty-state&quot; id=&quot;origEmptyState&quot;&gt;&lt;i data-lucide=&quot;image-plus&quot; size=&quot;36&quot;&gt;&lt;/i&gt;&lt;div&gt;No Original Requirement Image&lt;/div&gt;&lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;image-pane&quot;&gt;<br>                    &lt;div class=&quot;pane-header&quot;&gt;<br>                        &lt;span style=&quot;color: #34d399;&quot;&gt;&lt;i data-lucide=&quot;monitor-check&quot; size=&quot;14&quot;&gt;&lt;/i&gt; DEVELOPING OUTPUT (CLICK BOX TO EDIT)&lt;/span&gt;<br>                        &lt;div&gt;<br>                            &lt;button style=&quot;padding: 3px 8px; font-size: 0.74rem;&quot; onclick=&quot;document.getElementById(&#39;singleDevUpload&#39;).click()&quot;&gt;Attach Output&lt;/button&gt;<br>                            &lt;input type=&quot;file&quot; id=&quot;singleDevUpload&quot; accept=&quot;image/*&quot; onchange=&quot;replaceCurrentImage(&#39;dev&#39;, event)&quot;&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;pane-scroll&quot; id=&quot;devScrollPane&quot;&gt;<br>                        &lt;div class=&quot;canvas-wrapper&quot; id=&quot;devWrapper&quot;&gt;&lt;canvas id=&quot;devCanvas&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>                        &lt;div class=&quot;empty-state&quot; id=&quot;devEmptyState&quot;&gt;&lt;i data-lucide=&quot;layout-template&quot; size=&quot;36&quot;&gt;&lt;/i&gt;&lt;div&gt;Attach Developing Output Screenshot&lt;/div&gt;&lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/main&gt;<br><br>        &lt;aside class=&quot;sidebar-right&quot;&gt;<br>            &lt;div class=&quot;panel-header&quot;&gt;<br>                &lt;span&gt;2. Box Requirements &amp; QA&lt;/span&gt;<br>                &lt;div style=&quot;display: flex; gap: 6px;&quot;&gt;<br>                    &lt;button style=&quot;padding: 4px 8px; font-size: 0.75rem;&quot; onclick=&quot;openConfigModal()&quot; title=&quot;Configure sequential numbers and field label names&quot;&gt;<br>                        &lt;i data-lucide=&quot;settings&quot; size=&quot;13&quot;&gt;&lt;/i&gt; Field Config<br>                    &lt;/button&gt;<br>                    &lt;button class=&quot;primary&quot; style=&quot;padding: 4px 8px; font-size: 0.75rem;&quot; onclick=&quot;addManualRequirement()&quot; title=&quot;Add next sequential box from Field Config&quot;&gt;<br>                        + Add Box<br>                    &lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;summary-bar&quot;&gt;<br>                &lt;div class=&quot;stat-box&quot;&gt;&lt;div class=&quot;stat-val&quot; id=&quot;statTotal&quot;&gt;0&lt;/div&gt;&lt;div class=&quot;stat-label&quot;&gt;Total&lt;/div&gt;&lt;/div&gt;<br>                &lt;div class=&quot;stat-box&quot;&gt;&lt;div class=&quot;stat-val&quot; id=&quot;statPass&quot; style=&quot;color: var(--success);&quot;&gt;0&lt;/div&gt;&lt;div class=&quot;stat-label&quot;&gt;Pass&lt;/div&gt;&lt;/div&gt;<br>                &lt;div class=&quot;stat-box&quot;&gt;&lt;div class=&quot;stat-val&quot; id=&quot;statFail&quot; style=&quot;color: var(--danger);&quot;&gt;0&lt;/div&gt;&lt;div class=&quot;stat-label&quot;&gt;Fail&lt;/div&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div style=&quot;padding: 7px 12px; background: rgba(59,130,246,0.08); border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; font-size: 0.74rem; align-items: center;&quot;&gt;<br>                &lt;label style=&quot;display: flex; align-items: center; gap: 6px; cursor: pointer;&quot;&gt;<br>                    &lt;input type=&quot;checkbox&quot; id=&quot;fuzzyMatchToggle&quot; checked onchange=&quot;recalculateAllStatuses()&quot;&gt; Smart Normalize<br>                &lt;/label&gt;<br>                &lt;span style=&quot;color: #fbbf24; font-weight: 600;&quot; id=&quot;activeTargetLabel&quot;&gt;Ready&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;requirements-list&quot; id=&quot;requirementsList&quot;&gt;&lt;/div&gt;<br>        &lt;/aside&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- Field Sequence &amp; Label Config Modal --&gt;<br>    &lt;div class=&quot;modal-backdrop&quot; id=&quot;configModal&quot;&gt;<br>        &lt;div class=&quot;modal&quot; style=&quot;max-width: 650px;&quot;&gt;<br>            &lt;div class=&quot;modal-header&quot;&gt;<br>                &lt;h3 style=&quot;font-size: 1rem;&quot;&gt;⚙️ Field Sequence &amp; Label Config Table&lt;/h3&gt;<br>                &lt;div style=&quot;display: flex; gap: 8px;&quot;&gt;<br>                    &lt;button class=&quot;primary&quot; onclick=&quot;addConfigRow()&quot;&gt;+ Add Row&lt;/button&gt;<br>                    &lt;button class=&quot;success&quot; onclick=&quot;applyConfigToCurrentSheet()&quot;&gt;Apply Names to Current Sheet&lt;/button&gt;<br>                    &lt;button onclick=&quot;closeConfigModal()&quot;&gt;Done&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;modal-body&quot;&gt;<br>                &lt;p style=&quot;font-size: 0.8rem; color: var(--text-muted); margin-bottom: 12px;&quot;&gt;<br>                    Configure your standard sequential numbers and field names below. Clicking &lt;b&gt;+ Add Box&lt;/b&gt; or picking from the dropdown will automatically pull from this table.<br>                &lt;/p&gt;<br>                &lt;table class=&quot;config-table&quot;&gt;<br>                    &lt;thead&gt;<br>                        &lt;tr&gt;<br>                            &lt;th style=&quot;width: 90px;&quot;&gt;Box #&lt;/th&gt;<br>                            &lt;th&gt;Field Label Name&lt;/th&gt;<br>                            &lt;th style=&quot;width: 70px; text-align: center;&quot;&gt;Action&lt;/th&gt;<br>                        &lt;/tr&gt;<br>                    &lt;/thead&gt;<br>                    &lt;tbody id=&quot;configTableBody&quot;&gt;&lt;/tbody&gt;<br>                &lt;/table&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- QA Report Modal --&gt;<br>    &lt;div class=&quot;modal-backdrop&quot; id=&quot;reportModal&quot;&gt;<br>        &lt;div class=&quot;modal&quot;&gt;<br>            &lt;div class=&quot;modal-header&quot;&gt;<br>                &lt;h3 style=&quot;font-size: 1rem;&quot;&gt;QA Validation Report&lt;/h3&gt;<br>                &lt;div style=&quot;display: flex; gap: 8px;&quot;&gt;<br>                    &lt;button class=&quot;success&quot; onclick=&quot;exportExcelReport()&quot;&gt;&lt;i data-lucide=&quot;download&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Export Excel (.xlsx)&lt;/button&gt;<br>                    &lt;button class=&quot;success&quot; onclick=&quot;exportCsvReport()&quot;&gt;&lt;i data-lucide=&quot;file-text&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Export CSV&lt;/button&gt;<br>                    &lt;button class=&quot;primary&quot; onclick=&quot;exportHtmlReport()&quot;&gt;&lt;i data-lucide=&quot;file-code&quot; size=&quot;15&quot;&gt;&lt;/i&gt; Export HTML&lt;/button&gt;<br>                    &lt;button onclick=&quot;closeReportModal()&quot;&gt;Close&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;modal-body&quot; id=&quot;reportModalBody&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div id=&quot;toast&quot;&gt;<br>        &lt;div class=&quot;spinner&quot; id=&quot;toastSpinner&quot;&gt;&lt;/div&gt;<br>        &lt;span id=&quot;toastText&quot;&gt;Processing...&lt;/span&gt;<br>    &lt;/div&gt;<br><br>    &lt;script&gt;<br>        pdfjsLib.GlobalWorkerOptions.workerSrc = &#39;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js&#39;;<br><br>        let state = {<br>            sheets: [],<br>            activeSheetId: null,<br>            currentTool: &#39;draw&#39;,<br>            zoom: 1.0,<br>            selectedReqId: null,<br>            activeRedrawTarget: null, // { reqId, side } when user clicks re-draw on a specific box<br>            lockedDevTemplate: [],<br>            fieldConfig: [<br>                { number: 1, name: &quot;Quality Acceptance Report&quot; },<br>                { number: 2, name: &quot;Customer Name&quot; },<br>                { number: 3, name: &quot;Report ID&quot; },<br>                { number: 4, name: &quot;Report Date&quot; },<br>                { number: 5, name: &quot;Status&quot; },<br>                { number: 6, name: &quot;Account Code&quot; },<br>                { number: 7, name: &quot;Total Amount&quot; },<br>                { number: 8, name: &quot;Contact Email&quot; },<br>                { number: 9, name: &quot;Reviewer&quot; }<br>            ]<br>        };<br><br>        let tesseractWorker = null;<br>        let origImgObj = new Image();<br>        let devImgObj = new Image();<br><br>        // Canvas interaction states (drawing new box OR moving/resizing existing box)<br>        let interactionMode = null; // &#39;draw&#39; | &#39;move&#39; | &#39;resize-nw&#39; | &#39;resize-ne&#39; | &#39;resize-sw&#39; | &#39;resize-se&#39;<br>        let activeCanvasSide = null; // &#39;orig&#39; | &#39;dev&#39;<br>        let startX = 0, startY = 0, currX = 0, currY = 0;<br>        let initialBoxSnapshot = null;<br><br>        window.addEventListener(&#39;DOMContentLoaded&#39;, async () =&gt; {<br>            lucide.createIcons();<br>            setupCanvasEvents(&#39;origCanvas&#39;, &#39;orig&#39;);<br>            setupCanvasEvents(&#39;devCanvas&#39;, &#39;dev&#39;);<br>            window.addEventListener(&#39;resize&#39;, () =&gt; applyDisplayZoom());<br>            addBlankSheet(&quot;Requirement #1&quot;);<br><br>            try { tesseractWorker = await Tesseract.createWorker(&#39;eng&#39;); } catch (e) {}<br>        });<br><br>        function getConfiguredNameForNumber(num) {<br>            const found = state.fieldConfig.find(c =&gt; Number(c.number) === Number(num));<br>            return found ? found.name : `Field #${num}`;<br>        }<br><br>        function getNextSequentialNumber(sheet) {<br>            const existingNums = new Set(sheet.requirements.map(r =&gt; Number(r.number)));<br>            // First check config table in order for any number not yet added<br>            const sortedCfg = [...state.fieldConfig].sort((a, b) =&gt; a.number - b.number);<br>            for (const item of sortedCfg) {<br>                if (!existingNums.has(Number(item.number))) return Number(item.number);<br>            }<br>            // Otherwise return max existing + 1<br>            const maxNum = sheet.requirements.reduce((m, r) =&gt; Math.max(m, Number(r.number) || 0), 0);<br>            return maxNum + 1;<br>        }<br><br>        async function runOcrOnCrop(imageObj, box, digitsOnly = false) {<br>            if (!imageObj || !imageObj.src || !box || box.w &lt; 4 || box.h &lt; 4) return &quot;&quot;;<br>            try {<br>                if (!tesseractWorker) tesseractWorker = await Tesseract.createWorker(&#39;eng&#39;);<br>                const scale = 2.5;<br>                const offCanvas = document.createElement(&#39;canvas&#39;);<br>                offCanvas.width = Math.round(box.w * scale);<br>                offCanvas.height = Math.round(box.h * scale);<br>                const ctx = offCanvas.getContext(&#39;2d&#39;);<br>                ctx.fillStyle = &quot;#FFFFFF&quot;;<br>                ctx.fillRect(0, 0, offCanvas.width, offCanvas.height);<br>                ctx.drawImage(imageObj, box.x, box.y, box.w, box.h, 0, 0, offCanvas.width, offCanvas.height);<br><br>                if (digitsOnly) {<br>                    const imgData = ctx.getImageData(0, 0, offCanvas.width, offCanvas.height);<br>                    const d = imgData.data;<br>                    for (let i = 0; i &lt; d.length; i += 4) {<br>                        const r = d[i], g = d[i+1], b = d[i+2];<br>                        if (r &gt; 180 &amp;&amp; g &gt; 180 &amp;&amp; b &gt; 180) {<br>                            d[i] = 0; d[i+1] = 0; d[i+2] = 0;<br>                        } else {<br>                            d[i] = 255; d[i+1] = 255; d[i+2] = 255;<br>                        }<br>                    }<br>                    ctx.putImageData(imgData, 0, 0);<br>                }<br><br>                const { data: { text } } = await tesseractWorker.recognize(offCanvas);<br>                const clean = text.replace(/\n+/g, &#39; &#39;).trim();<br>                if (digitsOnly) {<br>                    const match = clean.match(/\d+/);<br>                    return match ? parseInt(match[0], 10) : null;<br>                }<br>                return clean;<br>            } catch (err) {<br>                return digitsOnly ? null : &quot;&quot;;<br>            }<br>        }<br><br>        function switchUploadMode(opt) {<br>            document.getElementById(&#39;tabOpt1&#39;).classList.toggle(&#39;active&#39;, opt === 1);<br>            document.getElementById(&#39;tabOpt2&#39;).classList.toggle(&#39;active&#39;, opt === 2);<br>            document.getElementById(&#39;opt1Panel&#39;).style.display = opt === 1 ? &#39;block&#39; : &#39;none&#39;;<br>            document.getElementById(&#39;opt2Panel&#39;).style.display = opt === 2 ? &#39;block&#39; : &#39;none&#39;;<br>        }<br><br>        async function handleDocOrPdfUpload(event) {<br>            const file = event.target.files[0];<br>            if (!file) return;<br>            const ext = file.name.split(&#39;.&#39;).pop().toLowerCase();<br>            showToast(`Parsing ${file.name}...`, true);<br>            try {<br>                if (ext === &#39;docx&#39;) await parseDocxFile(file);<br>                else if (ext === &#39;pdf&#39;) await parsePdfFile(file);<br>            } catch (err) { alert(err.message); } finally { event.target.value = &#39;&#39;; hideToast(); }<br>        }<br><br>        async function parseDocxFile(file) {<br>            const arrayBuffer = await file.arrayBuffer();<br>            const result = await mammoth.convertToHtml({ arrayBuffer });<br>            const doc = new DOMParser().parseFromString(result.value, &#39;text/html&#39;);<br>            let currentTitle = file.name.replace(/\.docx$/i, &#39;&#39;);<br>            let extracted = [];<br>            Array.from(doc.body.children).forEach(el =&gt; {<br>                if ([&#39;H1&#39;, &#39;H2&#39;, &#39;H3&#39;].includes(el.tagName)) currentTitle = el.textContent.trim();<br>                el.querySelectorAll(&#39;img&#39;).forEach(img =&gt; {<br>                    if (img.src &amp;&amp; img.src.startsWith(&#39;data:image&#39;)) extracted.push({ title: currentTitle, src: img.src });<br>                });<br>            });<br>            if (state.sheets.length === 1 &amp;&amp; !state.sheets[0].origImageSrc) state.sheets = [];<br>            extracted.forEach(item =&gt; {<br>                const idx = state.sheets.length + 1;<br>                state.sheets.push({<br>                    id: &#39;s_&#39; + Math.random(),<br>                    index: idx,<br>                    title: `${idx}. ${item.title}`,<br>                    origImageSrc: item.src,<br>                    devImageSrc: null,<br>                    requirements: cloneLockedDevReqs()<br>                });<br>            });<br>            selectSheet(state.sheets[0].id);<br>            renderSheetList();<br>        }<br><br>        async function parsePdfFile(file) {<br>            const pdf = await pdfjsLib.getDocument({ data: await file.arrayBuffer() }).promise;<br>            if (state.sheets.length === 1 &amp;&amp; !state.sheets[0].origImageSrc) state.sheets = [];<br>            for (let i = 1; i &lt;= pdf.numPages; i++) {<br>                const page = await pdf.getPage(i);<br>                const viewport = page.getViewport({ scale: 1.5 });<br>                const canvas = document.createElement(&#39;canvas&#39;);<br>                canvas.width = viewport.width; canvas.height = viewport.height;<br>                await page.render({ canvasContext: canvas.getContext(&#39;2d&#39;), viewport }).promise;<br>                const idx = state.sheets.length + 1;<br>                state.sheets.push({<br>                    id: &#39;s_&#39; + Math.random(),<br>                    index: idx,<br>                    title: `${idx}. Page ${i}`,<br>                    origImageSrc: canvas.toDataURL(),<br>                    devImageSrc: null,<br>                    requirements: cloneLockedDevReqs()<br>                });<br>            }<br>            selectSheet(state.sheets[0].id);<br>            renderSheetList();<br>        }<br><br>        async function handleBatchOrigImages(event) {<br>            const files = Array.from(event.target.files);<br>            if (files.length === 0) return;<br>            files.sort((a, b) =&gt; a.name.localeCompare(b.name, undefined, { numeric: true }));<br>            showToast(`Loading ${files.length} images...`, true);<br>            if (state.sheets.length === 1 &amp;&amp; !state.sheets[0].origImageSrc) state.sheets = [];<br><br>            for (let i = 0; i &lt; files.length; i++) {<br>                const dataUrl = await readFileAsDataURL(files[i]);<br>                const idx = state.sheets.length + 1;<br>                state.sheets.push({<br>                    id: &#39;s_&#39; + Math.random(),<br>                    index: idx,<br>                    title: `Req #${idx} (${files[i].name.replace(/\.[^/.]+$/, &quot;&quot;)})`,<br>                    origImageSrc: dataUrl,<br>                    devImageSrc: null,<br>                    requirements: cloneLockedDevReqs()<br>                });<br>            }<br>            event.target.value = &#39;&#39;;<br>            selectSheet(state.sheets[0].id);<br>            renderSheetList();<br>            hideToast();<br>        }<br><br>        function cloneLockedDevReqs() {<br>            return JSON.parse(JSON.stringify(state.lockedDevTemplate || []));<br>        }<br><br>        function readFileAsDataURL(file) {<br>            return new Promise(res =&gt; { const r = new FileReader(); r.onload = () =&gt; res(r.result); r.readAsDataURL(file); });<br>        }<br><br>        function getActiveSheet() { return state.sheets.find(s =&gt; s.id === state.activeSheetId); }<br><br>        function addBlankSheet(title) {<br>            const idx = state.sheets.length + 1;<br>            state.sheets.push({<br>                id: &#39;s_&#39; + Math.random(),<br>                index: idx,<br>                title: title || `Req #${idx}`,<br>                origImageSrc: null,<br>                devImageSrc: null,<br>                requirements: cloneLockedDevReqs()<br>            });<br>            selectSheet(state.sheets[state.sheets.length - 1].id);<br>            renderSheetList();<br>        }<br><br>        function deleteSheet(id, e) {<br>            e.stopPropagation();<br>            if (state.sheets.length &lt;= 1) return;<br>            state.sheets = state.sheets.filter(s =&gt; s.id !== id);<br>            state.sheets.forEach((s, i) =&gt; s.index = i + 1);<br>            selectSheet(state.sheets[0].id);<br>            renderSheetList();<br>        }<br><br>        async function selectSheet(id) {<br>            state.activeSheetId = id;<br>            state.selectedReqId = null;<br>            state.activeRedrawTarget = null;<br>            const sheet = getActiveSheet();<br>            loadCanvasImages(sheet);<br>            renderSheetList();<br>            renderRequirementsPanel();<br>        }<br><br>        async function replaceCurrentImage(target, event) {<br>            const file = event.target.files[0];<br>            if (!file) return;<br>            const sheet = getActiveSheet();<br>            const dataUrl = await readFileAsDataURL(file);<br>            if (target === &#39;orig&#39;) sheet.origImageSrc = dataUrl;<br>            else sheet.devImageSrc = dataUrl;<br>            event.target.value = &#39;&#39;;<br>            loadCanvasImages(sheet);<br>            renderSheetList();<br>            setTimeout(() =&gt; runOcrForCurrentSheet(), 250);<br>        }<br><br>        function renderSheetList() {<br>            const list = document.getElementById(&#39;sheetList&#39;);<br>            document.getElementById(&#39;sheetCountBadge&#39;).textContent = `${state.sheets.length} Sheets`;<br>            list.innerHTML = &#39;&#39;;<br>            state.sheets.forEach(sheet =&gt; {<br>                const pass = sheet.requirements.filter(r =&gt; r.status === &#39;PASS&#39;).length;<br>                const fail = sheet.requirements.filter(r =&gt; r.status === &#39;FAIL&#39;).length;<br>                const st = fail &gt; 0 ? `${fail} Fail` : (pass &gt; 0 ? `${pass} Pass` : &#39;Pending&#39;);<br>                list.innerHTML += `<br>                    &lt;div class=&quot;sheet-item ${sheet.id === state.activeSheetId ? &#39;selected&#39; : &#39;&#39;}&quot; onclick=&quot;selectSheet(&#39;${sheet.id}&#39;)&quot;&gt;<br>                        &lt;div class=&quot;sheet-item-top&quot;&gt;<br>                            &lt;span class=&quot;index-badge&quot;&gt;#${sheet.index}&lt;/span&gt;<br>                            &lt;input class=&quot;sheet-title-input&quot; value=&quot;${escapeHtml(sheet.title)}&quot; onclick=&quot;event.stopPropagation()&quot; onchange=&quot;updateSheetTitle(&#39;${sheet.id}&#39;, this.value)&quot;&gt;<br>                            &lt;button style=&quot;border:none; background:transparent; color:#94a3b8;&quot; onclick=&quot;deleteSheet(&#39;${sheet.id}&#39;, event)&quot;&gt;✕&lt;/button&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;sheet-meta&quot;&gt;&lt;span&gt;${sheet.requirements.length} boxes&lt;/span&gt;&lt;span&gt;${st}&lt;/span&gt;&lt;/div&gt;<br>                    &lt;/div&gt;<br>                `;<br>            });<br>        }<br><br>        function updateSheetTitle(id, val) { const s = state.sheets.find(x =&gt; x.id === id); if (s) s.title = val; }<br><br>        function loadCanvasImages(sheet) {<br>            const origCanvas = document.getElementById(&#39;origCanvas&#39;);<br>            const devCanvas = document.getElementById(&#39;devCanvas&#39;);<br><br>            if (sheet.origImageSrc) {<br>                document.getElementById(&#39;origEmptyState&#39;).style.display = &#39;none&#39;;<br>                document.getElementById(&#39;origWrapper&#39;).style.display = &#39;flex&#39;;<br>                origImgObj = new Image();<br>                origImgObj.onload = () =&gt; {<br>                    origCanvas.width = origImgObj.width;<br>                    origCanvas.height = origImgObj.height;<br>                    fitImagesToView();<br>                    redrawAllCanvases();<br>                };<br>                origImgObj.src = sheet.origImageSrc;<br>            } else {<br>                document.getElementById(&#39;origEmptyState&#39;).style.display = &#39;flex&#39;;<br>                document.getElementById(&#39;origWrapper&#39;).style.display = &#39;none&#39;;<br>                origCanvas.width = 0; origCanvas.height = 0;<br>            }<br><br>            if (sheet.devImageSrc) {<br>                document.getElementById(&#39;devEmptyState&#39;).style.display = &#39;none&#39;;<br>                document.getElementById(&#39;devWrapper&#39;).style.display = &#39;flex&#39;;<br>                devImgObj = new Image();<br>                devImgObj.onload = () =&gt; {<br>                    devCanvas.width = devImgObj.width;<br>                    devCanvas.height = devImgObj.height;<br>                    fitImagesToView();<br>                    redrawAllCanvases();<br>                };<br>                devImgObj.src = sheet.devImageSrc;<br>            } else {<br>                document.getElementById(&#39;devEmptyState&#39;).style.display = &#39;flex&#39;;<br>                document.getElementById(&#39;devWrapper&#39;).style.display = &#39;none&#39;;<br>                devCanvas.width = 0; devCanvas.height = 0;<br>            }<br>        }<br><br>        function fitImagesToView() {<br>            const pane = document.getElementById(&#39;origScrollPane&#39;);<br>            const w = Math.max(200, pane.clientWidth - 48);<br>            const h = Math.max(200, pane.clientHeight - 48);<br>            const scales = [];<br>            if (origImgObj.width &gt; 0) scales.push(Math.min(w / origImgObj.width, h / origImgObj.height));<br>            if (devImgObj.width &gt; 0) scales.push(Math.min(w / devImgObj.width, h / devImgObj.height));<br>            let scale = scales.length &gt; 0 ? Math.min(1.0, ...scales) : 1.0;<br>            state.zoom = Math.max(0.15, scale);<br>            applyDisplayZoom();<br>        }<br><br>        function applyDisplayZoom() {<br>            document.getElementById(&#39;zoomLabel&#39;).textContent = Math.round(state.zoom * 100) + &#39;%&#39;;<br>            [&#39;origCanvas&#39;, &#39;devCanvas&#39;].forEach(id =&gt; {<br>                const c = document.getElementById(id);<br>                if (c.width &gt; 0) {<br>                    c.style.width = Math.round(c.width * state.zoom) + &#39;px&#39;;<br>                    c.style.height = Math.round(c.height * state.zoom) + &#39;px&#39;;<br>                }<br>            });<br>        }<br><br>        function changeZoom(d) {<br>            state.zoom = Math.max(0.15, Math.min(3.0, state.zoom + d));<br>            applyDisplayZoom();<br>            redrawAllCanvases();<br>        }<br><br>        function redrawAllCanvases() {<br>            const sheet = getActiveSheet();<br>            if (!sheet) return;<br>            drawCanvas(&#39;origCanvas&#39;, origImgObj, sheet.requirements, &#39;orig&#39;);<br>            drawCanvas(&#39;devCanvas&#39;, devImgObj, sheet.requirements, &#39;dev&#39;);<br>        }<br><br>        function drawCanvas(id, img, reqs, side) {<br>            const canvas = document.getElementById(id);<br>            if (!canvas.width) return;<br>            const ctx = canvas.getContext(&#39;2d&#39;);<br>            ctx.clearRect(0, 0, canvas.width, canvas.height);<br>            if (img.complete &amp;&amp; img.src) ctx.drawImage(img, 0, 0);<br><br>            const uiScale = Math.max(1, 1 / state.zoom);<br>            const handleSize = Math.round(8 * uiScale);<br><br>            reqs.forEach(req =&gt; {<br>                const b = side === &#39;orig&#39; ? req.origBox : req.devBox;<br>                if (!b) return;<br>                const sel = req.id === state.selectedReqId;<br>                let col = req.status === &#39;PASS&#39; ? &#39;#10b981&#39; : (req.status === &#39;FAIL&#39; ? &#39;#ef4444&#39; : &#39;#3b82f6&#39;);<br>                if (sel) col = &#39;#f59e0b&#39;;<br><br>                ctx.fillStyle = col + (sel ? &#39;38&#39; : &#39;22&#39;);<br>                ctx.fillRect(b.x, b.y, b.w, b.h);<br>                ctx.lineWidth = (sel ? 3 : 2) * uiScale;<br>                ctx.strokeStyle = col;<br>                ctx.strokeRect(b.x, b.y, b.w, b.h);<br><br>                // Draw corner resize handles when selected so user can easily drag/resize!<br>                if (sel) {<br>                    ctx.fillStyle = &#39;#ffffff&#39;;<br>                    ctx.strokeStyle = &#39;#0f172a&#39;;<br>                    ctx.lineWidth = 1.5 * uiScale;<br>                    const corners = [<br>                        [b.x, b.y],<br>                        [b.x + b.w, b.y],<br>                        [b.x, b.y + b.h],<br>                        [b.x + b.w, b.y + b.h]<br>                    ];<br>                    corners.forEach(([cx, cy]) =&gt; {<br>                        ctx.fillRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);<br>                        ctx.strokeRect(cx - handleSize / 2, cy - handleSize / 2, handleSize, handleSize);<br>                    });<br>                }<br><br>                const label = `#${req.number} ${req.name}`;<br>                ctx.font = `bold ${Math.round(12 * uiScale)}px Inter`;<br>                const tw = ctx.measureText(label).width;<br>                const bh = Math.round(20 * uiScale);<br>                const by = b.y - bh &gt;= 0 ? b.y - bh : b.y;<br>                ctx.fillStyle = col;<br>                ctx.fillRect(b.x, by, tw + (12 * uiScale), bh);<br>                ctx.fillStyle = &#39;#fff&#39;;<br>                ctx.fillText(label, b.x + (6 * uiScale), by + Math.round(14 * uiScale));<br>            });<br><br>            if (interactionMode === &#39;draw&#39; &amp;&amp; activeCanvasSide === side) {<br>                ctx.strokeStyle = &#39;#f59e0b&#39;;<br>                ctx.lineWidth = 2 * uiScale;<br>                ctx.strokeRect(Math.min(startX, currX), Math.min(startY, currY), Math.abs(currX - startX), Math.abs(currY - startY));<br>            }<br>        }<br><br>        function hitTestHandle(box, x, y, tolerance) {<br>            if (Math.abs(x - box.x) &lt;= tolerance &amp;&amp; Math.abs(y - box.y) &lt;= tolerance) return &#39;resize-nw&#39;;<br>            if (Math.abs(x - (box.x + box.w)) &lt;= tolerance &amp;&amp; Math.abs(y - box.y) &lt;= tolerance) return &#39;resize-ne&#39;;<br>            if (Math.abs(x - box.x) &lt;= tolerance &amp;&amp; Math.abs(y - (box.y + box.h)) &lt;= tolerance) return &#39;resize-sw&#39;;<br>            if (Math.abs(x - (box.x + box.w)) &lt;= tolerance &amp;&amp; Math.abs(y - (box.y + box.h)) &lt;= tolerance) return &#39;resize-se&#39;;<br>            return null;<br>        }<br><br>        function setupCanvasEvents(id, side) {<br>            const canvas = document.getElementById(id);<br><br>            canvas.addEventListener(&#39;mousedown&#39;, (e) =&gt; {<br>                const sheet = getActiveSheet();<br>                if (!sheet) return;<br>                const rect = canvas.getBoundingClientRect();<br>                const x = (e.clientX - rect.left) * (canvas.width / rect.width);<br>                const y = (e.clientY - rect.top) * (canvas.height / rect.height);<br>                const tolerance = Math.max(8, 10 / state.zoom);<br><br>                // 1. If user explicitly armed a specific box to re-draw, start drawing immediately<br>                if (state.activeRedrawTarget &amp;&amp; state.activeRedrawTarget.side === side) {<br>                    interactionMode = &#39;draw&#39;;<br>                    activeCanvasSide = side;<br>                    startX = currX = x; startY = currY = y;<br>                    return;<br>                }<br><br>                // 2. Check if clicking an existing box or its resize handle!<br>                // Even in Draw mode, clicking directly inside an existing box on Developing Output selects it for easy editing<br>                const selectedReq = sheet.requirements.find(r =&gt; r.id === state.selectedReqId);<br>                if (selectedReq) {<br>                    const sb = side === &#39;orig&#39; ? selectedReq.origBox : selectedReq.devBox;<br>                    if (sb) {<br>                        const handle = hitTestHandle(sb, x, y, tolerance);<br>                        if (handle) {<br>                            interactionMode = handle;<br>                            activeCanvasSide = side;<br>                            startX = x; startY = y;<br>                            initialBoxSnapshot = { ...sb };<br>                            return;<br>                        }<br>                    }<br>                }<br><br>                // Check if clicking inside any existing box on this side<br>                const hit = [...sheet.requirements].reverse().find(r =&gt; {<br>                    const b = side === &#39;orig&#39; ? r.origBox : r.devBox;<br>                    return b &amp;&amp; x &gt;= b.x &amp;&amp; x &lt;= b.x + b.w &amp;&amp; y &gt;= b.y &amp;&amp; y &lt;= b.y + b.h;<br>                });<br><br>                if (hit &amp;&amp; (state.currentTool === &#39;select&#39; || side === &#39;dev&#39;)) {<br>                    state.selectedReqId = hit.id;<br>                    const b = side === &#39;orig&#39; ? hit.origBox : hit.devBox;<br>                    const handle = hitTestHandle(b, x, y, tolerance);<br>                    interactionMode = handle || &#39;move&#39;;<br>                    activeCanvasSide = side;<br>                    startX = x; startY = y;<br>                    initialBoxSnapshot = { ...b };<br>                    redrawAllCanvases();<br>                    renderRequirementsPanel();<br>                    return;<br>                }<br><br>                // 3. Otherwise start drawing a new box<br>                interactionMode = &#39;draw&#39;;<br>                activeCanvasSide = side;<br>                startX = currX = x; startY = currY = y;<br>            });<br><br>            canvas.addEventListener(&#39;mousemove&#39;, (e) =&gt; {<br>                const sheet = getActiveSheet();<br>                if (!sheet) return;<br>                const rect = canvas.getBoundingClientRect();<br>                const x = (e.clientX - rect.left) * (canvas.width / rect.width);<br>                const y = (e.clientY - rect.top) * (canvas.height / rect.height);<br><br>                if (!interactionMode) {<br>                    // Hover cursor feedback<br>                    const hit = sheet.requirements.find(r =&gt; {<br>                        const b = side === &#39;orig&#39; ? r.origBox : r.devBox;<br>                        return b &amp;&amp; x &gt;= b.x - 6 &amp;&amp; x &lt;= b.x + b.w + 6 &amp;&amp; y &gt;= b.y - 6 &amp;&amp; y &lt;= b.y + b.h + 6;<br>                    });<br>                    canvas.style.cursor = (hit &amp;&amp; (state.currentTool === &#39;select&#39; || side === &#39;dev&#39;)) ? &#39;move&#39; : &#39;crosshair&#39;;<br>                    return;<br>                }<br><br>                if (activeCanvasSide !== side) return;<br><br>                if (interactionMode === &#39;draw&#39;) {<br>                    currX = x; currY = y;<br>                    redrawAllCanvases();<br>                    return;<br>                }<br><br>                const req = sheet.requirements.find(r =&gt; r.id === state.selectedReqId);<br>                if (!req || !initialBoxSnapshot) return;<br>                const box = side === &#39;orig&#39; ? req.origBox : req.devBox;<br>                const dx = Math.round(x - startX);<br>                const dy = Math.round(y - startY);<br><br>                if (interactionMode === &#39;move&#39;) {<br>                    box.x = Math.max(0, Math.min(canvas.width - box.w, initialBoxSnapshot.x + dx));<br>                    box.y = Math.max(0, Math.min(canvas.height - box.h, initialBoxSnapshot.y + dy));<br>                } else if (interactionMode === &#39;resize-se&#39;) {<br>                    box.w = Math.max(10, initialBoxSnapshot.w + dx);<br>                    box.h = Math.max(10, initialBoxSnapshot.h + dy);<br>                } else if (interactionMode === &#39;resize-nw&#39;) {<br>                    const newX = Math.min(initialBoxSnapshot.x + initialBoxSnapshot.w - 10, initialBoxSnapshot.x + dx);<br>                    const newY = Math.min(initialBoxSnapshot.y + initialBoxSnapshot.h - 10, initialBoxSnapshot.y + dy);<br>                    box.w = (initialBoxSnapshot.x + initialBoxSnapshot.w) - newX;<br>                    box.h = (initialBoxSnapshot.y + initialBoxSnapshot.h) - newY;<br>                    box.x = newX; box.y = newY;<br>                } else if (interactionMode === &#39;resize-ne&#39;) {<br>                    const newY = Math.min(initialBoxSnapshot.y + initialBoxSnapshot.h - 10, initialBoxSnapshot.y + dy);<br>                    box.w = Math.max(10, initialBoxSnapshot.w + dx);<br>                    box.h = (initialBoxSnapshot.y + initialBoxSnapshot.h) - newY;<br>                    box.y = newY;<br>                } else if (interactionMode === &#39;resize-sw&#39;) {<br>                    const newX = Math.min(initialBoxSnapshot.x + initialBoxSnapshot.w - 10, initialBoxSnapshot.x + dx);<br>                    box.w = (initialBoxSnapshot.x + initialBoxSnapshot.w) - newX;<br>                    box.h = Math.max(10, initialBoxSnapshot.h + dy);<br>                    box.x = newX;<br>                }<br><br>                redrawAllCanvases();<br>            });<br><br>            canvas.addEventListener(&#39;mouseup&#39;, async () =&gt; {<br>                if (!interactionMode || activeCanvasSide !== side) return;<br>                const mode = interactionMode;<br>                interactionMode = null;<br><br>                const sheet = getActiveSheet();<br>                if (!sheet) return;<br><br>                if (mode === &#39;draw&#39;) {<br>                    const box = {<br>                        x: Math.round(Math.min(startX, currX)),<br>                        y: Math.round(Math.min(startY, currY)),<br>                        w: Math.round(Math.abs(currX - startX)),<br>                        h: Math.round(Math.abs(currY - startY))<br>                    };<br>                    if (box.w &gt; 5 &amp;&amp; box.h &gt; 5) await handleBoxDrawn(side, box);<br>                } else {<br>                    // User finished moving or resizing an existing box -&gt; Re-run OCR on updated position!<br>                    const req = sheet.requirements.find(r =&gt; r.id === state.selectedReqId);<br>                    if (req) {<br>                        showToast(`Re-reading OCR for #${req.number}...`, true);<br>                        if (side === &#39;orig&#39; &amp;&amp; req.origBox) {<br>                            req.origValue = await runOcrOnCrop(origImgObj, req.origBox);<br>                        } else if (side === &#39;dev&#39; &amp;&amp; req.devBox) {<br>                            req.devValue = await runOcrOnCrop(devImgObj, req.devBox);<br>                        }<br>                        hideToast();<br>                        evalReq(req);<br>                        renderRequirementsPanel();<br>                        renderSheetList();<br>                    }<br>                }<br>                redrawAllCanvases();<br>            });<br>        }<br><br>        async function handleBoxDrawn(side, box) {<br>            const sheet = getActiveSheet();<br>            let req = null;<br><br>            // 1. Check if user clicked &quot;Re-draw / Edit&quot; button on a specific requirement card<br>            if (state.activeRedrawTarget &amp;&amp; state.activeRedrawTarget.side === side) {<br>                req = sheet.requirements.find(r =&gt; r.id === state.activeRedrawTarget.reqId);<br>                state.activeRedrawTarget = null;<br>            }<br>            // 2. Otherwise pair with the first requirement missing a box on this side<br>            else {<br>                req = sheet.requirements.find(r =&gt; side === &#39;orig&#39; ? !r.origBox : !r.devBox);<br>            }<br><br>            // 3. Otherwise create a brand-new requirement using the next sequential number &amp; label from Field Config!<br>            if (!req) {<br>                const nextNum = getNextSequentialNumber(sheet);<br>                const cfgName = getConfiguredNameForNumber(nextNum);<br>                req = {<br>                    id: &#39;r_&#39; + Math.random(),<br>                    number: nextNum,<br>                    name: cfgName,<br>                    origBox: null, devBox: null, origValue: &#39;&#39;, devValue: &#39;&#39;, status: &#39;PENDING&#39;<br>                };<br>                sheet.requirements.push(req);<br>                sheet.requirements.sort((a, b) =&gt; a.number - b.number);<br>            }<br><br>            state.selectedReqId = req.id;<br>            showToast(`Extracting OCR for #${req.number} (${req.name})...`, true);<br><br>            if (side === &#39;orig&#39;) {<br>                req.origBox = box;<br>                req.origValue = await runOcrOnCrop(origImgObj, box);<br>            } else {<br>                req.devBox = box;<br>                req.devValue = await runOcrOnCrop(devImgObj, box);<br>            }<br><br>            hideToast();<br>            evalReq(req);<br>            renderRequirementsPanel();<br>            renderSheetList();<br>        }<br><br>        // ==========================================<br>        // EDIT / RE-DRAW / CLEAR BOX CONTROLS<br>        // ==========================================<br>        function armRedrawBox(reqId, side) {<br>            state.selectedReqId = reqId;<br>            state.activeRedrawTarget = { reqId, side };<br>            setTool(&#39;draw&#39;);<br>            const s = getActiveSheet();<br>            const r = s.requirements.find(x =&gt; x.id === reqId);<br>            const sideLabel = side === &#39;dev&#39; ? &#39;DEVELOPING OUTPUT&#39; : &#39;ORIGINAL IMAGE&#39;;<br>            document.getElementById(&#39;activeTargetLabel&#39;).textContent = `Re-drawing #${r.number} on ${sideLabel}`;<br>            redrawAllCanvases();<br>            showToast(`Click and drag on ${sideLabel} to redraw Box #${r.number}`, false);<br>            setTimeout(hideToast, 2500);<br>        }<br><br>        function clearSingleSideBox(reqId, side) {<br>            const s = getActiveSheet();<br>            const r = s.requirements.find(x =&gt; x.id === reqId);<br>            if (!r) return;<br>            if (side === &#39;dev&#39;) {<br>                r.devBox = null;<br>                r.devValue = &#39;&#39;;<br>            } else {<br>                r.origBox = null;<br>                r.origValue = &#39;&#39;;<br>            }<br>            evalReq(r);<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            renderSheetList();<br>        }<br><br>        function deleteRequirement(id) {<br>            const s = getActiveSheet();<br>            s.requirements = s.requirements.filter(r =&gt; r.id !== id);<br>            if (state.selectedReqId === id) state.selectedReqId = null;<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            renderSheetList();<br>        }<br><br>        // ==========================================<br>        // FIELD SEQUENCE &amp; LABEL CONFIG TABLE MODAL<br>        // ==========================================<br>        function openConfigModal() {<br>            renderConfigTable();<br>            document.getElementById(&#39;configModal&#39;).style.display = &#39;flex&#39;;<br>        }<br><br>        function closeConfigModal() {<br>            document.getElementById(&#39;configModal&#39;).style.display = &#39;none&#39;;<br>            renderRequirementsPanel();<br>        }<br><br>        function renderConfigTable() {<br>            const tbody = document.getElementById(&#39;configTableBody&#39;);<br>            tbody.innerHTML = &#39;&#39;;<br>            state.fieldConfig.sort((a, b) =&gt; a.number - b.number);<br>            state.fieldConfig.forEach((row, idx) =&gt; {<br>                tbody.innerHTML += `<br>                    &lt;tr&gt;<br>                        &lt;td&gt;&lt;input type=&quot;number&quot; class=&quot;cfg-input&quot; value=&quot;${row.number}&quot; onchange=&quot;updateConfigRow(${idx}, &#39;number&#39;, this.value)&quot;&gt;&lt;/td&gt;<br>                        &lt;td&gt;&lt;input type=&quot;text&quot; class=&quot;cfg-input&quot; value=&quot;${escapeHtml(row.name)}&quot; placeholder=&quot;Enter field label...&quot; onchange=&quot;updateConfigRow(${idx}, &#39;name&#39;, this.value)&quot;&gt;&lt;/td&gt;<br>                        &lt;td style=&quot;text-align: center;&quot;&gt;<br>                            &lt;button class=&quot;danger-btn&quot; style=&quot;padding: 4px 8px;&quot; onclick=&quot;deleteConfigRow(${idx})&quot;&gt;✕&lt;/button&gt;<br>                        &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                `;<br>            });<br>        }<br><br>        function addConfigRow() {<br>            const nextNum = state.fieldConfig.reduce((m, r) =&gt; Math.max(m, Number(r.number) || 0), 0) + 1;<br>            state.fieldConfig.push({ number: nextNum, name: `Field #${nextNum}` });<br>            renderConfigTable();<br>        }<br><br>        function updateConfigRow(idx, field, val) {<br>            if (field === &#39;number&#39;) state.fieldConfig[idx].number = parseInt(val, 10) || 1;<br>            else state.fieldConfig[idx].name = val;<br>        }<br><br>        function deleteConfigRow(idx) {<br>            state.fieldConfig.splice(idx, 1);<br>            renderConfigTable();<br>        }<br><br>        function applyConfigToCurrentSheet() {<br>            const s = getActiveSheet();<br>            if (!s) return;<br>            s.requirements.forEach(r =&gt; {<br>                const cfg = state.fieldConfig.find(c =&gt; Number(c.number) === Number(r.number));<br>                if (cfg) r.name = cfg.name;<br>            });<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            showToast(&quot;Updated current sheet names from Field Config!&quot;, false);<br>            setTimeout(hideToast, 2000);<br>        }<br><br>        function applyConfigDropdownSelection(reqId, configNumber) {<br>            const s = getActiveSheet();<br>            const r = s.requirements.find(x =&gt; x.id === reqId);<br>            const cfg = state.fieldConfig.find(c =&gt; Number(c.number) === Number(configNumber));<br>            if (r &amp;&amp; cfg) {<br>                r.number = Number(cfg.number);<br>                r.name = cfg.name;<br>                s.requirements.sort((a, b) =&gt; a.number - b.number);<br>                redrawAllCanvases();<br>                renderRequirementsPanel();<br>            }<br>        }<br><br>        // ==========================================<br>        // LOCK DEVELOPING OUTPUT BOXES TO ALL SHEETS<br>        // ==========================================<br>        async function lockDevBoxesToAllSheets() {<br>            const current = getActiveSheet();<br>            if (!current || current.requirements.length === 0) {<br>                alert(&quot;Please map boxes on the Developing Output image first.&quot;);<br>                return;<br>            }<br>            if (!confirm(`Lock these fixed Developing Output box positions across ALL ${state.sheets.length} sheets?`)) return;<br><br>            state.lockedDevTemplate = current.requirements.map(r =&gt; ({<br>                id: &#39;r_&#39; + Math.random(),<br>                number: r.number,<br>                name: r.name,<br>                origBox: null,<br>                devBox: r.devBox ? { ...r.devBox } : null,<br>                origValue: &#39;&#39;,<br>                devValue: &#39;&#39;,<br>                status: &#39;PENDING&#39;<br>            }));<br><br>            for (const s of state.sheets) {<br>                state.lockedDevTemplate.forEach(tpl =&gt; {<br>                    let existing = s.requirements.find(x =&gt; x.number === tpl.number);<br>                    if (existing) {<br>                        existing.devBox = tpl.devBox ? { ...tpl.devBox } : null;<br>                        existing.name = tpl.name;<br>                    } else {<br>                        s.requirements.push(JSON.parse(JSON.stringify(tpl)));<br>                    }<br>                });<br><br>                if (s.devImageSrc) {<br>                    const img = await loadImg(s.devImageSrc);<br>                    for (const r of s.requirements) {<br>                        if (r.devBox) r.devValue = await runOcrOnCrop(img, r.devBox);<br>                    }<br>                }<br>                s.requirements.sort((a, b) =&gt; a.number - b.number);<br>                s.requirements.forEach(evalReq);<br>            }<br><br>            renderSheetList();<br>            renderRequirementsPanel();<br>            showToast(&quot;Developing Output box positions locked to all sheets!&quot;, false);<br>            setTimeout(hideToast, 2500);<br>        }<br><br>        function loadImg(src) {<br>            return new Promise(res =&gt; { const i = new Image(); i.onload = () =&gt; res(i); i.src = src; });<br>        }<br><br>        // ==========================================<br>        // SMART RED-BOX DETECTOR (PRESERVES DEV BOXES)<br>        // ==========================================<br>        async function detectRedBoxesOnImage(imgObj, existingReqs) {<br>            const w = imgObj.width, h = imgObj.height;<br>            const c = document.createElement(&#39;canvas&#39;); c.width = w; c.height = h;<br>            const ctx = c.getContext(&#39;2d&#39;); ctx.drawImage(imgObj, 0, 0);<br>            const data = ctx.getImageData(0, 0, w, h).data;<br><br>            const mask = new Uint8Array(w * h);<br>            for (let i = 0; i &lt; w * h; i++) {<br>                const r = data[i*4], g = data[i*4+1], b = data[i*4+2];<br>                if (r &gt; 165 &amp;&amp; g &lt; 85 &amp;&amp; b &lt; 85 &amp;&amp; (r - g) &gt; 85) mask[i] = 1;<br>            }<br><br>            let rawComponents = [];<br>            let visited = new Uint8Array(w * h);<br>            for (let y = 0; y &lt; h; y += 2) {<br>                for (let x = 0; x &lt; w; x += 2) {<br>                    const idx = y * w + x;<br>                    if (mask[idx] &amp;&amp; !visited[idx]) {<br>                        let minX = x, maxX = x, minY = y, maxY = y, count = 0;<br>                        let stack = [[x, y]]; visited[idx] = 1;<br>                        while (stack.length) {<br>                            let [cx, cy] = stack.pop(); count++;<br>                            if (cx &lt; minX) minX = cx; if (cx &gt; maxX) maxX = cx;<br>                            if (cy &lt; minY) minY = cy; if (cy &gt; maxY) maxY = cy;<br>                            [[cx+2,cy],[cx-2,cy],[cx,cy+2],[cx,cy-2]].forEach(([nx,ny]) =&gt; {<br>                                if (nx &gt;= 0 &amp;&amp; nx &lt; w &amp;&amp; ny &gt;= 0 &amp;&amp; ny &lt; h &amp;&amp; mask[ny*w+nx] &amp;&amp; !visited[ny*w+nx]) {<br>                                    visited[ny*w+nx] = 1; stack.push([nx,ny]);<br>                                }<br>                            });<br>                        }<br>                        const bw = maxX - minX, bh = maxY - minY;<br>                        if (bw &gt; 24 &amp;&amp; bh &gt; 16 &amp;&amp; count &gt; 40) {<br>                            rawComponents.push({ x: minX, y: minY, w: bw, h: bh });<br>                        }<br>                    }<br>                }<br>            }<br><br>            rawComponents.sort((a, b) =&gt; Math.abs(a.y - b.y) &lt; 12 ? a.x - b.x : a.y - b.y);<br><br>            const detectedItems = [];<br>            for (let i = 0; i &lt; rawComponents.length; i++) {<br>                const comp = rawComponents[i];<br>                let tabBottomY = comp.y;<br>                let tabMinX = comp.x + comp.w, tabMaxX = comp.x;<br>                for (let sy = comp.y; sy &lt; Math.min(h, comp.y + comp.h); sy++) {<br>                    let redRowCount = 0, rowFirstX = -1, rowLastX = -1;<br>                    for (let sx = comp.x; sx &lt;= comp.x + comp.w; sx++) {<br>                        if (mask[sy * w + sx]) {<br>                            redRowCount++;<br>                            if (rowFirstX === -1) rowFirstX = sx;<br>                            rowLastX = sx;<br>                        }<br>                    }<br>                    const span = rowLastX - rowFirstX;<br>                    if (span &gt;= 14 &amp;&amp; span &lt;= 55 &amp;&amp; (redRowCount / (span + 1)) &gt; 0.55) {<br>                        tabBottomY = sy;<br>                        if (rowFirstX &lt; tabMinX) tabMinX = rowFirstX;<br>                        if (rowLastX &gt; tabMaxX) tabMaxX = rowLastX;<br>                    } else if (tabBottomY &gt; comp.y + 8) {<br>                        break;<br>                    }<br>                }<br><br>                let detectedNum = null;<br>                if (tabBottomY &gt; comp.y + 8 &amp;&amp; tabMaxX &gt; tabMinX + 8) {<br>                    const badgeBox = {<br>                        x: Math.max(0, tabMinX + 1),<br>                        y: Math.max(0, comp.y + 1),<br>                        w: Math.max(6, (tabMaxX - tabMinX) - 2),<br>                        h: Math.max(6, (tabBottomY - comp.y) - 2)<br>                    };<br>                    detectedNum = await runOcrOnCrop(imgObj, badgeBox, true);<br>                }<br><br>                const valBoxTop = tabBottomY &gt; comp.y + 8 ? tabBottomY + 1 : comp.y;<br>                const valueBox = { x: comp.x, y: valBoxTop, w: comp.w, h: Math.max(12, (comp.y + comp.h) - valBoxTop) };<br>                const innerCrop = { x: valueBox.x + 3, y: valueBox.y + 2, w: Math.max(8, valueBox.w - 6), h: Math.max(8, valueBox.h - 4) };<br>                const extractedValue = await runOcrOnCrop(imgObj, innerCrop, false);<br><br>                const finalNum = detectedNum || (i + 1);<br>                const cfgName = getConfiguredNameForNumber(finalNum);<br><br>                detectedItems.push({<br>                    number: finalNum,<br>                    name: cfgName,<br>                    origBox: valueBox,<br>                    origValue: extractedValue<br>                });<br>            }<br><br>            detectedItems.sort((a, b) =&gt; a.number - b.number);<br><br>            const updatedReqs = [];<br>            const usedNumbers = new Set();<br><br>            detectedItems.forEach((det) =&gt; {<br>                usedNumbers.add(det.number);<br>                const existing = existingReqs.find(r =&gt; r.number === det.number);<br>                if (existing) {<br>                    existing.origBox = det.origBox;<br>                    existing.origValue = det.origValue;<br>                    if (!existing.name || existing.name.startsWith(&#39;Field #&#39;)) existing.name = det.name;<br>                    evalReq(existing);<br>                    updatedReqs.push(existing);<br>                } else {<br>                    const lockedDev = state.lockedDevTemplate.find(t =&gt; t.number === det.number);<br>                    updatedReqs.push({<br>                        id: &#39;r_&#39; + Math.random(),<br>                        number: det.number,<br>                        name: det.name,<br>                        origBox: det.origBox,<br>                        devBox: lockedDev ? { ...lockedDev.devBox } : null,<br>                        origValue: det.origValue,<br>                        devValue: &#39;&#39;,<br>                        status: &#39;PENDING&#39;<br>                    });<br>                }<br>            });<br><br>            existingReqs.forEach(existing =&gt; {<br>                if (!usedNumbers.has(existing.number)) {<br>                    existing.origBox = null;<br>                    existing.origValue = &#39;&#39;;<br>                    evalReq(existing);<br>                    updatedReqs.push(existing);<br>                }<br>            });<br><br>            updatedReqs.sort((a, b) =&gt; a.number - b.number);<br>            return updatedReqs;<br>        }<br><br>        async function autoDetectRedBoxesCurrent() {<br>            const sheet = getActiveSheet();<br>            if (!sheet || !sheet.origImageSrc) {<br>                alert(&quot;Please load an Original Requirement image first.&quot;);<br>                return;<br>            }<br>            showToast(&quot;Detecting red numbered boxes...&quot;, true);<br>            sheet.requirements = await detectRedBoxesOnImage(origImgObj, sheet.requirements);<br><br>            if (sheet.devImageSrc) {<br>                for (const r of sheet.requirements) {<br>                    if (r.devBox &amp;&amp; !r.devValue) r.devValue = await runOcrOnCrop(devImgObj, r.devBox);<br>                    evalReq(r);<br>                }<br>            }<br><br>            hideToast();<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            renderSheetList();<br>        }<br><br>        async function autoDetectRedBoxesAllSheets() {<br>            if (state.sheets.length === 0) return;<br>            showToast(`Scanning all ${state.sheets.length} sheets...`, true);<br><br>            for (let i = 0; i &lt; state.sheets.length; i++) {<br>                const s = state.sheets[i];<br>                if (!s.origImageSrc) continue;<br>                const img = await loadImg(s.origImageSrc);<br>                s.requirements = await detectRedBoxesOnImage(img, s.requirements);<br><br>                if (s.devImageSrc) {<br>                    const devImg = await loadImg(s.devImageSrc);<br>                    for (const r of s.requirements) {<br>                        if (r.devBox) r.devValue = await runOcrOnCrop(devImg, r.devBox);<br>                        evalReq(r);<br>                    }<br>                }<br>            }<br><br>            hideToast();<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            renderSheetList();<br>            showToast(&quot;Red-box detection completed across all sheets!&quot;, false);<br>            setTimeout(hideToast, 2500);<br>        }<br><br>        async function runOcrForCurrentSheet() {<br>            const sheet = getActiveSheet();<br>            if (!sheet) return;<br>            for (const r of sheet.requirements) {<br>                if (r.origBox &amp;&amp; sheet.origImageSrc) r.origValue = await runOcrOnCrop(origImgObj, r.origBox);<br>                if (r.devBox &amp;&amp; sheet.devImageSrc) r.devValue = await runOcrOnCrop(devImgObj, r.devBox);<br>                evalReq(r);<br>            }<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            renderSheetList();<br>        }<br><br>        function evalReq(r) {<br>            const fuzzy = document.getElementById(&#39;fuzzyMatchToggle&#39;).checked;<br>            let o = (r.origValue || &#39;&#39;).trim(), d = (r.devValue || &#39;&#39;).trim();<br>            if (fuzzy) { o = o.toLowerCase().replace(/\s+/g, &#39; &#39;); d = d.toLowerCase().replace(/\s+/g, &#39; &#39;); }<br>            if (!o &amp;&amp; !d) r.status = &#39;PENDING&#39;;<br>            else if (o === d) r.status = &#39;PASS&#39;;<br>            else r.status = &#39;FAIL&#39;;<br>        }<br><br>        function recalculateAllStatuses() {<br>            state.sheets.forEach(s =&gt; s.requirements.forEach(evalReq));<br>            redrawAllCanvases();<br>            renderRequirementsPanel();<br>            renderSheetList();<br>        }<br><br>        function addManualRequirement() {<br>            const s = getActiveSheet();<br>            if (!s) return;<br>            const nextNum = getNextSequentialNumber(s);<br>            const cfgName = getConfiguredNameForNumber(nextNum);<br>            const newReq = {<br>                id: &#39;r_&#39; + Math.random(),<br>                number: nextNum,<br>                name: cfgName,<br>                origBox: null, devBox: null, origValue: &#39;&#39;, devValue: &#39;&#39;, status: &#39;PENDING&#39;<br>            };<br>            s.requirements.push(newReq);<br>            s.requirements.sort((a, b) =&gt; a.number - b.number);<br>            state.selectedReqId = newReq.id;<br>            renderRequirementsPanel();<br>            redrawAllCanvases();<br>        }<br><br>        function renderRequirementsPanel() {<br>            const s = getActiveSheet();<br>            const list = document.getElementById(&#39;requirementsList&#39;);<br>            list.innerHTML = &#39;&#39;;<br>            document.getElementById(&#39;activeTargetLabel&#39;).textContent = state.activeRedrawTarget ? `Re-drawing Box...` : &#39;Click any Dev Box to Edit&#39;;<br><br>            if (!s || s.requirements.length === 0) {<br>                list.innerHTML = `&lt;div style=&quot;text-align:center; color:var(--text-muted); padding:20px;&quot;&gt;Click &lt;b&gt;+ Add Box&lt;/b&gt; (uses Field Config sequence) or &lt;b&gt;Detect Red Boxes&lt;/b&gt;.&lt;/div&gt;`;<br>                document.getElementById(&#39;statTotal&#39;).textContent = 0;<br>                document.getElementById(&#39;statPass&#39;).textContent = 0;<br>                document.getElementById(&#39;statFail&#39;).textContent = 0;<br>                return;<br>            }<br><br>            let pass = 0, fail = 0;<br>            s.requirements.forEach(r =&gt; {<br>                if (r.status === &#39;PASS&#39;) pass++; if (r.status === &#39;FAIL&#39;) fail++;<br><br>                // Build dropdown options from Field Config Table (#1 Label, #2 Label...)<br>                let configOptions = `&lt;option value=&quot;&quot; disabled selected&gt;Config #...&lt;/option&gt;`;<br>                [...state.fieldConfig].sort((a, b) =&gt; a.number - b.number).forEach(cfg =&gt; {<br>                    configOptions += `&lt;option value=&quot;${cfg.number}&quot;&gt;#${cfg.number} - ${escapeHtml(cfg.name)}&lt;/option&gt;`;<br>                });<br><br>                list.innerHTML += `<br>                    &lt;div class=&quot;req-card ${r.id === state.selectedReqId ? &#39;selected&#39; : &#39;&#39;}&quot; onclick=&quot;state.selectedReqId=&#39;${r.id}&#39;; redrawAllCanvases();&quot;&gt;<br>                        &lt;div class=&quot;req-card-header&quot;&gt;<br>                            &lt;input class=&quot;req-num-input&quot; type=&quot;number&quot; value=&quot;${r.number}&quot; title=&quot;Requirement Sequence Number&quot; onchange=&quot;updateReqNumber(&#39;${r.id}&#39;, this.value)&quot;&gt;<br>                            &lt;input class=&quot;req-name-input&quot; value=&quot;${escapeHtml(r.name)}&quot; onchange=&quot;updateReqName(&#39;${r.id}&#39;, this.value)&quot;&gt;<br>                            &lt;select class=&quot;template-select&quot; onchange=&quot;applyConfigDropdownSelection(&#39;${r.id}&#39;, this.value); this.selectedIndex=0;&quot; title=&quot;Select sequence # and label from Field Config&quot;&gt;<br>                                ${configOptions}<br>                            &lt;/select&gt;<br>                            &lt;button class=&quot;danger-btn&quot; style=&quot;padding:4px 7px;&quot; title=&quot;Delete entire requirement card&quot; onclick=&quot;event.stopPropagation(); deleteRequirement(&#39;${r.id}&#39;)&quot;&gt;<br>                                &lt;i data-lucide=&quot;trash-2&quot; size=&quot;13&quot;&gt;&lt;/i&gt;<br>                            &lt;/button&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;comparison-grid&quot;&gt;<br>                            &lt;div class=&quot;val-box&quot;&gt;<br>                                &lt;div class=&quot;val-label&quot;&gt;<br>                                    &lt;span&gt;Orig Box ${r.origBox ? &#39;📍&#39; : &#39;❌&#39;}&lt;/span&gt;<br>                                    &lt;div class=&quot;val-label-actions&quot;&gt;<br>                                        &lt;button class=&quot;mini-icon-btn&quot; title=&quot;Re-draw Original Box&quot; onclick=&quot;event.stopPropagation(); armRedrawBox(&#39;${r.id}&#39;, &#39;orig&#39;)&quot;&gt;✏️&lt;/button&gt;<br>                                        ${r.origBox ? `&lt;button class=&quot;mini-icon-btn del&quot; title=&quot;Clear Original Box&quot; onclick=&quot;event.stopPropagation(); clearSingleSideBox(&#39;${r.id}&#39;, &#39;orig&#39;)&quot;&gt;✕&lt;/button&gt;` : &#39;&#39;}<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                                &lt;textarea class=&quot;val-input&quot; oninput=&quot;updateVal(&#39;${r.id}&#39;, &#39;origValue&#39;, this.value)&quot;&gt;${escapeHtml(r.origValue)}&lt;/textarea&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;val-box&quot;&gt;<br>                                &lt;div class=&quot;val-label&quot;&gt;<br>                                    &lt;span&gt;Dev Output ${r.devBox ? &#39;📍&#39; : &#39;❌&#39;}&lt;/span&gt;<br>                                    &lt;div class=&quot;val-label-actions&quot;&gt;<br>                                        &lt;button class=&quot;mini-icon-btn&quot; title=&quot;Re-draw Developing Output Box&quot; onclick=&quot;event.stopPropagation(); armRedrawBox(&#39;${r.id}&#39;, &#39;dev&#39;)&quot;&gt;✏️&lt;/button&gt;<br>                                        ${r.devBox ? `&lt;button class=&quot;mini-icon-btn del&quot; title=&quot;Clear Developing Output Box to Redo&quot; onclick=&quot;event.stopPropagation(); clearSingleSideBox(&#39;${r.id}&#39;, &#39;dev&#39;)&quot;&gt;✕&lt;/button&gt;` : &#39;&#39;}<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                                &lt;textarea class=&quot;val-input&quot; oninput=&quot;updateVal(&#39;${r.id}&#39;, &#39;devValue&#39;, this.value)&quot;&gt;${escapeHtml(r.devValue)}&lt;/textarea&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;req-footer&quot;&gt;<br>                            &lt;span class=&quot;status-pill status-${r.status.toLowerCase()}&quot;&gt;${r.status}&lt;/span&gt;<br>                            &lt;span style=&quot;color: var(--text-muted); font-size: 0.7rem;&quot;&gt;<br>                                ${r.devBox ? `Dev Pos: (${r.devBox.x}, ${r.devBox.y})` : &#39;No Dev Box&#39;}<br>                            &lt;/span&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                `;<br>            });<br>            document.getElementById(&#39;statTotal&#39;).textContent = s.requirements.length;<br>            document.getElementById(&#39;statPass&#39;).textContent = pass;<br>            document.getElementById(&#39;statFail&#39;).textContent = fail;<br>            lucide.createIcons();<br>        }<br><br>        function updateReqNumber(id, val) {<br>            const s = getActiveSheet();<br>            const r = s.requirements.find(x =&gt; x.id === id);<br>            if (r) {<br>                r.number = parseInt(val, 10) || r.number;<br>                // Auto-pull label from Field Config if current name is generic<br>                const cfg = state.fieldConfig.find(c =&gt; Number(c.number) === r.number);<br>                if (cfg &amp;&amp; (r.name.startsWith(&#39;Field #&#39;) || !r.name)) r.name = cfg.name;<br>                s.requirements.sort((a, b) =&gt; a.number - b.number);<br>                redrawAllCanvases();<br>                renderRequirementsPanel();<br>            }<br>        }<br>        function updateReqName(id, val) { const r = getActiveSheet().requirements.find(x =&gt; x.id === id); if (r) { r.name = val; redrawAllCanvases(); } }<br>        function updateVal(id, field, val) {<br>            const r = getActiveSheet().requirements.find(x =&gt; x.id === id);<br>            if (r) { r[field] = val; evalReq(r); redrawAllCanvases(); renderSheetList(); }<br>        }<br><br>        function setTool(t) {<br>            state.currentTool = t;<br>            document.getElementById(&#39;toolDrawBox&#39;).classList.toggle(&#39;active-tool&#39;, t === &#39;draw&#39;);<br>            document.getElementById(&#39;toolSelect&#39;).classList.toggle(&#39;active-tool&#39;, t === &#39;select&#39;);<br>        }<br><br>        function openReportModal() {<br>            let html = `&lt;table class=&quot;report-table&quot;&gt;&lt;tr&gt;&lt;th&gt;Sheet&lt;/th&gt;&lt;th&gt;Box #&lt;/th&gt;&lt;th&gt;Field Label&lt;/th&gt;&lt;th&gt;Orig Value&lt;/th&gt;&lt;th&gt;Dev Output Value&lt;/th&gt;&lt;th&gt;Status&lt;/th&gt;&lt;/tr&gt;`;<br>            state.sheets.forEach(s =&gt; {<br>                s.requirements.forEach(r =&gt; {<br>                    html += `&lt;tr&gt;&lt;td&gt;${escapeHtml(s.title)}&lt;/td&gt;&lt;td&gt;#${r.number}&lt;/td&gt;&lt;td&gt;${escapeHtml(r.name)}&lt;/td&gt;&lt;td&gt;${escapeHtml(r.origValue)}&lt;/td&gt;&lt;td&gt;${escapeHtml(r.devValue)}&lt;/td&gt;&lt;td&gt;&lt;b&gt;${r.status}&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;`;<br>                });<br>            });<br>            html += `&lt;/table&gt;`;<br>            document.getElementById(&#39;reportModalBody&#39;).innerHTML = html;<br>            document.getElementById(&#39;reportModal&#39;).style.display = &#39;flex&#39;;<br>        }<br><br>        function closeReportModal() { document.getElementById(&#39;reportModal&#39;).style.display = &#39;none&#39;; }<br>        <br>        function exportExcelReport() {<br>            const data = [];<br>            state.sheets.forEach(s =&gt; s.requirements.forEach(r =&gt; data.push({ Sheet: s.title, Box_Number: r.number, Field_Label: r.name, Orig_Value: r.origValue, Dev_Output: r.devValue, Status: r.status })));<br>            const ws = XLSX.utils.json_to_sheet(data); const wb = XLSX.utils.book_new();<br>            XLSX.utils.book_append_sheet(wb, ws, &quot;QA_Report&quot;); XLSX.writeFile(wb, &quot;QA_Validation_Report.xlsx&quot;);<br>        }<br><br>        function exportCsvReport() {<br>            const data = [];<br>            state.sheets.forEach(s =&gt; s.requirements.forEach(r =&gt; data.push({ Sheet: s.title, Box_Number: r.number, Field_Label: r.name, Orig_Value: r.origValue, Dev_Output: r.devValue, Status: r.status })));<br>            const ws = XLSX.utils.json_to_sheet(data);<br>            const csv = XLSX.utils.sheet_to_csv(ws);<br>            const blob = new Blob([csv], { type: &#39;text/csv;charset=utf-8;&#39; });<br>            const a = document.createElement(&#39;a&#39;); a.href = URL.createObjectURL(blob); a.download = &quot;QA_Validation_Report.csv&quot;; a.click();<br>        }<br><br>        function exportHtmlReport() {<br>            const blob = new Blob([document.getElementById(&#39;reportModalBody&#39;).innerHTML], {type: &#39;text/html&#39;});<br>            const a = document.createElement(&#39;a&#39;); a.href = URL.createObjectURL(blob); a.download = &quot;QA_Report.html&quot;; a.click();<br>        }<br><br>        function exportProjectJSON() {<br>            const blob = new Blob([JSON.stringify(state, null, 2)], {type: &#39;application/json&#39;});<br>            const a = document.createElement(&#39;a&#39;); a.href = URL.createObjectURL(blob); a.download = &quot;VisualQA_Project.json&quot;; a.click();<br>        }<br><br>        function importProjectJSON(e) {<br>            const r = new FileReader();<br>            r.onload = (evt) =&gt; {<br>                state = JSON.parse(evt.target.result);<br>                if (!state.fieldConfig) state.fieldConfig = [];<br>                if (state.sheets.length) selectSheet(state.sheets[0].id);<br>                renderSheetList();<br>            };<br>            r.readAsText(e.target.files[0]);<br>        }<br><br>        function showToast(msg, spin) {<br>            document.getElementById(&#39;toastText&#39;).textContent = msg;<br>            document.getElementById(&#39;toastSpinner&#39;).style.display = spin ? &#39;block&#39; : &#39;none&#39;;<br>            document.getElementById(&#39;toast&#39;).style.display = &#39;flex&#39;;<br>        }<br>        function hideToast() { document.getElementById(&#39;toast&#39;).style.display = &#39;none&#39;; }<br>        function escapeHtml(str) { return String(str || &#39;&#39;).replace(/&amp;/g, &quot;&amp;amp;&quot;).replace(/&lt;/g, &quot;&amp;lt;&quot;).replace(/&gt;/g, &quot;&amp;gt;&quot;); }<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f727a6439e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QA Screenshot & Screen Capture Studio]]></title>
            <link>https://medium.com/@barabonajansen/qa-screenshot-screen-capture-studio-c332cbcd9776?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c332cbcd9776</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 06:07:45 GMT</pubDate>
            <atom:updated>2026-11-14T06:07:45.159Z</atom:updated>
            <content:encoded><![CDATA[<p>Windows screen capture · QA evidence · Screenshot annotations</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;QA Screenshot &amp; Screen Capture Studio&lt;/title&gt;<br>&lt;style&gt;<br>:root {<br>  --bg:#0b1020;--panel:#121a2d;--panel2:#192640;<br>  --border:#2b3b57;--text:#eaf0ff;--muted:#91a0ba;<br>  --accent:#6d8cff;--danger:#ff6477;--green:#31c48d;<br>}<br>*{box-sizing:border-box}<br>body{margin:0;background:var(--bg);color:var(--text);font:14px Arial,sans-serif}<br>button,input{font:inherit}<br>button{padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--panel2);color:var(--text);cursor:pointer}<br>button:hover{border-color:var(--accent)}<br>button:disabled{opacity:.45;cursor:not-allowed}<br>.primary{background:var(--accent);border-color:var(--accent);color:white}<br>.danger{color:#ff9ba6;border-color:#783b49}<br>.success{color:#75e3b5;border-color:#286b55}<br>header{padding:17px 21px;background:#10182a;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}<br>h1{font-size:20px;margin:0}<br>header p{font-size:12px;color:var(--muted);margin:5px 0 0}<br>.app{display:grid;grid-template-columns:275px minmax(0,1fr) 270px;min-height:calc(100vh - 75px)}<br>.sidebar,.rightbar{padding:15px;background:var(--panel);overflow-y:auto}<br>.sidebar{border-right:1px solid var(--border)}<br>.rightbar{border-left:1px solid var(--border)}<br>.workspace{padding:16px;min-width:0}<br>.section{margin-bottom:22px}<br>.section h3{font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin:0 0 12px}<br>.panel{background:var(--panel);border:1px solid var(--border);border-radius:11px;padding:13px;margin-bottom:14px}<br>.panel-title{font-weight:bold;margin-bottom:12px}<br>.toolbar{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:10px}<br>.toolbar button.active{background:var(--accent);border-color:var(--accent)}<br>.small{font-size:11px;color:var(--muted);line-height:1.6}<br>input[type=text],input[type=number]{width:100%;background:#0c1425;border:1px solid var(--border);border-radius:7px;color:white;padding:9px}<br>input[type=color]{width:42px;height:35px;border:0;background:transparent}<br>input[type=checkbox]{accent-color:var(--accent)}<br>.label-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;max-height:340px;overflow-y:auto;padding-right:3px}<br>.label-item{padding:7px 3px;border:1px solid var(--border);border-radius:7px;text-align:center;background:#0d1628;cursor:pointer;overflow:hidden}<br>.label-item.active{outline:2px solid var(--accent);background:#25365b}<br>.label-item strong,.label-item span{display:block}<br>.label-item span{font-size:10px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}<br>.edit-label{display:flex;gap:7px;margin-top:9px}<br>.edit-label input[type=text]{flex:1;min-width:0}<br>.count-row{display:flex;gap:7px;margin:10px 0}<br>.count-row input{flex:1;min-width:0}<br>.toggle-row{display:flex;align-items:center;gap:8px;margin:12px 0;cursor:pointer}<br>.screenshot-list,.annotation-list{display:flex;flex-direction:column;gap:8px}<br>.screenshot-item{display:flex;align-items:center;gap:7px;padding:7px;border:1px solid var(--border);border-radius:8px;background:#0d1628;cursor:pointer}<br>.screenshot-item.active{border-color:var(--accent)}<br>.screenshot-item img{width:55px;height:44px;object-fit:contain;background:#080d18}<br>.screenshot-info{flex:1;min-width:0}<br>.screenshot-info strong{display:block;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}<br>.screenshot-info span{font-size:10px;color:var(--muted)}<br>.delete-image{padding:5px 7px;font-size:11px}<br>.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px}<br>.stat{background:var(--panel);border:1px solid var(--border);padding:11px;border-radius:8px}<br>.stat strong{display:block;font-size:19px}<br>.stat span{font-size:11px;color:var(--muted)}<br>.stage-wrap{background:#080d18;border:1px dashed #35435e;border-radius:9px;min-height:350px;padding:12px;overflow:auto;display:flex;justify-content:center;align-items:flex-start}<br>.stage{position:relative;display:inline-block;line-height:0;max-width:100%}<br>#base{display:block;max-width:100%;height:auto;user-select:none}<br>#overlay{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:crosshair}<br>.empty{text-align:center;color:var(--muted);padding:100px 15px;line-height:1.8}<br>.annotation-item{display:flex;align-items:center;gap:8px;padding:8px;border:1px solid var(--border);border-radius:7px;background:#0d1628;cursor:pointer;font-size:11px}<br>.annotation-item.active{border-color:var(--accent)}<br>.annotation-dot{width:12px;height:12px;border-radius:50%;flex-shrink:0}<br>.annotation-item span:nth-child(2){flex:1}<br>.annotation-item button{padding:4px 6px}<br>.preview-video{display:block;width:100%;max-height:420px;background:#05080e;object-fit:contain;border-radius:8px}<br>.capture-status{padding:9px;border:1px solid var(--border);border-radius:8px;margin:8px 0;color:var(--muted);font-size:11px}<br>#livePanel{display:none}<br>@media(max-width:1100px){.app{grid-template-columns:240px minmax(0,1fr)}.rightbar{grid-column:1/-1;border-left:0;border-top:1px solid var(--border)}}<br>@media(max-width:700px){.app{display:block}.sidebar,.rightbar{border:0;border-bottom:1px solid var(--border)}}<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;header&gt;<br> &lt;div&gt;<br>  &lt;h1&gt;QA Screenshot &amp; Screen Capture Studio&lt;/h1&gt;<br>  &lt;p&gt;Windows screen capture · QA evidence · Screenshot annotations&lt;/p&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;toolbar&quot;&gt;<br>  &lt;button class=&quot;primary&quot; onclick=&quot;startScreenCapture()&quot;&gt;▣ Capture Screen&lt;/button&gt;<br>  &lt;button onclick=&quot;document.getElementById(&#39;fileInput&#39;).click()&quot;&gt;＋ Upload Images&lt;/button&gt;<br> &lt;/div&gt;<br>&lt;/header&gt;<br><br>&lt;input type=&quot;file&quot; id=&quot;fileInput&quot; accept=&quot;image/*&quot; multiple hidden&gt;<br><br>&lt;div class=&quot;app&quot;&gt;<br>&lt;aside class=&quot;sidebar&quot;&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Windows Screen Capture&lt;/h3&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;startScreenCapture()&quot;&gt;Choose Screen / Window / Tab&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot;&gt;<br>   The next dialog lets you select your entire screen, an application window, or a browser tab.<br>  &lt;/div&gt;<br>  &lt;div id=&quot;captureStatus&quot; class=&quot;capture-status&quot;&gt;Screen capture is not active.&lt;/div&gt;<br>  &lt;div id=&quot;livePanel&quot;&gt;<br>   &lt;video id=&quot;liveVideo&quot; class=&quot;preview-video&quot; autoplay muted playsinline&gt;&lt;/video&gt;<br>   &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;captureFrame()&quot;&gt;Take Screenshot&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;stopScreenCapture()&quot;&gt;Stop Sharing&lt;/button&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Screenshot Manager&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;imageCount&quot;&gt;0 screenshots&lt;/div&gt;<br>  &lt;div class=&quot;screenshot-list&quot; id=&quot;screenshots&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Merge Images&lt;/h3&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button onclick=&quot;mergeImages(&#39;vertical&#39;)&quot;&gt;Vertical&lt;/button&gt;<br>   &lt;button onclick=&quot;mergeImages(&#39;horizontal&#39;)&quot;&gt;Horizontal&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;button class=&quot;danger&quot; onclick=&quot;removeAllImages()&quot;&gt;Delete All Images&lt;/button&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;QA Labels&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;Number of labels (1–999)&lt;/div&gt;<br>  &lt;div class=&quot;count-row&quot;&gt;<br>   &lt;input type=&quot;number&quot; id=&quot;labelCount&quot; min=&quot;1&quot; max=&quot;999&quot; value=&quot;200&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;applyLabelCount()&quot;&gt;Apply&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;label class=&quot;toggle-row&quot;&gt;<br>   &lt;input type=&quot;checkbox&quot; id=&quot;autoIncrement&quot;&gt;<br>   Auto-increment labels<br>  &lt;/label&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;autoStatus&quot;&gt;OFF: manually select labels.&lt;/div&gt;<br>  &lt;div class=&quot;label-grid&quot; id=&quot;labels&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;edit-label&quot;&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;labelName&quot; placeholder=&quot;Label name&quot;&gt;<br>   &lt;input type=&quot;color&quot; id=&quot;labelColor&quot; value=&quot;#ff4242&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot; style=&quot;margin-top:8px&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;saveLabel()&quot;&gt;Save Label&lt;/button&gt;<br>   &lt;button onclick=&quot;resetLabels()&quot;&gt;Reset&lt;/button&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br><br>&lt;/aside&gt;<br><br>&lt;main class=&quot;workspace&quot;&gt;<br> &lt;div class=&quot;stats&quot;&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statImages&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Screenshots&lt;/span&gt;&lt;/div&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statAnnotations&quot;&gt;0&lt;/strong&gt;&lt;span&gt;Annotations&lt;/span&gt;&lt;/div&gt;<br>  &lt;div class=&quot;stat&quot;&gt;&lt;strong id=&quot;statLabels&quot;&gt;200&lt;/strong&gt;&lt;span&gt;QA Labels&lt;/span&gt;&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Annotation Tools&lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button id=&quot;boxTool&quot; class=&quot;active&quot; onclick=&quot;setMode(&#39;box&#39;)&quot;&gt;▢ Rectangle&lt;/button&gt;<br>   &lt;button id=&quot;circleTool&quot; onclick=&quot;setMode(&#39;circle&#39;)&quot;&gt;◯ Circle&lt;/button&gt;<br>   &lt;button onclick=&quot;undo()&quot;&gt;↶ Undo&lt;/button&gt;<br>   &lt;button class=&quot;danger&quot; onclick=&quot;deleteSelected()&quot;&gt;Delete Selected&lt;/button&gt;<br>   &lt;button class=&quot;danger&quot; onclick=&quot;clearAnnotations()&quot;&gt;Clear Annotations&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;toolbar&quot;&gt;<br>   &lt;button class=&quot;primary&quot; onclick=&quot;exportPNG()&quot;&gt;Export Current PNG&lt;/button&gt;<br>   &lt;button onclick=&quot;exportAllPNG()&quot;&gt;Export All PNG&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;toolStatus&quot;&gt;Current tool: Rectangle&lt;/div&gt;<br> &lt;/div&gt;<br><br> &lt;div class=&quot;panel&quot;&gt;<br>  &lt;div class=&quot;panel-title&quot;&gt;Screenshot Workspace&lt;/div&gt;<br>  &lt;div class=&quot;stage-wrap&quot;&gt;<br>   &lt;div id=&quot;empty&quot; class=&quot;empty&quot;&gt;<br>    &lt;div style=&quot;font-size:40px&quot;&gt;▣&lt;/div&gt;<br>    &lt;strong&gt;No screenshot loaded&lt;/strong&gt;<br>    &lt;div&gt;Capture your Windows screen or upload an image.&lt;/div&gt;<br>   &lt;/div&gt;<br>   &lt;div id=&quot;stage&quot; class=&quot;stage&quot; hidden&gt;<br>    &lt;img id=&quot;base&quot; alt=&quot;Screenshot&quot;&gt;<br>    &lt;canvas id=&quot;overlay&quot;&gt;&lt;/canvas&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;imageStatus&quot; style=&quot;margin-top:9px&quot;&gt;No active screenshot.&lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/main&gt;<br><br>&lt;aside class=&quot;rightbar&quot;&gt;<br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;Annotation History&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot; id=&quot;annotationCount&quot;&gt;0 annotations&lt;/div&gt;<br>  &lt;div class=&quot;annotation-list&quot; id=&quot;annotations&quot;&gt;&lt;/div&gt;<br> &lt;/div&gt;<br> &lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;How to use&lt;/h3&gt;<br>  &lt;div class=&quot;small&quot;&gt;<br>   1. Click Choose Screen / Window / Tab.&lt;br&gt;&lt;br&gt;<br>   2. Select a source in the browser sharing dialog.&lt;br&gt;&lt;br&gt;<br>   3. Click Take Screenshot to add it to the manager.&lt;br&gt;&lt;br&gt;<br>   4. Select a QA label (set how many labels you need with the Apply box).&lt;br&gt;&lt;br&gt;<br>   5. Draw a rectangle or circle on the screenshot.&lt;br&gt;&lt;br&gt;<br>   6. Enable auto-increment to advance the QA label after each annotation.&lt;br&gt;&lt;br&gt;<br>   7. Export your annotated PNG.<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/aside&gt;<br>&lt;/div&gt;<br><br>&lt;script&gt;<br>const $ = id =&gt; document.getElementById(id);<br>const DEFAULT_LABEL_COUNT=200;<br>const MAX_LABELS=999;<br>let images=[];<br>let current=-1;<br>function makeLabels(n,old=[]){<br> return Array.from({length:n},(_,i)=&gt;old[i]||{id:i+1,name:`QA ${i+1}`,color:&#39;#ff4242&#39;});<br>}<br>let labels=makeLabels(DEFAULT_LABEL_COUNT);<br>let selectedLabel=1;<br>let mode=&#39;box&#39;;<br>let annotations=[];<br>let selected=null;<br>let drag=null;<br>let history=[];<br>let screenStream=null;<br><br>const base=$(&#39;base&#39;);<br>const overlay=$(&#39;overlay&#39;);<br>const ctx=overlay.getContext(&#39;2d&#39;);<br><br>// SCREEN CAPTURE<br>async function startScreenCapture(){<br> if(!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia){<br>  alert(&#39;Screen capture is unavailable. Open this page in Chrome or Edge using HTTPS or localhost.&#39;);<br>  return;<br> }<br> try{<br>  stopScreenCapture(false);<br>  screenStream=await navigator.mediaDevices.getDisplayMedia({<br>   video:{frameRate:15},<br>   audio:false<br>  });<br>  $(&#39;liveVideo&#39;).srcObject=screenStream;<br>  $(&#39;livePanel&#39;).style.display=&#39;block&#39;;<br>  $(&#39;captureStatus&#39;).textContent=&#39;Screen sharing is active. Click Take Screenshot to save the current frame.&#39;;<br>  screenStream.getVideoTracks()[0].addEventListener(&#39;ended&#39;,()=&gt;{<br>   stopScreenCapture();<br>  });<br>  await $(&#39;liveVideo&#39;).play();<br> }catch(error){<br>  if(error.name===&#39;NotAllowedError&#39;){<br>   $(&#39;captureStatus&#39;).textContent=&#39;Screen sharing was cancelled or permission was denied.&#39;;<br>  }else{<br>   $(&#39;captureStatus&#39;).textContent=&#39;Capture error: &#39;+error.message;<br>   console.error(error);<br>  }<br> }<br>}<br><br>function captureFrame(){<br> const video=$(&#39;liveVideo&#39;);<br> if(!screenStream || !video.videoWidth){<br>  alert(&#39;Start screen sharing first and wait for the preview.&#39;);<br>  return;<br> }<br> const canvas=document.createElement(&#39;canvas&#39;);<br> canvas.width=video.videoWidth;<br> canvas.height=video.videoHeight;<br> canvas.getContext(&#39;2d&#39;).drawImage(video,0,0,canvas.width,canvas.height);<br> canvas.toBlob(blob=&gt;{<br>  if(blob) addImageFromBlob(blob,`Screen Capture ${new Date().toLocaleString()}`);<br>  else alert(&#39;Could not capture this screen.&#39;);<br> },&#39;image/png&#39;);<br>}<br><br>function stopScreenCapture(updateStatus=true){<br> if(screenStream){<br>  screenStream.getTracks().forEach(track=&gt;track.stop());<br>  screenStream=null;<br> }<br> $(&#39;liveVideo&#39;).srcObject=null;<br> $(&#39;livePanel&#39;).style.display=&#39;none&#39;;<br> if(updateStatus) $(&#39;captureStatus&#39;).textContent=&#39;Screen capture stopped.&#39;;<br>}<br><br>// IMAGE UPLOAD AND PASTE<br>$(&#39;fileInput&#39;).addEventListener(&#39;change&#39;,e=&gt;{<br> Array.from(e.target.files||[]).forEach(file=&gt;{<br>  if(file.type.startsWith(&#39;image/&#39;)) addImageFromBlob(file,file.name);<br> });<br> e.target.value=&#39;&#39;;<br>});<br><br>document.addEventListener(&#39;paste&#39;,e=&gt;{<br> const item=Array.from(e.clipboardData?.items||[]).find(x=&gt;x.type.startsWith(&#39;image/&#39;));<br> if(item){<br>  const file=item.getAsFile();<br>  if(file) addImageFromBlob(file,`Pasted Screenshot ${Date.now()}`);<br> }<br>});<br><br>function addImageFromBlob(blob,name){<br> const url=URL.createObjectURL(blob);<br> const img=new Image();<br> img.onload=()=&gt;{<br>  images.push({img,url,name,width:img.naturalWidth,height:img.naturalHeight});<br>  current=images.length-1;<br>  showImage();<br>  renderImages();<br> };<br> img.onerror=()=&gt;URL.revokeObjectURL(url);<br> img.src=url;<br>}<br><br>// INDIVIDUAL IMAGE DELETE<br>function deleteImage(index){<br> if(index&lt;0||index&gt;=images.length)return;<br> if(!confirm(`Delete &quot;${images[index].name}&quot; and its annotations?`))return;<br> const oldCurrent=current;<br> const item=images[index];<br> if(item.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(item.url);<br> images.splice(index,1);<br> annotations=annotations.filter(a=&gt;a.image!==index).map(a=&gt;({...a,image:a.image&gt;index?a.image-1:a.image}));<br> selected=null;<br> history=[];<br> if(!images.length)current=-1;<br> else if(oldCurrent&gt;index)current=oldCurrent-1;<br> else if(oldCurrent===index)current=Math.min(index,images.length-1);<br> else current=oldCurrent;<br> renderImages();<br> if(current&gt;=0)showImage();<br> else{<br>  $(&#39;stage&#39;).hidden=true;<br>  $(&#39;empty&#39;).hidden=false;<br>  $(&#39;imageStatus&#39;).textContent=&#39;No active screenshot.&#39;;<br> }<br> render();<br>}<br><br>function removeAllImages(){<br> if(!images.length)return;<br> if(!confirm(&#39;Delete all screenshots and annotations?&#39;))return;<br> images.forEach(i=&gt;{if(i.url?.startsWith(&#39;blob:&#39;))URL.revokeObjectURL(i.url)});<br> images=[];<br> annotations=[];<br> current=-1;<br> selected=null;<br> history=[];<br> $(&#39;stage&#39;).hidden=true;<br> $(&#39;empty&#39;).hidden=false;<br> $(&#39;imageStatus&#39;).textContent=&#39;No active screenshot.&#39;;<br> renderImages();<br> render();<br>}<br><br>function renderImages(){<br> const list=$(&#39;screenshots&#39;);<br> list.innerHTML=&#39;&#39;;<br> $(&#39;imageCount&#39;).textContent=images.length+&#39; screenshots&#39;;<br> images.forEach((item,i)=&gt;{<br>  const row=document.createElement(&#39;div&#39;);<br>  row.className=&#39;screenshot-item&#39;+(i===current?&#39; active&#39;:&#39;&#39;);<br>  const img=document.createElement(&#39;img&#39;);<br>  img.src=item.url;<br>  const info=document.createElement(&#39;div&#39;);<br>  info.className=&#39;screenshot-info&#39;;<br>  const name=document.createElement(&#39;strong&#39;);<br>  name.textContent=item.name;<br>  const size=document.createElement(&#39;span&#39;);<br>  size.textContent=`${item.width} × ${item.height}`;<br>  info.append(name,size);<br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;delete-image danger&#39;;<br>  del.textContent=&#39;✕&#39;;<br>  del.title=&#39;Delete screenshot&#39;;<br>  del.onclick=e=&gt;{e.stopPropagation();deleteImage(i)};<br>  row.append(img,info,del);<br>  row.onclick=()=&gt;{current=i;showImage();renderImages()};<br>  list.appendChild(row);<br> });<br> updateStats();<br>}<br><br>function showImage(){<br> if(current&lt;0||!images[current])return;<br> const item=images[current];<br> $(&#39;stage&#39;).hidden=false;<br> $(&#39;empty&#39;).hidden=true;<br> base.onload=()=&gt;{<br>  overlay.width=item.width;<br>  overlay.height=item.height;<br>  render();<br> };<br> base.src=item.url;<br> $(&#39;imageStatus&#39;).textContent=`${item.name} · ${item.width} × ${item.height}`;<br>}<br><br>// LABELS<br>function drawLabels(){<br> $(&#39;labels&#39;).innerHTML=&#39;&#39;;<br> labels.forEach(label=&gt;{<br>  const div=document.createElement(&#39;div&#39;);<br>  div.className=&#39;label-item&#39;+(selectedLabel===label.id?&#39; active&#39;:&#39;&#39;);<br>  div.style.borderLeft=`3px solid ${label.color}`;<br>  const number=document.createElement(&#39;strong&#39;);<br>  number.textContent=label.id;<br>  const name=document.createElement(&#39;span&#39;);<br>  name.textContent=label.name;<br>  div.append(number,name);<br>  div.onclick=()=&gt;{<br>   selectedLabel=label.id;<br>   $(&#39;labelName&#39;).value=label.name;<br>   $(&#39;labelColor&#39;).value=label.color;<br>   drawLabels();<br>  };<br>  $(&#39;labels&#39;).appendChild(div);<br> });<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(label){<br>  $(&#39;labelName&#39;).value=label.name;<br>  $(&#39;labelColor&#39;).value=label.color;<br> }<br> $(&#39;labelCount&#39;).value=labels.length;<br> updateStats();<br>}<br><br>function applyLabelCount(){<br> let n=parseInt($(&#39;labelCount&#39;).value,10);<br> if(!n||n&lt;1)return alert(&#39;Enter a number from 1 to &#39;+MAX_LABELS+&#39;.&#39;);<br> n=Math.min(n,MAX_LABELS);<br> if(n&lt;labels.length){<br>  const used=annotations.some(a=&gt;a.label&gt;n);<br>  if(used&amp;&amp;!confirm(&#39;Some annotations use labels above &#39;+n+&#39;. They will keep their numbers but those labels will no longer be selectable. Continue?&#39;))return;<br> }<br> labels=makeLabels(n,labels);<br> if(selectedLabel&gt;n)selectedLabel=n;<br> drawLabels();<br> render();<br>}<br><br>function saveLabel(){<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(!label)return;<br> if(!$(&#39;labelName&#39;).value.trim())return alert(&#39;Enter a label name.&#39;);<br> label.name=$(&#39;labelName&#39;).value.trim();<br> label.color=$(&#39;labelColor&#39;).value;<br> drawLabels();<br> render();<br>}<br><br>function resetLabels(){<br> if(!confirm(&#39;Reset all QA labels?&#39;))return;<br> labels=makeLabels(labels.length);<br> selectedLabel=1;<br> drawLabels();<br> render();<br>}<br><br>$(&#39;autoIncrement&#39;).addEventListener(&#39;change&#39;,()=&gt;{<br> $(&#39;autoStatus&#39;).textContent=$(&#39;autoIncrement&#39;).checked<br>  ?&#39;ON: next label selected after each annotation.&#39;<br>  :&#39;OFF: manually select labels.&#39;;<br>});<br><br>function autoIncrementLabel(){<br> if(!$(&#39;autoIncrement&#39;).checked)return;<br> selectedLabel=selectedLabel&gt;=labels.length?1:selectedLabel+1;<br> drawLabels();<br> const active=$(&#39;labels&#39;).querySelector(&#39;.label-item.active&#39;);<br> if(active)active.scrollIntoView({block:&#39;nearest&#39;});<br>}<br><br>// DRAW TOOLS<br>function setMode(value){<br> mode=value;<br> $(&#39;boxTool&#39;).classList.toggle(&#39;active&#39;,value===&#39;box&#39;);<br> $(&#39;circleTool&#39;).classList.toggle(&#39;active&#39;,value===&#39;circle&#39;);<br> $(&#39;toolStatus&#39;).textContent=&#39;Current tool: &#39;+(value===&#39;box&#39;?&#39;Rectangle&#39;:&#39;Circle&#39;);<br>}<br><br>function pointerPosition(e){<br> const r=overlay.getBoundingClientRect();<br> return{x:(e.clientX-r.left)*overlay.width/r.width,y:(e.clientY-r.top)*overlay.height/r.height};<br>}<br><br>overlay.addEventListener(&#39;pointerdown&#39;,e=&gt;{<br> if(current&lt;0)return;<br> e.preventDefault();<br> const p=pointerPosition(e);<br> history.push(JSON.stringify(annotations));<br> drag={startX:p.x,startY:p.y,x:p.x,y:p.y};<br> overlay.setPointerCapture(e.pointerId);<br>});<br><br>overlay.addEventListener(&#39;pointermove&#39;,e=&gt;{<br> if(!drag)return;<br> const p=pointerPosition(e);<br> drag.x=p.x;drag.y=p.y;<br> render(drag);<br>});<br><br>overlay.addEventListener(&#39;pointerup&#39;,e=&gt;{<br> if(!drag)return;<br> const p=pointerPosition(e);<br> drag.x=p.x;drag.y=p.y;<br> const x=Math.min(drag.startX,drag.x);<br> const y=Math.min(drag.startY,drag.y);<br> const w=Math.abs(drag.x-drag.startX);<br> const h=Math.abs(drag.y-drag.startY);<br> if(w&lt;3&amp;&amp;h&lt;3){<br>  history.pop();drag=null;render();return;<br> }<br> const label=labels.find(l=&gt;l.id===selectedLabel);<br> if(!label){drag=null;render();return}<br> const a={<br>  id:crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.random()),<br>  image:current,label:label.id,name:label.name,color:label.color,type:mode,x,y,w,h<br> };<br> annotations.push(a);<br> selected=a.id;<br> drag=null;<br> autoIncrementLabel();<br> render();<br>});<br><br>overlay.addEventListener(&#39;pointercancel&#39;,()=&gt;{drag=null;render()});<br><br>// ANNOTATION RENDERING<br>function drawAnnotation(a,isSelected=false){<br> ctx.save();<br> ctx.strokeStyle=a.color;<br> ctx.fillStyle=a.color;<br> ctx.lineWidth=Math.max(3,overlay.width/500);<br> if(a.type===&#39;circle&#39;){<br>  const radius=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>  ctx.beginPath();<br>  ctx.arc(a.x+a.w/2,a.y+a.h/2,radius,0,Math.PI*2);<br>  ctx.stroke();<br>  ctx.fillStyle=a.color;<br>  ctx.font=`bold ${Math.max(14,radius)}px Arial`;<br>  ctx.textAlign=&#39;center&#39;;ctx.textBaseline=&#39;middle&#39;;<br>  ctx.fillText(String(a.label),a.x+a.w/2,a.y+a.h/2);<br> }else{<br>  ctx.strokeRect(a.x,a.y,a.w,a.h);<br>  const mw=Math.max(32,String(a.label).length*11+15);<br>  ctx.fillRect(a.x,Math.max(0,a.y-25),mw,25);<br>  ctx.fillStyle=&#39;white&#39;;<br>  ctx.font=&#39;bold 15px Arial&#39;;<br>  ctx.textAlign=&#39;center&#39;;ctx.textBaseline=&#39;middle&#39;;<br>  ctx.fillText(String(a.label),a.x+mw/2,Math.max(0,a.y-25)+12.5);<br> }<br> if(isSelected){<br>  ctx.setLineDash([7,5]);ctx.strokeStyle=&#39;white&#39;;ctx.lineWidth=2;<br>  if(a.type===&#39;circle&#39;){<br>   const r=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>   ctx.beginPath();ctx.arc(a.x+a.w/2,a.y+a.h/2,r+6,0,Math.PI*2);ctx.stroke();<br>  }else ctx.strokeRect(a.x-4,a.y-4,a.w+8,a.h+8);<br> }<br> ctx.restore();<br>}<br><br>function render(preview=null){<br> if(!overlay.width||!overlay.height){renderAnnotationList();updateStats();return}<br> ctx.clearRect(0,0,overlay.width,overlay.height);<br> annotations.filter(a=&gt;a.image===current).forEach(a=&gt;drawAnnotation(a,a.id===selected));<br> if(preview){<br>  const l=labels.find(x=&gt;x.id===selectedLabel);<br>  if(l){<br>   ctx.save();ctx.globalAlpha=.65;<br>   drawAnnotation({<br>    type:mode,x:Math.min(preview.startX,preview.x),<br>    y:Math.min(preview.startY,preview.y),<br>    w:Math.abs(preview.x-preview.startX),<br>    h:Math.abs(preview.y-preview.startY),<br>    label:l.id,color:l.color<br>   });<br>   ctx.restore();<br>  }<br> }<br> renderAnnotationList();<br> updateStats();<br>}<br><br>function renderAnnotationList(){<br> const list=$(&#39;annotations&#39;);<br> list.innerHTML=&#39;&#39;;<br> const visible=annotations.filter(a=&gt;a.image===current);<br> $(&#39;annotationCount&#39;).textContent=visible.length+&#39; annotations&#39;;<br> visible.forEach(a=&gt;{<br>  const row=document.createElement(&#39;div&#39;);<br>  row.className=&#39;annotation-item&#39;+(a.id===selected?&#39; active&#39;:&#39;&#39;);<br>  const dot=document.createElement(&#39;span&#39;);<br>  dot.className=&#39;annotation-dot&#39;;<br>  dot.style.background=a.color;<br>  const text=document.createElement(&#39;span&#39;);<br>  text.textContent=`#${a.label} · ${a.name} · ${a.type}`;<br>  const del=document.createElement(&#39;button&#39;);<br>  del.className=&#39;danger&#39;;del.textContent=&#39;✕&#39;;<br>  del.onclick=e=&gt;{e.stopPropagation();deleteAnnotation(a.id)};<br>  row.append(dot,text,del);<br>  row.onclick=()=&gt;{selected=a.id;render()};<br>  list.appendChild(row);<br> });<br>}<br><br>function deleteAnnotation(id){<br> history.push(JSON.stringify(annotations));<br> annotations=annotations.filter(a=&gt;a.id!==id);<br> if(selected===id)selected=null;<br> render();<br>}<br><br>function deleteSelected(){<br> if(!selected)return alert(&#39;Select an annotation first.&#39;);<br> deleteAnnotation(selected);<br>}<br><br>function undo(){<br> if(!history.length)return alert(&#39;Nothing to undo.&#39;);<br> annotations=JSON.parse(history.pop());<br> selected=null;<br> render();<br>}<br><br>function clearAnnotations(){<br> const count=annotations.filter(a=&gt;a.image===current).length;<br> if(!count)return;<br> if(!confirm(&#39;Clear annotations on this screenshot?&#39;))return;<br> history.push(JSON.stringify(annotations));<br> annotations=annotations.filter(a=&gt;a.image!==current);<br> selected=null;<br> render();<br>}<br><br>// MERGE IMAGES<br>function mergeImages(direction){<br> if(images.length&lt;2)return alert(&#39;Upload at least two screenshots.&#39;);<br> const source=images.slice();<br> const canvas=document.createElement(&#39;canvas&#39;);<br> const c=canvas.getContext(&#39;2d&#39;);<br> if(direction===&#39;vertical&#39;){<br>  canvas.width=Math.max(...source.map(x=&gt;x.width));<br>  canvas.height=source.reduce((n,x)=&gt;n+x.height,0);<br>  let y=0;<br>  source.forEach(x=&gt;{c.drawImage(x.img,0,y);y+=x.height});<br> }else{<br>  canvas.width=source.reduce((n,x)=&gt;n+x.width,0);<br>  canvas.height=Math.max(...source.map(x=&gt;x.height));<br>  let x=0;<br>  source.forEach(i=&gt;{c.drawImage(i.img,x,0);x+=i.width});<br> }<br> canvas.toBlob(blob=&gt;{if(blob)addImageFromBlob(blob,`Merged ${direction} ${Date.now()}`)},&#39;image/png&#39;);<br>}<br><br>// EXPORT<br>function drawExportAnnotation(c,a,width){<br> c.save();c.strokeStyle=a.color;c.fillStyle=a.color;<br> c.lineWidth=Math.max(3,width/500);<br> if(a.type===&#39;circle&#39;){<br>  const r=Math.max(15,Math.min(a.w,a.h,55)/2||18);<br>  c.beginPath();c.arc(a.x+a.w/2,a.y+a.h/2,r,0,Math.PI*2);c.stroke();<br>  c.font=`bold ${Math.max(14,r)}px Arial`;<br>  c.textAlign=&#39;center&#39;;c.textBaseline=&#39;middle&#39;;<br>  c.fillText(String(a.label),a.x+a.w/2,a.y+a.h/2);<br> }else{<br>  c.strokeRect(a.x,a.y,a.w,a.h);<br>  const mw=Math.max(32,String(a.label).length*11+15);<br>  c.fillRect(a.x,Math.max(0,a.y-25),mw,25);<br>  c.fillStyle=&#39;white&#39;;c.font=&#39;bold 15px Arial&#39;;<br>  c.textAlign=&#39;center&#39;;c.textBaseline=&#39;middle&#39;;<br>  c.fillText(String(a.label),a.x+mw/2,Math.max(0,a.y-25)+12.5);<br> }<br> c.restore();<br>}<br><br>function createExportCanvas(index){<br> const item=images[index];if(!item)return null;<br> const canvas=document.createElement(&#39;canvas&#39;);<br> canvas.width=item.width;canvas.height=item.height;<br> const c=canvas.getContext(&#39;2d&#39;);<br> c.drawImage(item.img,0,0);<br> annotations.filter(a=&gt;a.image===index).forEach(a=&gt;drawExportAnnotation(c,a,item.width));<br> return canvas;<br>}<br><br>function downloadCanvas(canvas,name){<br> canvas.toBlob(blob=&gt;{<br>  if(!blob)return alert(&#39;Could not export image. It may be too large.&#39;);<br>  const url=URL.createObjectURL(blob);<br>  const link=document.createElement(&#39;a&#39;);<br>  link.href=url;link.download=name;link.click();<br>  setTimeout(()=&gt;URL.revokeObjectURL(url),1500);<br> },&#39;image/png&#39;);<br>}<br><br>function exportPNG(){<br> if(current&lt;0)return alert(&#39;Load a screenshot first.&#39;);<br> const canvas=createExportCanvas(current);<br> if(canvas)downloadCanvas(canvas,`QA-Evidence-${Date.now()}.png`);<br>}<br><br>function exportAllPNG(){<br> if(!images.length)return alert(&#39;No screenshots to export.&#39;);<br> images.forEach((item,i)=&gt;{<br>  const canvas=createExportCanvas(i);<br>  if(canvas)downloadCanvas(canvas,`QA-Evidence-${i+1}.png`);<br> });<br>}<br><br>function updateStats(){<br> $(&#39;statImages&#39;).textContent=images.length;<br> $(&#39;statAnnotations&#39;).textContent=annotations.length;<br> $(&#39;statLabels&#39;).textContent=labels.length;<br>}<br><br>// INITIALIZE<br>drawLabels();<br>renderImages();<br>render();<br>updateStats();<br><br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c332cbcd9776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[updating2..]]></title>
            <link>https://medium.com/@barabonajansen/updating2-2b56a1e7824d?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b56a1e7824d</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 05:51:37 GMT</pubDate>
            <atom:updated>2026-11-14T05:51:37.708Z</atom:updated>
            <content:encoded><![CDATA[<pre><br>&lt;script&gt;<br>/* =========================================================<br>   QA SCREENSHOT STUDIO<br>   Complete JavaScript<br>   ========================================================= */<br><br>/* -------------------------<br>   STATE<br>------------------------- */<br><br>let images = [];<br>let annotations = [];<br>let current = -1;<br><br>let labels = Array.from({ length: 56 }, (_, i) =&gt; ({<br>    id: i + 1,<br>    name: `QA ${i + 1}`,<br>    color: &quot;#ff4242&quot;<br>}));<br><br>let selectedLabel = 1;<br>let nextLabelId = 57;<br><br>let autoIncrement = true;<br>let annotationMode = &quot;rectangle&quot;;<br>let isDrawing = false;<br>let startPoint = null;<br>let previewAnnotation = null;<br><br>let screenStream = null;<br>let undoHistory = [];<br><br>/* -------------------------<br>   ELEMENT HELPERS<br>------------------------- */<br><br>function el(id) {<br>    return document.getElementById(id);<br>}<br><br>function notify(message) {<br>    alert(message);<br>}<br><br>function saveSettings() {<br>    try {<br>        localStorage.setItem(&quot;qa_labels&quot;, JSON.stringify(labels));<br>        localStorage.setItem(&quot;qa_next_label_id&quot;, String(nextLabelId));<br>        localStorage.setItem(&quot;qa_selected_label&quot;, String(selectedLabel));<br>        localStorage.setItem(&quot;qa_auto_increment&quot;, String(autoIncrement));<br>    } catch (error) {<br>        console.warn(&quot;Could not save settings:&quot;, error);<br>    }<br>}<br><br>function loadSettings() {<br>    try {<br>        const savedLabels = JSON.parse(localStorage.getItem(&quot;qa_labels&quot;));<br><br>        if (Array.isArray(savedLabels) &amp;&amp; savedLabels.length) {<br>            labels = savedLabels;<br>        }<br><br>        nextLabelId = Math.max(<br>            Number(localStorage.getItem(&quot;qa_next_label_id&quot;)) || 57,<br>            ...labels.map(label =&gt; Number(label.id) + 1)<br>        );<br><br>        const savedSelected = Number(<br>            localStorage.getItem(&quot;qa_selected_label&quot;)<br>        );<br><br>        if (labels.some(label =&gt; label.id === savedSelected)) {<br>            selectedLabel = savedSelected;<br>        }<br><br>        autoIncrement =<br>            localStorage.getItem(&quot;qa_auto_increment&quot;) !== &quot;false&quot;;<br><br>    } catch (error) {<br>        console.warn(&quot;Settings could not be loaded:&quot;, error);<br>    }<br>}<br><br>/* -------------------------<br>   LABEL MANAGEMENT<br>------------------------- */<br><br>function addLabel() {<br>    const id = nextLabelId++;<br><br>    labels.push({<br>        id,<br>        name: `QA ${id}`,<br>        color: &quot;#ff4242&quot;<br>    });<br><br>    selectedLabel = id;<br><br>    saveSettings();<br>    drawLabels();<br>}<br><br>function addLabels(amount = 10) {<br>    for (let i = 0; i &lt; amount; i++) {<br>        const id = nextLabelId++;<br><br>        labels.push({<br>            id,<br>            name: `QA ${id}`,<br>            color: &quot;#ff4242&quot;<br>        });<br>    }<br><br>    selectedLabel = labels[labels.length - 1].id;<br><br>    saveSettings();<br>    drawLabels();<br>}<br><br>function drawLabels() {<br>    const container = el(&quot;labelList&quot;);<br>    if (!container) return;<br><br>    container.innerHTML = &quot;&quot;;<br><br>    const search = el(&quot;labelSearch&quot;);<br>    const query = search ? search.value.toLowerCase() : &quot;&quot;;<br><br>    labels<br>        .filter(label =&gt;<br>            String(label.id).includes(query) ||<br>            label.name.toLowerCase().includes(query)<br>        )<br>        .forEach(label =&gt; {<br>            const button = document.createElement(&quot;button&quot;);<br><br>            button.type = &quot;button&quot;;<br>            button.textContent = `${label.id} - ${label.name}`;<br>            button.style.display = &quot;block&quot;;<br>            button.style.width = &quot;100%&quot;;<br>            button.style.marginBottom = &quot;5px&quot;;<br>            button.style.padding = &quot;8px&quot;;<br>            button.style.border = &quot;1px solid #555&quot;;<br>            button.style.borderRadius = &quot;6px&quot;;<br>            button.style.cursor = &quot;pointer&quot;;<br>            button.style.background =<br>                label.id === selectedLabel ? &quot;#333&quot; : &quot;#191919&quot;;<br>            button.style.color = &quot;#fff&quot;;<br>            button.style.borderLeft = `5px solid ${label.color}`;<br><br>            button.onclick = () =&gt; {<br>                selectedLabel = label.id;<br>                drawLabels();<br>                updateLabelEditor();<br>                saveSettings();<br>            };<br><br>            container.appendChild(button);<br>        });<br><br>    if (el(&quot;labelCount&quot;)) {<br>        el(&quot;labelCount&quot;).textContent =<br>            `${labels.length} labels available`;<br>    }<br><br>    updateLabelEditor();<br><br>    const toggle = el(&quot;autoIncrement&quot;);<br>    if (toggle) toggle.checked = autoIncrement;<br>}<br><br>function updateLabelEditor() {<br>    const label = labels.find(l =&gt; l.id === selectedLabel);<br>    if (!label) return;<br><br>    if (el(&quot;labelName&quot;)) el(&quot;labelName&quot;).value = label.name;<br>    if (el(&quot;labelColor&quot;)) el(&quot;labelColor&quot;).value = label.color;<br>}<br><br>function saveLabel() {<br>    const label = labels.find(l =&gt; l.id === selectedLabel);<br>    if (!label) return;<br><br>    const name = el(&quot;labelName&quot;);<br>    const color = el(&quot;labelColor&quot;);<br><br>    if (name) label.name = name.value.trim() || `QA ${label.id}`;<br>    if (color) label.color = color.value;<br><br>    saveSettings();<br>    drawLabels();<br>}<br><br>function deleteLabel() {<br>    if (labels.length &lt;= 1) {<br>        notify(&quot;At least one QA label must remain.&quot;);<br>        return;<br>    }<br><br>    const label = labels.find(l =&gt; l.id === selectedLabel);<br>    if (!label) return;<br><br>    if (!confirm(`Delete ${label.name}?`)) return;<br><br>    labels = labels.filter(l =&gt; l.id !== selectedLabel);<br><br>    selectedLabel = labels[0].id;<br><br>    saveSettings();<br>    drawLabels();<br>}<br><br>function autoIncrementLabel() {<br>    if (!autoIncrement) return;<br><br>    const next = labels.find(l =&gt; l.id &gt; selectedLabel);<br><br>    if (next) {<br>        selectedLabel = next.id;<br>        drawLabels();<br>    } else {<br>        addLabel();<br>    }<br><br>    saveSettings();<br>}<br><br>function toggleAutoIncrement(value) {<br>    autoIncrement = Boolean(value);<br>    saveSettings();<br>}<br><br>/* -------------------------<br>   LABEL INITIALIZATION<br>------------------------- */<br><br>loadSettings();<br><br>/* -------------------------<br>   SCREEN CAPTURE<br>------------------------- */<br><br>async function startScreenCapture() {<br>    try {<br>        if (!navigator.mediaDevices ||<br>            !navigator.mediaDevices.getDisplayMedia) {<br>            notify(<br>                &quot;Screen capture is unavailable. Open this page using Chrome or Edge on localhost or HTTPS.&quot;<br>            );<br>            return;<br>        }<br><br>        screenStream = await navigator.mediaDevices.getDisplayMedia({<br>            video: {<br>                frameRate: 15<br>            },<br>            audio: false<br>        });<br><br>        const video = el(&quot;liveVideo&quot;);<br><br>        if (!video) {<br>            notify(&quot;Missing HTML element: liveVideo&quot;);<br>            stopScreenCapture();<br>            return;<br>        }<br><br>        video.srcObject = screenStream;<br>        await video.play();<br><br>        const track = screenStream.getVideoTracks()[0];<br><br>        track.addEventListener(&quot;ended&quot;, () =&gt; {<br>            video.srcObject = null;<br>            screenStream = null;<br>        });<br><br>    } catch (error) {<br>        console.error(error);<br><br>        if (error.name === &quot;NotAllowedError&quot;) {<br>            notify(&quot;Screen sharing was cancelled or permission was denied.&quot;);<br>        } else {<br>            notify(&quot;Screen capture failed: &quot; + error.message);<br>        }<br>    }<br>}<br><br>function stopScreenCapture() {<br>    if (screenStream) {<br>        screenStream.getTracks().forEach(track =&gt; track.stop());<br>        screenStream = null;<br>    }<br><br>    const video = el(&quot;liveVideo&quot;);<br><br>    if (video) {<br>        video.srcObject = null;<br>    }<br>}<br><br>function captureFrame() {<br>    const video = el(&quot;liveVideo&quot;);<br><br>    if (!video || !video.srcObject || !video.videoWidth) {<br>        notify(&quot;Start screen sharing first.&quot;);<br>        return;<br>    }<br><br>    const canvas = document.createElement(&quot;canvas&quot;);<br><br>    canvas.width = video.videoWidth;<br>    canvas.height = video.videoHeight;<br><br>    const context = canvas.getContext(&quot;2d&quot;);<br>    context.drawImage(video, 0, 0);<br><br>    canvas.toBlob(blob =&gt; {<br>        if (blob) addImageFromBlob(blob, &quot;Screen Capture&quot;);<br>    }, &quot;image/png&quot;);<br>}<br><br>/* -------------------------<br>   IMAGE MANAGEMENT<br>------------------------- */<br><br>function addImageFromBlob(blob, name = &quot;Screenshot&quot;) {<br>    const url = URL.createObjectURL(blob);<br><br>    const image = new Image();<br><br>    image.onload = () =&gt; {<br>        images.push({<br>            name,<br>            url,<br>            image<br>        });<br><br>        current = images.length - 1;<br><br>        renderImages();<br>        renderCanvas();<br>    };<br><br>    image.onerror = () =&gt; {<br>        URL.revokeObjectURL(url);<br>        notify(&quot;Could not load the screenshot.&quot;);<br>    };<br><br>    image.src = url;<br>}<br><br>function uploadImages(event) {<br>    const files = Array.from(event.target.files || []);<br><br>    files.forEach(file =&gt; {<br>        if (file.type.startsWith(&quot;image/&quot;)) {<br>            addImageFromBlob(file, file.name);<br>        }<br>    });<br><br>    event.target.value = &quot;&quot;;<br>}<br><br>function pasteImage(event) {<br>    const items = event.clipboardData?.items || [];<br><br>    for (const item of items) {<br>        if (item.type.startsWith(&quot;image/&quot;)) {<br>            const blob = item.getAsFile();<br><br>            if (blob) {<br>                addImageFromBlob(blob, &quot;Pasted Screenshot&quot;);<br>            }<br>        }<br>    }<br>}<br><br>document.addEventListener(&quot;paste&quot;, pasteImage);<br><br>function selectImage(index) {<br>    if (index &lt; 0 || index &gt;= images.length) return;<br><br>    current = index;<br>    renderImages();<br>    renderCanvas();<br>}<br><br>function deleteImage(index) {<br>    if (index &lt; 0 || index &gt;= images.length) return;<br><br>    if (!confirm(&quot;Delete this screenshot?&quot;)) return;<br><br>    URL.revokeObjectURL(images[index].url);<br><br>    const oldCurrent = current;<br><br>    images.splice(index, 1);<br><br>    annotations = annotations<br>        .filter(a =&gt; a.image !== index)<br>        .map(a =&gt; ({<br>            ...a,<br>            image: a.image &gt; index ? a.image - 1 : a.image<br>        }));<br><br>    if (oldCurrent &gt; index) {<br>        current = oldCurrent - 1;<br>    } else if (oldCurrent === index) {<br>        current = Math.min(index, images.length - 1);<br>    } else {<br>        current = oldCurrent;<br>    }<br><br>    current = images.length ? current : -1;<br><br>    undoHistory = [];<br><br>    renderImages();<br>    renderCanvas();<br>    renderAnnotationHistory();<br>}<br><br>function deleteAllImages() {<br>    if (!images.length) return;<br><br>    if (!confirm(&quot;Delete all screenshots and annotations?&quot;)) return;<br><br>    images.forEach(item =&gt; URL.revokeObjectURL(item.url));<br><br>    images = [];<br>    annotations = [];<br>    undoHistory = [];<br>    current = -1;<br><br>    renderImages();<br>    renderCanvas();<br>    renderAnnotationHistory();<br>}<br><br>/* -------------------------<br>   IMAGE LIST<br>------------------------- */<br><br>function renderImages() {<br>    const container = el(&quot;imageList&quot;);<br>    if (!container) return;<br><br>    container.innerHTML = &quot;&quot;;<br><br>    images.forEach((item, index) =&gt; {<br>        const wrapper = document.createElement(&quot;div&quot;);<br><br>        wrapper.style.display = &quot;inline-block&quot;;<br>        wrapper.style.margin = &quot;6px&quot;;<br>        wrapper.style.padding = &quot;6px&quot;;<br>        wrapper.style.border =<br>            current === index ? &quot;2px solid #36a3ff&quot; : &quot;1px solid #555&quot;;<br>        wrapper.style.borderRadius = &quot;8px&quot;;<br><br>        const thumbnail = document.createElement(&quot;img&quot;);<br><br>        thumbnail.src = item.url;<br>        thumbnail.alt = item.name;<br>        thumbnail.style.width = &quot;110px&quot;;<br>        thumbnail.style.height = &quot;75px&quot;;<br>        thumbnail.style.objectFit = &quot;cover&quot;;<br>        thumbnail.style.cursor = &quot;pointer&quot;;<br>        thumbnail.onclick = () =&gt; selectImage(index);<br><br>        const name = document.createElement(&quot;div&quot;);<br>        name.textContent = item.name;<br>        name.style.fontSize = &quot;12px&quot;;<br><br>        const selectButton = document.createElement(&quot;button&quot;);<br>        selectButton.textContent = &quot;Select&quot;;<br>        selectButton.onclick = () =&gt; selectImage(index);<br><br>        const deleteButton = document.createElement(&quot;button&quot;);<br>        deleteButton.textContent = &quot;Delete&quot;;<br>        deleteButton.onclick = () =&gt; deleteImage(index);<br><br>        wrapper.append(<br>            thumbnail,<br>            name,<br>            selectButton,<br>            deleteButton<br>        );<br><br>        container.appendChild(wrapper);<br>    });<br><br>    if (el(&quot;imageCount&quot;)) {<br>        el(&quot;imageCount&quot;).textContent = `${images.length} screenshots`;<br>    }<br>}<br><br>/* -------------------------<br>   CANVAS<br>------------------------- */<br><br>function getCanvas() {<br>    return el(&quot;imageCanvas&quot;);<br>}<br><br>function renderCanvas() {<br>    const canvas = getCanvas();<br>    if (!canvas) return;<br><br>    const ctx = canvas.getContext(&quot;2d&quot;);<br><br>    if (current &lt; 0 || !images[current]) {<br>        canvas.width = 900;<br>        canvas.height = 500;<br><br>        ctx.fillStyle = &quot;#222&quot;;<br>        ctx.fillRect(0, 0, canvas.width, canvas.height);<br><br>        ctx.fillStyle = &quot;#aaa&quot;;<br>        ctx.font = &quot;20px Arial&quot;;<br>        ctx.textAlign = &quot;center&quot;;<br>        ctx.fillText(<br>            &quot;Upload or capture a screenshot&quot;,<br>            canvas.width / 2,<br>            canvas.height / 2<br>        );<br><br>        return;<br>    }<br><br>    const img = images[current].image;<br><br>    canvas.width = img.naturalWidth;<br>    canvas.height = img.naturalHeight;<br><br>    ctx.drawImage(img, 0, 0);<br><br>    annotations<br>        .filter(a =&gt; a.image === current)<br>        .forEach(a =&gt; drawAnnotation(ctx, a));<br><br>    if (previewAnnotation) {<br>        drawAnnotation(ctx, previewAnnotation);<br>    }<br>}<br><br>function getPointerPosition(event) {<br>    const canvas = getCanvas();<br>    const rect = canvas.getBoundingClientRect();<br><br>    return {<br>        x: (event.clientX - rect.left) *<br>            (canvas.width / rect.width),<br>        y: (event.clientY - rect.top) *<br>            (canvas.height / rect.height)<br>    };<br>}<br><br>/* -------------------------<br>   ANNOTATION DRAWING<br>------------------------- */<br><br>function getSelectedLabel() {<br>    return labels.find(l =&gt; l.id === selectedLabel) || {<br>        id: selectedLabel,<br>        name: `QA ${selectedLabel}`,<br>        color: &quot;#ff4242&quot;<br>    };<br>}<br><br>function drawAnnotation(ctx, annotation) {<br>    const color = annotation.color || &quot;#ff4242&quot;;<br><br>    ctx.save();<br><br>    ctx.strokeStyle = color;<br>    ctx.fillStyle = color;<br>    ctx.lineWidth = 4;<br><br>    if (annotation.type === &quot;rectangle&quot;) {<br>        const width = annotation.width || 0;<br>        const height = annotation.height || 0;<br><br>        ctx.strokeRect(<br>            annotation.x,<br>            annotation.y,<br>            width,<br>            height<br>        );<br><br>        ctx.font = &quot;bold 22px Arial&quot;;<br><br>        const text = String(annotation.label);<br><br>        ctx.fillStyle = color;<br>        ctx.fillRect(<br>            annotation.x,<br>            Math.max(0, annotation.y - 30),<br>            48,<br>            28<br>        );<br><br>        ctx.fillStyle = &quot;#fff&quot;;<br>        ctx.fillText(<br>            text,<br>            annotation.x + 8,<br>            Math.max(20, annotation.y - 9)<br>        );<br><br>    } else if (annotation.type === &quot;circle&quot;) {<br>        const radius = annotation.radius || 20;<br><br>        ctx.beginPath();<br>        ctx.arc(<br>            annotation.x,<br>            annotation.y,<br>            radius,<br>            0,<br>            Math.PI * 2<br>        );<br><br>        ctx.stroke();<br><br>        ctx.fillStyle = color;<br>        ctx.beginPath();<br>        ctx.arc(<br>            annotation.x,<br>            annotation.y,<br>            radius,<br>            0,<br>            Math.PI * 2<br>        );<br>        ctx.fill();<br><br>        ctx.fillStyle = &quot;#fff&quot;;<br>        ctx.font = &quot;bold 16px Arial&quot;;<br>        ctx.textAlign = &quot;center&quot;;<br>        ctx.textBaseline = &quot;middle&quot;;<br>        ctx.fillText(<br>            String(annotation.label),<br>            annotation.x,<br>            annotation.y<br>        );<br>    }<br><br>    ctx.restore();<br>}<br><br>/* -------------------------<br>   ANNOTATION EVENTS<br>------------------------- */<br><br>function setAnnotationMode(mode) {<br>    annotationMode = mode;<br>}<br><br>function startDrawing(event) {<br>    if (current &lt; 0) {<br>        notify(&quot;Select or capture a screenshot first.&quot;);<br>        return;<br>    }<br><br>    const canvas = getCanvas();<br>    if (!canvas) return;<br><br>    isDrawing = true;<br>    startPoint = getPointerPosition(event);<br><br>    canvas.setPointerCapture?.(event.pointerId);<br><br>    const label = getSelectedLabel();<br><br>    previewAnnotation = {<br>        image: current,<br>        label: label.id,<br>        name: label.name,<br>        color: label.color,<br>        type: annotationMode,<br>        x: startPoint.x,<br>        y: startPoint.y,<br>        width: 0,<br>        height: 0,<br>        radius: 20<br>    };<br>}<br><br>function moveDrawing(event) {<br>    if (!isDrawing || !startPoint) return;<br><br>    const point = getPointerPosition(event);<br><br>    if (annotationMode === &quot;rectangle&quot;) {<br>        previewAnnotation.width = point.x - startPoint.x;<br>        previewAnnotation.height = point.y - startPoint.y;<br>    } else {<br>        previewAnnotation.radius = Math.max(<br>            15,<br>            Math.sqrt(<br>                Math.pow(point.x - startPoint.x, 2) +<br>                Math.pow(point.y - startPoint.y, 2)<br>            )<br>        );<br>    }<br><br>    renderCanvas();<br>}<br><br>function finishDrawing() {<br>    if (!isDrawing || !previewAnnotation) return;<br><br>    isDrawing = false;<br><br>    if (<br>        previewAnnotation.type === &quot;rectangle&quot; &amp;&amp;<br>        (<br>            Math.abs(previewAnnotation.width) &lt; 3 ||<br>            Math.abs(previewAnnotation.height) &lt; 3<br>        )<br>    ) {<br>        previewAnnotation = null;<br>        renderCanvas();<br>        return;<br>    }<br><br>    undoHistory.push(<br>        annotations.map(a =&gt; ({ ...a }))<br>    );<br><br>    annotations.push({<br>        ...previewAnnotation<br>    });<br><br>    previewAnnotation = null;<br>    startPoint = null;<br><br>    renderCanvas();<br>    renderAnnotationHistory();<br><br>    autoIncrementLabel();<br>}<br><br>/* -------------------------<br>   ANNOTATION HISTORY<br>------------------------- */<br><br>function renderAnnotationHistory() {<br>    const container = el(&quot;annotationHistory&quot;);<br>    if (!container) return;<br><br>    container.innerHTML = &quot;&quot;;<br><br>    annotations<br>        .filter(a =&gt; a.image === current)<br>        .forEach((annotation, index) =&gt; {<br>            const row = document.createElement(&quot;div&quot;);<br><br>            row.style.padding = &quot;7px&quot;;<br>            row.style.borderBottom = &quot;1px solid #444&quot;;<br><br>            const info = document.createElement(&quot;span&quot;);<br>            info.textContent =<br>                `${annotation.label} - ${annotation.name} (${annotation.type})`;<br><br>            const remove = document.createElement(&quot;button&quot;);<br>            remove.textContent = &quot;Delete&quot;;<br><br>            remove.onclick = () =&gt; {<br>                const globalIndex = annotations.indexOf(annotation);<br><br>                undoHistory.push(<br>                    annotations.map(a =&gt; ({ ...a }))<br>                );<br><br>                annotations.splice(globalIndex, 1);<br><br>                renderCanvas();<br>                renderAnnotationHistory();<br>            };<br><br>            row.append(info, remove);<br>            container.appendChild(row);<br>        });<br>}<br><br>function undoAnnotation() {<br>    if (!undoHistory.length) return;<br><br>    annotations = undoHistory.pop();<br><br>    renderCanvas();<br>    renderAnnotationHistory();<br>}<br><br>function clearCurrentAnnotations() {<br>    if (current &lt; 0) return;<br><br>    undoHistory.push(<br>        annotations.map(a =&gt; ({ ...a }))<br>    );<br><br>    annotations = annotations.filter(a =&gt; a.image !== current);<br><br>    renderCanvas();<br>    renderAnnotationHistory();<br>}<br><br>/* -------------------------<br>   EXPORT<br>------------------------- */<br><br>function exportCurrentPNG() {<br>    if (current &lt; 0) {<br>        notify(&quot;No screenshot selected.&quot;);<br>        return;<br>    }<br><br>    const canvas = getCanvas();<br><br>    canvas.toBlob(blob =&gt; {<br>        if (blob) downloadBlob(<br>            blob,<br>            `QA-Screenshot-${current + 1}.png`<br>        );<br>    }, &quot;image/png&quot;);<br>}<br><br>function exportAllPNG() {<br>    if (!images.length) {<br>        notify(&quot;No screenshots available.&quot;);<br>        return;<br>    }<br><br>    const original = current;<br><br>    images.forEach((image, index) =&gt; {<br>        current = index;<br>        renderCanvas();<br><br>        const canvas = getCanvas();<br><br>        canvas.toBlob(blob =&gt; {<br>            if (blob) {<br>                downloadBlob(<br>                    blob,<br>                    `QA-Screenshot-${index + 1}.png`<br>                );<br>            }<br><br>            if (index === images.length - 1) {<br>                current = original;<br>                renderCanvas();<br>            }<br>        }, &quot;image/png&quot;);<br>    });<br>}<br><br>function downloadBlob(blob, filename) {<br>    const url = URL.createObjectURL(blob);<br><br>    const link = document.createElement(&quot;a&quot;);<br>    link.href = url;<br>    link.download = filename;<br><br>    document.body.appendChild(link);<br>    link.click();<br>    link.remove();<br><br>    setTimeout(() =&gt; URL.revokeObjectURL(url), 1000);<br>}<br><br>/* -------------------------<br>   MERGE SCREENSHOTS<br>------------------------- */<br><br>function mergeImages(direction = &quot;vertical&quot;) {<br>    if (images.length &lt; 2) {<br>        notify(&quot;Upload at least two screenshots to merge.&quot;);<br>        return;<br>    }<br><br>    const loaded = images.map(item =&gt; item.image);<br><br>    let width = 0;<br>    let height = 0;<br><br>    if (direction === &quot;vertical&quot;) {<br>        width = Math.max(...loaded.map(img =&gt; img.width));<br>        height = loaded.reduce((sum, img) =&gt; sum + img.height, 0);<br>    } else {<br>        width = loaded.reduce((sum, img) =&gt; sum + img.width, 0);<br>        height = Math.max(...loaded.map(img =&gt; img.height));<br>    }<br><br>    const canvas = document.createElement(&quot;canvas&quot;);<br>    canvas.width = width;<br>    canvas.height = height;<br><br>    const ctx = canvas.getContext(&quot;2d&quot;);<br><br>    let offset = 0;<br><br>    loaded.forEach(img =&gt; {<br>        if (direction === &quot;vertical&quot;) {<br>            ctx.drawImage(img, 0, offset);<br>            offset += img.height;<br>        } else {<br>            ctx.drawImage(img, offset, 0);<br>            offset += img.width;<br>        }<br>    });<br><br>    canvas.toBlob(blob =&gt; {<br>        if (blob) addImageFromBlob(blob, &quot;Merged Screenshot&quot;);<br>    }, &quot;image/png&quot;);<br>}<br><br>/* -------------------------<br>   EVENT INITIALIZATION<br>------------------------- */<br><br>function initializeQAStudio() {<br>    drawLabels();<br>    renderImages();<br>    renderCanvas();<br>    renderAnnotationHistory();<br><br>    const canvas = getCanvas();<br><br>    if (canvas &amp;&amp; !canvas.dataset.eventsAttached) {<br>        canvas.dataset.eventsAttached = &quot;true&quot;;<br><br>        canvas.addEventListener(&quot;pointerdown&quot;, startDrawing);<br>        canvas.addEventListener(&quot;pointermove&quot;, moveDrawing);<br>        canvas.addEventListener(&quot;pointerup&quot;, finishDrawing);<br>        canvas.addEventListener(&quot;pointercancel&quot;, finishDrawing);<br>    }<br><br>    const toggle = el(&quot;autoIncrement&quot;);<br><br>    if (toggle) {<br>        toggle.checked = autoIncrement;<br><br>        toggle.addEventListener(&quot;change&quot;, event =&gt; {<br>            toggleAutoIncrement(event.target.checked);<br>        });<br>    }<br><br>    const search = el(&quot;labelSearch&quot;);<br><br>    if (search) {<br>        search.addEventListener(&quot;input&quot;, drawLabels);<br>    }<br>}<br><br>if (document.readyState === &quot;loading&quot;) {<br>    document.addEventListener(<br>        &quot;DOMContentLoaded&quot;,<br>        initializeQAStudio<br>    );<br>} else {<br>    initializeQAStudio();<br>}<br>&lt;/script&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b56a1e7824d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[updating…]]></title>
            <link>https://medium.com/@barabonajansen/updating-fcde267584a8?source=rss-7bc118dd1dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcde267584a8</guid>
            <dc:creator><![CDATA[Barabonajansen]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 05:39:54 GMT</pubDate>
            <atom:updated>2026-11-14T05:39:54.607Z</atom:updated>
            <content:encoded><![CDATA[<pre><br>&lt;div class=&quot;section&quot;&gt;<br>  &lt;h3&gt;QA Labels&lt;/h3&gt;<br><br>  &lt;label class=&quot;toggle-row&quot;&gt;<br>    &lt;input type=&quot;checkbox&quot; id=&quot;autoIncrement&quot;&gt;<br>    Auto-increment labels<br>  &lt;/label&gt;<br><br>  &lt;div class=&quot;small&quot; id=&quot;autoStatus&quot;&gt;<br>    OFF: manually select labels.<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;toolbar&quot;&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;addLabel()&quot;&gt;＋ Add QA Label&lt;/button&gt;<br>    &lt;button onclick=&quot;addLabels(10)&quot;&gt;＋ Add 10&lt;/button&gt;<br>  &lt;/div&gt;<br><br>  &lt;input type=&quot;text&quot; id=&quot;labelSearch&quot;<br>         placeholder=&quot;Search QA labels...&quot;<br>         oninput=&quot;drawLabels()&quot;&gt;<br><br>  &lt;div class=&quot;edit-label&quot;&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;labelName&quot; placeholder=&quot;Label name&quot;&gt;<br>    &lt;input type=&quot;color&quot; id=&quot;labelColor&quot; value=&quot;#ff4242&quot;&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;toolbar&quot;&gt;<br>    &lt;button class=&quot;primary&quot; onclick=&quot;saveLabel()&quot;&gt;Save Label&lt;/button&gt;<br>    &lt;button class=&quot;danger&quot; onclick=&quot;deleteLabel()&quot;&gt;Delete Label&lt;/button&gt;<br>  &lt;/div&gt;<br><br>  &lt;div class=&quot;small&quot; id=&quot;labelCount&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;label-grid&quot; id=&quot;labels&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><pre><br>let labels = Array.from({length: 56}, (_, i) =&gt; ({<br>  id: i + 1,<br>  name: `QA ${i + 1}`,<br>  color: &#39;#ff4242&#39;<br>}));<br><br>let selectedLabel = 1;<br><br>function addLabel() {<br>  const nextId = Math.max(0, ...labels.map(l =&gt; l.id)) + 1;<br><br>  labels.push({<br>    id: nextId,<br>    name: `QA ${nextId}`,<br>    color: &#39;#ff4242&#39;<br>  });<br><br>  selectedLabel = nextId;<br>  drawLabels();<br>}<br><br>function addLabels(amount) {<br>  for (let i = 0; i &lt; amount; i++) {<br>    const nextId = Math.max(0, ...labels.map(l =&gt; l.id)) + 1;<br><br>    labels.push({<br>      id: nextId,<br>      name: `QA ${nextId}`,<br>      color: &#39;#ff4242&#39;<br>    });<br>  }<br><br>  selectedLabel = labels[labels.length - 1].id;<br>  drawLabels();<br>}<br><br>function drawLabels() {<br>  const container = document.getElementById(&#39;labels&#39;);<br>  const search = document.getElementById(&#39;labelSearch&#39;)?.value<br>    .toLowerCase() || &#39;&#39;;<br><br>  container.innerHTML = &#39;&#39;;<br><br>  const filtered = labels.filter(label =&gt;<br>    String(label.id).includes(search) ||<br>    label.name.toLowerCase().includes(search)<br>  );<br><br>  filtered.forEach(label =&gt; {<br>    const div = document.createElement(&#39;div&#39;);<br><br>    div.className = &#39;label-item&#39; +<br>      (selectedLabel === label.id ? &#39; active&#39; : &#39;&#39;);<br><br>    div.style.borderLeft = `3px solid ${label.color}`;<br><br>    const number = document.createElement(&#39;strong&#39;);<br>    number.textContent = label.id;<br><br>    const name = document.createElement(&#39;span&#39;);<br>    name.textContent = label.name;<br><br>    div.append(number, name);<br><br>    div.onclick = () =&gt; {<br>      selectedLabel = label.id;<br>      document.getElementById(&#39;labelName&#39;).value = label.name;<br>      document.getElementById(&#39;labelColor&#39;).value = label.color;<br>      drawLabels();<br>    };<br><br>    container.appendChild(div);<br>  });<br><br>  const selected = labels.find(l =&gt; l.id === selectedLabel);<br><br>  if (selected) {<br>    document.getElementById(&#39;labelName&#39;).value = selected.name;<br>    document.getElementById(&#39;labelColor&#39;).value = selected.color;<br>  }<br><br>  document.getElementById(&#39;labelCount&#39;).textContent =<br>    `${labels.length} total QA labels`;<br>}<br><br>function saveLabel() {<br>  const label = labels.find(l =&gt; l.id === selectedLabel);<br>  if (!label) return;<br><br>  const name = document.getElementById(&#39;labelName&#39;).value.trim();<br><br>  if (!name) {<br>    alert(&#39;Enter a label name.&#39;);<br>    return;<br>  }<br><br>  label.name = name;<br>  label.color = document.getElementById(&#39;labelColor&#39;).value;<br><br>  drawLabels();<br>  render();<br>}<br><br>function deleteLabel() {<br>  if (labels.length &lt;= 1) {<br>    alert(&#39;You must keep at least one QA label.&#39;);<br>    return;<br>  }<br><br>  if (!confirm(`Delete QA label ${selectedLabel}?`)) return;<br><br>  labels = labels.filter(l =&gt; l.id !== selectedLabel);<br><br>  selectedLabel = labels[0].id;<br><br>  drawLabels();<br>}<br><br>function autoIncrementLabel() {<br>  if (!document.getElementById(&#39;autoIncrement&#39;).checked) return;<br><br>  let next = labels.find(l =&gt; l.id &gt; selectedLabel);<br><br>  if (!next) {<br>    addLabel();<br>    return;<br>  }<br><br>  selectedLabel = next.id;<br>  drawLabels();<br>}<br><br>document.getElementById(&#39;autoIncrement&#39;).addEventListener(&#39;change&#39;, () =&gt; {<br>  document.getElementById(&#39;autoStatus&#39;).textContent =<br>    document.getElementById(&#39;autoIncrement&#39;).checked<br>      ? &#39;ON: automatically selects the next QA label.&#39;<br>      : &#39;OFF: manually select labels.&#39;;<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcde267584a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>