{"id":974,"date":"2026-08-10T16:36:10","date_gmt":"2026-08-10T16:36:10","guid":{"rendered":"https:\/\/freewebtools.co.in\/?page_id=974"},"modified":"2026-08-10T17:15:06","modified_gmt":"2026-08-10T17:15:06","slug":"smart-ai-copy-paste","status":"publish","type":"page","link":"https:\/\/freewebtools.co.in\/index.php\/smart-ai-copy-paste\/","title":{"rendered":"Smart AI Copy Paste"},"content":{"rendered":"\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>AI Notes Smart Copy<\/title>\n    <style>\n        \/* Scoped to #ai-notes-smart-copy wrapper for WordPress \/ Elementor safety *\/\n        #ai-notes-smart-copy {\n            --bg-primary: #f8fafc;\n            --bg-secondary: #ffffff;\n            --bg-card: #ffffff;\n            --text-primary: #0f172a;\n            --text-secondary: #475569;\n            --border-color: #cbd5e1;\n            --accent-color: #2563eb;\n            --accent-hover: #1d4ed8;\n            --accent-light: #eff6ff;\n            --danger-color: #dc2626;\n            --danger-hover: #b91c1c;\n            --success-color: #16a34a;\n            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);\n            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n            --radius: 8px;\n            font-family: system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n            background-color: var(--bg-primary);\n            color: var(--text-primary);\n            min-height: 100vh;\n            display: flex;\n            flex-direction: column;\n            box-sizing: border-box;\n            transition: background-color 0.2s, color 0.2s;\n            width: 100%;\n            max-width: 100%;\n            overflow-x: hidden;\n            padding: 20px;\n        }\n\n        #ai-notes-smart-copy *, #ai-notes-smart-copy *::before, #ai-notes-smart-copy *::after {\n            box-sizing: border-box;\n        }\n\n        #ai-notes-smart-copy[data-theme=\"dark\"] {\n            --bg-primary: #0f172a;\n            --bg-secondary: #1e293b;\n            --bg-card: #1e293b;\n            --text-primary: #f8fafc;\n            --text-secondary: #94a3b8;\n            --border-color: #334155;\n            --accent-color: #3b82f6;\n            --accent-hover: #2563eb;\n            --accent-light: #172554;\n            --danger-color: #ef4444;\n            --danger-hover: #dc2626;\n            --success-color: #22c55e;\n            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);\n            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4), 0 2px 4px -1px rgba(0, 0, 0, 0.2);\n        }\n\n        .ansc-container {\n            max-width: 1200px;\n            width: 100%;\n            margin: 0 auto;\n            display: flex;\n            flex-direction: column;\n            gap: 20px;\n            min-width: 0;\n            flex: 1;\n        }\n\n        \/* Header *\/\n        .ansc-header {\n            display: flex;\n            justify-content: space-between;\n            align-items: center;\n            background: var(--bg-card);\n            padding: 16px 24px;\n            border-radius: var(--radius);\n            border: 1px solid var(--border-color);\n            box-shadow: var(--shadow-sm);\n            flex-wrap: wrap;\n            gap: 12px;\n        }\n\n        .ansc-title-area h1 {\n            font-size: 1.5rem;\n            margin: 0 0 4px 0;\n            font-weight: 700;\n            word-break: break-word;\n        }\n\n        .ansc-subtitle {\n            font-size: 0.875rem;\n            color: var(--text-secondary);\n            margin: 0;\n        }\n\n        .ansc-header-actions {\n            display: flex;\n            align-items: center;\n            gap: 8px;\n            flex-wrap: wrap;\n        }\n\n        \/* Toolbar \/ Actions *\/\n        .ansc-toolbar {\n            display: flex;\n            flex-wrap: wrap;\n            gap: 10px;\n            background: var(--bg-card);\n            padding: 12px 16px;\n            border-radius: var(--radius);\n            border: 1px solid var(--border-color);\n            box-shadow: var(--shadow-sm);\n            align-items: center;\n            justify-content: space-between;\n        }\n\n        .ansc-toolbar-group {\n            display: flex;\n            flex-wrap: wrap;\n            gap: 8px;\n            align-items: center;\n        }\n\n        \/* Search & Replace Bar *\/\n        .ansc-search-bar {\n            display: none;\n            flex-direction: column;\n            gap: 8px;\n            background: var(--bg-card);\n            padding: 12px 16px;\n            border-radius: var(--radius);\n            border: 1px solid var(--border-color);\n            box-shadow: var(--shadow-sm);\n        }\n\n        .ansc-search-bar.active {\n            display: flex;\n        }\n\n        .ansc-search-row {\n            display: flex;\n            gap: 8px;\n            align-items: center;\n            flex-wrap: wrap;\n        }\n\n        \/* Buttons *\/\n        .ansc-btn {\n            background-color: var(--bg-secondary);\n            color: var(--text-primary);\n            border: 1px solid var(--border-color);\n            padding: 8px 14px;\n            border-radius: 6px;\n            font-size: 0.875rem;\n            font-weight: 500;\n            cursor: pointer;\n            display: inline-flex;\n            align-items: center;\n            gap: 6px;\n            transition: background-color 0.15s, border-color 0.15s, transform 0.05s;\n            white-space: nowrap;\n            min-height: 40px;\n        }\n\n        .ansc-btn:hover {\n            background-color: var(--accent-light);\n            border-color: var(--accent-color);\n        }\n\n        .ansc-btn:active {\n            transform: scale(0.98);\n        }\n\n        .ansc-btn:disabled {\n            opacity: 0.5;\n            cursor: not-allowed;\n            pointer-events: none;\n        }\n\n        .ansc-btn-primary {\n            background-color: var(--accent-color);\n            color: #ffffff;\n            border-color: var(--accent-color);\n        }\n\n        .ansc-btn-primary:hover {\n            background-color: var(--accent-hover);\n            border-color: var(--accent-hover);\n        }\n\n        .ansc-btn-danger {\n            color: var(--danger-color);\n        }\n\n        .ansc-btn-danger:hover {\n            background-color: #fef2f2;\n            border-color: var(--danger-color);\n        }\n\n        #ai-notes-smart-copy[data-theme=\"dark\"] .ansc-btn-danger:hover {\n            background-color: #450a0a;\n        }\n\n        \/* Dropdowns & Inputs *\/\n        .ansc-select, .ansc-input {\n            background-color: var(--bg-secondary);\n            color: var(--text-primary);\n            border: 1px solid var(--border-color);\n            padding: 8px 12px;\n            border-radius: 6px;\n            font-size: 0.875rem;\n            outline: none;\n            max-width: 100%;\n            min-height: 40px;\n        }\n\n        .ansc-select:focus, .ansc-input:focus {\n            border-color: var(--accent-color);\n            box-shadow: 0 0 0 2px var(--accent-light);\n        }\n\n        \/* Main Workspace Layout *\/\n        .ansc-workspace {\n            display: grid;\n            grid-template-columns: 1fr 1fr;\n            gap: 20px;\n            flex: 1;\n            min-width: 0;\n        }\n\n        @media (max-width: 900px) {\n            .ansc-workspace {\n                grid-template-columns: 1fr;\n            }\n        }\n\n        .ansc-panel {\n            background: var(--bg-card);\n            border: 1px solid var(--border-color);\n            border-radius: var(--radius);\n            box-shadow: var(--shadow-sm);\n            display: flex;\n            flex-direction: column;\n            overflow: hidden;\n            min-height: 400px;\n            min-width: 0;\n        }\n\n        .ansc-panel-header {\n            padding: 12px 16px;\n            border-bottom: 1px solid var(--border-color);\n            display: flex;\n            justify-content: space-between;\n            align-items: center;\n            background-color: var(--bg-secondary);\n            gap: 8px;\n            flex-wrap: wrap;\n        }\n\n        .ansc-panel-title {\n            font-weight: 600;\n            font-size: 0.95rem;\n            margin: 0;\n        }\n\n        .ansc-panel-body {\n            flex: 1;\n            display: flex;\n            flex-direction: column;\n            position: relative;\n            min-width: 0;\n        }\n\n        \/* Editors and Previews *\/\n        .ansc-textarea, .ansc-preview-pane {\n            flex: 1;\n            width: 100%;\n            border: none;\n            padding: 16px;\n            resize: none;\n            font-family: inherit;\n            font-size: 0.95rem;\n            line-height: 1.6;\n            background: transparent;\n            color: var(--text-primary);\n            outline: none;\n            word-break: break-word;\n            overflow-wrap: anywhere;\n        }\n\n        .ansc-preview-pane {\n            overflow-y: auto;\n        }\n\n        .ansc-preview-pane h1, .ansc-preview-pane h2, .ansc-preview-pane h3 {\n            margin-top: 1em;\n            margin-bottom: 0.5em;\n        }\n\n        .ansc-preview-pane ul, .ansc-preview-pane ol {\n            padding-left: 20px;\n            margin-bottom: 1em;\n        }\n\n        .ansc-preview-pane pre {\n            background: var(--bg-primary);\n            padding: 10px;\n            border-radius: 4px;\n            overflow-x: auto;\n        }\n\n        \/* Stats Bar *\/\n        .ansc-stats-bar {\n            display: flex;\n            flex-wrap: wrap;\n            gap: 16px;\n            background: var(--bg-card);\n            padding: 10px 16px;\n            border-radius: var(--radius);\n            border: 1px solid var(--border-color);\n            font-size: 0.8rem;\n            color: var(--text-secondary);\n            align-items: center;\n        }\n\n        .ansc-stat-item {\n            display: flex;\n            gap: 4px;\n        }\n\n        .ansc-stat-value {\n            font-weight: 600;\n            color: var(--text-primary);\n        }\n\n        \/* Footer *\/\n        .ansc-footer {\n            text-align: center;\n            font-size: 0.8rem;\n            color: var(--text-secondary);\n            padding: 10px 0;\n        }\n\n        \/* Toast Notifications *\/\n        .ansc-toast-container {\n            position: fixed;\n            bottom: 20px;\n            right: 20px;\n            display: flex;\n            flex-direction: column;\n            gap: 10px;\n            z-index: 9999;\n        }\n\n        .ansc-toast {\n            background: var(--bg-card);\n            color: var(--text-primary);\n            border: 1px solid var(--border-color);\n            padding: 12px 18px;\n            border-radius: 6px;\n            box-shadow: var(--shadow-md);\n            font-size: 0.875rem;\n            display: flex;\n            align-items: center;\n            gap: 10px;\n            animation: anscSlideIn 0.2s ease-out;\n        }\n\n        .ansc-toast.success { border-left: 4px solid var(--success-color); }\n        .ansc-toast.error { border-left: 4px solid var(--danger-color); }\n\n        @keyframes anscSlideIn {\n            from { transform: translateY(100%); opacity: 0; }\n            to { transform: translateY(0); opacity: 1; }\n        }\n\n        \/* Modal Overlay *\/\n        .ansc-modal-backdrop {\n            position: fixed;\n            top: 0; left: 0; width: 100%; height: 100%;\n            background: rgba(0, 0, 0, 0.5);\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            z-index: 10000;\n            opacity: 0;\n            pointer-events: none;\n            transition: opacity 0.2s;\n            padding: 16px;\n        }\n\n        .ansc-modal-backdrop.active {\n            opacity: 1;\n            pointer-events: auto;\n        }\n\n        .ansc-modal {\n            background: var(--bg-card);\n            border: 1px solid var(--border-color);\n            border-radius: var(--radius);\n            width: 100%;\n            max-width: 500px;\n            padding: 24px;\n            box-shadow: var(--shadow-md);\n            display: flex;\n            flex-direction: column;\n            gap: 16px;\n            max-height: 90vh;\n            overflow-y: auto;\n        }\n\n        .ansc-modal h3 {\n            margin: 0;\n            font-size: 1.2rem;\n        }\n\n        \/* Scoped Print CSS *\/\n        @media print {\n            body * {\n                visibility: hidden !important;\n            }\n            #ai-notes-smart-copy, #ai-notes-smart-copy * {\n                visibility: visible !important;\n            }\n            #ai-notes-smart-copy {\n                position: absolute !important;\n                left: 0 !important;\n                top: 0 !important;\n                width: 100% !important;\n                background: #ffffff !important;\n                color: #000000 !important;\n                padding: 0 !important;\n            }\n            .ansc-toolbar, .ansc-header-actions, .ansc-search-bar, .ansc-stats-bar, .ansc-footer, .ansc-panel:first-child, .ansc-header {\n                display: none !important;\n            }\n            .ansc-workspace {\n                display: block !important;\n            }\n            .ansc-panel {\n                border: none !important;\n                box-shadow: none !important;\n                height: auto !important;\n                background: transparent !important;\n            }\n        }\n    <\/style>\n<\/head>\n<body>\n\n<div id=\"ai-notes-smart-copy\" data-theme=\"light\">\n    <div class=\"ansc-container\">\n        \n        <!-- Header -->\n        <header class=\"ansc-header\">\n            <div class=\"ansc-title-area\">\n                <h1>AI Notes Smart Copy<\/h1>\n                <p class=\"ansc-subtitle\">Client-side intelligent note cleaner, formatter, and multi-format exporter.<\/p>\n            <\/div>\n            <div class=\"ansc-header-actions\">\n                <button class=\"ansc-btn\" id=\"anscNewBtn\" title=\"Create New Document\" aria-label=\"Create New Document\" type=\"button\">\ud83d\udcc4 New<\/button>\n                <button class=\"ansc-btn\" id=\"anscRecentBtn\" title=\"Recent Documents\" aria-label=\"Recent Documents\" type=\"button\">\ud83d\udcc2 Recent<\/button>\n                <button class=\"ansc-btn\" id=\"anscPrintBtn\" title=\"Print Notes\" aria-label=\"Print Notes\" type=\"button\">\ud83d\udda8\ufe0f Print<\/button>\n                <button class=\"ansc-btn\" id=\"anscThemeBtn\" title=\"Toggle Theme\" aria-label=\"Toggle Theme\" type=\"button\">\ud83c\udf19 Theme<\/button>\n            <\/div>\n        <\/header>\n\n        <!-- Toolbar -->\n        <div class=\"ansc-toolbar\">\n            <div class=\"ansc-toolbar-group\">\n                <button class=\"ansc-btn ansc-btn-primary\" id=\"anscPasteBtn\" aria-label=\"Paste Notes\" type=\"button\">\ud83d\udccb Paste Notes<\/button>\n                <button class=\"ansc-btn\" id=\"anscDetectBtn\" aria-label=\"Detect Structure\" type=\"button\">\ud83d\udd0d Detect Structure<\/button>\n                <select class=\"ansc-select\" id=\"anscFormatStyleSelect\" aria-label=\"Format Style\">\n                    <option value=\"study\">Study Notes<\/option>\n                    <option value=\"clean\">Clean Notes<\/option>\n                    <option value=\"outline\">Outline<\/option>\n                    <option value=\"revision\">Revision Notes<\/option>\n                    <option value=\"qa\">Q&#038;A Notes<\/option>\n                    <option value=\"summary\">Summary<\/option>\n                    <option value=\"bullets\">Bullet Points<\/option>\n                    <option value=\"exam\">Exam Revision<\/option>\n                    <option value=\"cornell\">Cornell-style Notes<\/option>\n                <\/select>\n                <button class=\"ansc-btn ansc-btn-primary\" id=\"anscFormatBtn\" aria-label=\"Format Notes\" type=\"button\">\u26a1 Format<\/button>\n            <\/div>\n            <div class=\"ansc-toolbar-group\">\n                <button class=\"ansc-btn\" id=\"anscUndoBtn\" title=\"Undo (Ctrl+Z)\" aria-label=\"Undo\" type=\"button\">\u21a9\ufe0f Undo<\/button>\n                <button class=\"ansc-btn\" id=\"anscRedoBtn\" title=\"Redo (Ctrl+Y)\" aria-label=\"Redo\" type=\"button\">\u21aa\ufe0f Redo<\/button>\n                <button class=\"ansc-btn\" id=\"anscSearchToggleBtn\" title=\"Search (Ctrl+F)\" aria-label=\"Search\" type=\"button\">\ud83d\udd0e Search<\/button>\n                <button class=\"ansc-btn ansc-btn-danger\" id=\"anscClearBtn\" aria-label=\"Clear Editor\" type=\"button\">\ud83d\uddd1\ufe0f Clear<\/button>\n            <\/div>\n        <\/div>\n\n        <!-- Search & Replace Bar -->\n        <div class=\"ansc-search-bar\" id=\"anscSearchBar\">\n            <div class=\"ansc-search-row\">\n                <input type=\"text\" class=\"ansc-input\" id=\"anscSearchInput\" placeholder=\"Find...\" aria-label=\"Find text\" style=\"flex: 1;\">\n                <input type=\"text\" class=\"ansc-input\" id=\"anscReplaceInput\" placeholder=\"Replace with...\" aria-label=\"Replace with text\" style=\"flex: 1;\">\n                <label style=\"font-size: 0.85rem; display: flex; align-items: center; gap: 4px; cursor: pointer;\">\n                    <input type=\"checkbox\" id=\"anscCaseCheck\" aria-label=\"Case sensitive\"> Case sensitive\n                <\/label>\n                <button class=\"ansc-btn\" id=\"anscSearchCloseBtn\" aria-label=\"Close search\" type=\"button\">\u2715<\/button>\n            <\/div>\n            <div class=\"ansc-search-row\">\n                <span id=\"anscMatchCountLabel\" style=\"font-size: 0.8rem; color: var(--text-secondary);\">0 matches<\/span>\n                <button class=\"ansc-btn\" id=\"anscSearchPrevBtn\" aria-label=\"Previous match\" type=\"button\">Previous<\/button>\n                <button class=\"ansc-btn\" id=\"anscSearchNextBtn\" aria-label=\"Next match\" type=\"button\">Next<\/button>\n                <button class=\"ansc-btn\" id=\"anscReplaceBtn\" aria-label=\"Replace current match\" type=\"button\">Replace<\/button>\n                <button class=\"ansc-btn ansc-btn-primary\" id=\"anscReplaceAllBtn\" aria-label=\"Replace all matches\" type=\"button\">Replace All<\/button>\n            <\/div>\n        <\/div>\n\n        <!-- Workspace -->\n        <div class=\"ansc-workspace\">\n            <!-- Left Panel: Editor \/ Input -->\n            <div class=\"ansc-panel\">\n                <div class=\"ansc-panel-header\">\n                    <input type=\"text\" class=\"ansc-input\" id=\"anscTitleInput\" value=\"Untitled Notes\" aria-label=\"Document Title\" style=\"border: none; background: transparent; font-weight: 600; padding: 0; width: 100%;\">\n                    <span id=\"anscSaveStatus\" style=\"font-size: 0.75rem; color: var(--text-secondary); white-space: nowrap;\">New<\/span>\n                <\/div>\n                <div class=\"ansc-panel-body\">\n                    <textarea class=\"ansc-textarea\" id=\"anscEditor\" placeholder=\"Paste or type your messy notes here...\" aria-label=\"Notes Editor\"><\/textarea>\n                <\/div>\n            <\/div>\n\n            <!-- Right Panel: Preview \/ Formatted Result -->\n            <div class=\"ansc-panel\">\n                <div class=\"ansc-panel-header\">\n                    <h3 class=\"ansc-panel-title\">Formatted Preview<\/h3>\n                    <div class=\"ansc-toolbar-group\" style=\"gap: 6px;\">\n                        <button class=\"ansc-btn\" id=\"anscCopyBtn\" aria-label=\"Copy Formatted Notes\" type=\"button\">\ud83d\udccb Copy<\/button>\n                        <select class=\"ansc-select\" id=\"anscExportFormatSelect\" aria-label=\"Export Format\" style=\"padding: 6px 8px;\">\n                            <option value=\"txt\">.txt<\/option>\n                            <option value=\"md\">.md<\/option>\n                            <option value=\"html\">.html<\/option>\n                            <option value=\"json\">.json<\/option>\n                            <option value=\"csv\">.csv<\/option>\n                            <option value=\"rtf\">.rtf<\/option>\n                        <\/select>\n                        <button class=\"ansc-btn\" id=\"anscDownloadBtn\" aria-label=\"Download File\" type=\"button\">\ud83d\udcbe Download<\/button>\n                        <button class=\"ansc-btn ansc-btn-primary\" id=\"anscSaveBtn\" aria-label=\"Save Note\" type=\"button\">Save<\/button>\n                    <\/div>\n                <\/div>\n                <div class=\"ansc-panel-body\">\n                    <div class=\"ansc-preview-pane\" id=\"anscPreview\" role=\"region\" aria-label=\"Formatted Preview Pane\">Your formatted notes preview will appear here&#8230;<\/div>\n                <\/div>\n            <\/div>\n        <\/div>\n\n        <!-- Statistics Bar -->\n        <div class=\"ansc-stats-bar\">\n            <div class=\"ansc-stat-item\">Words: <span class=\"ansc-stat-value\" id=\"anscStatWords\">0<\/span><\/div>\n            <div class=\"ansc-stat-item\">Characters: <span class=\"ansc-stat-value\" id=\"anscStatChars\">0<\/span><\/div>\n            <div class=\"ansc-stat-item\">Chars (no spaces): <span class=\"ansc-stat-value\" id=\"anscStatCharsNoSpace\">0<\/span><\/div>\n            <div class=\"ansc-stat-item\">Lines: <span class=\"ansc-stat-value\" id=\"anscStatLines\">0<\/span><\/div>\n            <div class=\"ansc-stat-item\">Paragraphs: <span class=\"ansc-stat-value\" id=\"anscStatParagraphs\">0<\/span><\/div>\n            <div class=\"ansc-stat-item\">Reading Time: <span class=\"ansc-stat-value\" id=\"anscStatReadingTime\">0 min<\/span><\/div>\n        <\/div>\n\n        <!-- Footer -->\n        <footer class=\"ansc-footer\">\n            AI Notes Smart Copy &copy; 2026. Fully Client-Side &#038; Secure.\n        <\/footer>\n\n    <\/div>\n<\/div>\n\n<!-- Paste Modal -->\n<div class=\"ansc-modal-backdrop\" id=\"anscPasteModal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"anscPasteTitle\">\n    <div class=\"ansc-modal\">\n        <h3 id=\"anscPasteTitle\">Paste Your Notes<\/h3>\n        <p style=\"font-size: 0.85rem; color: var(--text-secondary); margin: 0;\">Paste text below to insert into your editor:<\/p>\n        <textarea id=\"anscModalPasteInput\" placeholder=\"Paste text here...\" aria-label=\"Paste modal input\" style=\"width: 100%; height: 150px; padding: 12px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-secondary); color: var(--text-primary); resize: vertical; outline: none;\"><\/textarea>\n        <div class=\"ansc-modal-actions\" style=\"display: flex; justify-content: flex-end; gap: 10px;\">\n            <button class=\"ansc-btn\" id=\"anscModalCancelBtn\" aria-label=\"Cancel paste\" type=\"button\">Cancel<\/button>\n            <button class=\"ansc-btn ansc-btn-primary\" id=\"anscModalInsertBtn\" aria-label=\"Insert text\" type=\"button\">Insert Text<\/button>\n        <\/div>\n    <\/div>\n<\/div>\n\n<!-- Recent Documents Modal -->\n<div class=\"ansc-modal-backdrop\" id=\"anscRecentModal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"anscRecentTitle\">\n    <div class=\"ansc-modal\" style=\"max-width: 600px;\">\n        <h3 id=\"anscRecentTitle\">Recent Notes<\/h3>\n        <div id=\"anscRecentList\" style=\"display: flex; flex-direction: column; gap: 8px; max-height: 300px; overflow-y: auto;\" role=\"region\" aria-label=\"Recent Notes List\">\n            <!-- Dynamic recent docs -->\n        <\/div>\n        <div class=\"ansc-modal-actions\" style=\"display: flex; justify-content: flex-end; gap: 10px;\">\n            <button class=\"ansc-btn\" id=\"anscRecentCloseBtn\" aria-label=\"Close recent notes\" type=\"button\">Close<\/button>\n        <\/div>\n    <\/div>\n<\/div>\n\n<!-- Draft Recovery Modal -->\n<div class=\"ansc-modal-backdrop\" id=\"anscDraftModal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"anscDraftTitle\">\n    <div class=\"ansc-modal\">\n        <h3 id=\"anscDraftTitle\">Recover Unsaved Draft?<\/h3>\n        <p style=\"font-size: 0.9rem; color: var(--text-secondary); margin: 0;\">An unsaved draft from your previous session was found.<\/p>\n        <div class=\"ansc-modal-actions\" style=\"display: flex; justify-content: flex-end; gap: 10px;\">\n            <button class=\"ansc-btn\" id=\"anscDraftDiscardBtn\" aria-label=\"Discard draft\" type=\"button\">Discard<\/button>\n            <button class=\"ansc-btn ansc-btn-primary\" id=\"anscDraftRecoverBtn\" aria-label=\"Recover draft\" type=\"button\">Recover<\/button>\n        <\/div>\n    <\/div>\n<\/div>\n\n<!-- Toast Container -->\n<div class=\"ansc-toast-container\" id=\"anscToastContainer\" aria-live=\"polite\"><\/div>\n\n<script>\n(function () {\n    'use strict';\n\n    function initApp() {\n        const rootEl = document.getElementById('ai-notes-smart-copy');\n        if (!rootEl) return false;\n        if (rootEl.dataset.appInitialized === 'true') return true;\n        rootEl.dataset.appInitialized = 'true';\n\n        \/\/ Storage Keys\n        const NOTES_KEY = 'ai_notes_smart_copy_notes';\n        const DRAFT_KEY = 'ai_notes_smart_copy_draft';\n        const THEME_KEY = 'ai_notes_smart_copy_theme';\n\n        \/\/ Application State\n        const state = {\n            title: 'Untitled Notes',\n            content: '',\n            formattedContent: '',\n            mode: 'study',\n            exportFormat: 'txt',\n            currentNoteId: null,\n            dirty: false,\n            formattedStale: true,\n            isRestoringHistory: false,\n            history: [''],\n            historyIndex: 0,\n            searchMatchIndex: -1,\n            searchMatches: [],\n            theme: 'light',\n            activeModal: null,\n            lastFocusedElement: null,\n            structure: {\n                title: '',\n                headings: [],\n                subheadings: [],\n                paragraphs: [],\n                bullets: [],\n                numberedItems: [],\n                questions: [],\n                answers: [],\n                definitions: [],\n                importantPoints: []\n            }\n        };\n\n        let autoSaveTimer = null;\n\n        \/\/ DOM Elements Cache Scoped to Root\n        const editorEl = rootEl.querySelector('#anscEditor');\n        const previewEl = rootEl.querySelector('#anscPreview');\n        const titleInputEl = rootEl.querySelector('#anscTitleInput');\n        const saveStatusEl = rootEl.querySelector('#anscSaveStatus');\n\n        const newBtn = rootEl.querySelector('#anscNewBtn');\n        const recentBtn = rootEl.querySelector('#anscRecentBtn');\n        const printBtn = rootEl.querySelector('#anscPrintBtn');\n        const themeBtn = rootEl.querySelector('#anscThemeBtn');\n        const pasteBtn = rootEl.querySelector('#anscPasteBtn');\n        const clearBtn = rootEl.querySelector('#anscClearBtn');\n        const formatBtn = rootEl.querySelector('#anscFormatBtn');\n        const detectBtn = rootEl.querySelector('#anscDetectBtn');\n        const formatStyleSelect = rootEl.querySelector('#anscFormatStyleSelect');\n        const copyBtn = rootEl.querySelector('#anscCopyBtn');\n        const downloadBtn = rootEl.querySelector('#anscDownloadBtn');\n        const saveBtn = rootEl.querySelector('#anscSaveBtn');\n        const exportFormatSelect = rootEl.querySelector('#anscExportFormatSelect');\n\n        const undoBtn = rootEl.querySelector('#anscUndoBtn');\n        const redoBtn = rootEl.querySelector('#anscRedoBtn');\n        const searchToggleBtn = rootEl.querySelector('#anscSearchToggleBtn');\n        const searchBar = rootEl.querySelector('#anscSearchBar');\n        const searchInput = rootEl.querySelector('#anscSearchInput');\n        const replaceInput = rootEl.querySelector('#anscReplaceInput');\n        const caseCheck = rootEl.querySelector('#anscCaseCheck');\n        const matchCountLabel = rootEl.querySelector('#anscMatchCountLabel');\n        const searchPrevBtn = rootEl.querySelector('#anscSearchPrevBtn');\n        const searchNextBtn = rootEl.querySelector('#anscSearchNextBtn');\n        const replaceBtn = rootEl.querySelector('#anscReplaceBtn');\n        const replaceAllBtn = rootEl.querySelector('#anscReplaceAllBtn');\n        const searchCloseBtn = rootEl.querySelector('#anscSearchCloseBtn');\n\n        const statWords = rootEl.querySelector('#anscStatWords');\n        const statChars = rootEl.querySelector('#anscStatChars');\n        const statCharsNoSpace = rootEl.querySelector('#anscStatCharsNoSpace');\n        const statLines = rootEl.querySelector('#anscStatLines');\n        const statParagraphs = rootEl.querySelector('#anscStatParagraphs');\n        const statReadingTime = rootEl.querySelector('#anscStatReadingTime');\n        const toastContainer = document.getElementById('anscToastContainer') || (function() {\n            const div = document.createElement('div');\n            div.id = 'anscToastContainer';\n            div.className = 'ansc-toast-container';\n            div.setAttribute('aria-live', 'polite');\n            document.body.appendChild(div);\n            return div;\n        })();\n\n        const pasteModal = document.getElementById('anscPasteModal');\n        const modalPasteInput = document.getElementById('anscModalPasteInput');\n        const modalCancelBtn = document.getElementById('anscModalCancelBtn');\n        const modalInsertBtn = document.getElementById('anscModalInsertBtn');\n\n        const recentModal = document.getElementById('anscRecentModal');\n        const recentList = document.getElementById('anscRecentList');\n        const recentCloseBtn = document.getElementById('anscRecentCloseBtn');\n\n        const draftModal = document.getElementById('anscDraftModal');\n        const draftRecoverBtn = document.getElementById('anscDraftRecoverBtn');\n        const draftDiscardBtn = document.getElementById('anscDraftDiscardBtn');\n\n        \/\/ Toast Utility\n        function showToast(message, type = 'success') {\n            try {\n                if (!toastContainer) return;\n                const toast = document.createElement('div');\n                toast.className = `ansc-toast ${type}`;\n                toast.textContent = message;\n                toastContainer.appendChild(toast);\n                setTimeout(() => {\n                    toast.style.opacity = '0';\n                    setTimeout(() => toast.remove(), 200);\n                }, 3000);\n            } catch (e) {}\n        }\n\n        \/\/ Save Status Update\n        function updateSaveState(status) {\n            if (saveStatusEl) saveStatusEl.textContent = status;\n        }\n\n        \/\/ Unique ID Generator\n        function generateUUID() {\n            if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n                try {\n                    return crypto.randomUUID();\n                } catch (e) {}\n            }\n            return 'note_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9);\n        }\n\n        \/\/ Escape HTML for safe rendering\n        function escapeHtml(str) {\n            if (!str) return '';\n            return String(str)\n                .replace(\/&\/g, \"&amp;\")\n                .replace(\/<\/g, \"&lt;\")\n                .replace(\/>\/g, \"&gt;\")\n                .replace(\/\"\/g, \"&quot;\")\n                .replace(\/'\/g, \"&#039;\");\n        }\n\n        \/\/ Filename Sanitization\n        function sanitizeFilename(name) {\n            if (!name || typeof name !== 'string') return 'ai-notes';\n            return name.toLowerCase()\n                .replace(\/[\\\\\/:*?\"<>|]\/g, '')\n                .trim()\n                .replace(\/\\s+\/g, '-')\n                .replace(\/-+\/g, '-')\n                .replace(\/^-|-$\/g, '') || 'ai-notes';\n        }\n\n        \/\/ Statistics Calculator\n        function updateStats(text) {\n            if (!text || typeof text !== 'string') {\n                if (statWords) statWords.textContent = '0';\n                if (statChars) statChars.textContent = '0';\n                if (statCharsNoSpace) statCharsNoSpace.textContent = '0';\n                if (statLines) statLines.textContent = '0';\n                if (statParagraphs) statParagraphs.textContent = '0';\n                if (statReadingTime) statReadingTime.textContent = '0 min';\n                return;\n            }\n            const chars = text.length;\n            const charsNoSpace = text.replace(\/\\s\/g, '').length;\n            const wordsMatch = text.match(\/[\\p{L}\\p{N}_]+\/gu);\n            const words = wordsMatch ? wordsMatch.length : 0;\n            const lines = text === '' ? 0 : text.split(\/\\r\\n|\\r|\\n\/).length;\n            const paragraphs = text === '' ? 0 : text.split(\/\\n\\s*\\n\/).filter(p => p.trim().length > 0).length;\n            const readingTimeMins = Math.max(1, Math.ceil(words \/ 200));\n\n            if (statWords) statWords.textContent = words;\n            if (statChars) statChars.textContent = chars;\n            if (statCharsNoSpace) statCharsNoSpace.textContent = charsNoSpace;\n            if (statLines) statLines.textContent = lines;\n            if (statParagraphs) statParagraphs.textContent = paragraphs;\n            if (statReadingTime) statReadingTime.textContent = `${readingTimeMins} min`;\n        }\n\n        \/\/ Render Preview Safely\n        function renderPreview() {\n            if (!previewEl) return;\n            if (state.formattedStale || !state.formattedContent || !state.formattedContent.trim()) {\n                previewEl.innerHTML = state.content.trim() \n                    ? '<i>Notes changed. Click <b>Format<\/b> to refresh preview.<\/i>' \n                    : 'Your formatted notes preview will appear here...';\n                return;\n            }\n\n            const escaped = escapeHtml(state.formattedContent);\n            const html = escaped.split('\\n').map(line => {\n                const t = line.trim();\n                if (t.startsWith('# ')) return `<h1>${t.substring(2)}<\/h1>`;\n                if (t.startsWith('## ')) return `<h2>${t.substring(3)}<\/h2>`;\n                if (t.startsWith('### ')) return `<h3>${t.substring(4)}<\/h3>`;\n                if (t.startsWith('\u2022 ') || t.startsWith('- ') || t.startsWith('* ')) return `<li>${t.substring(2)}<\/li>`;\n                if (t.startsWith('>')) return `<blockquote>${t.substring(1).trim()}<\/blockquote>`;\n                if (t === '') return '<br>';\n                return `<p>${t}<\/p>`;\n            }).join('');\n\n            previewEl.innerHTML = html;\n        }\n\n        \/\/ History Management\n        function pushHistory(text) {\n            if (state.isRestoringHistory) return;\n            if (state.history[state.historyIndex] === text) return;\n            state.history = state.history.slice(0, state.historyIndex + 1);\n            state.history.push(text);\n            if (state.history.length > 100) state.history.shift();\n            state.historyIndex = state.history.length - 1;\n            updateUndoRedoButtons();\n        }\n\n        function updateUndoRedoButtons() {\n            if (undoBtn) undoBtn.disabled = state.historyIndex <= 0;\n            if (redoBtn) redoBtn.disabled = state.historyIndex >= state.history.length - 1;\n        }\n\n        function undo() {\n            if (state.historyIndex <= 0) return;\n            state.historyIndex--;\n            state.isRestoringHistory = true;\n            const targetText = state.history[state.historyIndex];\n            setContentCore(targetText);\n            state.isRestoringHistory = false;\n            updateUndoRedoButtons();\n            performSearch();\n        }\n\n        function redo() {\n            if (state.historyIndex >= state.history.length - 1) return;\n            state.historyIndex++;\n            state.isRestoringHistory = true;\n            const targetText = state.history[state.historyIndex];\n            setContentCore(targetText);\n            state.isRestoringHistory = false;\n            updateUndoRedoButtons();\n            performSearch();\n        }\n\n        \/\/ Search Engine\n        function performSearch() {\n            if (!searchInput) return;\n            const query = searchInput.value;\n            if (!query) {\n                state.searchMatches = [];\n                state.searchMatchIndex = -1;\n                if (matchCountLabel) matchCountLabel.textContent = '0 matches';\n                if (searchPrevBtn) searchPrevBtn.disabled = true;\n                if (searchNextBtn) searchNextBtn.disabled = true;\n                if (replaceBtn) replaceBtn.disabled = true;\n                if (replaceAllBtn) replaceAllBtn.disabled = true;\n                return;\n            }\n\n            const text = state.content;\n            const flags = caseCheck && caseCheck.checked ? 'g' : 'gi';\n            try {\n                const escaped = query.replace(\/[.*+?^${}()|[\\]\\\\]\/g, '\\\\$&');\n                const regex = new RegExp(escaped, flags);\n                state.searchMatches = [];\n                let match;\n                while ((match = regex.exec(text)) !== null) {\n                    state.searchMatches.push({\n                        start: match.index,\n                        end: match.index + match[0].length\n                    });\n                    if (match[0].length === 0) {\n                        regex.lastIndex++;\n                    }\n                }\n\n                const count = state.searchMatches.length;\n                if (matchCountLabel) matchCountLabel.textContent = `${count} match${count === 1 ? '' : 'es'}`;\n                \n                const hasMatches = count > 0;\n                if (searchPrevBtn) searchPrevBtn.disabled = !hasMatches;\n                if (searchNextBtn) searchNextBtn.disabled = !hasMatches;\n                if (replaceBtn) replaceBtn.disabled = !hasMatches;\n                if (replaceAllBtn) replaceAllBtn.disabled = !hasMatches;\n\n                if (hasMatches) {\n                    if (state.searchMatchIndex < 0 || state.searchMatchIndex >= count) {\n                        state.searchMatchIndex = 0;\n                    }\n                    highlightMatch(state.searchMatchIndex);\n                } else {\n                    state.searchMatchIndex = -1;\n                }\n            } catch (e) {\n                if (matchCountLabel) matchCountLabel.textContent = '0 matches';\n            }\n        }\n\n        function highlightMatch(idx) {\n            if (state.searchMatches.length === 0 || !editorEl) return;\n            const match = state.searchMatches[idx];\n            editorEl.focus();\n            editorEl.setSelectionRange(match.start, match.end);\n            if (matchCountLabel) matchCountLabel.textContent = `Match ${idx + 1} of ${state.searchMatches.length}`;\n        }\n\n        \/\/ Storage Helpers\n        function loadNotesFromStorage() {\n            try {\n                const raw = localStorage.getItem(NOTES_KEY);\n                if (!raw) return {};\n                const parsed = JSON.parse(raw);\n                if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n                    return parsed;\n                }\n                if (Array.isArray(parsed)) {\n                    const map = {};\n                    parsed.forEach(n => { if (n && n.id) map[n.id] = n; });\n                    return map;\n                }\n                return {};\n            } catch (e) {\n                return {};\n            }\n        }\n\n        function saveNotesToStorage(notesObj) {\n            try {\n                localStorage.setItem(NOTES_KEY, JSON.stringify(notesObj));\n                return true;\n            } catch (e) {\n                if (e.name === 'QuotaExceededError' || e.code === 22) {\n                    showToast('Storage limit reached. Please delete some saved notes.', 'error');\n                } else {\n                    showToast('Unable to save notes in this browser.', 'error');\n                }\n                return false;\n            }\n        }\n\n        \/\/ Draft Autosave Scheduler\n        function scheduleDraftAutosave() {\n            clearTimeout(autoSaveTimer);\n            autoSaveTimer = setTimeout(() => {\n                try {\n                    if (!state.content.trim() && state.title === 'Untitled Notes') {\n                        localStorage.removeItem(DRAFT_KEY);\n                        return;\n                    }\n                    const draft = {\n                        title: state.title,\n                        content: state.content,\n                        formattedContent: state.formattedContent,\n                        mode: state.mode,\n                        exportFormat: state.exportFormat,\n                        structure: state.structure,\n                        currentNoteId: state.currentNoteId,\n                        updatedAt: new Date().toISOString()\n                    };\n                    localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));\n                    if (state.dirty) {\n                        updateSaveState('Auto-saved');\n                    }\n                } catch (e) {}\n            }, 1000);\n        }\n\n        \/\/ Core content setter without history trigger\n        function setContentCore(text) {\n            state.content = text;\n            state.formattedStale = true;\n            if (editorEl && editorEl.value !== text) {\n                editorEl.value = text;\n            }\n            updateStats(text);\n            renderPreview();\n        }\n\n        \/\/ Set Content & Synchronize State with History\n        function setContent(text) {\n            setContentCore(text);\n            if (!state.isRestoringHistory) {\n                pushHistory(text);\n            }\n            state.dirty = true;\n            updateSaveState('Unsaved changes');\n            scheduleDraftAutosave();\n            performSearch();\n        }\n\n        \/\/ Reset Document State for New Note\n        function resetDocument() {\n            state.title = 'Untitled Notes';\n            state.content = '';\n            state.formattedContent = '';\n            state.currentNoteId = null;\n            state.dirty = false;\n            state.formattedStale = true;\n            state.history = [''];\n            state.historyIndex = 0;\n            state.searchMatches = [];\n            state.searchMatchIndex = -1;\n            state.structure = {\n                title: '', headings: [], subheadings: [], paragraphs: [],\n                bullets: [], numberedItems: [], questions: [], answers: [],\n                definitions: [], importantPoints: []\n            };\n\n            if (titleInputEl) titleInputEl.value = state.title;\n            if (editorEl) editorEl.value = '';\n\n            updateStats('');\n            renderPreview();\n            updateSaveState('New');\n            updateUndoRedoButtons();\n            performSearch();\n            try { localStorage.removeItem(DRAFT_KEY); } catch (e) {}\n        }\n\n        \/\/ Modal Management helpers\n        function openModal(modalEl, focusEl) {\n            if (!modalEl) return;\n            state.lastFocusedElement = document.activeElement;\n            modalEl.classList.add('active');\n            document.body.style.overflow = 'hidden';\n            if (modalEl === pasteModal) state.activeModal = 'paste';\n            else if (modalEl === recentModal) state.activeModal = 'recent';\n            else if (modalEl === draftModal) state.activeModal = 'draft';\n\n            if (focusEl) {\n                setTimeout(() => focusEl.focus(), 50);\n            }\n        }\n\n        function closeModal(modalEl) {\n            if (!modalEl || !modalEl.classList.contains('active')) return;\n            modalEl.classList.remove('active');\n            document.body.style.overflow = '';\n            state.activeModal = null;\n            if (state.lastFocusedElement && typeof state.lastFocusedElement.focus === 'function') {\n                try {\n                    state.lastFocusedElement.focus();\n                } catch (e) {}\n            }\n        }\n\n        function closeActiveModal() {\n            if (searchBar && searchBar.classList.contains('active')) {\n                searchBar.classList.remove('active');\n                return true;\n            }\n            if (pasteModal && pasteModal.classList.contains('active')) {\n                closeModal(pasteModal);\n                return true;\n            }\n            if (recentModal && recentModal.classList.contains('active')) {\n                closeModal(recentModal);\n                return true;\n            }\n            if (draftModal && draftModal.classList.contains('active')) {\n                closeModal(draftModal);\n                return true;\n            }\n            return false;\n        }\n\n        \/\/ Theme Switcher\n        function setTheme(themeName) {\n            state.theme = themeName;\n            if (rootEl) rootEl.setAttribute('data-theme', themeName);\n            if (themeBtn) {\n                themeBtn.textContent = themeName === 'dark' ? '\u2600\ufe0f Theme' : '\ud83c\udf19 Theme';\n                themeBtn.setAttribute('aria-label', themeName === 'dark' ? 'Switch to light theme' : 'Switch to dark theme');\n            }\n            try {\n                localStorage.setItem(THEME_KEY, themeName);\n            } catch (e) {}\n        }\n\n        function toggleTheme() {\n            const next = state.theme === 'light' ? 'dark' : 'light';\n            setTheme(next);\n        }\n\n        \/\/ Advanced Structure Detection\n        function detectStructure() {\n            if (!state.content || !state.content.trim()) {\n                return null;\n            }\n            const lines = state.content.split('\\n');\n            const structure = {\n                title: state.title,\n                headings: [],\n                subheadings: [],\n                paragraphs: [],\n                bullets: [],\n                numberedItems: [],\n                questions: [],\n                answers: [],\n                definitions: [],\n                importantPoints: []\n            };\n\n            let currentPara = [];\n            const flushPara = () => {\n                if (currentPara.length > 0) {\n                    const pText = currentPara.join(' ').trim();\n                    if (pText) structure.paragraphs.push(pText);\n                    currentPara = [];\n                }\n            };\n\n            lines.forEach(line => {\n                const trimmed = line.trim();\n                if (!trimmed) {\n                    flushPara();\n                    return;\n                }\n\n                if (trimmed.startsWith('# ')) {\n                    flushPara();\n                    structure.headings.push(trimmed.replace(\/^#\\s*\/, ''));\n                    return;\n                }\n                if (trimmed.startsWith('## ') || trimmed.startsWith('### ')) {\n                    flushPara();\n                    structure.subheadings.push(trimmed.replace(\/^#{2,3}\\s*\/, ''));\n                    return;\n                }\n                if (trimmed.startsWith('- ') || trimmed.startsWith('* ') || trimmed.startsWith('\u2022 ')) {\n                    flushPara();\n                    structure.bullets.push(trimmed.replace(\/^[-*\u2022]\\s*\/, ''));\n                    return;\n                }\n                if (\/^\\d+[\\.\\)]\\s+\/.test(trimmed)) {\n                    flushPara();\n                    structure.numberedItems.push(trimmed.replace(\/^\\d+[\\.\\)]\\s*\/, ''));\n                    return;\n                }\n                if (\/^(q:|question:)\/i.test(trimmed) || trimmed.endsWith('?')) {\n                    flushPara();\n                    structure.questions.push(trimmed.replace(\/^(q:|question:)\\s*\/i, ''));\n                    return;\n                }\n                if (\/^(a:|answer:)\/i.test(trimmed)) {\n                    flushPara();\n                    structure.answers.push(trimmed.replace(\/^(a:|answer:)\\s*\/i, ''));\n                    return;\n                }\n                if (\/^(definition:|term:)\/i.test(trimmed) || \/is defined as\/i.test(trimmed)) {\n                    flushPara();\n                    structure.definitions.push(trimmed);\n                    return;\n                }\n                if (\/^(important:|important point:|key point:|note:|remember:)\/i.test(trimmed)) {\n                    flushPara();\n                    structure.importantPoints.push(trimmed.replace(\/^(important:|important point:|key point:|note:|remember:)\\s*\/i, ''));\n                    return;\n                }\n                if (trimmed.length < 50 &#038;&#038; !\/[.!?]$\/.test(trimmed) &#038;&#038; (line === line.trim() &#038;&#038; lines.indexOf(line) === 0 || trimmed.length < 30)) {\n                    flushPara();\n                    structure.headings.push(trimmed);\n                    return;\n                }\n\n                currentPara.push(trimmed);\n            });\n            flushPara();\n\n            state.structure = structure;\n            return structure;\n        }\n\n        \/\/ Formatters Implementation\n        const formatters = {\n            study: (text) => {\n                const struct = detectStructure() || { headings: [], paragraphs: [], bullets: [], importantPoints: [] };\n                let res = [`# Study Notes\\n`];\n                if (struct.headings.length > 0) res.push(`## Main Topic\\n${struct.headings[0]}`);\n                if (struct.paragraphs.length > 0) res.push(`\\n## Overview\\n${struct.paragraphs[0]}`);\n                if (struct.importantPoints.length > 0) {\n                    res.push(`\\n### Important Points`);\n                    struct.importantPoints.forEach(p => res.push(`\u2022 ${p}`));\n                }\n                if (struct.bullets.length > 0) {\n                    res.push(`\\n### Key Concepts`);\n                    struct.bullets.forEach(b => res.push(`\u2022 ${b}`));\n                }\n                if (res.length === 1) {\n                    const lines = text.split('\\n').map(l => l.trim()).filter(Boolean);\n                    res.push(`## Notes Summary\\n\u2022 ${lines[0] || 'General Notes'}`);\n                    lines.slice(1).forEach(l => res.push(`\u2022 ${l}`));\n                }\n                return res.join('\\n');\n            },\n            clean: (text) => {\n                const lines = text.split('\\n');\n                let res = [];\n                lines.forEach(l => {\n                    const t = l.trim().replace(\/\\s+\/g, ' ');\n                    if (t) res.push(t);\n                    else if (res.length > 0 && res[res.length - 1] !== '') res.push('');\n                });\n                return res.join('\\n');\n            },\n            outline: (text) => {\n                const struct = detectStructure() || { headings: [], paragraphs: [], bullets: [] };\n                let res = [`# Outline: ${state.title}\\n`];\n                let idx = 1;\n                const items = [...struct.headings, ...struct.paragraphs, ...struct.bullets];\n                if (items.length === 0) items.push(...text.split('\\n').map(l => l.trim()).filter(Boolean));\n                items.forEach(item => {\n                    res.push(`${idx}. ${item}\\n   - Sub-point \/ Detail`);\n                    idx++;\n                });\n                return res.join('\\n\\n');\n            },\n            revision: (text) => {\n                const struct = detectStructure() || {};\n                let res = [`# Revision Notes\\n`];\n                if (struct.importantPoints && struct.importantPoints.length > 0) {\n                    res.push(`## Key Concepts`);\n                    struct.importantPoints.forEach(p => res.push(`\u2022 ${p}`));\n                }\n                if (struct.definitions && struct.definitions.length > 0) {\n                    res.push(`\\n## Definitions`);\n                    struct.definitions.forEach(d => res.push(`- ${d}`));\n                }\n                const fallbackLines = text.split('\\n').map(l => l.trim()).filter(Boolean);\n                res.push(`\\n## Quick Review`);\n                fallbackLines.slice(0, 5).forEach(l => res.push(`\u2022 ${l}`));\n                return res.join('\\n');\n            },\n            qa: (text) => {\n                const struct = detectStructure() || {};\n                let res = [`# Q&A Notes\\n`];\n                if (struct.questions && struct.questions.length > 0) {\n                    struct.questions.forEach((q, i) => {\n                        const ans = struct.answers[i] || '[Review concept for answer]';\n                        res.push(`Q${i+1}. ${q}\\nAnswer:\\n${ans}\\n`);\n                    });\n                } else {\n                    const lines = text.split('\\n').map(l => l.trim()).filter(Boolean);\n                    lines.forEach((l, i) => {\n                        res.push(`Q${i+1}. What is meant by: \"${l}\"?\\nAnswer:\\n[Refer to source notes]\\n`);\n                    });\n                }\n                return res.join('\\n');\n            },\n            summary: (text) => {\n                const struct = detectStructure() || {};\n                let res = [`# Executive Summary\\n`];\n                const summarySource = [...(struct.headings || []), ...(struct.paragraphs || []), ...(struct.bullets || [])];\n                if (summarySource.length > 0) {\n                    res.push(`> ${summarySource[0]}`);\n                    if (summarySource.length > 1) {\n                        res.push(`\\n## Key Takeaways`);\n                        summarySource.slice(1, 5).forEach(s => res.push(`- ${s}`));\n                    }\n                } else {\n                    res.push(`> ${text.substring(0, 150)}...`);\n                }\n                return res.join('\\n');\n            },\n            bullets: (text) => {\n                const lines = text.split('\\n').map(l => l.trim()).filter(Boolean);\n                let res = [`# Bullet Points\\n`];\n                lines.forEach(l => {\n                    const clean = l.replace(\/^[-*\u2022]\\s*\/, '');\n                    res.push(`\u2022 ${clean}`);\n                });\n                return res.join('\\n');\n            },\n            exam: (text) => {\n                const struct = detectStructure() || {};\n                let res = [`# Exam Revision Guide\\n`];\n                if (struct.importantPoints && struct.importantPoints.length > 0) {\n                    res.push(`## Must Remember`);\n                    struct.importantPoints.forEach(p => res.push(`\u26a1 ${p}`));\n                }\n                res.push(`\\n## Core Facts`);\n                const lines = text.split('\\n').map(l => l.trim()).filter(Boolean);\n                lines.slice(0, 6).forEach(l => res.push(`\u2022 ${l}`));\n                return res.join('\\n');\n            },\n            cornell: (text) => {\n                const struct = detectStructure() || {};\n                let res = [`# Cornell Notes\\n`];\n                res.push(`## Cues \/ Questions`);\n                if (struct.questions && struct.questions.length > 0) {\n                    struct.questions.forEach(q => res.push(`\u2022 ${q}`));\n                } else {\n                    res.push(`\u2022 Review core concepts from notes`);\n                }\n                res.push(`\\n## Notes \/ Details`);\n                const lines = text.split('\\n').map(l => l.trim()).filter(Boolean);\n                lines.forEach(l => res.push(`- ${l}`));\n                res.push(`\\n## Summary`);\n                res.push(`> ${lines[0] || 'Summary of notes session.'}`);\n                return res.join('\\n');\n            }\n        };\n\n        \/\/ Get Current Export Source\n        function getCurrentExportText() {\n            if (!state.content.trim()) return '';\n            if (state.formattedStale || !state.formattedContent) {\n                const formatter = formatters[state.mode] || formatters.study;\n                state.formattedContent = formatter(state.content);\n                state.formattedStale = false;\n            }\n            return state.formattedContent;\n        }\n\n        \/\/ Exporters\n        const exporters = {\n            txt: (title, content) => content.replace(\/#{1,6}\\s\/g, '').replace(\/[>*_]\/g, ''),\n            md: (title, content) => `# ${title}\\n\\n${content}`,\n            html: (title, content) => {\n                const safeTitle = escapeHtml(title);\n                const escaped = escapeHtml(content);\n                const bodyHtml = escaped.split('\\n').map(line => {\n                    const t = line.trim();\n                    if (t.startsWith('# ')) return `<h1>${t.substring(2)}<\/h1>`;\n                    if (t.startsWith('## ')) return `<h2>${t.substring(3)}<\/h2>`;\n                    if (t.startsWith('### ')) return `<h3>${t.substring(4)}<\/h3>`;\n                    if (t.startsWith('\u2022 ') || t.startsWith('- ') || t.startsWith('* ')) return `<li>${t.substring(2)}<\/li>`;\n                    if (t.startsWith('>')) return `<blockquote>${t.substring(1).trim()}<\/blockquote>`;\n                    if (t === '') return '<br>';\n                    return `<p>${t}<\/p>`;\n                }).join('\\n');\n\n                return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>${safeTitle}<\/title>\n<style>\nbody { font-family: system-ui, -apple-system, sans-serif; line-height: 1.6; max-width: 800px; margin: 40px auto; padding: 0 20px; color: #111; background: #fdfdfd; }\nh1 { font-size: 1.8rem; border-bottom: 2px solid #eaeaea; padding-bottom: 10px; }\nh2 { font-size: 1.4rem; margin-top: 1.5em; }\nh3 { font-size: 1.1rem; }\nblockquote { border-left: 4px solid #2563eb; margin: 0; padding-left: 16px; color: #475569; }\nli { margin-bottom: 6px; }\n<\/style>\n<\/head>\n<body>\n<h1>${safeTitle}<\/h1>\n${bodyHtml}\n<\/body>\n<\/html>`;\n            },\n            json: (title, content) => {\n                detectStructure();\n                return JSON.stringify({\n                    title: title,\n                    content: state.content,\n                    formattedContent: content,\n                    format: state.mode,\n                    structure: state.structure,\n                    updatedAt: new Date().toISOString()\n                }, null, 2);\n            },\n            csv: (title, content) => {\n                const escapeCSV = (str) => `\"${String(str || '').replace(\/\"\/g, '\"\"')}\"`;\n                let rows = [`\"Type\",\"Title\",\"Content\"`];\n                rows.push(`\"Note\",${escapeCSV(title)},${escapeCSV(content)}`);\n                return rows.join('\\r\\n');\n            },\n            rtf: (title, content) => {\n                const escapeRTF = (str) => String(str || '').replace(\/[\\\\]\/g, '\\\\\\\\').replace(\/[{}]\/g, '\\\\$&').replace(\/\\n\/g, '\\\\par ');\n                return `{\\\\rtf1\\\\ansi\\\\deff0 {\\\\fonttbl {\\\\f0 Helvetica;}} \\\\f0\\\\fs28 \\\\b ${escapeRTF(title)}\\\\b0\\\\par\\\\par \\\\fs20 ${escapeRTF(content)}}`;\n            }\n        };\n\n        \/\/ Save Note Functionality\n        function saveNote() {\n            if (!state.content.trim() && !state.title.trim()) {\n                showToast('Please enter some notes before saving.', 'error');\n                return;\n            }\n\n            const notes = loadNotesFromStorage();\n            const now = new Date().toISOString();\n\n            if (!state.currentNoteId) {\n                state.currentNoteId = generateUUID();\n            }\n\n            const currentFormatted = getCurrentExportText();\n            detectStructure();\n\n            const existingNote = notes[state.currentNoteId] || {};\n\n            notes[state.currentNoteId] = {\n                id: state.currentNoteId,\n                title: state.title.trim() || 'Untitled Notes',\n                content: state.content,\n                formattedContent: currentFormatted,\n                mode: state.mode,\n                exportFormat: state.exportFormat,\n                structure: state.structure,\n                createdAt: existingNote.createdAt || now,\n                updatedAt: now\n            };\n\n            if (saveNotesToStorage(notes)) {\n                state.dirty = false;\n                updateSaveState('Saved');\n                showToast('Note saved successfully!');\n                try { localStorage.removeItem(DRAFT_KEY); } catch (e) {}\n                if (recentModal && recentModal.classList.contains('active')) {\n                    openRecentModal();\n                }\n            }\n        }\n\n        \/\/ Open Recent Modal & Render List\n        function openRecentModal() {\n            try {\n                const notes = loadNotesFromStorage();\n                const keys = Object.keys(notes);\n                if (recentList) {\n                    recentList.innerHTML = '';\n                    if (keys.length === 0) {\n                        recentList.innerHTML = '<p style=\"color: var(--text-secondary); text-align: center; padding: 20px;\">No saved notes yet.<\/p>';\n                    } else {\n                        keys.sort((a, b) => new Date(notes[b].updatedAt || 0) - new Date(notes[a].updatedAt || 0)).forEach(id => {\n                            const note = notes[id];\n                            const item = document.createElement('div');\n                            item.style.cssText = 'display: flex; justify-content: space-between; align-items: center; padding: 12px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-secondary); gap: 10px;';\n                            \n                            const info = document.createElement('div');\n                            info.style.cssText = 'flex: 1; min-width: 0;';\n                            \n                            const titleSpan = document.createElement('strong');\n                            titleSpan.textContent = note.title || 'Untitled';\n                            titleSpan.style.cssText = 'display: block; font-size: 0.95rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;';\n                            \n                            const previewSnippet = document.createElement('div');\n                            previewSnippet.textContent = (note.content || '').substring(0, 80) + '...';\n                            previewSnippet.style.cssText = 'font-size: 0.8rem; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px;';\n\n                            const subInfo = document.createElement('div');\n                            subInfo.style.cssText = 'font-size: 0.75rem; color: var(--text-secondary); margin-top: 4px;';\n                            subInfo.textContent = new Date(note.updatedAt).toLocaleString();\n                            \n                            info.appendChild(titleSpan);\n                            info.appendChild(previewSnippet);\n                            info.appendChild(subInfo);\n\n                            const actions = document.createElement('div');\n                            actions.style.cssText = 'display: flex; gap: 6px; flex-shrink: 0;';\n\n                            const openBtn = document.createElement('button');\n                            openBtn.className = 'ansc-btn ansc-btn-primary';\n                            openBtn.textContent = 'Open';\n                            openBtn.type = 'button';\n                            openBtn.setAttribute('aria-label', `Open note ${note.title || 'Untitled'}`);\n                            openBtn.dataset.noteId = note.id;\n                            openBtn.addEventListener('click', () => {\n                                state.currentNoteId = note.id;\n                                state.title = note.title || 'Untitled Notes';\n                                if (titleInputEl) titleInputEl.value = state.title;\n                                state.mode = note.mode || 'study';\n                                if (formatStyleSelect) formatStyleSelect.value = state.mode;\n                                state.exportFormat = note.exportFormat || 'txt';\n                                if (exportFormatSelect) exportFormatSelect.value = state.exportFormat;\n                                state.formattedContent = note.formattedContent || '';\n                                state.formattedStale = false;\n                                state.structure = note.structure || state.structure;\n\n                                state.history = [note.content || ''];\n                                state.historyIndex = 0;\n                                updateUndoRedoButtons();\n\n                                setContentCore(note.content || '');\n                                updateStats(note.content || '');\n                                renderPreview();\n                                state.dirty = false;\n                                updateSaveState('Saved');\n                                closeModal(recentModal);\n                                performSearch();\n                                showToast('Note opened.');\n                            });\n\n                            const delBtn = document.createElement('button');\n                            delBtn.className = 'ansc-btn ansc-btn-danger';\n                            delBtn.textContent = 'Delete';\n                            delBtn.type = 'button';\n                            delBtn.setAttribute('aria-label', `Delete note ${note.title || 'Untitled'}`);\n                            delBtn.addEventListener('click', (e) => {\n                                e.stopPropagation();\n                                if (confirm('Delete this note?')) {\n                                    const freshNotes = loadNotesFromStorage();\n                                    delete freshNotes[note.id];\n                                    if (saveNotesToStorage(freshNotes)) {\n                                        if (state.currentNoteId === note.id) {\n                                            state.currentNoteId = null;\n                                        }\n                                        openRecentModal();\n                                        showToast('Note deleted.');\n                                    }\n                                }\n                            });\n\n                            actions.appendChild(openBtn);\n                            actions.appendChild(delBtn);\n                            item.appendChild(info);\n                            item.appendChild(actions);\n                            recentList.appendChild(item);\n                        });\n                    }\n                }\n                openModal(recentModal, recentCloseBtn);\n            } catch (e) {\n                showToast('Failed to load recent notes.', 'error');\n            }\n        }\n\n        \/\/ Fallback Copy Function\n        function fallbackCopy(text, callback) {\n            try {\n                const textArea = document.createElement(\"textarea\");\n                textArea.value = text;\n                textArea.style.position = \"fixed\";\n                textArea.style.top = \"0\";\n                textArea.style.left = \"0\";\n                textArea.style.opacity = \"0\";\n                document.body.appendChild(textArea);\n                textArea.focus();\n                textArea.select();\n                const successful = document.execCommand('copy');\n                document.body.removeChild(textArea);\n                callback(successful);\n            } catch (err) {\n                callback(false);\n            }\n        }\n\n        \/\/ Event Listeners for UI Actions\n        if (copyBtn) {\n            copyBtn.addEventListener('click', () => {\n                const textToCopy = getCurrentExportText();\n                if (!textToCopy.trim()) {\n                    showToast('Please enter or paste some notes first.', 'error');\n                    return;\n                }\n\n                const cleanText = textToCopy.replace(\/#{1,6}\\s\/g, '').replace(\/[>*_]\/g, '');\n\n                if (navigator.clipboard && navigator.clipboard.writeText) {\n                    navigator.clipboard.writeText(cleanText).then(() => {\n                        const orig = copyBtn.textContent;\n                        copyBtn.textContent = '\u2713 Copied';\n                        setTimeout(() => copyBtn.textContent = orig, 1500);\n                        showToast('Copied to clipboard successfully!');\n                    }).catch(() => {\n                        fallbackCopy(cleanText, (success) => {\n                            if (success) {\n                                const orig = copyBtn.textContent;\n                                copyBtn.textContent = '\u2713 Copied';\n                                setTimeout(() => copyBtn.textContent = orig, 1500);\n                                showToast('Copied to clipboard successfully!');\n                            } else {\n                                showToast('Clipboard access unavailable. Please copy manually.', 'error');\n                            }\n                        });\n                    });\n                } else {\n                    fallbackCopy(cleanText, (success) => {\n                        if (success) {\n                            const orig = copyBtn.textContent;\n                            copyBtn.textContent = '\u2713 Copied';\n                            setTimeout(() => copyBtn.textContent = orig, 1500);\n                            showToast('Copied to clipboard successfully!');\n                        } else {\n                            showToast('Clipboard access unavailable. Please copy manually.', 'error');\n                        }\n                    });\n                }\n            });\n        }\n\n        if (exportFormatSelect) {\n            exportFormatSelect.addEventListener('change', (e) => {\n                state.exportFormat = e.target.value;\n                state.dirty = true;\n                scheduleDraftAutosave();\n            });\n        }\n\n        if (downloadBtn) {\n            downloadBtn.addEventListener('click', () => {\n                if (!state.content || !state.content.trim()) {\n                    showToast('Please enter or paste some notes first.', 'error');\n                    return;\n                }\n\n                try {\n                    const content = getCurrentExportText();\n                    const exporter = exporters[state.exportFormat] || exporters.txt;\n                    const fileContent = exporter(state.title, content);\n\n                    const mimeMap = {\n                        txt: 'text\/plain',\n                        md: 'text\/markdown',\n                        html: 'text\/html',\n                        json: 'application\/json',\n                        csv: 'text\/csv',\n                        rtf: 'application\/rtf'\n                    };\n                    const mime = mimeMap[state.exportFormat] || 'text\/plain';\n\n                    const blob = new Blob([fileContent], { type: `${mime};charset=utf-8` });\n                    const url = URL.createObjectURL(blob);\n                    const a = document.createElement('a');\n                    a.href = url;\n                    a.download = `${sanitizeFilename(state.title)}.${state.exportFormat}`;\n                    document.body.appendChild(a);\n                    a.click();\n                    document.body.removeChild(a);\n                    URL.revokeObjectURL(url);\n\n                    showToast('Downloaded successfully.');\n                } catch (e) {\n                    showToast('Unable to export this file. Please try again.', 'error');\n                }\n            });\n        }\n\n        if (detectBtn) {\n            detectBtn.addEventListener('click', () => {\n                if (!state.content || !state.content.trim()) {\n                    showToast('Please enter or paste some notes first.', 'error');\n                    return;\n                }\n                const struct = detectStructure();\n                if (struct) {\n                    const totalHeadings = struct.headings.length + struct.subheadings.length;\n                    showToast(`Structure detected: ${totalHeadings} headings, ${struct.paragraphs.length} paragraphs, ${struct.bullets.length} bullets, ${struct.questions.length} questions.`, 'success');\n                }\n            });\n        }\n\n        if (formatBtn) {\n            formatBtn.addEventListener('click', () => {\n                if (!state.content || !state.content.trim()) {\n                    showToast('Please enter or paste some notes first.', 'error');\n                    return;\n                }\n                try {\n                    detectStructure();\n                    const formatter = formatters[state.mode] || formatters.study;\n                    state.formattedContent = formatter(state.content);\n                    state.formattedStale = false;\n                    renderPreview();\n                    showToast('Notes formatted successfully!');\n                    scheduleDraftAutosave();\n                } catch (e) {\n                    showToast('Unable to format these notes. Please try again.', 'error');\n                }\n            });\n        }\n\n        if (formatStyleSelect) {\n            formatStyleSelect.addEventListener('change', (e) => {\n                state.mode = e.target.value;\n                state.formattedStale = true;\n                state.dirty = true;\n                scheduleDraftAutosave();\n            });\n        }\n\n        if (editorEl) {\n            editorEl.addEventListener('input', (e) => {\n                setContent(e.target.value);\n            });\n        }\n\n        if (titleInputEl) {\n            titleInputEl.addEventListener('input', (e) => {\n                state.title = e.target.value.trim() || 'Untitled Notes';\n                state.dirty = true;\n                updateSaveState('Unsaved changes');\n                scheduleDraftAutosave();\n            });\n        }\n\n        if (clearBtn) {\n            clearBtn.addEventListener('click', () => {\n                if (state.content.trim() && confirm('Are you sure you want to clear the editor?')) {\n                    setContent('');\n                    showToast('Editor cleared.');\n                }\n            });\n        }\n\n        if (newBtn) {\n            newBtn.addEventListener('click', () => {\n                if (state.dirty && state.content.trim()) {\n                    if (!confirm('You have unsaved changes. Create a new document anyway?')) return;\n                }\n                resetDocument();\n                showToast('New document created.');\n            });\n        }\n\n        \/\/ Theme & Print & Paste bindings\n        if (themeBtn) themeBtn.addEventListener('click', toggleTheme);\n        if (printBtn) {\n            printBtn.addEventListener('click', () => {\n                if (!state.content || !state.content.trim()) {\n                    showToast('Please enter or paste some notes first.', 'error');\n                    return;\n                }\n                try {\n                    window.print();\n                } catch (e) {\n                    showToast('Unable to print notes.', 'error');\n                }\n            });\n        }\n\n        if (pasteBtn) {\n            pasteBtn.addEventListener('click', () => {\n                if (modalPasteInput) modalPasteInput.value = '';\n                openModal(pasteModal, modalPasteInput);\n            });\n        }\n\n        if (modalCancelBtn && pasteModal) {\n            modalCancelBtn.addEventListener('click', () => closeModal(pasteModal));\n        }\n\n        if (modalInsertBtn && pasteModal && modalPasteInput) {\n            modalInsertBtn.addEventListener('click', () => {\n                const pastedText = modalPasteInput.value.trim();\n                if (!pastedText) {\n                    showToast('Please enter or paste text to insert.', 'error');\n                    return;\n                }\n                const separator = state.content.trim() ? '\\n\\n' : '';\n                setContent(state.content + separator + pastedText);\n                closeModal(pasteModal);\n                showToast('Notes inserted successfully!');\n            });\n        }\n\n        \/\/ Backdrop click handlers for modals\n        [pasteModal, recentModal, draftModal].forEach(modal => {\n            if (modal) {\n                modal.addEventListener('click', (e) => {\n                    if (e.target === modal) {\n                        closeModal(modal);\n                    }\n                });\n            }\n        });\n\n        \/\/ Undo \/ Redo Bindings\n        if (undoBtn) undoBtn.addEventListener('click', undo);\n        if (redoBtn) redoBtn.addEventListener('click', redo);\n\n        \/\/ Search Bar Toggle & Close\n        if (searchToggleBtn && searchBar && searchInput) {\n            searchToggleBtn.addEventListener('click', () => {\n                searchBar.classList.toggle('active');\n                if (searchBar.classList.contains('active')) {\n                    searchInput.focus();\n                    performSearch();\n                }\n            });\n        }\n\n        if (searchCloseBtn && searchBar) {\n            searchCloseBtn.addEventListener('click', () => {\n                searchBar.classList.remove('active');\n            });\n        }\n\n        if (searchInput) searchInput.addEventListener('input', performSearch);\n        if (caseCheck) caseCheck.addEventListener('change', performSearch);\n\n        if (searchNextBtn) {\n            searchNextBtn.addEventListener('click', () => {\n                if (state.searchMatches.length === 0) return;\n                state.searchMatchIndex = (state.searchMatchIndex + 1) % state.searchMatches.length;\n                highlightMatch(state.searchMatchIndex);\n            });\n        }\n\n        if (searchPrevBtn) {\n            searchPrevBtn.addEventListener('click', () => {\n                if (state.searchMatches.length === 0) return;\n                state.searchMatchIndex = (state.searchMatchIndex - 1 + state.searchMatches.length) % state.searchMatches.length;\n                highlightMatch(state.searchMatchIndex);\n            });\n        }\n\n        if (replaceBtn) {\n            replaceBtn.addEventListener('click', () => {\n                if (state.searchMatches.length === 0 || state.searchMatchIndex < 0) {\n                    showToast('No matches found.', 'error');\n                    return;\n                }\n                const match = state.searchMatches[state.searchMatchIndex];\n                const text = state.content;\n                const rep = replaceInput ? replaceInput.value : '';\n                const newText = text.substring(0, match.start) + rep + text.substring(match.end);\n                setContent(newText);\n                showToast('Replacement made.');\n            });\n        }\n\n        if (replaceAllBtn) {\n            replaceAllBtn.addEventListener('click', () => {\n                if (!searchInput || !searchInput.value) return;\n                const query = searchInput.value;\n                const text = state.content;\n                const rep = replaceInput ? replaceInput.value : '';\n                const flags = caseCheck && caseCheck.checked ? 'g' : 'gi';\n                try {\n                    const escaped = query.replace(\/[.*+?^${}()|[\\]\\\\]\/g, '\\\\$&');\n                    const regex = new RegExp(escaped, flags);\n                    const count = (text.match(regex) || []).length;\n                    if (count === 0) {\n                        showToast('No matches to replace.', 'error');\n                        return;\n                    }\n                    const newText = text.replace(regex, rep);\n                    setContent(newText);\n                    showToast(`${count} replacements made.`);\n                } catch (e) {\n                    showToast('Replace All failed.', 'error');\n                }\n            });\n        }\n\n        \/\/ Keyboard Shortcuts\n        document.addEventListener('keydown', (e) => {\n            if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {\n                e.preventDefault();\n                saveNote();\n            } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') {\n                e.preventDefault();\n                if (searchBar && searchInput) {\n                    searchBar.classList.add('active');\n                    searchInput.focus();\n                    performSearch();\n                }\n            } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {\n                e.preventDefault();\n                if (e.shiftKey) {\n                    redo();\n                } else {\n                    undo();\n                }\n            } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'y') {\n                e.preventDefault();\n                redo();\n            } else if (e.key === 'Escape') {\n                if (closeActiveModal()) {\n                    e.preventDefault();\n                }\n            }\n        });\n\n        if (saveBtn) saveBtn.addEventListener('click', saveNote);\n        if (recentBtn) recentBtn.addEventListener('click', openRecentModal);\n        if (recentCloseBtn && recentModal) recentCloseBtn.addEventListener('click', () => closeModal(recentModal));\n\n        \/\/ Draft Modal Actions\n        if (draftRecoverBtn && draftModal) {\n            draftRecoverBtn.addEventListener('click', () => {\n                try {\n                    const raw = localStorage.getItem(DRAFT_KEY);\n                    if (raw) {\n                        const draft = JSON.parse(raw);\n                        state.title = draft.title || 'Untitled Notes';\n                        if (titleInputEl) titleInputEl.value = state.title;\n                        state.mode = draft.mode || 'study';\n                        if (formatStyleSelect) formatStyleSelect.value = state.mode;\n                        state.exportFormat = draft.exportFormat || 'txt';\n                        if (exportFormatSelect) exportFormatSelect.value = state.exportFormat;\n                        state.formattedContent = draft.formattedContent || '';\n                        state.formattedStale = false;\n                        state.structure = draft.structure || state.structure;\n                        state.currentNoteId = draft.currentNoteId || null;\n\n                        if (draft.content) {\n                            state.history = [draft.content];\n                            state.historyIndex = 0;\n                            updateUndoRedoButtons();\n                            setContentCore(draft.content);\n                            updateStats(draft.content);\n                            renderPreview();\n                        }\n                        state.dirty = true;\n                        updateSaveState('Unsaved changes');\n                        performSearch();\n                        showToast('Draft recovered.');\n                    }\n                } catch (e) {\n                    localStorage.removeItem(DRAFT_KEY);\n                }\n                closeModal(draftModal);\n            });\n        }\n\n        if (draftDiscardBtn && draftModal) {\n            draftDiscardBtn.addEventListener('click', () => {\n                try { localStorage.removeItem(DRAFT_KEY); } catch (e) {}\n                closeModal(draftModal);\n                showToast('Draft discarded.');\n            });\n        }\n\n        \/\/ Initialization & Draft Recovery Check on Startup\n        try {\n            \/\/ Restore Theme\n            const savedTheme = localStorage.getItem(THEME_KEY);\n            if (savedTheme === 'dark' || savedTheme === 'light') {\n                setTheme(savedTheme);\n            } else {\n                setTheme('light');\n            }\n\n            loadNotesFromStorage();\n\n            const draftRaw = localStorage.getItem(DRAFT_KEY);\n            if (draftRaw) {\n                const draft = JSON.parse(draftRaw);\n                if (draft && (draft.content || draft.title !== 'Untitled Notes')) {\n                    openModal(draftModal, draftRecoverBtn);\n                    return true;\n                }\n            }\n\n            if (editorEl) {\n                const initialText = editorEl.value || '';\n                state.content = initialText;\n                state.history = [initialText];\n                state.historyIndex = 0;\n                updateUndoRedoButtons();\n                updateStats(initialText);\n                renderPreview();\n                if (initialText.trim()) {\n                    updateSaveState('Unsaved changes');\n                }\n            }\n            if (titleInputEl) {\n                state.title = titleInputEl.value.trim() || 'Untitled Notes';\n            }\n            performSearch();\n        } catch (e) {\n            try { localStorage.removeItem(DRAFT_KEY); } catch (err) {}\n        }\n\n        return true;\n    }\n\n    if (document.readyState === 'loading') {\n        document.addEventListener('DOMContentLoaded', initApp, { once: true });\n    } else {\n        initApp();\n    }\n\n    \/\/ Fallback lightweight MutationObserver for dynamic Elementor widget hydration\n    const observer = new MutationObserver(() => {\n        const root = document.getElementById('ai-notes-smart-copy');\n        if (root && root.dataset.appInitialized !== 'true') {\n            if (initApp()) {\n                observer.disconnect();\n            }\n        }\n    });\n    observer.observe(document.body, { childList: true, subtree: true });\n\n})();\n<\/script>\n\n<\/body>\n<\/html>\n","protected":false},"excerpt":{"rendered":"<p>AI Notes Smart Copy AI Notes Smart Copy Client-side intelligent note cleaner, formatter, and multi-format exporter. \ud83d\udcc4 New \ud83d\udcc2 Recent \ud83d\udda8\ufe0f Print \ud83c\udf19 Theme \ud83d\udccb Paste Notes \ud83d\udd0d Detect Structure Study NotesClean NotesOutlineRevision NotesQ&#038;A NotesSummaryBullet PointsExam RevisionCornell-style Notes \u26a1 Format \u21a9\ufe0f Undo \u21aa\ufe0f Redo \ud83d\udd0e Search \ud83d\uddd1\ufe0f Clear Case sensitive \u2715 0 matches Previous Next [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-974","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/pages\/974","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/comments?post=974"}],"version-history":[{"count":9,"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/pages\/974\/revisions"}],"predecessor-version":[{"id":987,"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/pages\/974\/revisions\/987"}],"wp:attachment":[{"href":"https:\/\/freewebtools.co.in\/index.php\/wp-json\/wp\/v2\/media?parent=974"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}