function loadFirebaseScripts(){return new Promise((n,t)=>{const i=document.createElement("script"),r=document.createElement("script");i.src="https://www.gstatic.com/firebasejs/11.0.2/firebase-app-compat.js";r.src="https://www.gstatic.com/firebasejs/11.0.2/firebase-messaging-compat.js";i.onload=()=>{document.body.appendChild(r),r.onload=n,r.onerror=t};i.onerror=t;document.body.appendChild(i)})}async function initializeFirebase(){try{await loadFirebaseScripts();firebase.initializeApp(FIREBASE_CONFIG);return firebase.messaging()}catch(n){console.error("Failed to load Firebase scripts:",n);throw n;}}async function registerServiceWorker(){if("serviceWorker"in navigator)try{const t=await navigator.serviceWorker.getRegistrations();for(let n of t)n.scope.includes("firebase-cloud-messaging-push-scope")&&await n.unregister();const n=await navigator.serviceWorker.getRegistration("/firebase-messaging-sw.js");if(n)return n;return await navigator.serviceWorker.register(`/firebase-messaging-sw.js?v=${SW_VERSION}`)}catch(n){console.error("Service Worker registration failed:",n);throw n;}else console.error("Service Workers are not supported in this browser.")}function urlBase64ToUint8Array(n){const r="=".repeat((4-n.length%4)%4),u=(n+r).replace(/\-/g,"+").replace(/_/g,"/"),t=window.atob(u),i=new Uint8Array(t.length);for(let n=0;n<t.length;++n)i[n]=t.charCodeAt(n);return i}async function checkExistingToken(n,t){try{const r=urlBase64ToUint8Array(VAPID_PUBLIC_KEY),i=await n.getToken({vapidKey:VAPID_PUBLIC_KEY,serviceWorkerRegistration:t});return i?(await sendTokenToServer(i),i):null}catch(i){console.error("Error retrieving FCM token:",i);throw i;}}async function requestNotificationPermission(n,t){const i=document.querySelector(".notification-overlay");i&&(i.style.display="none");try{if(!firebase.messaging.isSupported()){alert("Push Notification is not supported in this browser.");localStorage.setItem("fcm_token","Not Supported");localStorage.setItem("hideNotification",(new Date).toISOString());return}let i="";if(Notification.permission!="granted"&&(i=await Notification.requestPermission()),i==="granted"){const i=await n.getToken({vapidKey:VAPID_PUBLIC_KEY,serviceWorkerRegistration:t});i?await sendTokenToServer(i):console.error("Failed to retrieve FCM token.")}else console.error("Notification permission denied.")}catch(r){console.error("An error occurred while requesting notification permission:",r)}}async function sendTokenToServer(n){const t=localStorage.getItem("fcm_token");if(t!==n)try{const t=await fetch("/pushnotification/savetoken",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:n})});if(t.ok){const i=await t.json();i.NotificationId>0&&localStorage.setItem("notificationId",i.NotificationId);localStorage.setItem("fcm_token",n);localStorage.setItem("hideNotification",(new Date).toISOString())}else console.error("Failed to send FCM Token to server:",await t.text())}catch(i){console.error("An error occurred while sending token to server:",i)}}function maybeLaterNotificationPermission(){localStorage.setItem("hideNotification",(new Date).toISOString());const n=document.querySelector(".notification-overlay");n&&(n.style.display="none")}async function updateSubscriptionButtonUI(){const n=document.getElementById("subscribeButton"),t=document.getElementById("message");Notification.permission==="granted"?(n.disabled=!0,n.textContent="Already Subscribed",t.textContent="You have already subscribed to notifications."):Notification.permission==="denied"?(n.disabled=!0,n.textContent="Notifications Blocked",t.textContent="You have blocked notifications. Please enable them in browser settings."):(n.disabled=!1,n.textContent="Subscribe to Notifications",t.textContent="")}function handleForegroundMessages(){return!1}function handleStandaloneAppNavigation(){(navigator.standalone||window.matchMedia("(display-mode: standalone)").matches)&&document.addEventListener("DOMContentLoaded",()=>{navigator.serviceWorker.addEventListener("notificationclick",handleNotificationClick)})}function handleNotificationClick(n){n.notification.close();const t=n.notification.data?.url||"/";n.waitUntil(clients.matchAll({type:"window",includeUncontrolled:!0}).then(n=>{const i=n.find(n=>n.url===t);i?(i.window.url=t,i.focus()):clients.openWindow(t)}))}async function setupFCM(){try{const n=await initializeFirebase(),t=await registerServiceWorker();if(!VAPID_PUBLIC_KEY)throw new Error("VAPID_PUBLIC_KEY is not configured");if(Notification.permission==="granted")try{await checkExistingToken(n,t)}catch(i){console.warn("Failed to retrieve existing token:",i)}else window.requestPermission=async function(){await requestNotificationPermission(n,t)};handleStandaloneAppNavigation()}catch(n){console.error("Failed to set up FCM:",n)}}const VAPID_PUBLIC_KEY="BFxMftKB2D8lBOwyed3qjSujh8sjL7chpxHIOYX47m-x0YntEAy47V0WlqGFvE7uaMWZK9yZJm7mn72cuIpwB6g",FIREBASE_CONFIG={apiKey:"AIzaSyB9hgi5H38t4HutIEgQTa-kSH5-xM0DqoA",authDomain:"indiaforums-webpush.firebaseapp.com",projectId:"indiaforums-webpush",storageBucket:"indiaforums-webpush.firebasestorage.app",messagingSenderId:"737132450189",appId:"1:737132450189:web:d89e49cc7352a656bdadc4",measurementId:"G-WBC5WSFVXT"},SW_VERSION="1.0.32";setupFCM().catch(n=>{console.error("FCM setup failed:",n)});
