Weaving Reality

Uncovering the narratives that truly define our times and lives.

Writer's Dashboard

Total Stories
-
Published
-
Top Stories

Manage Categories

Loading categories...

Admin Settings

Fix Old Story Order

Click this if older stories are missing or out of order. It updates their date format for the database.

Draft
CategoryDate

A
Admin
Author • RTNews

Share this story


Privacy Policy

Last updated: November 2025

At RTNews, accessible from our website, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by RTNews and how we use it.

1. Information Collection

We collect information to provide better services to all our users. This may include personal information such as name, email address, and phone number when voluntarily provided via contact forms or newsletters.

2. Log Files

RTNews follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this as a part of hosting services' analytics. The information collected by log files includes internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable.

3. Cookies and Web Beacons

Like any other website, RTNews uses 'cookies'. These cookies are used to store information including visitors' preferences, and the pages on the website that the visitor accessed or visited. The information is used to optimize the users' experience by customizing our web page content based on visitors' browser type and/or other information.

4. Google DoubleClick DART Cookie

Google is one of a third-party vendor on our site. It also uses cookies, known as DART cookies, to serve ads to our site visitors based upon their visit to our site and other sites on the internet. However, visitors may choose to decline the use of DART cookies by visiting the Google ad and content network Privacy Policy at the following URL – https://policies.google.com/technologies/ads

5. Advertising Partners Privacy Policies

You may consult this list to find the Privacy Policy for each of the advertising partners of RTNews. Third-party ad servers or ad networks use technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on RTNews, which are sent directly to users' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit.

Note that RTNews has no access to or control over these cookies that are used by third-party advertisers.

6. GDPR & CCPA Rights

We would like to make sure you are fully aware of all of your data protection rights. Every user is entitled to the right to access, rectification, erasure, and data portability. If you make a request, we have one month to respond to you.

7. Children's Information

Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity. RTNews does not knowingly collect any Personal Identifiable Information from children under the age of 13.

ADVERTISEMENT

