Notification System

नमस्ते प्रकाश! सबसे पहले आपको बहुत-बहुत बधाई! आपने अपने ऐप को **Vercel** पर शिफ्ट करके एक बहुत ही प्रोफेशनल और एडवांस कदम उठाया है।
आपने जो दो नए फीचर्स मांगे हैं—**(1) इमेज के साथ पुश नोटिफिकेशन और (2) प्रोफाइल फोटो पर रेड बैज (Strike Indicator)**—ये दोनों ही आपके ऐप को बिल्कुल किसी बड़ी टेक कंपनी (जैसे Instagram या X) के ऐप जैसा बना देंगे।
**एक टेक्निकल सच्चाई (Candor):** आपने रेडियस (100KM) के हिसाब से नोटिफिकेशन भेजने की बात कही। चूँकि हम Google Apps Script (फ्री सर्वर) का इस्तेमाल कर रहे हैं, अगर हम हर बार न्यूज़ पब्लिश होने पर हज़ारों यूज़र्स का लोकेशन कैलकुलेट करके उन्हें एक-एक करके नोटिफिकेशन भेजेंगे, तो फ्री सर्वर क्रैश (Timeout) हो जाएगा।
**हमारा स्मार्ट सलूशन:** मैंने इसे "Smart Broadcast (स्मार्ट ब्रॉडकास्ट)" सिस्टम पर सेट किया है। जैसे ही कोई न्यूज़ डालेगा, नोटिफिकेशन **सभी** को जाएगा, लेकिन उस नोटिफिकेशन के टाइटल में **लोकेशन का नाम और फ़ोटो (Image)** साफ़-साफ़ दिखेगा (जैसे: 📍 Garhia में नई खबर!)। इससे यूज़र अपने आप समझ जाएगा कि यह उसके काम की खबर है या नहीं।
यहाँ आपका **पूरा कंबाइंड (Combined) 100% फुल कोड** 3 हिस्सों में दिया गया है। इसे ध्यान से अपने प्रोजेक्ट में लगा लें:
### 1. Apps Script (Backend) की सेटिंग और पूरा कोड
चूँकि हम Google का ओरिजिनल Firebase नोटिफिकेशन यूज़ कर रहे हैं, इसलिए आपको अपने Apps Script में 2 काम करने होंगे:
**A. Project Link & Permissions (यह बहुत ज़रूरी है):**
 1. Apps Script की Settings (⚙️) में जाएँ और **"Google Cloud Platform (GCP) Project"** में अपने Firebase का प्रोजेक्ट नंबर डाल दें।
 2. उसी Settings में **"Show 'appsscript.json' manifest file in editor"** पर टिक लगाएँ।
 3. एडिटर में appsscript.json खोलें और उसमें "oauthScopes" जोड़ें, ताकि स्क्रिप्ट को नोटिफिकेशन भेजने की पावर मिल सके:
