<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Apne English keyboard se asani se Hindi mein likhein. Hamare free online transliteration tool se 'English se Hindi typing' karein aur ek click mein copy karein.">
    <meta name="keywords" content="english se hindi typing, hindi me type kare, online hindi typing, english to hindi typing tool, indic typing, transliteration, online notepad, hindi typing keyboard">
    <meta name="theme-color" content="#21808d">
    <title>English Se Hindi Typing - Free Online Tool | Hindi Me Type Kare</title>
    
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://hindime.net/">
    <meta property="og:title" content="English Se Hindi Typing - Free Online Tool | Hindi Me Type Kare">
    <meta property="og:description" content="Apne English keyboard se asani se Hindi mein likhein. Hamare free online transliteration tool se 'English se Hindi typing' karein aur ek click mein copy karein.">
    <meta property="og:image" content="https://hindime.net/social-banner.jpg">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:url" content="https://hindime.net/">
    <meta name="twitter:title" content="English Se Hindi Typing - Free Online Tool | Hindi Me Type Kare">
    <meta name="twitter:description" content="Apne English keyboard se asani se Hindi mein likhein. Hamare free online transliteration tool se 'English se Hindi typing' karein aur ek click mein copy karein.">
    <meta name="twitter:image" content="https://hindime.net/social-banner.jpg">
    
    <link rel="icon" type="image/png" sizes="32x32" href="favicon.png">
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
    <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
    
    <link rel="stylesheet" href="style.css">
    
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7673195738743060" data-overlays="bottom" crossorigin="anonymous"></script>
    
    <script>

(function(){const l={tid:"G-WSFV1QYEL1",timeout:18e5,ext:["pdf","xls","xlsx","doc","docx","txt","rtf","csv","exe","key","pps","ppt","pptx","7z","pkg","rar","gz","zip","avi","mov","mp4","mpe","mpeg","wmv","mid","midi","mp3","wav","wma"]},g=Math.floor(Math.random()*1e9)+1,f=Date.now();let h=f,o=!1,r=!1,c=!1,_,y,j,b,i=!1;const e=function(){try{return localStorage.setItem("t","t"),localStorage.removeItem("t"),localStorage}catch{return{getItem:()=>null,setItem:()=>null,removeItem:()=>null}}}(),t=document,d=document.documentElement,u=document.body,s=document.location,w=window,m=screen,a=navigator||{};function n(n,d,u,p){const z=Date.now()-h;h=Date.now();const P=()=>Math.floor(Math.random()*1e9)+1,M=()=>Math.floor(Date.now()/1e3),L=()=>P()+"."+M(),T=()=>(e.cid_v4||(e.cid_v4=L()),e.cid_v4),B=e.getItem("cid_v4"),K=()=>B?0[0]:o==!0?0[0]:"1",y=M(),N=e.getItem("_ga_last")||0;let j=e.getItem("_ga_sid"),b=e.getItem("_ga_sct")||0,O=!1;(!j||y-N>l.timeout/1e3)&&(O=!0,j=y,b=Number(b)+1,e.setItem("_ga_sid",j),e.setItem("_ga_sct",b),e.setItem("_ga_hits","0")),e.setItem("_ga_last",y);const w=Number(e.getItem("_ga_hits")||0)+1;e.setItem("_ga_hits",w);const v=s.search,x=new URLSearchParams(v),_=e=>x.get("utm_"+e);let C=_("source"),D=_("medium"),F=_("campaign");O&&(C?(e.setItem("_ga_utm_source",C),e.setItem("_ga_utm_medium",D||""),e.setItem("_ga_utm_campaign",F||"")):(e.removeItem("_ga_utm_source"),e.removeItem("_ga_utm_medium"),e.removeItem("_ga_utm_campaign")));const S=["q","s","search","query","keyword"],R=S.some(e=>v.includes("&"+e+"=")||v.includes("?"+e+"=")),A=()=>R==!0?"view_search_results":o==!0?"scroll":r==!0?"file_download":c==!0?"user_engagement":i==!0?"click":"page_view",H=()=>o==!0?"90":0[0],I=()=>{if(A()=="view_search_results"){for(let e of x)if(S.includes(e[0]))return e[1]}else return 0[0]},k=encodeURIComponent,V=e=>{let t=[];for(let n in e)e.hasOwnProperty(n)&&e[n]!==0[0]&&t.push(k(n)+"="+k(e[n]));return t.join("&")},$=!1,W="https://www.google-analytics.com/g/collect",U=V({v:"2",tid:l.tid,_p:g,sr:m.width+"x"+m.height,ul:(a.language||0[0]).toLowerCase(),cid:T(),_fv:K(),dl:s.origin+s.pathname+v,dt:t.title||0[0],dr:t.referrer||0[0],seg:w>1||Date.now()-f>1e4?"1":0[0],"epn.percent_scrolled":H(),"ep.search_term":I(),"ep.file_extension":n||0[0],"ep.file_name":d||0[0],"ep.link_text":u||0[0],"ep.link_url":p||0[0],_s:w,sid:j,sct:b,_ss:O?"1":0[0],en:A(),_et:z,cs:e.getItem("_ga_utm_source")||0[0],cm:e.getItem("_ga_utm_medium")||0[0],cn:e.getItem("_ga_utm_campaign")||0[0],"ep.outbound":i?"true":0[0],_dbg:$?1:0[0]}),E=W+"?"+U;if(a.sendBeacon)a.sendBeacon(E);else{let e=new XMLHttpRequest;e.open("POST",E,!0)}}n();function v(){return(d.scrollTop||u.scrollTop)/((d.scrollHeight||u.scrollHeight)-d.clientHeight)*100}t.addEventListener("scroll",p,{passive:!0});function p(){const e=v();if(e<90)return;o=!0,n(),t.removeEventListener("scroll",p,{passive:!0}),o=!1}t.addEventListener("click",function(e){const t=e.target.closest("a");if(t&&t.getAttribute("href")){const e=t.getAttribute("href"),a=e.substring(e.lastIndexOf("/")+1),o=a.split(".").pop();t.hasAttribute("download")||l.ext.includes(o)?(r=!0,n(o,a.replace("."+o,""),t.innerText||t.textContent,e.replace(s.origin,"")),r=!1):t.hostname&&t.hostname!==s.hostname&&(i=!0,n(0[0],0[0],t.innerText||t.textContent,e),i=!1)}}),t.addEventListener("visibilitychange",function(){t.visibilityState==="hidden"&&(c=!0,n(),c=!1)})})()

</script>