`; // Initialize Firebase let db; let isFirebaseReady = false; // ** SEPARATE ARRAYS FOR OPTIMIZATION ** // 'publicArticles': Sirf woh 6-12 stories jo visitor dekh raha hai // 'adminArticles': Saari stories jo sirf admin login ke baad aayengi let publicArticles = []; let adminArticles = []; // ** GLOBAL CATEGORY SET (Persistent) ** // Default categories added to ensure visibility immediately let allKnownCategories = new Set(['All', 'Technology', 'Fiction', 'Life', 'Sports', 'Business', 'Health', 'Education']); let categoryList = []; // Array of objects {id, name} // ** PAGINATION VARIABLES ** let lastVisibleDoc = null; // Database ko batane ke liye kahan se shuru karna hai let isFetchingMore = false; let hasMoreStories = true; const BATCH_SIZE = 6; try { firebase.initializeApp(firebaseConfig); db = firebase.firestore(); db.settings({ cacheSizeBytes: firebase.firestore.CACHE_SIZE_UNLIMITED }); isFirebaseReady = true; console.log("Firebase Connected Successfully"); } catch(e) { console.error("Firebase Init Error:", e); } let currentStatus = 'draft'; let tempImages = []; let isAdmin = sessionStorage.getItem('pw_admin') === 'true'; let logoClickCount = 0; let logoClickTimer; let searchQuery = ""; let selectedCategory = "All"; if (!localStorage.getItem('pw_admin_password')) localStorage.setItem('pw_admin_password', 'admin123'); // --- 0. CATEGORY MANAGEMENT FUNCTIONS --- async function fetchCategories() { if(!isFirebaseReady) return; try { const snap = await db.collection('categories').orderBy('name').get(); categoryList = snap.docs.map(doc => ({ id: doc.id, ...doc.data() })); // If no categories in DB (first run), add defaults locally or show empty if(categoryList.length === 0 && !isAdmin) { // Keep UI clean, user will add via dashboard } // Refresh UIs renderCategoriesManager(); // In Dashboard renderHome(); // Update Home Filters } catch(e) { console.error("Cat Fetch Error", e); } } async function addNewCategory() { const input = document.getElementById('new-category-name'); const name = input.value.trim(); if(!name) return alert("Enter category name"); // Check duplicate local if(categoryList.find(c => c.name.toLowerCase() === name.toLowerCase())) return alert("Category exists"); const btn = input.nextElementSibling; btn.innerText = "..."; try { await db.collection('categories').add({ name: name, createdAt: new Date().toISOString() }); input.value = ""; await fetchCategories(); // Reload all } catch(e) { alert("Error adding: " + e.message); } finally { btn.innerText = "Add"; } } async function deleteCategoryItem(id) { if(!confirm("Remove this category? Stories with this category won't be deleted, just the filter.")) return; try { await db.collection('categories').doc(id).delete(); await fetchCategories(); } catch(e) { alert("Error: " + e.message); } } function renderCategoriesManager() { const container = document.getElementById('categories-manage-list'); if(!container) return; if(categoryList.length === 0) { container.innerHTML = '
No categories found. Add one above.
'; return; } container.innerHTML = categoryList.map(c => `
${c.name}
`).join(''); lucide.createIcons(); } // --- 1. OPTIMIZED PUBLIC FETCH (Smart Fallback for Old Data) --- async function fetchPublicArticles(isNext = false) { if (!isFirebaseReady) return; if (isFetchingMore) return; if (!isNext) { publicArticles = []; lastVisibleDoc = null; hasMoreStories = true; document.getElementById('articles-list').innerHTML = `
`; } else { isFetchingMore = true; document.getElementById('load-more-text').innerText = "Loading..."; document.getElementById('load-more-spinner').classList.remove('hidden'); } try { // STEP 1: Try fetching with SORT (Best for new/updated stories) let ref = db.collection("articles") .where("status", "==", "published"); // ** SERVER-SIDE CATEGORY FILTER ** if (selectedCategory !== "All") { ref = ref.where("category", "==", selectedCategory); } ref = ref.orderBy("createdAt", "desc") .limit(BATCH_SIZE); if (isNext && lastVisibleDoc) { ref = ref.startAfter(lastVisibleDoc); } let snapshot = await ref.get(); // STEP 2: Fallback for OLD stories (missing 'createdAt') if (snapshot.empty && !isNext && publicArticles.length === 0) { console.log("No sorted stories found. Attempting fallback for old data..."); ref = db.collection("articles") .where("status", "==", "published"); // Add category filter to fallback too if (selectedCategory !== "All") { ref = ref.where("category", "==", selectedCategory); } ref = ref.limit(BATCH_SIZE); snapshot = await ref.get(); } if (!snapshot.empty) { lastVisibleDoc = snapshot.docs[snapshot.docs.length - 1]; const newDocs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); // ** UPDATE GLOBAL CATEGORIES ** newDocs.forEach(d => allKnownCategories.add(d.category || 'General')); // *** CLIENT SIDE SORT as temporary fix for Fallback *** if (!isNext) { newDocs.sort((a, b) => { let dA = a.createdAt ? new Date(a.createdAt) : new Date(a.date); let dB = b.createdAt ? new Date(b.createdAt) : new Date(b.date); if(isNaN(dA)) dA = new Date(0); if(isNaN(dB)) dB = new Date(0); return dB - dA; }); } publicArticles = [...publicArticles, ...newDocs]; if (snapshot.docs.length < BATCH_SIZE) hasMoreStories = false; } else { hasMoreStories = false; } renderHome(); } catch (e) { console.error("Fetch Error:", e); // Index Error Handling if(e.message.toLowerCase().includes("index")) { alert("Database Setup Needed: Category + Sort requires a new Index. Open Console (F12) and click the link."); // Fallback attempt in case of index error if(!isNext) { try { let fallbackRef = db.collection("articles").where("status", "==", "published"); if(selectedCategory !== "All") fallbackRef = fallbackRef.where("category", "==", selectedCategory); const snap = await fallbackRef.limit(BATCH_SIZE).get(); publicArticles = snap.docs.map(doc => ({ id: doc.id, ...doc.data() })); renderHome(); } catch(err) { console.error("Fallback failed", err); } } } } finally { isFetchingMore = false; const btnText = document.getElementById('load-more-text'); const btnSpin = document.getElementById('load-more-spinner'); if(btnText) btnText.innerText = "Load More Stories"; if(btnSpin) btnSpin.classList.add('hidden'); } } // --- 1.5 FETCH RELATED STORIES (NEW) --- async function fetchRelatedStories(category, currentId) { const container = document.getElementById('related-stories-list'); if(!container) return; container.innerHTML = '
Finding stories...
'; if(!isFirebaseReady) return; try { // Strategy: Get 5 items from same category, exclude current let ref = db.collection('articles') .where('status', '==', 'published') .where('category', '==', category) .limit(5); // Get enough to filter out current let snapshot = await ref.get(); let related = snapshot.docs .map(doc => ({id: doc.id, ...doc.data()})) .filter(a => a.id !== currentId) .slice(0, 4); // Keep max 4 // Fallback: If not enough related stories, fetch recent ones if(related.length < 2) { const recentSnap = await db.collection('articles') .where('status', '==', 'published') .orderBy('createdAt', 'desc') .limit(5) .get(); const recents = recentSnap.docs .map(doc => ({id: doc.id, ...doc.data()})) .filter(a => a.id !== currentId && !related.find(r => r.id === a.id)) .slice(0, 4 - related.length); related = [...related, ...recents]; } if(related.length === 0) { container.innerHTML = '
No other stories found.
'; return; } container.innerHTML = ''; related.forEach(a => { const th = getThumbnail(a.content); const img = th ? `
` : ''; const urduClass = a.isUrdu ? 'urdu-text' : ''; container.innerHTML += `
${img}
${a.category || 'General'}