```json
{
  "timeZone": "Asia/Kolkata",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/firebase.messaging",
    "https://www.googleapis.com/auth/spreadsheets"
  ]
}

```
**B. पूरा Apps Script Code (इसे Code.gs में पेस्ट करें):**
*(ध्यान दें: इसमें YOUR_FIREBASE_PROJECT_ID की जगह अपना ID ज़रूर डालें और **New Deployment** करें)*
```javascript
function doGet(e) {
  var action = e.parameter.action;
  if (action == "getNews") return getNews(e);
  if (action == "addView") return addView(e);
  if (action == "report") return reportNews(e);
  if (action == "deleteNews") return deleteNews(e);
  if (action == "checkStrikes") return checkStrikes(e);
  return ContentService.createTextOutput("Local Updates API is Online");
}

function checkStrikes(e) {
  var email = e.parameter.email;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  var blockSheet = ss.getSheetByName("BLOCKED_USERS");
  if(blockSheet) {
    var blockedList = blockSheet.getDataRange().getValues();
    for(var b=1; b<blockedList.length; b++){
      if(blockedList[b][0] == email) return ContentService.createTextOutput("blocked");
    }
  }
  
  var strikeSheet = ss.getSheetByName("STRIKES");
  if(strikeSheet) {
    var strikeData = strikeSheet.getDataRange().getValues();
    for(var s=1; s<strikeData.length; s++) {
      if(strikeData[s][0] == email) {
        return ContentService.createTextOutput(strikeData[s][1].toString());
      }
    }
  }
  return ContentService.createTextOutput("0");
}

function doPost(e) {
  try {
    var data = JSON.parse(e.postData.contents);
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    
    // FIREBASE TOPIC SUBSCRIPTION LOGIC
    if (data.action === "subscribe") {
      var url = "https://iid.googleapis.com/iid/v1:batchAdd";
      var payload = { "to": "/topics/all_users", "registration_tokens": [data.token] };
      var options = {
        "method": "post",
        "headers": {
          "Authorization": "Bearer " + ScriptApp.getOAuthToken(),
          "Content-Type": "application/json"
        },
        "payload": JSON.stringify(payload),
        "muteHttpExceptions": true
      };
      UrlFetchApp.fetch(url, options);
      return ContentService.createTextOutput("subscribed");
    }

    var sheet = ss.getSheetByName("NEWS");
    var blockSheet = ss.getSheetByName("BLOCKED_USERS");
    
    var blockedList = blockSheet.getDataRange().getValues();
    for(var b=0; b<blockedList.length; b++){
      if(blockedList[b][0] == data.email) return ContentService.createTextOutput("blocked");
    }

    if (data.action === "saveUser") {
        var userSheet = ss.getSheetByName("USERS");
        var userRows = userSheet.getDataRange().getValues();
        var found = false;
        for(var u = 1; u < userRows.length; u++) {
            if(userRows[u][0] === data.email) { found = true; break; }
        }
        if(!found) { userSheet.appendRow([data.email, data.name, data.photo, new Date()]); }
        return ContentService.createTextOutput("user_saved");
    }

    if (data.action === "editNews") {
       var rows = sheet.getDataRange().getValues();
       for(var i=1; i<rows.length; i++) {
         if(rows[i][0] == data.id && rows[i][5] == data.email) { 
            sheet.getRange(i+1, 2).setValue(data.headline);
            sheet.getRange(i+1, 3).setValue(data.text);
            if(data.imageUrl) sheet.getRange(i+1, 12).setValue(data.imageUrl); 
            sheet.getRange(i+1, 13).setValue(data.locationName);
            sheet.getRange(i+1, 14).setValue(true); 
            return ContentService.createTextOutput("edited");
         }
       }
       return ContentService.createTextOutput("not_found");
    }

    sheet.appendRow([
      new Date().getTime(), data.headline, data.text, data.username, data.photo, 
      data.email, data.latitude, data.longitude, new Date().getTime(), 
      0, "", data.imageUrl || "", data.locationName || "Local", false
    ]);
    
    // 🔥 SEND FIREBASE PUSH NOTIFICATION WITH IMAGE 🔥
    sendFirebaseNotification(data.headline, data.locationName || "Local", data.imageUrl);

    return ContentService.createTextOutput("success");
  } catch (err) { return ContentService.createTextOutput("error: " + err.message); }
}

function sendFirebaseNotification(headline, location, imageUrl) {
  var projectId = "YOUR_FIREBASE_PROJECT_ID"; // ⚠️ यहाँ अपना प्रोजेक्ट ID डालें
  var url = "https://fcm.googleapis.com/v1/projects/" + projectId + "/messages:send";
  var token = ScriptApp.getOAuthToken(); 

  var payload = {
    "message": {
      "topic": "all_users",
      "notification": {
        "title": "📍 " + location + " में नई खबर!",
        "body": headline,
        "image": imageUrl || "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxZYThJov7nVLeejJp30nZ130Js5tuIKOicgFSzAT8BV-sWAhDWy2oWKX5uzTY9BpRefSvN-leUHeaIvcTPDYCX7G2qjChtibiJapDQ1IzCTVekLffx7d-jZopQRENCRh-12BzEHwC4azCmX1mcavCBGCfa8Yf3Rhv0XxucZ6IwppXX1m_flG5YV1X8ig/s1600/20260412_015639_0000.png"
      },
      "webpush": {
        "fcm_options": { "link": "https://baithkeenews.vercel.app" } // ⚠️ अपना Vercel लिंक डालें
      }
    }
  };

  var options = {
    "method": "post",
    "headers": {
      "Authorization": "Bearer " + token,
      "Content-Type": "application/json"
    },
    "payload": JSON.stringify(payload),
    "muteHttpExceptions": true
  };
  UrlFetchApp.fetch(url, options);
}

// ... (बाकी के getNews, addView, reportNews, deleteNews, addStrikeToUser, calculateDistance फंक्शन बिल्कुल पुराने वाले ही रहेंगे) ...
function deleteNews(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("NEWS");
  var rows = sheet.getDataRange().getValues();
  for(var i=1; i<rows.length; i++) {
      if(rows[i][0] == e.parameter.id && rows[i][5] == e.parameter.email) {
          sheet.deleteRow(i+1);
          return ContentService.createTextOutput("deleted");
      }
  }
  return ContentService.createTextOutput("error");
}

function getNews(e) {
  var uLat = parseFloat(e.parameter.lat);
  var uLon = parseFloat(e.parameter.lon);
  var range = parseFloat(e.parameter.range) || 10; 
  var sharedNewsId = e.parameter.newsId; 
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("NEWS");
  var rows = sheet.getDataRange().getValues();
  
  var strikeSheet = ss.getSheetByName("STRIKES");
  var strikeRows = strikeSheet.getDataRange().getValues();
  var penaltyMap = {};
  var now = new Date().getTime();
  for(var s=1; s<strikeRows.length; s++) {
     var lastStrike = strikeRows[s][2]; 
     if (lastStrike && (now - lastStrike) <= (7 * 24 * 60 * 60 * 1000)) {
        penaltyMap[strikeRows[s][0]] = true; 
     }
  }

  var result = [];
  for (var i = rows.length - 1; i > 0; i--) {
    var row = rows[i];
    var hours = (now - row[8]) / 3600000;
    var isSharedNews = (sharedNewsId && row[0] == sharedNewsId);

    if (hours > 24 && !isSharedNews) { sheet.deleteRow(i + 1); continue; }
    var dist = calculateDistance(uLat, uLon, row[6], row[7]);
    
    if (dist <= range || isSharedNews) {
      result.push({
        id: row[0], headline: row[1], text: row[2], username: row[3], photo: row[4], email: row[5], 
        time: row[8], views: row[9] || 0, distance: dist, image: row[11] || "", locationName: row[12] || "Local Area",
        isEdited: row[13] || false, hideBlueTick: penaltyMap[row[5]] || false
      });
    }
  }
  result.sort((a, b) => b.views - a.views); 
  return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON);
}

function addView(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("NEWS");
  var data = sheet.getDataRange().getValues();
  for (var i = 1; i < data.length; i++) {
    if (data[i][0] == e.parameter.id) {
      sheet.getRange(i + 1, 10).setValue((Number(data[i][9]) || 0) + 1);
      break;
    }
  }
  return ContentService.createTextOutput("done");
}

function reportNews(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("NEWS");
  var data = sheet.getDataRange().getValues();
  for (var i = 1; i < data.length; i++) {
    if (data[i][0] == e.parameter.id) {
      var reports = data[i][10] ? data[i][10].split(",") : [];
      if (reports.indexOf(e.parameter.email) == -1) {
        reports.push(e.parameter.email);
        if (reports.length >= 5) { 
          var authorEmail = data[i][5]; 
          sheet.deleteRow(i + 1);
          addStrikeToUser(authorEmail, ss); 
        } else {
          sheet.getRange(i + 1, 11).setValue(reports.join(","));
        }
      }
      break;
    }
  }
  return ContentService.createTextOutput("reported");
}

function addStrikeToUser(email, ss) {
  if(!email) return;
  var strikeSheet = ss.getSheetByName("STRIKES");
  var blockSheet = ss.getSheetByName("BLOCKED_USERS");
  var strikeData = strikeSheet.getDataRange().getValues();
  var found = false;
  var now = new Date().getTime();

  for(var s=1; s<strikeData.length; s++) {
    if(strikeData[s][0] == email) {
      var currentStrikes = Number(strikeData[s][1]) + 1;
      strikeSheet.getRange(s+1, 2).setValue(currentStrikes);
      strikeSheet.getRange(s+1, 3).setValue(now); 
      found = true;
      if(currentStrikes >= 3) { blockSheet.appendRow([email, new Date()]); }
      break;
    }
  }
  if(!found) { strikeSheet.appendRow([email, 1, now]); }
}

function calculateDistance(lat1, lon1, lat2, lon2) {
  var R = 6371; var dLat = (lat2-lat1)*Math.PI/180; var dLon = (lon2-lon1)*Math.PI/180;
  var a = Math.sin(dLat/2)*Math.sin(dLat/2) + Math.cos(lat1*Math.PI/180)*Math.cos(lat2*Math.PI/180)*Math.sin(dLon/2)*Math.sin(dLon/2);
  return R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)));
}

```
### 2. Vercel की Root Directory फाइल (firebase-messaging-sw.js)
Vercel पर बैकग्राउंड में नोटिफिकेशन प्राप्त करने के लिए आपके फोल्डर में बिल्कुल इसी नाम से एक फाइल होनी चाहिए।
```javascript
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');

// ⚠️ यहाँ अपने Firebase प्रोजेक्ट की डिटेल्स डालें
const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
};

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxZYThJov7nVLeejJp30nZ130Js5tuIKOicgFSzAT8BV-sWAhDWy2oWKX5uzTY9BpRefSvN-leUHeaIvcTPDYCX7G2qjChtibiJapDQ1IzCTVekLffx7d-jZopQRENCRh-12BzEHwC4azCmX1mcavCBGCfa8Yf3Rhv0XxucZ6IwppXX1m_flG5YV1X8ig/s1600/20260412_015639_0000.png',
    image: payload.notification.image // न्यूज़ की फोटो भी लॉक स्क्रीन पर दिखेगी
  };
  self.registration.showNotification(notificationTitle, notificationOptions);
});

```
### 3. Frontend HTML (पूरा कंबाइंड कोड)
इसमें स्ट्राइक बैज का CSS/JS और Firebase नोटिफिकेशन माँगने का पूरा लॉजिक जोड़ दिया गया है।
*(ध्यान दें: जहाँ YOUR_API_KEY और YOUR_VAPID_KEY लिखा है, वहाँ Firebase से निकालकर अपनी Keys डालें)।*
```html
<!DOCTYPE html>
<html lang="hi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#1C1C1E">
    <title>BaithKee News Local Updates</title>

    <link href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxZYThJov7nVLeejJp30nZ130Js5tuIKOicgFSzAT8BV-sWAhDWy2oWKX5uzTY9BpRefSvN-leUHeaIvcTPDYCX7G2qjChtibiJapDQ1IzCTVekLffx7d-jZopQRENCRh-12BzEHwC4azCmX1mcavCBGCfa8Yf3Rhv0XxucZ6IwppXX1m_flG5YV1X8ig/s1600/20260412_015639_0000.png" rel="icon" sizes="32x32" type="image/png" />
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Laila:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://accounts.google.com/gsi/client" async defer></script>

    <style>
        /* (आपके सारे पुराने CSS यहाँ मौजूद हैं, मैंने सिर्फ प्रोफाइल बैज का CSS जोड़ा है) */
        :root { --primary: #FF3B30; --dark: #1C1C1E; --gray: #8E8E93; --light: #F2F2F7; --white: #FFFFFF; --shadow: 0 4px 12px rgba(0, 0, 0, 0.08); }
        body { margin: 0; font-family: 'Laila', sans-serif; background: var(--light); color: var(--dark); -webkit-tap-highlight-color: transparent; user-select: none; -webkit-user-select: none; transition: background-color 0.3s, color 0.3s; }
        input, textarea { user-select: text !important; -webkit-user-select: text !important; font-family: 'Laila', sans-serif; }
        header { background: var(--dark); color: var(--white); padding: 10px 15px; position: sticky; top: 0; z-index: 1000; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); }
        .brand-menu { position: relative; display: flex; align-items: center; cursor: pointer; }
        .brand-menu img { width: 35px; height: 35px; border-radius: 8px; object-fit: cover; }
        .search-container { flex: 1; display: flex; justify-content: center; padding: 0 10px; position: relative; }
        .search-box { width: 100%; max-width: 300px; position: relative; }
        .search-box input { width: 100%; padding: 8px 30px 8px 15px; border-radius: 20px; border: none; outline: none; background: rgba(255, 255, 255, 0.2); color: white; box-sizing: border-box; }
        .search-box input::placeholder { color: #ccc; }
        .clear-search { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: white; cursor: pointer; display: none; font-weight: bold; font-family: sans-serif; }
        
        .profile-container { width: 40px; display: flex; justify-content: flex-end; }
        .user-menu { position: relative; display: flex; align-items: center; cursor: pointer; }
        .user-menu img { width: 35px; height: 35px; border-radius: 50%; border: 2px solid var(--white); object-fit: cover; }
        
        /* 🔥 PROFILE STRIKE NOTIFICATION BADGE CSS 🔥 */
        .strike-badge { position: absolute; top: -4px; right: -4px; background: #FF3B30; color: white; border-radius: 50%; width: 16px; height: 16px; font-size: 10px; font-weight: 800; display: none; align-items: center; justify-content: center; border: 2px solid var(--dark); z-index: 10; }
        body.dark-mode .strike-badge { border-color: #111111; }

        .dropdown { display: none; position: absolute; top: 45px; background: white; color: inherit; box-shadow: var(--shadow); border-radius: 8px; overflow: hidden; min-width: 130px; z-index: 2000; left: 0; }
        .dropdown.right { left: auto; right: 0; }
        .dropdown div, .dropdown a { padding: 12px 16px; font-weight: 600; border-bottom: 1px solid #eee; display: block; color: black; text-decoration: none; cursor: pointer; }
        
        #newsContainer { padding: 10px 0 110px 0; min-height: 50vh; }
        #loadingState { text-align: center; padding: 30px 20px 10px 20px; color: var(--gray); display: none; }
        .spinner { border: 4px solid rgba(255, 59, 48, 0.2); border-top: 4px solid var(--primary); border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 0 auto 10px auto; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        .skeleton { background: #e0e0e0; animation: pulse 1.5s infinite; }
        @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } }
        .skeleton-strip { display: flex; height: 85px; margin: 10px 12px; background: white; border-radius: 14px; box-shadow: var(--shadow); overflow: hidden; }
        .skeleton-img { width: 110px; height: 100%; flex-shrink: 0; }
        .skeleton-text { height: 16px; margin: 10px; border-radius: 4px; }

        .newsStrip { background: var(--white); margin: 10px 12px; border-radius: 14px; display: flex; flex-direction: row; align-items: stretch; box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08), 0 2px 4px rgba(0, 0, 0, 0.05); border-bottom: 3px solid #e5e5ea; cursor: pointer; transition: transform 0.2s; overflow: hidden; }
        .newsStrip:active { transform: scale(0.96) translateY(2px); border-bottom: 1px solid #e5e5ea; }
        .strip-img { width: 110px; min-height: 75px; aspect-ratio: 16/9; object-fit: cover; background: #eee; flex-shrink: 0; pointer-events: none; border-right: 1px solid #eaeaea; }
        .strip-content { padding: 10px 12px; flex: 1; display: flex; flex-direction: column; justify-content: space-between; min-width: 0; }
        .headlineText { font-size: 16px; font-weight: 700; line-height: 1.3; color: #1C1C1E; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-bottom: 5px; }
        .strip-meta { display: grid; grid-template-columns: 1fr 1fr 1fr; width: 100%; border-top: 1px solid #f0f0f0; padding-top: 6px; gap: 5px; }
        .meta-box { display: flex; flex-direction: column; justify-content: center; overflow: hidden; }
        .meta-box.left { align-items: flex-start; text-align: left; }
        .meta-box.center { align-items: center; text-align: center; border-left: 1px solid #eaeaea; border-right: 1px solid #eaeaea; }
        .meta-box.right { align-items: flex-end; text-align: right; }
        .meta-label { font-size: 8px; color: #8E8E93; text-transform: uppercase; font-weight: 700; margin-bottom: 2px; letter-spacing: 0.5px; }
        .meta-item { font-size: 11px; font-weight: 600; display: flex; align-items: center; gap: 3px; white-space: nowrap; }
        .locTag { color: #007AFF; max-width: 100%; overflow: hidden; text-overflow: ellipsis; display: inline-block; vertical-align: middle; }
        .viewsTag { color: var(--primary); }
        .timeTag { color: var(--gray); }

        .ad-strip { display: block; text-decoration: none; background: #fffbe6; border: 1px solid #ffe58f; margin: 12px; padding: 8px; border-radius: 10px; }
        .sticky-ad { position: sticky; top: -25px; z-index: 2010; background: var(--white); margin: -25px -25px 10px -25px; padding: 10px 0 0 0; border-bottom: 1px solid #ffe58f; display: block; text-align: center; }
        .sticky-ad .ad-img { width: 100%; height: 100%; border-radius: 0; }
        .ad-img { width: 100%; height: 100%; border-radius: 6px; object-fit: 100% 100%; }
        .ad-label { font-size: 5px; color: #d48806; font-weight: bold; margin-bottom: 1px; display: block; text-align: center; padding: 0; }

        .fab { position: fixed; right: 20px; width: 60px; height: 60px; border-radius: 50%; border: none; color: white; display: flex; align-items: center; justify-content: center; z-index: 999; cursor: pointer; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); }
        #rangeBtn { bottom: 105px; background: white; color: #EA4335; border: 2px solid #EA4335; }
        #publishBtn { bottom: 30px; background: linear-gradient(135deg, #FF3B30, #FF2D55); font-size: 30px; animation: attractUser 3s infinite; }
        @keyframes attractUser { 0% { box-shadow: 0 0 0 0 rgba(255, 59, 48, 0.7); transform: rotate(0deg) scale(1); } 5% { transform: rotate(-15deg) scale(1.15); } 10% { transform: rotate(15deg) scale(1.15); } 15% { transform: rotate(-15deg) scale(1.15); } 20% { transform: rotate(0deg) scale(1); box-shadow: 0 0 0 15px rgba(255, 59, 48, 0); } 100% { box-shadow: 0 0 0 0 rgba(255, 59, 48, 0); transform: rotate(0deg) scale(1); } }

        .overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(5px); z-index: 2000; align-items: flex-end; justify-content: center; }
        .popup { background: var(--white); width: 100%; max-width: 550px; border-radius: 25px 25px 0 0; padding: 25px; box-sizing: border-box; max-height: 90vh; overflow-y: auto; animation: slideUp 0.3s ease-out; position: relative; }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
        @keyframes slideDown { from { transform: translateY(0); } to { transform: translateY(100%); } }

        .stats-bar { display: flex; justify-content: space-between; align-items: center; background: var(--light); padding: 12px; border-radius: 10px; margin-bottom: 15px; }
        .action-btn { color: var(--gray); font-size: 14px; font-weight: 700; cursor: pointer; display: flex; align-items: center; gap: 4px; padding: 5px; }
        .news-content { font-size: 18px; line-height: 1.6; color: #333; margin-bottom: 25px; white-space: pre-wrap; word-wrap: break-word; }
        .premium-frame { background-color: #ffffff; padding: 5px; position: relative; margin: 10px 0 20px 0; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08); border-radius: 1px; box-sizing: border-box; }
        .premium-frame img { display: block; width: 100%; pointer-events: none; border-radius: 1px; }
        .premium-frame::after { content: ''; position: absolute; top: 2.5px; left: 2.5px; right: 2.5px; bottom: 2.5px; border: 1px dashed rgba(0, 0, 0, 0.4); border-radius: 0px; pointer-events: none; }
        .verified-badge { width: 18px; height: 18px; margin-left: 5px; vertical-align: middle; display: inline-block; }
        .stylish-upload { display: block; width: 100%; padding: 20px 10px; background: #f8f8f8; border: 2px dashed #FF3B30; border-radius: 12px; text-align: center; color: #FF3B30; font-weight: 700; cursor: pointer; box-sizing: border-box; font-size: 16px; margin-bottom: 15px; font-family: 'Laila', sans-serif; }
        .range-box { text-align: center; padding: 20px 0; }
        #rangeSlider { width: 100%; height: 10px; border-radius: 5px; background: #ddd; accent-color: var(--primary); margin: 25px 0; }
        .range-num { font-size: 35px; font-weight: 800; color: var(--primary); }

        .toast { position: fixed; bottom: -50px; left: 50%; transform: translateX(-50%); background: #1c1c1e; color: white; padding: 12px 24px; border-radius: 30px; font-weight: 600; font-family: 'Laila', sans-serif; transition: 0.3s; z-index: 4000; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); opacity: 0; }
        .toast.show { bottom: 30px; opacity: 1; }
        .btn-loader { border: 3px solid rgba(255, 255, 255, 0.3); border-top: 3px solid white; border-radius: 50%; width: 20px; height: 20px; animation: spin 1s linear infinite; display: none; margin-left: 10px; }

        .app-download-banner { display: none; position: fixed; bottom: 0; left: 0; width: 100%; background: #1C1C1E; color: white; padding: 20px; box-sizing: border-box; box-shadow: 0 -10px 25px rgba(0, 0, 0, 0.4); z-index: 9999; text-align: center; border-top-left-radius: 25px; border-top-right-radius: 25px; font-family: 'Laila', sans-serif; animation: slideUpPopup 0.5s ease-out; }
        @keyframes slideUpPopup { from { bottom: -100px; opacity: 0; } to { bottom: 0; opacity: 1; } }
        .app-download-banner h3 { margin: 0 0 8px 0; font-size: 20px; font-weight: 800; }
        .app-download-banner p { font-size: 13px; margin: 0 0 15px 0; color: #8E8E93; }
        .download-btn { background: linear-gradient(135deg, #008000, #008000); color: white; border: none; padding: 14px 20px; border-radius: 30px; font-size: 18px; font-weight: 700; cursor: pointer; width: 100%; font-family: 'Laila', sans-serif; box-shadow: 0 4px 15px rgba(0, 128, 0, 0.4); }
        .close-banner { color: #8E8E93; font-size: 14px; margin-top: 15px; cursor: pointer; font-weight: 600; }
        .bottom-close-btn { width: 100%; background-color: #F2F2F7; color: #1C1C1E; border: none; padding: 15px; border-radius: 12px; font-size: 16px; font-weight: 700; font-family: 'Laila', sans-serif; cursor: pointer; margin-top: 10px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); transition: transform 0.2s; }
        .bottom-close-btn:active { transform: scale(0.98); background-color: #E5E5EA; }
        
        #editNewsBtn { width: 100%; background: #fffbe6; color: #d48806; border: 1px solid #ffe58f; padding: 12px; border-radius: 8px; font-size: 14px; font-weight: bold; font-family: 'Laila', sans-serif; cursor: pointer; margin-bottom: 15px; display: none; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); }
        .action-split { display: flex; gap: 10px; width: 100%; margin-bottom: 20px; margin-top: 10px; }
        .action-split button { flex: 1; padding: 15px; border-radius: 12px; font-size: 16px; font-weight: 700; font-family: 'Laila', sans-serif; cursor: pointer; border: none; transition: transform 0.2s; }
        .action-split button:active { transform: scale(0.98); }
        #deleteNewsBtn { background: #ffebee; color: #d32f2f; display: none; }
        .action-split .bottom-close-btn { margin: 0 !important; background: #F2F2F7; color: #1C1C1E; }
        .edited-tag { font-size: 10px; color: #8e8e93; font-style: italic; background: #eee; padding: 2px 6px; border-radius: 4px; vertical-align: middle; margin-right: 5px; }

        body.dark-mode { --light: #000000; --dark: #F2F2F7; --white: #1C1C1E; background: var(--light); color: var(--dark); }
        body.dark-mode header { background: #111111; border-bottom: 1px solid #333; }
        body.dark-mode .newsStrip, body.dark-mode .popup, body.dark-mode .dropdown { background: var(--white); color: var(--dark); box-shadow: 0 4px 12px rgba(255, 255, 255, 0.05); }
        body.dark-mode .headlineText, body.dark-mode h2, body.dark-mode h3 { color: #ffffff !important; }
        body.dark-mode .news-content { color: #cccccc; }
        body.dark-mode .bottom-close-btn, body.dark-mode .stats-bar { background: #2C2C2E; color: #ffffff; }
        body.dark-mode .dropdown div, body.dark-mode .dropdown a, body.dark-mode #pName, body.dark-mode .brand-menu div { color: #ffffff !important; }
        body.dark-mode .dropdown div, body.dark-mode .dropdown a { border-bottom: 1px solid #444; }
        
        body.dark-mode .strip-img { background: #2C2C2E !important; border-right: 1px solid #333 !important; }
        body.dark-mode .premium-frame { background-color: #1C1C1E !important; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5) !important; }
        body.dark-mode .premium-frame::after { border-color: rgba(255, 255, 255, 0.2) !important; }
        body.dark-mode .ad-strip, body.dark-mode .sticky-ad > div, body.dark-mode a[style*="#fffbe6"] { background: #2a2510 !important; border-color: #5c430a !important; }
        body.dark-mode .sticky-ad { background: #1C1C1E !important; border-bottom: 1px solid #333 !important; z-index: 2010 !important; }
        body.dark-mode #deleteNewsBtn { background: #3a1c1c !important; color: #ff4d4d !important; }
        body.dark-mode #editNewsBtn { background: #2a2510 !important; border-color: #5c430a !important; color: #ffb74d !important; }
        body.dark-mode .bottom-close-btn { background-color: #2C2C2E !important; color: #ffffff !important; }
        body.dark-mode input[type="text"], body.dark-mode textarea { background-color: #2C2C2E !important; color: #ffffff !important; border: 1px solid #444 !important; }
        body.dark-mode .stylish-upload { background: #2C2C2E !important; }

        .premium-share-fab { position: fixed; right: 35px; bottom: 170px; background: transparent; border: none; z-index: 999; cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 0; outline: none; -webkit-tap-highlight-color: transparent; animation: denseNeonAlert 4s cubic-bezier(0.25, 0.8, 0.25, 1) infinite; }
        .premium-share-fab svg { width: 36px; height: 36px; stroke-width: 2.5px; transition: transform 0.2s ease-out; }
        .premium-share-fab:active svg { transform: scale(0.75) rotate(-15deg); }
        @keyframes denseNeonAlert { 0% { transform: translateY(0) scale(1); color: #000000; filter: drop-shadow(0 0 4px rgba(37, 211, 102, 0.5)); } 5% { transform: translateY(-2px) scale(1.15); color: #00FF66; filter: drop-shadow(0 0 8px rgba(0, 255, 102, 1)) drop-shadow(0 0 20px rgba(0, 255, 102, 0.8)) drop-shadow(0 0 35px rgba(0, 255, 102, 0.6)); } 10% { transform: translateY(-4px) scale(1); color: #25D366; filter: drop-shadow(0 0 4px rgba(37, 211, 102, 0.5)); } 15% { transform: translateY(-6px) scale(1.25); color: #00FF66; filter: drop-shadow(0 0 10px rgba(0, 255, 102, 1)) drop-shadow(0 0 25px rgba(0, 255, 102, 0.9)) drop-shadow(0 0 45px rgba(0, 255, 102, 0.7)); } 25% { transform: translateY(-4px) scale(1); color: #25D366; filter: drop-shadow(0 0 4px rgba(37, 211, 102, 0.5)); } 60% { transform: translateY(-10px) scale(1); color: #25D366; filter: drop-shadow(0 0 4px rgba(37, 211, 102, 0.4)); } 100% { transform: translateY(0) scale(1); color: #25D366; filter: drop-shadow(0 0 4px rgba(37, 211, 102, 0.5)); } }
    </style>
    
    <script type="module">
        import { initializeApp } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-app.js";
        import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-messaging.js";

        // ⚠️ यहाँ Firebase Project से निकालकर अपना config डालें
        const firebaseConfig = {
            apiKey: "YOUR_API_KEY",
            authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
            projectId: "YOUR_PROJECT_ID",
            storageBucket: "YOUR_PROJECT_ID.appspot.com",
            messagingSenderId: "YOUR_SENDER_ID",
            appId: "YOUR_APP_ID"
        };

        const app = initializeApp(firebaseConfig);
        const messaging = getMessaging(app);

        // ग्लोबल फंक्शन ताकि लॉगिन होने पर परमिशन माँगी जा सके
        window.requestNotificationPermission = function() {
            Notification.requestPermission().then((permission) => {
                if (permission === 'granted') {
                    // ⚠️ यहाँ अपनी VAPID Key डालें (Firebase Cloud Messaging settings से)
                    getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY_HERE' }).then((currentToken) => {
                        if (currentToken) {
                            // टोकन मिलने पर उसे Apps Script को भेजकर सब्सक्राइब करें
                            fetch(API_URL, {
                                method: 'POST',
                                body: JSON.stringify({ action: "subscribe", token: currentToken })
                            });
                        }
                    });
                }
            });
        };

        // जब यूज़र ऐप इस्तेमाल कर रहा हो तब मैसेज आए
        onMessage(messaging, (payload) => {
            let toast = document.getElementById("toastMsg");
            toast.innerText = "🔔 " + payload.notification.title;
            toast.classList.add("show");
            setTimeout(() => toast.classList.remove("show"), 4000);
        });
    </script>
</head>

<body oncontextmenu="if(event.target.tagName !== 'INPUT' && event.target.tagName !== 'TEXTAREA') return false;" onkeydown="return disableKeys(event);">

    <header>
        <div class="logo-container">
            <div class="brand-menu" onclick="toggleMenu('brandDropdown')">
                <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxZYThJov7nVLeejJp30nZ130Js5tuIKOicgFSzAT8BV-sWAhDWy2oWKX5uzTY9BpRefSvN-leUHeaIvcTPDYCX7G2qjChtibiJapDQ1IzCTVekLffx7d-jZopQRENCRh-12BzEHwC4azCmX1mcavCBGCfa8Yf3Rhv0XxucZ6IwppXX1m_flG5YV1X8ig/s1600/20260412_015639_0000.png" alt="Logo">
                <div class="dropdown" id="brandDropdown">
                    <a href="#">हमारे बारे में</a>
                    <a href="#">संपर्क करें</a>
                </div>
            </div>
        </div>
        <div class="search-container">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="लोकेशन हिंदी या English में लिखिए..." onkeyup="filterNews(this.value)">
                <span id="clearSearch" class="clear-search" onclick="clearSearchField()">✕</span>
            </div>
        </div>
        <div class="profile-container">
            <div id="authContainer">
                <div id="g_id_onload" data-client_id="1046845791568-jc7e5qn4rqhkgqlupdi1ga7j74otrnth.apps.googleusercontent.com" data-context="use" data-ux_mode="popup" data-callback="handleCredentialResponse" data-auto_prompt="false"></div>
                <div class="g_id_signin" data-type="icon" data-shape="circle"></div>
            </div>
            <div class="user-menu" id="userMenu" style="display: none;" onclick="toggleMenu('profileDropdown')">
                <img id="navProfilePic" src="">
                <span id="strikeBadge" class="strike-badge"></span>

                <div class="dropdown right" id="profileDropdown">
                    <div onclick="toggleTheme()" id="themeToggleBtn">🌚 डार्क मोड</div>
                    <div onclick="logoutUser()">Logout</div>
                </div>
            </div>
        </div>
    </header>
  
  <marquee direction="left" scrollamount="3" style="background:#fff3cd;border-top:1px solid #ff9800;border-bottom:1px solid #ff9800;color:#b30000;font-size:10px;font-weight:bold;padding:5px;position:fixed;bottom:0;left:0;width:100%;z-index:9999;">
⚠️ कृपया अपने आसपास के छोटे-Bade खबरों को एक बार पोस्ट जरूर कीजिए।
</marquee>

    <div id="loadingState">
        <div class="spinner"></div>
        <h3 style="margin:0; font-size:18px; color:#1c1c1e;">कृपया कुछ देर इंतज़ार करें...</h3>
        <p style="font-size:14px; margin-top:8px;">हम ताज़ा ख़बरें ला रहे हैं।</p>
        <p style="font-size:10px; margin-top:8px;">अगर ज्यादा टाइम ले रहा है तो प्लीज रिफ्रेश कर दीजिए।</p>
    </div>
    <div id="newsContainer"></div>

    <div id="installBanner" class="app-download-banner">
        <h3>BaithKee News ऐप डाउनलोड करें </h3>
        <p>अपने आस-पास की ताज़ा ख़बरों के लिए बैठकी न्यूज़ ऐप अभी इंस्टॉल करें।</p>
        <button id="downloadAppBtn" class="download-btn">अभी इंस्टॉल करें</button>
        <div class="close-banner" onclick="document.getElementById('installBanner').style.display='none'">बाद में</div>
    </div>

    <button id="shareAppBtn" class="premium-share-fab" onclick="shareApplication()">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
        </svg>
    </button>

    <button id="rangeBtn" class="fab" onclick="document.getElementById('rangeOverlay').style.display='flex'">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
        </svg>
    </button>
    <button id="publishBtn" class="fab" onclick="checkAuth()">+</button>

    <div id="detailOverlay" class="overlay" onclick="closePopup(event, 'detailOverlay')">
        <div class="popup" id="detailPopupContent" onclick="event.stopPropagation()">
            <a id="detailAd" class="sticky-ad dynamic-ad" href="#" target="_blank">
                <div style="background: #fffbe6; padding: 5px; border-radius: 6px;">
                    <span class="ad-label">SPONSORED</span><img class="ad-img" src="https://via.placeholder.com/500x70?text=Ad">
                </div>
            </a>
            <button id="editNewsBtn" onclick="openEditMode()">✏️ इस न्यूज़ को एडिट करें <span id="editTimerText" style="font-weight: 900; color: #FF3B30;"></span></button>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <img id="pImg" src="" style="width:45px; height:45px; border-radius:50%; border:2px solid var(--primary);">
                    <div>
                        <div style="font-weight:800; font-size:16px; color:#1c1c1e; display:flex; align-items:center;">
                            <span id="pName"></span>
                            <svg id="verifiedBadge" class="verified-badge" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <g fill="#007AFF"><rect x="3" y="3" width="18" height="18" rx="2" /><rect x="3" y="3" width="18" height="18" rx="2" transform="rotate(45 12 12)" /></g>
                                <path d="M10 16.5L6 12.5L7.5 11L10 13.5L16.5 7L18 8.5L10 16.5Z" fill="white" />
                            </svg>
                        </div>
                        <div id="pTime" style="font-size:12px; color:var(--gray); font-weight:600;"></div>
                    </div>
                </div>
                <div onclick="closeWithAnimation('detailOverlay')" style="font-size:26px; font-weight:bold; cursor:pointer; padding:5px;">✕</div>
            </div>
            <div class="stats-bar" style="flex-direction: column; align-items: flex-start; gap: 8px;">
                <div style="display: flex; justify-content: space-between; width: 100%; align-items: center;">
                    <div><span id="pViews" style="font-weight: 800; color: #007AFF; font-size:15px;"></span><div id="pExactTime" style="font-size:11px; color:var(--gray); margin-top:4px; font-weight:600;"></div></div>
                    <div style="display:flex; gap:15px; align-items:center;">
                        <span class="action-btn" style="font-size: 22px; margin-right: 10px;" onclick="toggleReader()" id="ttsBtn">🔊</span>
                        <span class="action-btn" onclick="shareNews()">🔗 शेयर</span>
                        <span class="action-btn" style="color:#FF3B30;" onclick="reportNews()">⚠️ रिपोर्ट</span>
                    </div>
                </div>
            </div>
            <h2 id="pHeadline" style="margin-top:0; font-size:24px; color: #1c1c1e;"></h2>
            <div id="pImages"></div>
            <div id="pContent" class="news-content"></div>
            <div id="bottomAdContainer" style="margin-top: 25px; margin-bottom: 15px;"></div>
            <div class="action-split">
                <button id="deleteNewsBtn" onclick="askDeleteConfirm()">🗑️ डिलीट करें</button>
                <button class="bottom-close-btn" onclick="closeWithAnimation('detailOverlay')">बंद करें</button>
            </div>
        </div>
    </div>

    <div id="publishOverlay" class="overlay" onclick="closePopup(event, 'publishOverlay')">
        <div class="popup" onclick="event.stopPropagation()">
            <h2 style="margin-top:0; margin-bottom:15px;">न्यूज़ पोस्ट</h2>
            <input type="text" id="headInput" maxlength="150" placeholder="Headline (Max 30 Words)..." style="width:100%; padding:15px; border-radius:12px; border:1px solid #ddd; margin-bottom:10px; box-sizing:border-box; font-size:16px;">
            <textarea id="bodyInput" rows="4" placeholder="Details (यहाँ पेस्ट कर सकते हैं)..." style="width:100%; padding:15px; border-radius:12px; border:1px solid #ddd; margin-bottom:10px; box-sizing:border-box; font-size:16px;"></textarea>
            <input type="text" id="locInput" maxlength="30" placeholder="लोकेशन (Max 3 Words)..." style="width:100%; padding:15px; border-radius:12px; border:1px solid #ddd; margin-bottom:15px; box-sizing:border-box; font-size:16px; border-left: 4px solid #007AFF;">
            <input type="file" id="imgInput" accept="image/*" onchange="previewSingleImage(event)" style="display:none;">
            <label for="imgInput" class="stylish-upload" id="uploadLabel">📸 1 फोटो चुनें (Optional)</label>
            <div id="imgPreviewArea" style="display:flex; justify-content:center; margin-bottom:15px;"></div>
            <button id="submitBtn" onclick="publishNews()" style="background: linear-gradient(135deg, #FF3B30, #FF2D55); color:white; border:none; width:100%; padding:15px; border-radius:12px; font-size:18px; font-weight:bold; cursor:pointer; font-family: 'Laila', sans-serif; display:flex; justify-content:center; align-items:center;">
                <span id="submitText">पब्लिश करें</span>
                <div id="submitLoader" class="btn-loader"></div>
            </button>
            <p onclick="closeWithAnimation('publishOverlay')" style="text-align:center; color:gray; cursor:pointer; margin-top:15px; padding:10px; font-weight:bold;">Cancel</p>
        </div>
    </div>

    <div id="rangeOverlay" class="overlay" onclick="closePopup(event, 'rangeOverlay')">
        <div class="popup" onclick="event.stopPropagation()">
            <h3 style="text-align:center;">खबर देखने का रेडियस सेट करें (KM)</h3>
            <div class="range-box">
                <span class="range-num" id="rangeDisplay">100</span> <span style="font-size:20px; font-weight:bold;">KM</span>
                <input type="range" id="rangeSlider" min="1" max="100" value="100" oninput="document.getElementById('rangeDisplay').innerText = this.value">
            </div>
            <button onclick="updateRange()" style="background: linear-gradient(135deg, #007AFF, #5AC8FA); color:white; border:none; width:100%; padding:15px; border-radius:12px; font-weight:bold; font-family: 'Laila', sans-serif; font-size: 18px;">खबर खोजना शुरू करें</button>
        </div>
    </div>

    <div id="deleteConfirmOverlay" class="overlay" style="z-index: 3000; align-items: center;" onclick="closeDeleteConfirm()">
        <div class="popup" style="max-width: 320px; text-align: center; padding: 30px 20px; border-radius: 20px;" onclick="event.stopPropagation()">
            <div style="font-size: 50px; margin-bottom: 10px;">🗑️</div>
            <h3 style="margin-top: 0; color: #1c1c1e;">क्या आप सुनिश्चित हैं?</h3>
            <p style="color: #8e8e93; font-size: 14px; margin-bottom: 25px; line-height: 1.5;">यह न्यूज़ हमेशा के लिए डिलीट हो जाएगी और इसे किसी भी तरह वापस नहीं लाया जा सकेगा।</p>
            <div style="display: flex; gap: 10px;">
                <button onclick="closeDeleteConfirm()" style="flex: 1; padding: 12px; border-radius: 12px; border: none; background: #F2F2F7; color: #1C1C1E; font-weight: 700; cursor: pointer; font-family: 'Laila', sans-serif;">रद्द करें</button>
                <button onclick="proceedToDelete()" style="flex: 1; padding: 12px; border-radius: 12px; border: none; background: #FF3B30; color: white; font-weight: 700; cursor: pointer; font-family: 'Laila', sans-serif;">हाँ, डिलीट करें</button>
            </div>
        </div>
    </div>

    <div id="toastMsg" class="toast"></div>

    <script>
        const API_URL = "https://script.google.com/macros/s/AKfycbxu59eNH8lSjsVwHRrhxj1eBlM6ZLViupjrVswvFhVsqKaj3NsLnOrS01RlwSNswaGyFA/exec"; // अपना सही URL रखें

        const adList = [
            { url: "https://baithkeenews.blogspot.com", img: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgA7BkQyjbuST-pSEhjdyChzMYQuEi6KceSxTKvnPepdxQmmzvz9zJDi0f8Ya99xIU6rN5zPv16j_ghwz4dL6-w_G0HbIugqJmyAyqVC7MvQJ5yegnKSocS56QtKkx_Q9vuzGUQTlfpB6IOFXTHnZReseeLDUkRnIdmsoPvSncxkpQsSw/s1600/%E0%A4%AC%E0%A4%BF%E0%A4%A8%E0%A4%BE_20260420_130248_0000.png" },
            { url: "https://play.google.com/store/apps/details?id=com.useme.wallet&referrer=UM22040", img: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVG1g36WUUTF9Fc9mE6UTUpOmf_uXQICYOLAydWD6An5G1_bZPwuWRiJPb0-zlhF0f7WGMbiULF0ukm5ZViKx1dBWXdYqSob1zQpH8ommRCERscT0ekJwZOUhJuWDl9tc71amP_4ysU8JVqvtKRPI5bQJy2smplu0s86rbM2qwmIeIoQ/s1600/IMG-20260419-WA0009.jpg" },
            { url: "https://baithkeenews.blogspot.com", img: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhB56SmKrRX1ro5t5S4tu6-s2gWdkGLFIT-5mADSCBqra2XpZFnWE3akPKXeNcABpweYsnEktxqb8sw_rxD4Um-lOTU71R3RhkLznGDr7blMIblUeVbki1YIVZVuSU983VkLiJ8UoXCbBW1kRz7aD5-xqK6kdS55lSceHz3ZEJ-ChVkJA/s1600/jeremy-bishop-4kv4odtKd0U-unsplash-picsay.jpg" }
        ];

        let userLoc = { lat: 0, lon: 0 };
        let userData = null;
        let selectedRange = 100;
        let base64Image = "";
        let currentId = null;
        let allNewsData = [];
        let editingNewsId = null;
        let editInterval = null;

        function disableKeys(e) {
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return true;
            if (e.keyCode == 123) return false;
            if (e.ctrlKey && e.shiftKey && (e.keyCode == 73 || e.keyCode == 74)) return false;
            if (e.ctrlKey && e.keyCode == 85) return false;
        }

        window.onload = () => {
            checkSavedLogin();
            if (!userData) { setTimeout(() => { if (window.google) google.accounts.id.prompt(); }, 1500); }
            navigator.geolocation.getCurrentPosition(pos => {
                userLoc = { lat: pos.coords.latitude, lon: pos.coords.longitude };
                fetchNews();
            }, () => { fetchNews(); });
            startAdRotation();
        };

        // 🔥 स्ट्राइक (Strike) चेक करने का फंक्शन 🔥
        async function fetchUserStrikes() {
            if(!userData) return;
            try {
                let res = await fetch(`${API_URL}?action=checkStrikes&email=${userData.email}`);
                let text = await res.text();
                let badge = document.getElementById("strikeBadge");
                
                if(text === "blocked") {
                    badge.innerText = "X";
                    badge.style.background = "#000000"; // ब्लॉक होने पर काला
                    badge.style.display = "flex";
                } else if(Number(text) > 0) {
                    badge.innerText = text;
                    badge.style.display = "flex";
                } else {
                    badge.style.display = "none";
                }
            } catch(e) {}
        }

        function checkSavedLogin() {
            const saved = localStorage.getItem("baithkee_user");
            if (saved) {
                userData = JSON.parse(saved);
                document.getElementById("authContainer").style.display = "none";
                document.getElementById("userMenu").style.display = "flex";
                document.getElementById("navProfilePic").src = userData.photo;
                fetchUserStrikes(); // लोड होते ही स्ट्राइक चेक करें
            }
        }

        function handleCredentialResponse(response) {
            const payload = JSON.parse(atob(response.credential.split('.')[1]));
            userData = { name: payload.name, email: payload.email, photo: payload.picture };
            localStorage.setItem("baithkee_user", JSON.stringify(userData));
            document.getElementById("authContainer").style.display = "none";
            document.getElementById("userMenu").style.display = "flex";
            document.getElementById("navProfilePic").src = userData.photo;
            showToast("लॉगिन सफल!");

            fetch(API_URL, { method: "POST", body: JSON.stringify({ action: "saveUser", email: userData.email, name: userData.name, photo: userData.photo }) }).catch(err => console.log("User save error", err));
            
            fetchUserStrikes(); // लॉगिन होते ही स्ट्राइक चेक करें
            fetchNews();

            // लॉगिन होते ही नोटिफिकेशन की परमिशन मांगें (अगर पहले नहीं दी है)
            if(window.requestNotificationPermission) window.requestNotificationPermission();
        }

        function toggleMenu(menuId) { const d = document.getElementById(menuId); d.style.display = (d.style.display === "block") ? "none" : "block"; }
        function logoutUser() { localStorage.removeItem("baithkee_user"); location.reload(); }
        function showToast(msg) { let toast = document.getElementById("toastMsg"); toast.innerText = msg; toast.classList.add("show"); setTimeout(() => toast.classList.remove("show"), 3000); }

        function checkAuth() {
            if (!userData) {
                showToast("लॉगिन आवश्यक है!");
                if (window.google) google.accounts.id.prompt();
            } else {
                let badge = document.getElementById("strikeBadge");
                if (badge.innerText === "X") {
                    return showToast("🚨 आप ब्लॉक हैं! आप न्यूज़ पब्लिश नहीं कर सकते।");
                }
                document.getElementById("headInput").value = "";
                document.getElementById("publishOverlay").style.display = 'flex';
            }
        }

        function loadSkeletons() { document.getElementById("loadingState").style.display = "block"; let h = ""; for (let i = 0; i < 4; i++) { h += `<div class="skeleton-strip"><div class="skeleton-img skeleton"></div><div style="flex:1; display:flex; flex-direction:column; justify-content:center;"><div class="skeleton-text skeleton" style="width:90%"></div><div class="skeleton-text skeleton" style="width:60%"></div></div></div>`; } document.getElementById("newsContainer").innerHTML = h; }

        async function fetchNews() {
            loadSkeletons();
            const urlParams = new URLSearchParams(window.location.search);
            const newsId = urlParams.get('news') || "";
            try {
                const res = await fetch(`${API_URL}?action=getNews&lat=${userLoc.lat}&lon=${userLoc.lon}&range=${selectedRange}&newsId=${newsId}`);
                const responseText = await res.text();
                if (responseText === "blocked") { document.getElementById("loadingState").style.display = "none"; document.getElementById("newsContainer").innerHTML = `<h3 style="text-align:center; color:red; margin-top:50px;">नियमों का उल्लंघन करने के कारण आपका अकाउंट ब्लॉक कर दिया गया है।</h3>`; return; }
                allNewsData = JSON.parse(responseText);
                document.getElementById("loadingState").style.display = "none";
                renderNews(allNewsData);
                if (newsId) { const sharedNews = allNewsData.find(n => n.id == newsId); if (sharedNews) { showDetail(sharedNews); window.history.replaceState({}, document.title, window.location.pathname); } }
            } catch (e) { console.log(e); document.getElementById("loadingState").style.display = "none"; }
        }

        function filterNews(query) { let clearBtn = document.getElementById("clearSearch"); if (!query) { clearBtn.style.display = "none"; return renderNews(allNewsData); } clearBtn.style.display = "block"; let lowerQ = query.toLowerCase(); let filtered = allNewsData.filter(n => n.headline.toLowerCase().includes(lowerQ) || (n.locationName && n.locationName.toLowerCase().includes(lowerQ)) || (n.text && n.text.toLowerCase().includes(lowerQ))); renderNews(filtered); }
        function clearSearchField() { document.getElementById("searchInput").value = ""; filterNews(""); }

        function renderNews(data) {
            const container = document.getElementById("newsContainer");
            container.innerHTML = "";
            if (data.length === 0) { container.innerHTML = `<h3 style="text-align:center; color:var(--gray); margin-top:50px; line-height: 1.6;"> कोई खबर नहीं मिली।<br> <span style="font-size: 16px;">आप खुद अपने आस-पास की खबरों को यहाँ पब्लिश कर सकते हैं।</span><br> <span style="font-size: 14px;">न्यूज़ पोस्ट करने के लिए नीचे <b style="color:var(--primary); font-size:20px;">【+】</b> आइकॉन वाले बटन पर क्लिक कीजिए।</span> </h3>`; return; }
            data.forEach((item, index) => {
                let thumb = item.image ? `<img class="strip-img" src="${item.image}">` : `<div class="strip-img" style="display:flex; align-items:center; justify-content:center; font-size:30px;">📰</div>`;
                const strip = document.createElement("div");
                strip.className = "newsStrip"; strip.id = "strip_" + item.id;
                strip.innerHTML = `${thumb} <div class="strip-content"> <div class="headlineText">${item.headline}</div> <div class="strip-meta"> <div class="meta-box left"><span class="meta-label">लोकेशन</span><span class="meta-item locTag"><span style="display:inline-block; max-width:100%; overflow:hidden; text-overflow:ellipsis;">${item.locationName}</span></span></div> <div class="meta-box center"><span class="meta-label">व्यूज़</span><span class="meta-item viewsTag" id="stripView_${item.id}">${formatNumber(item.views)}</span></div> <div class="meta-box right"><span class="meta-label">समय</span><span class="meta-item timeTag" id="stripTime_${item.id}">${getTimeAgo(item.time)}</span></div> </div> </div>`;
                strip.onclick = () => showDetail(item);
                container.appendChild(strip);
                if ((index + 1) % 5 === 0) { insertAdStrip(container); }
            });
            if (data.length > 0 && data.length < 5) { insertAdStrip(container); }
        }

        function insertAdStrip(container) { let randomAd = adList[Math.floor(Math.random() * adList.length)]; let adEl = document.createElement("a"); adEl.className = "ad-strip dynamic-ad"; adEl.href = randomAd.url; adEl.target = "_blank"; adEl.innerHTML = `<span class="ad-label">SPONSORED</span><img class="ad-img" src="${randomAd.img}">`; container.appendChild(adEl); }
        function startAdRotation() { setInterval(() => { document.querySelectorAll('.dynamic-ad .ad-img').forEach(img => { let newAd = adList[Math.floor(Math.random() * adList.length)]; img.src = newAd.img; if (img.closest('a')) img.closest('a').href = newAd.url; }); }, 4000); }

        function showDetail(item) {
            currentId = item.id; document.getElementById("pImg").src = item.photo; document.getElementById("pName").innerText = item.username; document.getElementById("pTime").innerText = "📍 " + item.locationName; document.getElementById("pHeadline").innerText = item.headline;
            if (item.hideBlueTick) { document.getElementById("verifiedBadge").style.display = "none"; } else { document.getElementById("verifiedBadge").style.display = "inline-block"; }
            let contentHTML = "";
            if (item.isEdited) { contentHTML += `<span class="edited-tag">Edited</span> `; }
            contentHTML += item.text.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank">$1</a>');
            document.getElementById("pContent").innerHTML = contentHTML;

            clearInterval(editInterval);
            let editBtn = document.getElementById("editNewsBtn"); let delBtn = document.getElementById("deleteNewsBtn"); let timerText = document.getElementById("editTimerText");
            if (userData && userData.email === item.email) {
                delBtn.style.display = "block";
                let updateTimer = () => {
                    let timeLeft = (item.time + 5 * 60 * 1000) - Date.now();
                    if (timeLeft <= 0) { editBtn.style.display = "none"; clearInterval(editInterval); } else { editBtn.style.display = "block"; let m = Math.floor(timeLeft / 60000); let s = Math.floor((timeLeft % 60000) / 1000); timerText.innerText = `(${m}:${s < 10 ? '0' : ''}${s} शेष)`; }
                };
                updateTimer(); editInterval = setInterval(updateTimer, 1000);
            } else { editBtn.style.display = "none"; delBtn.style.display = "none"; }

            document.getElementById("pImages").innerHTML = item.image ? `<div class="premium-frame"><img src="${item.image}"></div>` : "";
            let exactDateObj = new Date(item.time); let exactOptions = { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }; document.getElementById("pExactTime").innerText = exactDateObj.toLocaleString('en-IN', exactOptions);
            let bottomAd = adList[Math.floor(Math.random() * adList.length)]; document.getElementById("bottomAdContainer").innerHTML = `<a class="ad-strip dynamic-ad" href="${bottomAd.url}" target="_blank" style="margin: 0; display: block; text-decoration: none; background: #fffbe6; border: 1px solid #ffe58f; border-radius: 4px; padding: 4px;"> <span class="ad-label" style="font-size: 5px; color: #d48806; font-weight: bold; margin-bottom: 4px; display: block; text-align: center;">SPONSORED</span> <img class="ad-img" src="${bottomAd.img}" style="width: 100%; height: 100%; border-radius: 2px; object-fit: 100% 100%;"> </a>`;
            document.getElementById("detailOverlay").style.display = "flex"; fetch(`${API_URL}?action=addView&id=${item.id}`); item.views = Number(item.views) + 1; document.getElementById("pViews").innerText = formatNumber(item.views) + " Views"; let stripView = document.getElementById("stripView_" + item.id); if (stripView) stripView.innerText = "" + formatNumber(item.views); document.getElementById("detailPopupContent").scrollTop = 0;
        }

        let isReading = false;
        function toggleReader() { let btn = document.getElementById("ttsBtn"); if (isReading) { window.speechSynthesis.cancel(); isReading = false; btn.innerHTML = "🔊"; return; } let textToRead = document.getElementById("pHeadline").innerText + ". " + document.getElementById("pContent").innerText; let speech = new SpeechSynthesisUtterance(textToRead); speech.lang = 'hi-IN'; speech.rate = 0.9; speech.onend = () => { isReading = false; btn.innerHTML = "🔊"; }; speech.onerror = () => { isReading = false; btn.innerHTML = "🔊"; }; isReading = true; btn.innerHTML = "🔇"; window.speechSynthesis.speak(speech); }
        function getTimeAgo(ts) { let diff = Math.floor((new Date().getTime() - ts) / 1000); if (diff < 60) return diff + "s ago"; if (diff < 3600) return Math.floor(diff / 60) + "m ago"; return Math.floor(diff / 3600) + "h ago"; }
        function formatNumber(v) { if (v >= 1000) return (v / 1000).toFixed(1) + "K"; return v; }
        function closePopup(e, id) { if (e.target.id === id) closeWithAnimation(id); }
        function closeWithAnimation(id) { window.speechSynthesis.cancel(); isReading = false; clearInterval(editInterval); if (document.getElementById("ttsBtn")) document.getElementById("ttsBtn").innerHTML = "🔊"; let popup = document.querySelector(`#${id} .popup`); popup.style.animation = "slideDown 0.3s ease-in forwards"; setTimeout(() => { document.getElementById(id).style.display = 'none'; popup.style.animation = "slideUp 0.3s ease-out"; }, 280); }
        
        function shareNews() { let shareUrl = window.location.href.split('?')[0] + "?news=" + currentId; let title = document.getElementById("pHeadline").innerText; if (navigator.share) { navigator.share({ title: 'BaithKee News Local Updates', text: title, url: shareUrl }); } else { navigator.clipboard.writeText(shareUrl); showToast("लिंक कॉपी हो गया!"); } }

        async function reportNews() { if (!userData) { showToast("लॉगिन करें!"); return; } showToast("रिपोर्ट दर्ज़ की जा रही है..."); await fetch(`${API_URL}?action=report&id=${currentId}&email=${userData.email}`); showToast("धन्यवाद! न्यूज़ को रिपोर्ट कर दिया गया है।"); closeWithAnimation("detailOverlay"); }
        function updateRange() { selectedRange = document.getElementById("rangeSlider").value; closeWithAnimation("rangeOverlay"); fetchNews(); }

        function previewSingleImage(e) { const file = e.target.files[0]; if (!file) return; document.getElementById("uploadLabel").innerText = "⏳ फोटो प्रोसेस हो रही है..."; let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = (event) => { let img = new Image(); img.src = event.target.result; img.onload = () => { let canvas = document.createElement('canvas'); let MAX_WIDTH = 400; let scale = img.width > MAX_WIDTH ? (MAX_WIDTH / img.width) : 1; canvas.width = img.width * scale; canvas.height = img.height * scale; let ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); base64Image = canvas.toDataURL('image/jpeg', 0.4); document.getElementById("imgPreviewArea").innerHTML = `<img src="${base64Image}" style="width:100px; height:100px; object-fit:cover; border-radius:12px; border: 2px solid var(--primary);">`; document.getElementById("uploadLabel").innerText = "✅ फोटो सेलेक्ट हो गई"; }; }; }

        async function publishNews() {
            const head = document.getElementById("headInput").value; const body = document.getElementById("bodyInput").value; const loc = document.getElementById("locInput").value;
            if (!head || !body || !loc) return showToast("Headline, Details aur Location भरना जरूरी है!");
            document.getElementById("submitBtn").disabled = true; document.getElementById("submitText").innerText = "खबर पब्लिश हो रही है..."; document.getElementById("submitLoader").style.display = "block";
            const payload = { action: editingNewsId ? "editNews" : "postNews", id: editingNewsId, headline: head, text: body, imageUrl: base64Image, locationName: loc, username: userData.name, email: userData.email, photo: userData.photo, latitude: userLoc.lat, longitude: userLoc.lon };
            try {
                let res = await fetch(API_URL, { method: "POST", body: JSON.stringify(payload) });
                let text = await res.text();
                if (text === "blocked") {
                    showToast("🚨 आपका अकाउंट ब्लॉक है। आप पोस्ट नहीं कर सकते!");
                } else {
                    showToast(editingNewsId ? "खबर अपडेट हो गई!" : "खबर पब्लिश हो गई");
                    document.getElementById("headInput").value = ""; document.getElementById("bodyInput").value = ""; document.getElementById("locInput").value = ""; document.getElementById("imgInput").value = ""; document.getElementById("imgPreviewArea").innerHTML = ""; document.getElementById("uploadLabel").innerText = "📸 1 फोटो चुनें (Optional)"; base64Image = ""; editingNewsId = null;
                }
            } catch (err) { console.log(err); showToast("Process में दिक्कत आई!"); }
            document.getElementById("submitBtn").disabled = false; document.getElementById("submitText").innerText = "खबर पब्लिश करें"; document.getElementById("submitLoader").style.display = "none";
            closeWithAnimation("publishOverlay"); fetchNews();
        }

        function openEditMode() { let item = allNewsData.find(n => n.id === currentId); if (!item) return; document.getElementById("headInput").value = item.headline; document.getElementById("bodyInput").value = item.text; document.getElementById("locInput").value = item.locationName; if (item.image) { base64Image = item.image; document.getElementById("imgPreviewArea").innerHTML = `<img src="${item.image}" style="width:100px; height:100px; object-fit:cover; border-radius:12px; border: 2px solid var(--primary);">`; document.getElementById("uploadLabel").innerText = "✅ पुरानी फोटो लोडेड (बदलने के लिए क्लिक करें)"; } else { base64Image = ""; document.getElementById("imgPreviewArea").innerHTML = ""; document.getElementById("uploadLabel").innerText = "📸 1 फोटो चुनें (Optional)"; } editingNewsId = item.id; document.getElementById("submitText").innerText = "अपडेट करें"; closeWithAnimation('detailOverlay'); setTimeout(() => { document.getElementById("publishOverlay").style.display = 'flex'; }, 300); }
        function askDeleteConfirm() { document.getElementById("deleteConfirmOverlay").style.display = "flex"; }
        function closeDeleteConfirm() { document.getElementById("deleteConfirmOverlay").style.display = "none"; }
        async function proceedToDelete() { closeDeleteConfirm(); showToast("न्यूज़ डिलीट की जा रही है..."); document.getElementById("deleteNewsBtn").innerText = "⏳..."; try { let res = await fetch(`${API_URL}?action=deleteNews&id=${currentId}&email=${userData.email}`); let text = await res.text(); if (text === "deleted") { showToast("न्यूज़ सफलतापूर्वक डिलीट हो गई!"); closeWithAnimation('detailOverlay'); fetchNews(); } else { showToast("एरर: न्यूज़ डिलीट नहीं हो पाई।"); } } catch (e) { showToast("सर्वर एरर!"); } document.getElementById("deleteNewsBtn").innerHTML = "🗑️ डिलीट करें"; }

        let deferredPrompt; window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); deferredPrompt = e; setTimeout(() => { document.getElementById('installBanner').style.display = 'block'; }, 2000); });
        document.getElementById('downloadAppBtn').addEventListener('click', async () => { document.getElementById('installBanner').style.display = 'none'; if (deferredPrompt) { deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; deferredPrompt = null; } });
        window.onclick = function(event) { if (!event.target.closest('.brand-menu')) { const brandDrop = document.getElementById('brandDropdown'); if (brandDrop && brandDrop.style.display === 'block') brandDrop.style.display = 'none'; } if (!event.target.closest('.user-menu')) { const profileDrop = document.getElementById('profileDropdown'); if (profileDrop && profileDrop.style.display === 'block') profileDrop.style.display = 'none'; } };
        setInterval(() => { if (allNewsData && allNewsData.length > 0) { allNewsData.forEach(item => { let timeElement = document.getElementById("stripTime_" + item.id); if (timeElement) { timeElement.innerText = getTimeAgo(item.time); } }); } }, 1000);

        function toggleTheme() { let body = document.body; let btn = document.getElementById("themeToggleBtn"); body.classList.toggle("dark-mode"); let isDark = body.classList.contains("dark-mode"); localStorage.setItem("localupdates_theme", isDark ? "dark" : "light"); btn.innerText = isDark ? "☀️ लाइट मोड" : "🌚 डार्क मोड"; }
        let savedTheme = localStorage.getItem("localupdates_theme"); if (savedTheme === "dark") { document.body.classList.add("dark-mode"); document.getElementById("themeToggleBtn").innerText = "☀️ लाइट मोड"; }

        function shareApplication() { const appUrl = "https://baithkeenews.blogspot.com"; const shareText = "🎤 आप खुद बनें रिपोर्टर: कहीं कुछ गलत हो रहा है या कोई अच्छा काम हुआ है? बस 1 क्लिक करें और अपनी ख़बर फोटो के साथ खुद पब्लिश करें\n\nसिर्फ सच्ची ख़बरें: कोई अफवाह या फालतू अलर्ट नहीं, सिर्फ आपके एरिया की काम की बातें।\n\nतो इंतज़ार किस बात का? आज ही अपने लोकल नेटवर्क से जुड़ें और अपनी आवाज़ को एक नई ताक़त दें। 👇 नीचे दिए गए लिंक पर *क्लिक करें* और *BaithKee News* - Local Updates से अभी जुड़ें:\n\n" + appUrl; let whatsappUrl = `https://wa.me/?text=${encodeURIComponent(shareText)}`; window.open(whatsappUrl, '_blank'); }
    </script>
</body>
</html>

```
इस अपडेट के बाद आपका ऐप नोटिफिकेशन और सिक्योरिटी के मामले में 100% परफेक्ट हो जाएगा। इसे लाइव करें और मुझे बताएं कि प्रोफाइल पर दिखने वाला 'रेड बैज' (Strike) कैसा लग रहा है!

इस ब्लॉग से लोकप्रिय पोस्ट

The History of the World – A Simple and Long Article for English Learners

High Level Advance Random English Words

1. The Art of Self-Discipline