</head>
<body>
    <div id="app">
        <header class="header">
            <div class="container nav">
                <div class="nav__brand">
                    <a href="/" style="text-decoration:none;"><h1>Type Kare</h1></a>
                </div>
                
                <div class="nav__links" id="navLinks">
                    <div class="dropdown">
                        <button class="dropbtn">Languages ▾</button>
                        <div class="dropdown-content">
                                                            <a href="/">Hindi Typing</a>
                                                            <a href="/odia">Odia Typing</a>
                                                            <a href="/bengali">Bengali Typing</a>
                                                            <a href="/marathi">Marathi Typing</a>
                                                            <a href="/tamil">Tamil Typing</a>
                                                            <a href="/telugu">Telugu Typing</a>
                                                            <a href="/kannada">Kannada Typing</a>
                                                            <a href="/malayalam">Malayalam Typing</a>
                                                            <a href="/gujarati">Gujarati Typing</a>
                                                            <a href="/punjabi">Punjabi Typing</a>
                                                    </div>
                    </div>

                    <a href="#features" class="nav__link">Features</a>
                    <button class="theme-toggle" id="themeToggleDesktop" title="Toggle Theme">
                        <span class="themeIcon">&#9789;</span>
                    </button>
                </div>

                <div class="nav__mobile-controls">
                    <button class="theme-toggle" id="themeToggleMobile" title="Toggle Theme">
                        <span class="themeIcon">&#9789;</span>
                    </button>
                    <button class="menu-toggle" id="menuToggle" title="Menu">
                        &#9776;
                    </button>
                </div>
            </div>
        </header>

        <div class="container">
            
            <div class="ads">
                <ins class="adsbygoogle"
                     style="display:block"
                     data-ad-client="ca-pub-7673195738743060"
                     data-ad-slot="3643649070"
                     data-ad-format="auto"
                     data-full-width-responsive="true"></ins>
                <script>
                     (adsbygoogle = window.adsbygoogle || []).push({});
                </script>
            </div>
            
            <div class="toolbar">
                <div class="toolbar__scroll" id="scrollableToolbar">
                    <div class="toolbar__group">
                        <button class="toolbar__btn" id="newBtn" title="New (Ctrl+N)">
                            <span class="toolbar__icon">&#128196;</span>
                            <span class="toolbar__text">New</span>
                        </button>
                        <button class="toolbar__btn" id="openBtn" title="Open (Ctrl+O)">
                            <span class="toolbar__icon">&#128193;</span>
                            <span class="toolbar__text">Open</span>
                        </button>
                        <button class="toolbar__btn" id="saveBtn" title="Save (Ctrl+S)">
                            <span class="toolbar__icon">&#128190;</span>
                            <span class="toolbar__text">Save</span>
                        </button>
                    </div>

                    <div class="toolbar__group">
                        <button class="toolbar__btn" id="findReplaceBtn" title="Find & Replace (Ctrl+F)">
                            <span class="toolbar__icon">&#128269;</span>
                        </button>
                        <button class="toolbar__btn" id="undoBtn" title="Undo (Ctrl+Z)">
                            <span class="toolbar__icon">&#8634;</span>
                        </button>
                        <button class="toolbar__btn" id="redoBtn" title="Redo (Ctrl+Y)">
                            <span class="toolbar__icon">&#8635;</span>
                        </button>
                    </div>

                    <div class="toolbar__group">
                        <select class="toolbar__select" id="fontFamily">
                            <option value="Arial, sans-serif">Arial</option>
                            <option value="'Courier New', monospace">Courier New</option>
                            <option value="Georgia, serif">Georgia</option>
                            <option value="monospace">Monospace</option>
                        </select>
                        <select class="toolbar__select" id="fontSize">
                            <option value="14">14px</option>
                            <option value="16" selected>16px</option>
                            <option value="18">18px</option>
                            <option value="20">20px</option>
                            <option value="24">24px</option>
                            <option value="32">32px</option>
                        </select>
                    </div>
                </div>
                
                <div class="scroll-hint" id="scrollHint"><span>&#10095;</span></div>

                <div class="toolbar__static">
                    <div class="toolbar__group language-select-wrapper">
                        <span title="Input Language">&#127760;</span>
                        <select class="toolbar__select" id="languageSelect" style="font-weight: bold; min-width: 120px;">
                            <option value="en">English</option>
                            <option value="hi-t-i0-und">हिन्दी</option>
                            <option value="or-t-i0-und">ଓଡ଼ିଆ</option>
                            <option value="bn-t-i0-und">বাংলা</option>
                            <option value="mr-t-i0-und">मराठी</option>
                            <option value="ta-t-i0-und">தமிழ்</option>
                            <option value="te-t-i0-und">తెలుగు</option>
                            <option value="kn-t-i0-und">ಕನ್ನಡ</option>
                            <option value="ml-t-i0-und">മലയാളം</option>
                            <option value="gu-t-i0-und">ગુજરાતી</option>
                            <option value="pa-t-i0-und">ਪੰਜਾਬੀ</option>
                        </select>
                        <div id="langIndicator" class="language-indicator">EN</div>
                    </div>

                    <div class="toolbar__group toolbar__group--right">
                        <button class="toolbar__btn" id="copyBtn" title="Copy Text">
                            <span class="toolbar__icon">&#128203;</span>
                            <span class="toolbar__text">Copy</span>
                        </button>
                        <button class="toolbar__btn" id="printBtn" title="Print (Ctrl+P)">
                            <span class="toolbar__icon">&#128424;</span>
                            <span class="toolbar__text">Print</span>
                        </button>
                        <button class="toolbar__btn" id="teleprompterBtn" title="Teleprompter Mode">
                            <span class="toolbar__icon">&#127909;</span>
                        </button>
                    </div>
                </div>
            </div>

            <div class="editor-container">
                <textarea id="editor" class="editor" placeholder="Start Writing here..."></textarea>
                
                <div id="suggestionBox" class="suggestion-box"></div>
                
                <div id="mirrorDiv" style="visibility:hidden; position:absolute; white-space:pre-wrap; word-wrap:break-word; overflow:hidden;"></div>
            </div>

            <div class="status-bar">
                <div class="status-bar__left">
                    <span class="status-item" id="autosaveStatus">Auto-saved</span>
                    <span class="status-item" id="wordCount">Words: 0</span>
                    <span class="status-item" id="charCount">Characters: 0</span>
                </div>
                
                <div class="status-bar__right">
                     <div class="case-buttons">
                        <button class="case-btn" id="emptyLinesBtn" title="Remove Empty Lines">Empty Lines</button>
                        <button class="case-btn" id="sentenceCase" title="Sentence case">Sentence case</button>
                        <button class="case-btn" id="lowerCase" title="lower case">lower case</button>
                        <button class="case-btn" id="upperCase" title="UPPER CASE">UPPER CASE</button>
                    </div>
                </div>
            </div>

            <div class="reading-time-section">
                <div class="reading-time-header">
                    <h3>&#128337; Script Reading Time Calculator</h3>
                    <span class="reading-time-display" id="readingTimeDisplay">0:00</span>
                </div>
                <div class="reading-time-controls">
                    <label for="readingSpeedSlider" class="reading-speed-label">
                        Reading Speed: <span id="readingSpeedValue">3</span> words/second
                    </label>
                    <input type="range" id="readingSpeedSlider" class="reading-speed-slider" min="1" max="5" step="1" value="3">
                    <div class="speed-labels">
                        <span>Slow</span>
                        <span>Fast</span>
                    </div>
                </div>
            </div>
            
            <div class="ads">
                <ins class="adsbygoogle"
                     style="display:block"
                     data-ad-client="ca-pub-7673195738743060"
                     data-ad-slot="3643649070"
                     data-ad-format="auto"
                     data-full-width-responsive="true"></ins>
                <script>
                     (adsbygoogle = window.adsbygoogle || []).push({});
                </script>
            </div>
        </div>

        <section class="features" id="features">
            <div class="container">
                <h2 style="text-align:center; margin-bottom:30px; color:var(--color-text);">Features</h2>
                <div class="features__grid">
                    <div class="feature-card">
                        <span class="feature-card__icon">&#127760;</span>
                        <h3>Indic Typing</h3>
                        <p>Type in English and get instant transliteration for Hindi, Odia, Bengali, and more.</p>
                    </div>
                    <div class="feature-card">
                        <span class="feature-card__icon">&#128190;</span>
                        <h3>Auto Save</h3>
                        <p>Your content is saved locally to your browser every 2 seconds.</p>
                    </div>
                    <div class="feature-card">
                        <span class="feature-card__icon">&#128337;</span>
                        <h3>Script Timer</h3>
                        <p>Built-in reading time calculator for video creators and podcasters.</p>
                    </div>
                    <div class="feature-card">
                        <span class="feature-card__icon">&#9789;</span>
                        <h3>Dark Mode</h3>
                        <p>Easy on the eyes with a built-in dark theme for night writing.</p>
                    </div>
                </div>
            </div>
        </section>

        <section class="seo-article container" style="padding: 40px 10px; margin-top: 20px;">
            <div style="margin: 0 auto; background: var(--color-surface); padding: 30px; border-radius: 8px; border: 1px solid var(--color-border); line-height: 1.6;">
                
    <h2 style="color: var(--color-primary); margin-top: 0; font-size: 1.8rem;"><strong>English Se Hindi Typing</strong> कैसे करें? (Free Online Tool)</h2>
    <p style="color: var(--color-text); font-size: 1.05rem;">आज के डिजिटल दौर में अपनी मातृभाषा में विचार व्यक्त करना बहुत ज़रूरी है। यदि आप इंटरनेट पर "<strong>English se Hindi typing</strong>" करना चाहते हैं, तो आप बिल्कुल सही जगह पर हैं। हमारा फ्री ऑनलाइन <strong>transliteration</strong> टूल आपको अपने रेगुलर <strong>English keyboard</strong> का इस्तेमाल करके शुद्ध हिंदी (देवनागरी लिपि) में आसानी से लिखने की सुविधा देता है।</p>

    <h3 style="color: var(--color-text); margin-top: 25px; font-size: 1.4rem;"><strong>Hindi Me Type Kare</strong> - बस एक क्लिक में</h3>
    <p style="color: var(--color-text-secondary); font-size: 1rem;">अब आपको कोई भारी सॉफ़्टवेयर या <strong>Hindi typing keyboard</strong> लेआउट डाउनलोड करने की ज़रूरत नहीं है। बस ऊपर दिए गए <strong>online notepad</strong> एडिटर में रोमन इंग्लिश (Hinglish) में टाइप करें (जैसे: <i>"Aap kaise hain?"</i>) और Space दबाते ही यह आटोमेटिक हिंदी में बदल जाएगा (<i>"आप कैसे हैं?"</i>)। इसे आप आसानी से कॉपी करके WhatsApp, Facebook, Blogs या Emails में इस्तेमाल कर सकते हैं।</p>

    <h3 style="color: var(--color-text); margin-top: 25px; font-size: 1.4rem;">इस <strong>Online Hindi Typing</strong> टूल के मुख्य फायदे</h3>
    <ul style="color: var(--color-text-secondary); padding-left: 20px; margin-bottom: 20px; font-size: 1rem;">
        <li style="margin-bottom: 10px;"><strong style="color: var(--color-text);">100% Free और Fast:</strong> बिना किसी छिपे हुए चार्ज या लॉगिन के अनलिमिटेड <strong>online Hindi typing</strong> करें।</li>
        <li style="margin-bottom: 10px;"><strong style="color: var(--color-text);">Privacy की पूरी गारंटी:</strong> आपका टाइप किया हुआ डेटा किसी सर्वर पर सेव नहीं होता। "Auto Save" फ़ीचर आपके डिवाइस के लोकल ब्राउज़र में ही काम करता है।</li>
        <li style="margin-bottom: 10px;"><strong style="color: var(--color-text);">Script Reading Timer & Teleprompter:</strong> YouTube क्रिएटर्स और व्लॉगर्स के लिए बेहतरीन स्क्रिप्ट राइटिंग और रीडिंग टूल।</li>
    </ul>

    <hr style="border: 0; border-top: 1px solid var(--color-border); margin: 40px 0;">

    <h2 style="color: var(--color-primary); font-size: 1.6rem; text-align: center; margin-bottom: 30px;">अक्सर पूछे जाने वाले सवाल (FAQs)</h2>
    
    <div style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid var(--color-secondary);">
        <h4 style="margin: 0 0 8px 0; color: var(--color-text); font-size: 1.1rem;">Q1. क्या यह <strong>English to Hindi typing tool</strong> पूरी तरह फ्री है?</h4>
        <p style="margin: 0; color: var(--color-text-secondary); font-size: 0.95rem;">हाँ, यह टूल 100% फ्री है। आप इसमें बिना किसी लॉगिन या रजिस्ट्रेशन के अनलिमिटेड शब्द टाइप, एडिट, फॉर्मेट और कॉपी कर सकते हैं।</p>
    </div>

    <div style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid var(--color-secondary);">
        <h4 style="margin: 0 0 8px 0; color: var(--color-text); font-size: 1.1rem;">Q2. टाइप किए गए हिंदी टेक्स्ट को कॉपी कैसे करें?</h4>
        <p style="margin: 0; color: var(--color-text-secondary); font-size: 0.95rem;">ऊपर टूलबार में दाईं ओर एक "Copy" बटन दिया गया है। एक बार आपका पैराग्राफ पूरा हो जाए, बस उस पर क्लिक करें और आपका पूरा टेक्स्ट क्लिपबोर्ड में कॉपी हो जाएगा।</p>
    </div>

    <div style="margin-bottom: 0;">
        <h4 style="margin: 0 0 8px 0; color: var(--color-text); font-size: 1.1rem;">Q3. क्या मेरा टाइप किया हुआ प्राइवेट डेटा सुरक्षित (Safe) है?</h4>
        <p style="margin: 0; color: var(--color-text-secondary); font-size: 0.95rem;">बिल्कुल! हमारा टूल लोकल ब्राउज़र स्टोरेज का इस्तेमाल करता है। इसका मतलब आप जो भी टाइप करते हैं वह सिर्फ आपके मोबाइल या कंप्यूटर तक ही सीमित रहता है, हमारे सर्वर पर बिल्कुल नहीं जाता।</p>
    </div>
            </div>
        </section>

        <footer class="footer">
            <div class="container">
                <p>&copy; 2026 HindiMe.net. All text is stored locally.</p>
                <div class="footer-langs">
                                            <a href="/">Hindi</a>
                                            <a href="/odia">Odia</a>
                                            <a href="/bengali">Bengali</a>
                                            <a href="/marathi">Marathi</a>
                                            <a href="/tamil">Tamil</a>
                                            <a href="/telugu">Telugu</a>
                                            <a href="/kannada">Kannada</a>
                                            <a href="/malayalam">Malayalam</a>
                                            <a href="/gujarati">Gujarati</a>
                                            <a href="/punjabi">Punjabi</a>
                                    </div>
            </div>
        </footer>
    </div>

    <input type="file" id="fileInput" accept=".txt" style="display: none;">
    
    <div id="teleprompterOverlay" class="teleprompter-overlay">
        <div id="teleprompterContent" class="teleprompter-content"></div>
        <div class="teleprompter-controls">
            <input type="range" id="teleProgressSlider" min="0" max="100" value="0" title="Scroll Position">

            <button class="tele-btn" id="telePlayBtn">&#9658;</button>
            <button class="tele-btn" id="teleRestartBtn">&#8635;</button>
            
            <div class="tele-slider-group">
                <span>Speed:</span>
                <input type="range" id="teleSpeedSlider" class="tele-slider" min="1" max="10" value="5">
            </div>
            <div class="tele-slider-group">
                <span>Size:</span>
                <input type="range" id="teleSizeSlider" class="tele-slider" min="14" max="35" value="17">
            </div>
            <button class="tele-btn" id="teleMirrorBtn">Mirror</button>
            <button class="tele-btn" id="teleCloseBtn">Close</button>
        </div>
    </div>

    <div id="findModal" class="modal">
        <div class="modal__content">
            <div class="modal__header">
                <h3>Find & Replace</h3>
                <button class="modal__close" id="closeFindModal">&times;</button>
            </div>
            <div class="modal__body">
                <div class="form-group">
                    <label for="findInput">Find:</label>
                    <input type="text" id="findInput" class="form-control" placeholder="Enter text to find">
                </div>
                <div class="form-group">
                    <label for="replaceInput">Replace with:</label>
                    <input type="text" id="replaceInput" class="form-control" placeholder="Enter replacement text">
                </div>
                <div class="modal__actions">
                    <button class="btn btn--secondary" id="findNext">Find Next</button>
                    <button class="btn btn--secondary" id="replaceOne">Replace</button>
                    <button class="btn btn--primary" id="replaceAll">Replace All</button>
                </div>
            </div>
        </div>
    </div>
    
    <div id="newDocumentModal" class="modal">
        <div class="modal__content">
            <div class="modal__header">
                <h3>New Document</h3>
                <button class="modal__close" id="closeNewDocumentModal">&times;</button>
            </div>
            <div class="modal__body">
                <p>Are you sure you want to create a new document?</p>
                <p><strong>Any unsaved changes will be lost.</strong></p>
                <div class="modal__actions">
                    <button class="btn btn--secondary" id="cancelNewDocument">Cancel</button>
                    <button class="btn btn--primary" id="confirmNewDocument">Create New Document</button>
                </div>
            </div>
        </div>
    </div>

    <div id="saveDocumentModal" class="modal">
        <div class="modal__content">
            <div class="modal__header">
                <h3>Save Document</h3>
                <button class="modal__close" id="closeSaveDocumentModal">&times;</button>
            </div>
            <div class="modal__body">
                <div class="form-group">
                    <label for="filenameInput">Filename:</label>
                    <input type="text" id="filenameInput" class="form-control" placeholder="Enter filename" value="New Document" maxlength="100">
                    <small class="form-text">File will be saved as .txt format</small>
                </div>
                <div class="modal__actions">
                    <button class="btn btn--secondary" id="cancelSaveDocument">Cancel</button>
                    <button class="btn btn--primary" id="confirmSaveDocument">Save</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // --- TRANSLITERATION MANAGER ---
        class TransliterationManager {
            constructor(editorId, selectId, suggestionBoxId, fontSelectId) {
                this.editor = document.getElementById(editorId);
                this.languageSelect = document.getElementById(selectId);
                this.suggestionBox = document.getElementById(suggestionBoxId);
                this.fontSelect = document.getElementById(fontSelectId);
                this.langCode = 'en';
                this.lastIndicLang = null; 
                this.currentWord = '';
                this.wordStartPos = 0; 
                this.suggestions = [];
                this.selectedIndex = 0;
                this.isSuggesting = false;
                
                this.defaultFonts = [
                    { name: 'Arial', value: 'Arial, sans-serif' },
                    { name: 'Courier New', value: "'Courier New', monospace" },
                    { name: 'Georgia', value: 'Georgia, serif' },
                    { name: 'Monospace', value: 'monospace' }
                ];
                
                this.fontMap = {
                    'hi': [{ name: 'Noto Sans Devanagari', value: "'Noto Sans Devanagari', sans-serif" }, { name: 'Poppins', value: "'Poppins', sans-serif" }, { name: 'Tiro Devanagari Hindi', value: "'Tiro Devanagari Hindi', serif" }, { name: 'Mukta', value: "'Mukta', sans-serif" }, { name: 'Kalam', value: "'Kalam', cursive" }],
                    'or': [{ name: 'Noto Sans Oriya', value: "'Noto Sans Oriya', sans-serif" }, { name: 'Baloo 2', value: "'Baloo 2', cursive" }, { name: 'Anek Odia', value: "'Anek Odia', sans-serif" }, { name: 'Noto Serif Oriya', value: "'Noto Serif Oriya', serif" }],
                    'bn': [{ name: 'Noto Sans Bengali', value: "'Noto Sans Bengali', sans-serif" }, { name: 'Tiro Bangla', value: "'Tiro Bangla', serif" }, { name: 'Baloo Da 2', value: "'Baloo Da 2', cursive" }, { name: 'Hind Siliguri', value: "'Hind Siliguri', sans-serif" }, { name: 'Galada', value: "'Galada', cursive" }],
                    'mr': [{ name: 'Noto Sans Devanagari', value: "'Noto Sans Devanagari', sans-serif" }, { name: 'Poppins', value: "'Poppins', sans-serif" }, { name: 'Tiro Devanagari Hindi', value: "'Tiro Devanagari Hindi', serif" }, { name: 'Mukta', value: "'Mukta', sans-serif" }, { name: 'Kalam', value: "'Kalam', cursive" }],
                    'ta': [{ name: 'Noto Sans Tamil', value: "'Noto Sans Tamil', sans-serif" }, { name: 'Tiro Tamil', value: "'Tiro Tamil', serif" }, { name: 'Hind Madurai', value: "'Hind Madurai', sans-serif" }, { name: 'Mukta Malar', value: "'Mukta Malar', sans-serif" }, { name: 'Arima', value: "'Arima', cursive" }],
                    'te': [{ name: 'Noto Sans Telugu', value: "'Noto Sans Telugu', sans-serif" }, { name: 'Tiro Telugu', value: "'Tiro Telugu', serif" }, { name: 'Mandali', value: "'Mandali', sans-serif" }, { name: 'Tenali Ramakrishna', value: "'Tenali Ramakrishna', sans-serif" }, { name: 'Ramabhadra', value: "'Ramabhadra', sans-serif" }],
                    'kn': [{ name: 'Noto Sans Kannada', value: "'Noto Sans Kannada', sans-serif" }, { name: 'Tiro Kannada', value: "'Tiro Kannada', serif" }, { name: 'Baloo Tamma 2', value: "'Baloo Tamma 2', cursive" }, { name: 'Anek Kannada', value: "'Anek Kannada', sans-serif" }],
                    'ml': [{ name: 'Noto Sans Malayalam', value: "'Noto Sans Malayalam', sans-serif" }, { name: 'Tiro Malayalam', value: "'Tiro Malayalam', serif" }, { name: 'Baloo Chettan 2', value: "'Baloo Chettan 2', cursive" }, { name: 'Manjari', value: "'Manjari', sans-serif" }],
                    'gu': [{ name: 'Noto Sans Gujarati', value: "'Noto Sans Gujarati', sans-serif" }, { name: 'Tiro Gujarati', value: "'Tiro Gujarati', serif" }, { name: 'Baloo Bhai 2', value: "'Baloo Bhai 2', cursive" }, { name: 'Mukta Vaani', value: "'Mukta Vaani', sans-serif" }],
                    'pa': [{ name: 'Noto Sans Gurmukhi', value: "'Noto Sans Gurmukhi', sans-serif" }, { name: 'Tiro Gurmukhi', value: "'Tiro Gurmukhi', serif" }, { name: 'Mukta Mahee', value: "'Mukta Mahee', sans-serif" }, { name: 'Baloo Paaji 2', value: "'Baloo Paaji 2', cursive" }]
                };
                
                this.placeholderMap = {
                    'en': 'Start Writing here...', 'hi': 'यहाँ लिखना शुरू करें...', 'or': 'ଏଠାରେ ଲେଖିବା ଆରମ୍ଭ କରନ୍ତୁ...', 'bn': 'এখানে লেখা শুরু করুন...', 'mr': 'इथे लिहायला सुरुवात करा...', 'ta': 'இங்கு எழுதத் தொடங்குங்கள்...', 'te': 'ఇక్కడ రాయడం ప్రారంభించండి...', 'kn': 'ಇಲ್ಲಿ ಬರೆಯಲು ಪ್ರಾರಂಭಿಸಿ...', 'ml': 'ഇവിടെ എഴുതിത്തുടങ്ങുക...', 'gu': 'અહીં લખવાનું શરૂ કરો...', 'pa': 'ਇੱਥੇ ਲਿਖਣਾ ਸ਼ੁਰੂ ਕਰੋ...'
                };
                
                this.numeralMap = {
                    'hi': ['०','१','२','३','४','५','६','७','८','९'], 'or': ['୦','୧','୨','୩','୪','୫','୬','୭','୮','୯'], 'bn': ['০','১','২','৩','৪','৫','৬','৭','৮','৯'], 'mr': ['०','१','२','३','४','५','६','७','८','९'], 'ta': ['௦','௧','௨','௩','௪','௫','௬','௭','௮','௯'], 'te': ['౦','౧','౨','౩','౪','౫','౬','౭','౮','౯'], 'kn': ['೦','೧','೨','೩','೪','೫','೬','೭','೮','೯'], 'ml': ['൦','൧','൨','൩','൪','൫','൬','൭','൮','൯'], 'gu': ['૦','૧','૨','૩','૪','૫','૬','૭','૮','૯'], 'pa': ['੦','੧','੨','੩','੪','੫','੬','੭','੮','੯']
                };
                
                this.init();
            }

            init() {
                this.languageSelect.addEventListener('change', (e) => {
                    this.langCode = e.target.value;
                    if (this.langCode !== 'en') { this.lastIndicLang = this.langCode; }
                    const indicator = document.getElementById('langIndicator');
                    const abbrevMap = { 'hi': 'HI', 'or': 'OD', 'bn': 'BN', 'mr': 'MR', 'ta': 'TA', 'te': 'TE', 'kn': 'KN', 'ml': 'ML', 'gu': 'GU', 'pa': 'PA' };
                    const shortCode = this.langCode.split('-')[0];
                    if (this.langCode !== 'en' && abbrevMap[shortCode]) {
                        indicator.textContent = abbrevMap[shortCode];
                        indicator.classList.add('active');
                    } else {
                        indicator.classList.remove('active');
                        this.hideSuggestions();
                    }
                    this.updateFonts(); 
                    this.updatePlaceholder(); 
                    this.editor.focus();
                });

                this.editor.addEventListener('input', (e) => {
                    const shortLang = this.langCode.split('-')[0];
                    const dandaLangs = ['hi', 'or', 'bn', 'pa', 'mr', 'gu']; 
                    
                    if (e.data === '.' && dandaLangs.includes(shortLang)) {
                        const cursor = this.editor.selectionStart;
                        const text = this.editor.value;
                        const prevChar = text.charAt(cursor - 2); 
                        if (prevChar === '।') { this.editor.setRangeText('.', cursor - 2, cursor, 'end'); return; }
                        if (/[\d०-९୦-୯০-৯௦-௯౦-౯೦-೯൦-൯૦-૯੦-੯]/.test(prevChar)) { return; }
                        this.editor.setRangeText('।', cursor - 1, cursor, 'end');
                        this.editor.dispatchEvent(new Event('input'));
                        return;
                    }

                    if (this.langCode === 'en') return;

                    if (e.data && /^[0-9]$/.test(e.data)) {
                        if (this.numeralMap && this.numeralMap[shortLang]) {
                            const cursor = this.editor.selectionStart;
                            const nativeNum = this.numeralMap[shortLang][parseInt(e.data)];
                            this.editor.setRangeText(nativeNum, cursor - 1, cursor, 'end');
                            this.hideSuggestions();
                            this.currentWord = '';
                            this.editor.dispatchEvent(new Event('input'));
                            return;
                        }
                    }
                    
                    const val = this.editor.value;
                    const cursorPos = this.editor.selectionStart;
                    let start = cursorPos - 1;
                    while (start >= 0 && !/\s/.test(val[start])) { start--; }
                    start++; 
                    const word = val.substring(start, cursorPos);
                    
                    if (e.data && /\s/.test(e.data)) { this.hideSuggestions(); this.currentWord = ''; return; }

                    if (word.length > 0 && /^[a-zA-Z]+$/.test(word)) {
                        this.currentWord = word;
                        this.wordStartPos = start;
                        this.fetchSuggestions(word);
                    } else {
                        this.hideSuggestions();
                        this.currentWord = '';
                    }
                });

                this.editor.addEventListener('keydown', (e) => {
                    if (e.ctrlKey && e.key === 'g') {
                        e.preventDefault();
                        if (!this.lastIndicLang) return;
                        this.languageSelect.value = this.languageSelect.value === 'en' ? this.lastIndicLang : 'en'; 
                        this.languageSelect.dispatchEvent(new Event('change'));
                        return;
                    }
                    if (this.langCode === 'en') return;
                    if (!this.isSuggesting) return;

                    if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        if (this.suggestions && this.suggestions.length > 0) {
                            this.selectedIndex = (this.selectedIndex + 1) % this.suggestions.length;
                            this.renderSuggestions();
                        }
                    } else if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        if (this.suggestions && this.suggestions.length > 0) {
                            this.selectedIndex = (this.selectedIndex - 1 + this.suggestions.length) % this.suggestions.length;
                            this.renderSuggestions();
                        }
                    } else if (e.key === 'Enter' || e.key === ' ') {
                        if (this.suggestions && this.suggestions.length > 0) {
                            e.preventDefault();
                            const shouldAddSpace = e.key === ' ';
                            this.applySuggestion(this.suggestions[this.selectedIndex], shouldAddSpace);
                        }
                    } else if (e.key === 'Escape') {
                        this.hideSuggestions();
                    }
                });
                
                document.addEventListener('click', (e) => {
                    if (e.target !== this.suggestionBox && e.target !== this.editor) { this.hideSuggestions(); }
                });
            }

            async fetchSuggestions(word) {
                try {
                    const url = `https://inputtools.google.com/request?text=${word}&itc=${this.langCode}&num=5&cp=0&cs=1&ie=utf-8&oe=utf-8&app=demopage`;
                    const response = await fetch(url);
                    const data = await response.json();
                    
                    if (data && data[0] === 'SUCCESS' && Array.isArray(data[1]) && data[1][0] && Array.isArray(data[1][0][1]) && data[1][0][1].length > 0) {
                        this.suggestions = data[1][0][1];
                        this.selectedIndex = 0;
                        this.showSuggestions();
                    } else {
                        this.hideSuggestions();
                    }
                } catch (err) {
                    console.error("Transliteration Error:", err);
                }
            }

            showSuggestions() {
                this.isSuggesting = true;
                this.suggestionBox.style.display = 'block';
                this.updateSuggestionPosition();
                this.renderSuggestions();
            }

            hideSuggestions() {
                this.isSuggesting = false;
                this.suggestionBox.style.display = 'none';
                this.suggestions = [];
            }

            renderSuggestions() {
                this.suggestionBox.innerHTML = '';
                this.suggestions.forEach((suggestion, index) => {
                    const div = document.createElement('div');
                    div.className = `suggestion-item ${index === this.selectedIndex ? 'selected' : ''}`;
                    div.innerHTML = `<span>${suggestion}</span> <span class="suggestion-index">${index + 1}</span>`;
                    
                    div.addEventListener('click', () => {
                        this.applySuggestion(suggestion);
                        this.editor.focus();
                    });
                    
                    this.suggestionBox.appendChild(div);
                });
            }

            applySuggestion(text, addSpace = false) {
                if (!text) return;
                this.editor.focus();
                const val = this.editor.value;
                const currentWordLen = (this.currentWord || '').length;
                if (this.wordStartPos < 0 || this.wordStartPos > val.length) return;
                const insertionText = addSpace ? text + ' ' : text;
                this.editor.setRangeText(insertionText, this.wordStartPos, this.wordStartPos + currentWordLen, 'end');
                this.hideSuggestions();
                this.currentWord = '';
                this.editor.dispatchEvent(new Event('input'));
            }

            updateSuggestionPosition() {
                const coords = getCaretCoordinates(this.editor, this.editor.selectionStart);
                const top = coords.top + 25; 
                const left = coords.left;
                this.suggestionBox.style.top = `${this.editor.offsetTop + top - this.editor.scrollTop}px`;
                this.suggestionBox.style.left = `${this.editor.offsetLeft + left - this.editor.scrollLeft}px`;
            }

            updateFonts() {
                const lang = this.langCode.split('-')[0]; 
                let fonts = this.defaultFonts;

                if (lang !== 'en' && this.fontMap[lang]) {
                    fonts = this.fontMap[lang];
                    const families = fonts.map(f => f.name.replace(/ /g, '+')).join('&family=');
                    const linkId = 'google-fonts-link';
                    let link = document.getElementById(linkId);
                    
                    if (!link) {
                        link = document.createElement('link');
                        link.id = linkId;
                        link.rel = 'stylesheet';
                        document.head.appendChild(link);
                    }
                    const newHref = `https://fonts.googleapis.com/css2?family=${families}&display=swap`;
                    if (link.href !== newHref) { link.href = newHref; }
                }

                this.fontSelect.innerHTML = '';
                fonts.forEach(f => {
                    const option = document.createElement('option');
                    option.value = f.value;
                    option.textContent = f.name;
                    this.fontSelect.appendChild(option);
                });

                if (fonts.length > 0) {
                    this.fontSelect.value = fonts[0].value;
                    this.editor.style.fontFamily = fonts[0].value;
                    this.fontSelect.dispatchEvent(new Event('change')); 
                }
            }

            updatePlaceholder() {
                const lang = this.langCode.split('-')[0];
                const placeholderText = this.placeholderMap[lang] || this.placeholderMap['en'];
                this.editor.placeholder = placeholderText;
            }
        }

        // --- HELPER: GET CARET COORDINATES ---
        function getCaretCoordinates(element, position) {
            const mirrorDiv = document.getElementById('mirrorDiv');
            const style = window.getComputedStyle(element);
            
            ['boxSizing', 'width', 'height', 'overflowX', 'overflowY', 
             'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth',
             'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
             'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize',
             'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent',
             'letterSpacing', 'wordSpacing'].forEach(prop => {
                mirrorDiv.style[prop] = style[prop];
            });

            mirrorDiv.textContent = element.value.substring(0, position);
            const span = document.createElement('span');
            span.textContent = element.value.substring(position) || '.';
            mirrorDiv.appendChild(span);

            return {
                top: span.offsetTop + parseInt(style['borderTopWidth']),
                left: span.offsetLeft + parseInt(style['borderLeftWidth'])
            };
        }

        // --- MAIN APP ---
        class OnlineNotepad {
            constructor() {
                this.editor = document.getElementById('editor');
                this.history = [];
                this.historyIndex = -1;
                this.maxHistorySize = 20;
                this.init();
            }

            init() {
                this.detectTheme();
                window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
                    if (!localStorage.getItem('theme')) { this.applyTheme(e.matches ? 'dark' : 'light'); }
                });

                const saved = localStorage.getItem('notepad-content');
                if (saved) this.editor.value = saved;
                this.loadSettings();
                this.updateStats();
                this.updateReadingTime();

                document.getElementById('themeToggleDesktop').addEventListener('click', () => this.toggleTheme());
                document.getElementById('themeToggleMobile').addEventListener('click', () => this.toggleTheme());
                document.getElementById('menuToggle').addEventListener('click', () => { document.getElementById('navLinks').classList.toggle('active'); });
                document.getElementById('newBtn').addEventListener('click', () => this.showNewDocumentModal());
                document.getElementById('saveBtn').addEventListener('click', () => this.showSaveDocumentModal());
                document.getElementById('openBtn').addEventListener('click', () => document.getElementById('fileInput').click());
                document.getElementById('fileInput').addEventListener('change', (e) => this.handleFile(e));
                document.getElementById('copyBtn').addEventListener('click', () => this.copyText());
                document.getElementById('printBtn').addEventListener('click', () => this.print());
                document.getElementById('teleprompterBtn').addEventListener('click', () => this.startTeleprompter());
                document.getElementById('teleCloseBtn').addEventListener('click', () => this.closeTeleprompter());
                document.getElementById('telePlayBtn').addEventListener('click', () => this.toggleTeleprompter());
                document.getElementById('teleRestartBtn').addEventListener('click', () => this.restartTeleprompter());
                document.getElementById('teleMirrorBtn').addEventListener('click', () => this.mirrorTeleprompter());
                document.getElementById('teleSpeedSlider').addEventListener('input', (e) => this.updateTeleprompterSpeed(e.target.value));
                document.getElementById('teleSizeSlider').addEventListener('input', (e) => this.updateTeleprompterSize(e.target.value));
                
                document.getElementById('teleProgressSlider').addEventListener('input', (e) => {
                    const display = document.getElementById('teleprompterContent');
                    const maxScroll = display.scrollHeight - display.clientHeight;
                    display.scrollTop = (e.target.value / 100) * maxScroll;
                });

                document.getElementById('closeSaveDocumentModal').addEventListener('click', () => this.closeSaveDocumentModal());
                document.getElementById('cancelSaveDocument').addEventListener('click', () => this.closeSaveDocumentModal());
                document.getElementById('confirmSaveDocument').addEventListener('click', () => this.confirmSaveDocument());
                document.getElementById('filenameInput').addEventListener('keydown', (e) => { if (e.key === 'Enter') this.confirmSaveDocument(); });
                
                document.getElementById('closeNewDocumentModal').addEventListener('click', () => this.closeNewDocumentModal());
                document.getElementById('cancelNewDocument').addEventListener('click', () => this.closeNewDocumentModal());
                document.getElementById('confirmNewDocument').addEventListener('click', () => this.confirmNewDocument());

                const scrollContainer = document.getElementById('scrollableToolbar');
                const scrollHint = document.getElementById('scrollHint');
                
                if (scrollContainer && scrollHint) {
                    const checkScroll = () => {
                        if (scrollContainer.scrollWidth - scrollContainer.clientWidth - scrollContainer.scrollLeft < 5) {
                            scrollHint.style.opacity = '0'; scrollHint.style.visibility = 'hidden';
                        } else {
                            scrollHint.style.opacity = '1'; scrollHint.style.visibility = 'visible';
                        }
                    };
                    scrollHint.addEventListener('click', () => { scrollContainer.scrollTo({ left: scrollContainer.scrollWidth, behavior: 'smooth' }); });
                    scrollContainer.addEventListener('scroll', checkScroll);
                    window.addEventListener('resize', checkScroll);
                    setTimeout(checkScroll, 100); 
                }

                document.getElementById('fontFamily').addEventListener('change', (e) => { this.editor.style.fontFamily = e.target.value; this.saveSettings(); });
                document.getElementById('fontSize').addEventListener('change', (e) => { this.editor.style.fontSize = e.target.value + 'px'; this.saveSettings(); });
                document.getElementById('upperCase').addEventListener('click', () => this.convertCase('upper'));
                document.getElementById('lowerCase').addEventListener('click', () => this.convertCase('lower'));
                document.getElementById('sentenceCase').addEventListener('click', () => this.convertCase('sentence'));
                document.getElementById('emptyLinesBtn').addEventListener('click', () => this.removeEmptyLines());

                document.getElementById('findReplaceBtn').addEventListener('click', () => document.getElementById('findModal').style.display = 'block');
                document.getElementById('closeFindModal').addEventListener('click', () => document.getElementById('findModal').style.display = 'none');
                document.getElementById('findNext').addEventListener('click', () => this.findNext());
                document.getElementById('replaceOne').addEventListener('click', () => this.replaceOne());
                document.getElementById('replaceAll').addEventListener('click', () => this.replaceAll());

                document.getElementById('readingSpeedSlider').addEventListener('input', (e) => {
                    document.getElementById('readingSpeedValue').textContent = e.target.value; this.updateReadingTime();
                });

                this.editor.addEventListener('input', () => { this.updateStats(); this.updateReadingTime(); this.save(); this.addToHistory(); });

                document.getElementById('undoBtn').addEventListener('click', () => this.undo());
                document.getElementById('redoBtn').addEventListener('click', () => this.redo());

                this.transliteration = new TransliterationManager('editor', 'languageSelect', 'suggestionBox', 'fontFamily');
                
                // DYNAMIC LANGUAGE INJECTION (REPLACED HARDCODED HINDI)
				document.getElementById('languageSelect').value = 'hi-t-i0-und';
				document.getElementById('languageSelect').dispatchEvent(new Event('change'));
            }

            detectTheme() {
                const savedTheme = localStorage.getItem('theme');
                if (savedTheme) { this.applyTheme(savedTheme); } 
                else { const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; this.applyTheme(systemPrefersDark ? 'dark' : 'light'); }
            }

            applyTheme(theme) {
                document.documentElement.setAttribute('data-theme', theme);
                const themeIcons = document.querySelectorAll('.themeIcon');
                themeIcons.forEach(icon => { icon.innerHTML = theme === 'dark' ? '&#9728;' : '&#9789;'; });
            }

            toggleTheme() {
                const current = document.documentElement.getAttribute('data-theme');
                const next = current === 'dark' ? 'light' : 'dark';
                localStorage.setItem('theme', next);
                this.applyTheme(next);
            }

            saveSettings() {
                const settings = { fontFamily: document.getElementById('fontFamily').value, fontSize: document.getElementById('fontSize').value };
                localStorage.setItem('notepad-settings', JSON.stringify(settings));
            }

            loadSettings() {
                const settings = JSON.parse(localStorage.getItem('notepad-settings'));
                if (settings) {
                    if (settings.fontFamily) { this.editor.style.fontFamily = settings.fontFamily; document.getElementById('fontFamily').value = settings.fontFamily; }
                    if (settings.fontSize) { this.editor.style.fontSize = settings.fontSize + 'px'; document.getElementById('fontSize').value = settings.fontSize; }
                }
            }

            save() {
                localStorage.setItem('notepad-content', this.editor.value);
                document.getElementById('autosaveStatus').textContent = "Saved";
                setTimeout(() => document.getElementById('autosaveStatus').textContent = "Auto-saved", 1000);
            }

            updateStats() {
                const text = this.editor.value;
                const words = text.trim() === '' ? 0 : text.trim().split(/\s+/).length;
                document.getElementById('wordCount').textContent = `Words: ${words}`;
                document.getElementById('charCount').textContent = `Characters: ${text.length}`;
            }

            updateReadingTime() {
                const text = this.editor.value;
                const words = text.trim() === '' ? 0 : text.trim().split(/\s+/).length;
                const speed = parseInt(document.getElementById('readingSpeedSlider').value);
                const totalSeconds = Math.ceil(words / speed);
                const min = Math.floor(totalSeconds / 60);
                const sec = totalSeconds % 60;
                document.getElementById('readingTimeDisplay').textContent = `${min}:${sec.toString().padStart(2,'0')}`;
            }

            showNewDocumentModal() {
                if (this.editor.value.trim()) { document.getElementById('newDocumentModal').style.display = 'block'; } 
                else { this.newDocument(); }
            }

            closeNewDocumentModal() { document.getElementById('newDocumentModal').style.display = 'none'; this.editor.focus(); }
            confirmNewDocument() { this.newDocument(); this.closeNewDocumentModal(); }
            newDocument() { this.editor.value = ''; this.history = []; this.historyIndex = -1; this.save(); this.updateStats(); this.updateReadingTime(); document.getElementById('autosaveStatus').textContent = 'New document'; }

            showSaveDocumentModal() {
                document.getElementById('saveDocumentModal').style.display = 'block';
                const filenameInput = document.getElementById('filenameInput');
                filenameInput.focus(); filenameInput.select();
            }

            closeSaveDocumentModal() { document.getElementById('saveDocumentModal').style.display = 'none'; this.editor.focus(); }
            confirmSaveDocument() { const filenameInput = document.getElementById('filenameInput'); const filename = filenameInput.value.trim() || 'New Document'; this.saveToFile(filename); this.closeSaveDocumentModal(); }

            saveToFile(filename = 'New Document') {
                const blob = new Blob([this.editor.value], {type: 'text/plain'});
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                if (!filename.endsWith('.txt')) { filename += '.txt'; }
                a.download = filename; a.click();
            }

            handleFile(e) {
                const file = e.target.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = (evt) => { this.editor.value = evt.target.result; this.updateStats(); this.updateReadingTime(); this.save(); };
                reader.readAsText(file);
            }
            
            copyText() {
                this.editor.select();
                const text = this.editor.value;
                if (navigator.clipboard) {
                      navigator.clipboard.writeText(text).then(() => {
                          const originalText = document.getElementById('copyBtn').innerHTML;
                          document.getElementById('copyBtn').innerHTML = '<span class="toolbar__icon">&#10003;</span> <span class="toolbar__text">Copied!</span>';
                          setTimeout(() => { document.getElementById('copyBtn').innerHTML = originalText; }, 2000);
                      }).catch(err => { console.error('Failed to copy: ', err); document.execCommand('copy'); });
                } else { document.execCommand('copy'); alert('Text copied to clipboard'); }
            }

            findNext() {
                const term = document.getElementById('findInput').value;
                if(!term) return;
                const text = this.editor.value;
                const start = this.editor.selectionEnd;
                let idx = text.indexOf(term, start);
                if(idx === -1) idx = text.indexOf(term, 0); 
                if(idx !== -1) { this.editor.setSelectionRange(idx, idx + term.length); this.editor.focus(); } 
                else { alert("Not found"); }
            }

            replaceOne() {
                const term = document.getElementById('findInput').value;
                const rep = document.getElementById('replaceInput').value;
                if(!term) return;
                const start = this.editor.selectionStart;
                const end = this.editor.selectionEnd;
                const sel = this.editor.value.substring(start, end);
                if(sel === term) { this.editor.setRangeText(rep); this.save(); }
                this.findNext();
            }

            replaceAll() {
                const term = document.getElementById('findInput').value;
                const rep = document.getElementById('replaceInput').value;
                if(!term) return;
                const regex = new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
                this.editor.value = this.editor.value.replace(regex, rep);
                this.save(); this.updateStats();
            }

            addToHistory() {
                const val = this.editor.value;
                if(this.history[this.historyIndex] !== val) {
                    this.history = this.history.slice(0, this.historyIndex + 1);
                    this.history.push(val);
                    if(this.history.length > this.maxHistorySize) this.history.shift(); else this.historyIndex++;
                }
            }
            undo() { if(this.historyIndex > 0) { this.historyIndex--; this.editor.value = this.history[this.historyIndex]; } }
            redo() { if(this.historyIndex < this.history.length - 1) { this.historyIndex++; this.editor.value = this.history[this.historyIndex]; } }

            print() {
                const content = this.editor.value;
                const fontFamilySelect = document.getElementById('fontFamily');
                const fontSizeSelect = document.getElementById('fontSize');
                const fontFamily = fontFamilySelect.value; 
                const fontSize = fontSizeSelect.value + 'px';
                const googleFontsLink = document.getElementById('google-fonts-link');
                let fontLinkHtml = '';
                if (googleFontsLink) { fontLinkHtml = googleFontsLink.outerHTML; }

                const iframe = document.createElement('iframe');
                iframe.style.position = 'fixed'; iframe.style.right = '0'; iframe.style.bottom = '0'; iframe.style.width = '0'; iframe.style.height = '0'; iframe.style.border = '0';
                document.body.appendChild(iframe);
                
                const doc = iframe.contentWindow.document;
                doc.open();
                doc.write(`
                    <html>
                    <head>
                        <title></title>
                        ${fontLinkHtml} <style>
                            @page { margin: 0; size: auto; }
                            body { font-family: ${fontFamily}; font-size: ${fontSize}; margin: 0 2.5cm; }
                            table { width: 100%; border-collapse: collapse; }
                            thead, tfoot { height: 20px; } 
                            .page-spacer { height: 20px; visibility: hidden; }
                            .print-content { white-space: pre-wrap; word-wrap: break-word; margin: 0; font-family: ${fontFamily} !important; font-size: ${fontSize} !important; line-height: 1.5; }
                        </style>
                    </head>
                    <body>
                        <table>
                            <thead><tr><td><div class="page-spacer">&nbsp;</div></td></tr></thead>
                            <tbody><tr><td><div class="print-content">${content.replace(/</g, "&lt;").replace(/>/g, "&gt;")}</div></td></tr></tbody>
                            <tfoot><tr><td><div class="page-spacer">&nbsp;</div></td></tr></tfoot>
                        </table>
                    </body>
                    </html>
                `);
                doc.close();
                setTimeout(() => { iframe.contentWindow.focus(); iframe.contentWindow.print(); setTimeout(() => { document.body.removeChild(iframe); }, 1000); }, 500); 
            }

            startTeleprompter() {
                const content = this.editor.value.replace(/\n/g, '<br>');
                const overlay = document.getElementById('teleprompterOverlay');
                const display = document.getElementById('teleprompterContent');
                display.innerHTML = content;
                overlay.classList.add('active');
                this.updateTeleprompterSize(document.getElementById('teleSizeSlider').value);
                this.teleprompterSpeed = parseInt(document.getElementById('teleSpeedSlider').value);
                this.isTeleprompterPlaying = false;
                document.getElementById('telePlayBtn').textContent = '►'; 
                display.scrollTop = 0;
                document.getElementById('teleProgressSlider').value = 0;
            }

            closeTeleprompter() { document.getElementById('teleprompterOverlay').classList.remove('active'); this.stopTeleprompterScroll(); }

            toggleTeleprompter() {
                if (this.isTeleprompterPlaying) { this.stopTeleprompterScroll(); document.getElementById('telePlayBtn').textContent = '►'; } 
                else { this.startTeleprompterScroll(); document.getElementById('telePlayBtn').textContent = '❚❚'; }
                this.isTeleprompterPlaying = !this.isTeleprompterPlaying;
            }

            startTeleprompterScroll() {
                if (this.teleprompterInterval) clearInterval(this.teleprompterInterval);
                const display = document.getElementById('teleprompterContent');
                const slider = document.getElementById('teleProgressSlider');
                this.teleprompterInterval = setInterval(() => {
                    display.scrollTop += 1;
                    const maxScroll = display.scrollHeight - display.clientHeight;
                    if (maxScroll > 0) { slider.value = (display.scrollTop / maxScroll) * 100; }
                    if (display.scrollTop + display.clientHeight >= display.scrollHeight) { this.stopTeleprompterScroll(); this.isTeleprompterPlaying = false; document.getElementById('telePlayBtn').textContent = '►'; }
                }, 200 / this.teleprompterSpeed); 
            }

            stopTeleprompterScroll() { if (this.teleprompterInterval) clearInterval(this.teleprompterInterval); }
            restartTeleprompter() { const display = document.getElementById('teleprompterContent'); display.scrollTop = 0; document.getElementById('teleProgressSlider').value = 0; }

            updateTeleprompterSpeed(speed) {
                this.teleprompterSpeed = parseInt(speed);
                if (this.isTeleprompterPlaying) { this.startTeleprompterScroll(); }
            }

            updateTeleprompterSize(size) { document.getElementById('teleprompterContent').style.fontSize = size + 'px'; }
            mirrorTeleprompter() { document.getElementById('teleprompterContent').classList.toggle('mirror'); }
            
            removeEmptyLines() {
                const text = this.editor.value;
                const cleanText = text.replace(/^\s*$(?:\r\n?|\n)/gm, "");
                this.editor.value = cleanText;
                this.updateStats(); this.updateReadingTime(); this.save(); this.addToHistory();
            }

            convertCase(type) {
                let start = this.editor.selectionStart;
                let end = this.editor.selectionEnd;
                let text = "";
                let isSelection = (start !== end);

                if(!isSelection) { text = this.editor.value; } 
                else { text = this.editor.value.substring(start, end); }
                
                if(type === 'upper') text = text.toUpperCase();
                if(type === 'lower') text = text.toLowerCase();
                if(type === 'sentence') { text = text.toLowerCase().replace(/(^\s*\w|[\.\!\?]\s*\w)/g, c => c.toUpperCase()); }
                
                if (isSelection) { this.editor.setRangeText(text); } else { this.editor.value = text; }
                this.save();
            }
        }

        window.addEventListener('DOMContentLoaded', () => { window.app = new OnlineNotepad(); });
    </script>
</body>
</html>