${a.title}

`; }); lucide.createIcons(); } catch(e) { console.error("Related fetch error", e); container.innerHTML = '
Could not load related stories.
'; } } // Load More Button Action function loadMoreStories() { if(hasMoreStories) { fetchPublicArticles(true); // true = load NEXT batch } } // --- 2. ADMIN FETCH (Sirf Login ke baad chalega) --- async function fetchAdminData() { if (!isFirebaseReady) return; try { // Admin ko SAB kuch chahiye (Drafts + Published) const snapshot = await db.collection("articles").get(); adminArticles = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); // ** UPDATE GLOBAL CATEGORIES from Admin List too ** adminArticles.forEach(d => allKnownCategories.add(d.category || 'General')); // Client side sorting for admin panel adminArticles.sort((a, b) => { const dateA = a.createdAt ? new Date(a.createdAt) : new Date(0); const dateB = b.createdAt ? new Date(b.createdAt) : new Date(0); return dateB - dateA; }); renderDashboard(); // Sirf ab dashboard bharega console.log("Admin Data Loaded"); } catch(e) { alert("Admin Data Load Error: " + e.message); } } // --- 3. FIX STORY DATES UTILITY --- async function fixStoryDates() { if (!isFirebaseReady || !isAdmin) return alert("Please login first"); const btn = document.getElementById('fix-date-btn'); btn.innerText = "Fixing..."; btn.disabled = true; try { const snapshot = await db.collection("articles").get(); let count = 0; const batch = db.batch(); snapshot.docs.forEach(doc => { const d = doc.data(); if (!d.createdAt && d.date) { const parsedDate = new Date(d.date); if (!isNaN(parsedDate)) { const ref = db.collection("articles").doc(doc.id); batch.update(ref, { createdAt: parsedDate.toISOString() }); count++; } } }); if (count > 0) { await batch.commit(); alert(`Fixed ${count} stories! Please refresh the page.`); } else { alert("All stories already have valid dates."); } } catch (e) { console.error("Fix Error", e); alert("Error: " + e.message); } finally { btn.innerText = "Fix Sorting Issues"; btn.disabled = false; } } // --- 4. SAVE ARTICLE (Updated for timestamp) --- async function saveArticle() { const title = document.getElementById('edit-title').value; if(!title) return alert("Title required"); let content = document.getElementById('rich-editor').innerHTML; const isUrdu = /[\u0600-\u06FF]/.test(title + content); const data = { title, subtitle: document.getElementById('edit-subtitle').value, category: document.getElementById('edit-category').value || 'General', content, author: "Admin", date: new Date().toLocaleDateString('en-US', {month:'short', day:'numeric', year:'numeric'}), createdAt: new Date().toISOString(), // Helps in sorting status: currentStatus, isFeatured: document.getElementById('edit-featured').checked, isUrdu: isUrdu, readTime: "3 min read" }; const editId = document.getElementById('edit-id').value; if (isFirebaseReady) { try { if (editId) { await db.collection("articles").doc(editId).update(data); } else { await db.collection("articles").add(data); } // Refresh Admin Data immediately await fetchAdminData(); navigateTo('dashboard'); // Reset public view silently fetchPublicArticles(false); } catch (e) { alert("Error saving: " + e.message); } } } // --- AUTHENTICATION & ADMIN LOGIC --- async function submitLogin() { const enteredPass = document.getElementById('modal-password-input').value; const savedPass = localStorage.getItem('pw_admin_password'); if(enteredPass === savedPass) { isAdmin = true; sessionStorage.setItem('pw_admin','true'); closeLoginModal(); updateAuthUI(); // ** MAGIC LINE ** // Sirf abhi Admin ka data database se mangwaya jayega await fetchAdminData(); // Fetch categories for admin management await fetchCategories(); navigateTo('dashboard'); } else { alert("Incorrect Password"); } } // --- UI RENDERING --- function renderHome() { const m = document.getElementById('articles-list'); const t = document.getElementById('top-stories-list'); const n = document.getElementById('new-stories-list'); const loadMoreContainer = document.getElementById('load-more-container'); m.innerHTML = ''; t.innerHTML = ''; n.innerHTML = ''; // ** RENDER DYNAMIC CATEGORIES ** // Default "All" + DB Categories const displayCategories = ['All', ...categoryList.map(c => c.name)]; document.getElementById('category-list').innerHTML = displayCategories.map(c => `` ).join(''); // Filter (Search only, Category is now server-side) const filtered = publicArticles.filter(a => (a.title.toLowerCase().includes(searchQuery) || (a.content && a.content.toLowerCase().includes(searchQuery))) ); if (filtered.length === 0) { m.innerHTML = '
No stories found.
'; loadMoreContainer.classList.add('hidden'); } else { filtered.forEach(a => { const th = getThumbnail(a.content); const img = th ? `
` : ''; const urduClass = a.isUrdu ? 'urdu-text' : ''; m.innerHTML += `
${a.category || 'General'} • ${a.date}

${a.title}

${img}

${a.subtitle||''}

`; }); // Show/Hide Load More Button if(hasMoreStories && searchQuery === "") { loadMoreContainer.classList.remove('hidden'); } else { loadMoreContainer.classList.add('hidden'); } } // Featured & New (From currently loaded batch) const featured = publicArticles.filter(a => a.isFeatured); featured.forEach(a => renderSideCard(a, t)); const recent = publicArticles.slice(0, 5); recent.forEach(a => renderSideCard(a, n)); lucide.createIcons(); } function renderSideCard(a, container) { const th = getThumbnail(a.content); const img = th ? `
` : ''; const urduClass = a.isUrdu ? 'urdu-text' : ''; container.innerHTML += `
${img}

${a.title}

${a.subtitle || ''}

${a.date}
`; } function renderDashboard() { // Uses 'adminArticles' instead of 'publicArticles' const total = adminArticles.length; const pub = adminArticles.filter(a => a.status === 'published').length; const feat = adminArticles.filter(a => a.isFeatured).length; document.getElementById('stat-total').innerText = total; document.getElementById('stat-published').innerText = pub; document.getElementById('stat-featured').innerText = feat; const l = document.getElementById('dashboard-list'); l.innerHTML = ''; adminArticles.forEach(a => { const starClass = a.isFeatured ? 'text-yellow-500 fill-yellow-500' : 'text-gray-300 hover:text-yellow-400'; const isPub = a.status === 'published'; const stClass = isPub ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'; const urduClass = a.isUrdu ? 'urdu-text' : ''; // Buttons now have specific IDs for targeting const btnTxt = isPub ? 'UNPUBLISH' : 'PUBLISH'; const btnColor = isPub ? 'text-blue-600 border-blue-600' : 'text-white bg-blue-600 border-blue-600 hover:bg-blue-700'; l.innerHTML += ` ${a.title} ${a.category || 'General'} ${a.status} `; }); lucide.createIcons(); } // --- READ SPECIFIC ARTICLE (Handle Direct Links) --- async function readArticle(id) { // Check if article is already loaded in public memory let a = publicArticles.find(x => x.id == id); // Check admin memory if logged in if(!a && isAdmin) a = adminArticles.find(x => x.id == id); // If not found in memory (direct link case), fetch from DB individually if (!a) { try { const doc = await db.collection("articles").doc(id).get(); if(doc.exists) { a = { id: doc.id, ...doc.data() }; } else { alert("Story not found"); return; } } catch(e) { console.error(e); return; } } // Render Article const rTitle = document.getElementById('read-title'); const rSub = document.getElementById('read-subtitle'); const rContent = document.getElementById('read-content'); document.getElementById('read-category').innerText = a.category || 'General'; const displayDate = a.createdAt ? new Date(a.createdAt).toLocaleDateString() : (a.date || 'Recent'); document.getElementById('read-date').innerText = displayDate; const isUrdu = /[\u0600-\u06FF]/.test(a.title + a.content); [rTitle, rSub, rContent].forEach(el => { if(isUrdu) { el.classList.add('urdu-text'); el.setAttribute('dir', 'rtl'); el.style.textAlign = 'right'; } else { el.classList.remove('urdu-text'); el.removeAttribute('dir'); el.style.textAlign = 'left'; } }); rTitle.innerText = a.title; rSub.innerText = a.subtitle || ''; // ... existing readArticle code ... let contentHTML = a.content; contentHTML = contentHTML.replace(/\[IMG: (.*?)\]/g, (m, url) => `` ); // --- MANUAL AD INJECTION LOGIC --- // Har 3 paragraphs ke baad ad lagayega const adFrequency = 3; const paragraphs = contentHTML.split('

'); let newContent = ''; paragraphs.forEach((para, index) => { newContent += para + '

'; if ((index + 1) % adFrequency === 0 && index !== paragraphs.length - 1) { newContent += adsterraBannerCode; } }); rContent.innerHTML = newContent; // ... existing code ... // ** TRIGGER RELATED STORIES FETCH HERE ** fetchRelatedStories(a.category, a.id); navigateTo('article'); const newUrl = window.location.origin + window.location.pathname + '?article=' + id; window.history.pushState({path: newUrl}, '', newUrl); } // --- OTHER HELPERS --- function handleSearch() { searchQuery = document.getElementById('search-input').value.toLowerCase(); renderHome(); } // ** UPDATED: Category Filter Now Resets and Fetches from Server ** function selectCategory(c) { selectedCategory = c; fetchPublicArticles(false); // Reload with new filter } // Deletion and Toggling (Requires Admin Fetch Refresh) async function deleteArticle(id) { if(!confirm("Delete?")) return; await db.collection("articles").doc(id).delete(); await fetchAdminData(); // Refresh admin list // Remove from public list locally to update UI instantly publicArticles = publicArticles.filter(x => x.id !== id); renderHome(); } // ** OPTIMISTIC UI: Toggle Featured ** async function toggleFeatured(id) { const btn = document.getElementById(`btn-star-${id}`); if(btn) btn.innerHTML = ``; // Show loader const a = adminArticles.find(x => x.id == id); if(a) { // Update local state first (Optimistic) a.isFeatured = !a.isFeatured; renderDashboard(); // Re-render to show change immediately // Send to DB try { await db.collection("articles").doc(id).update({ isFeatured: a.isFeatured }); } catch(e) { // Revert on error a.isFeatured = !a.isFeatured; renderDashboard(); alert("Failed to update"); } } } // ** OPTIMISTIC UI: Toggle Status ** async function toggleStatus(id) { const btn = document.getElementById(`btn-pub-${id}`); if(btn) { const originalText = btn.innerText; btn.innerText = "..."; btn.classList.add("btn-loading"); } const a = adminArticles.find(x => x.id == id); if(a) { const oldStatus = a.status; const newStatus = a.status === 'draft' ? 'published' : 'draft'; // Update local state first a.status = newStatus; // Try updating DB try { await db.collection("articles").doc(id).update({ status: newStatus }); renderDashboard(); // Re-render table row with new colors // Also update public list if needed silently if(newStatus === 'published') fetchPublicArticles(false); } catch(e) { // Revert a.status = oldStatus; renderDashboard(); alert("Failed: " + e.message); } } } // --- COMMON HELPERS (Same as before) --- function getThumbnail(c) { const div = document.createElement('div'); div.innerHTML = c; const img = div.querySelector('img'); return img ? img.src : (c.match(/\[IMG: (.*?)\]/)?.[1] || null); } function checkForUrdu(text) { return /[\u0600-\u06FF]/.test(text); } function toggleDarkMode() { document.documentElement.classList.toggle('dark'); updateThemeIcons(); } function updateThemeIcons() { const n = document.documentElement.classList.contains('dark') ? 'sun' : 'moon'; document.getElementById('theme-icon').setAttribute('data-lucide', n); document.getElementById('mobile-theme-icon').setAttribute('data-lucide', n); lucide.createIcons(); } function acceptCookies() { localStorage.setItem('pw_cookie_consent', 'true'); document.getElementById('cookie-banner').style.display = 'none'; } function toggleMobileMenu() { document.getElementById('mobile-menu').classList.toggle('hidden'); } function handleLogoClick() { logoClickCount++; clearTimeout(logoClickTimer); logoClickTimer = setTimeout(() => { if(logoClickCount < 5) { navigateTo('home'); } logoClickCount = 0; }, 1000); if(logoClickCount >= 5) { clearTimeout(logoClickTimer); logoClickCount = 0; promptLogin(); } } function promptLogin() { if(isAdmin) { navigateTo('dashboard'); return; } document.getElementById('login-modal').classList.remove('hidden'); document.getElementById('login-modal').classList.add('flex'); } function closeLoginModal() { document.getElementById('login-modal').classList.add('hidden'); document.getElementById('login-modal').classList.remove('flex'); } function closeLogoutModal() { document.getElementById('logout-modal').classList.add('hidden'); document.getElementById('logout-modal').classList.remove('flex'); } function toggleAuth() { if(isAdmin) { document.getElementById('logout-modal').classList.remove('hidden'); document.getElementById('logout-modal').classList.add('flex'); } else { promptLogin(); } } function confirmLogout() { isAdmin=false; sessionStorage.setItem('pw_admin','false'); closeLogoutModal(); updateAuthUI(); adminArticles=[]; // Clear admin data from memory document.getElementById('dashboard-list').innerHTML = ''; // Clear HTML navigateTo('home'); } function updateAuthUI() { const a = isAdmin; ['nav-write-btn','auth-btn','mobile-nav-write-btn','mobile-auth-btn'].forEach(id => { const el = document.getElementById(id); if(el) el.classList.toggle('hidden', !a); }); } function changePassword() { const cur=document.getElementById('settings-current-pass').value, neu=document.getElementById('settings-new-pass').value; if(cur!==localStorage.getItem('pw_admin_password')) return alert("Wrong password"); localStorage.setItem('pw_admin_password', neu); alert("Updated"); navigateTo('dashboard'); } // ** UPDATED EDITOR FUNCTION (FIXED BUG) ** function openEditor(a=null) { try { tempImages=[]; // ** POPULATE SELECT DROPDOWN FROM CATEGORY LIST ** const selectEl = document.getElementById('edit-category'); if(selectEl) { // Keep default 'Select Category' option let opts = ''; categoryList.forEach(c => { opts += ``; }); selectEl.innerHTML = opts; } if(a) { document.getElementById('edit-id').value = a.id; document.getElementById('edit-title').value = a.title; document.getElementById('edit-subtitle').value = a.subtitle; // Set Selected Option if(selectEl) selectEl.value = a.category || ""; document.getElementById('edit-featured').checked = a.isFeatured; let content = a.content || ''; content = content.replace(/\[IMG: (.*?)\]/g, (m, url) => ``); document.getElementById('rich-editor').innerHTML = content; document.getElementById('edit-urdu').checked = a.isUrdu || checkForUrdu(a.title); toggleUrduEditor(); currentStatus = a.status; } else { document.getElementById('edit-id').value=''; document.getElementById('edit-title').value=''; document.getElementById('edit-subtitle').value=''; if(selectEl) selectEl.value = ""; document.getElementById('rich-editor').innerHTML=''; document.getElementById('edit-urdu').checked=false; toggleUrduEditor(); currentStatus='draft'; } document.getElementById('editor-status-badge').innerText = currentStatus === 'published' ? 'Published' : 'Draft'; // Force navigation navigateTo('editor'); } catch (e) { console.error("Editor Error:", e); alert("Error opening editor: " + e.message); } } function toggleUrduEditor() { const isUrdu = document.getElementById('edit-urdu').checked; const editor = document.getElementById('rich-editor'); const title = document.getElementById('edit-title'); const sub = document.getElementById('edit-subtitle'); if(isUrdu) { editor.classList.add('urdu-text'); title.classList.add('urdu-text'); sub.classList.add('urdu-text'); editor.setAttribute('dir', 'rtl'); title.setAttribute('dir', 'rtl'); sub.setAttribute('dir', 'rtl'); } else { editor.classList.remove('urdu-text'); title.classList.remove('urdu-text'); sub.classList.remove('urdu-text'); editor.removeAttribute('dir'); title.removeAttribute('dir'); sub.removeAttribute('dir'); } } // ** NEW: Font Size Changer Function ** function changeFontSize(val) { if(!val) return; document.execCommand('fontSize', false, val); // Ensure focus returns to editor for UX document.getElementById('rich-editor').focus(); } function editArticle(id) { const a = adminArticles.find(x=>x.id==id); if(a) openEditor(a); } function triggerImageUpload() { document.getElementById('image-upload-input').click(); } function handleImageUpload(input) { const f=input.files[0]; if(!f)return; const r=new FileReader(); r.onload=function(e){ document.execCommand('insertImage', false, e.target.result); }; r.readAsDataURL(f); } function shareStory(p) { const u=window.location.href, t=document.getElementById('read-title').innerText; if(p==='whatsapp') window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(t)} ${u}`); else if(p==='copy') { navigator.clipboard.writeText(u); alert("Link Copied"); } } function scrollToTop() { window.scrollTo({ top: 0, behavior: 'smooth' }); } function navigateTo(s) { ['home','article','dashboard','editor','settings','policy','categories'].forEach(id => { const el=document.getElementById(id+'-section'); if(el) el.classList.toggle('hidden-section', id!==s); if(id===s) el.classList.add('fade-in'); }); if(['privacy','terms','about','contact'].includes(s)) { document.getElementById('policy-section').classList.remove('hidden-section'); showPolicyTab(s); } window.scrollTo(0,0); } function showPolicyTab(t) { ['privacy','terms','about','contact'].forEach(x => { document.getElementById('content-'+x).classList.toggle('hidden', x!==t); document.getElementById('tab-'+x).className = x===t ? "px-4 py-3 font-medium text-[#1e3a8a] border-b-2 border-[#1e3a8a]" : "px-4 py-3 font-medium text-gray-500 hover:text-[#1e3a8a]"; }); } window.onpopstate = function() { const id = new URLSearchParams(window.location.search).get('article'); if(id) readArticle(id); else navigateTo('home'); }; window.onscroll = function() { const b=document.getElementById("back-to-top"); if(document.body.scrollTop>300||document.documentElement.scrollTop>300) b.classList.remove("translate-y-20","opacity-0"); else b.classList.add("translate-y-20","opacity-0"); }; // START updateThemeIcons(); updateAuthUI(); if(!localStorage.getItem('pw_cookie_consent')) document.getElementById('cookie-banner').style.display = 'flex'; // ** OPTIMIZED STARTUP LOGIC ** // Check URL immediately const urlId = new URLSearchParams(window.location.search).get('article'); if(urlId) { // PRIORITY 1: Fetch and Show Article IMMEDIATELY readArticle(urlId); // PRIORITY 2: Load heavy background data slightly later setTimeout(() => { fetchPublicArticles(); fetchCategories(); }, 500); } else { // Normal Home Page Load fetchPublicArticles(); fetchCategories(); }