const firebaseConfig={apiKey:"AIzaSyBPJOeXNTo9WWEXKO4YYZ0Hl6n5hzQltfo",authDomain:"leadsagent-43461.firebaseapp.com",projectId:"leadsagent-43461",storageBucket:"leadsagent-43461.firebasestorage.app",messagingSenderId:"888240019238",appId:"1:888240019238:web:6a0a9ba957c8248ca093e7",measurementId:"G-G2L0947KHP",databaseId:"leadsagent"};let firebaseApp=null,firebaseAuth=null;async function initializeFirebase(){try{return firebaseApp||(firebaseApp=firebase.initializeApp(firebaseConfig),firebaseAuth=firebase.auth(),await firebaseAuth.setPersistence(firebase.auth.Auth.Persistence.NONE),setupAuthStateListener()),!0}catch(e){return!1}}function setupAuthStateListener(){firebaseAuth.onAuthStateChanged(async e=>{e&&(await saveUserData(e),notifyContentScripts({type:"AUTH_STATE_CHANGED",isAuthenticated:!0,user:await getUserDataObject(e)}))})}async function signInWithCredential(e){try{firebaseAuth||await initializeFirebase();const t=firebase.auth.GoogleAuthProvider.credential(null,e);await firebaseAuth.setPersistence(firebase.auth.Auth.Persistence.NONE);const a=await firebaseAuth.signInWithCredential(t);try{const e=await a.user.getIdToken();await initializeUserOnServer(a.user.uid,a.user.email,e)}catch(e){}return"undefined"!=typeof isProManager?await isProManager.init(a.user.uid,!0):"undefined"!=typeof isProManagerV2&&await isProManagerV2.init(a.user.uid,!0),await saveUserData(a.user),{success:!0,user:await getUserDataObject(a.user)}}catch(e){return{success:!1,error:e.message}}}async function signOut(){try{return await firebaseAuth.signOut(),await clearUserData(),"undefined"!=typeof isProManager&&await isProManager.clearCache(),{success:!0}}catch(e){return{success:!1,error:"Failed to sign out. Please try again."}}}async function checkAuthState(){try{const e=firebaseAuth.currentUser;if(e)return await saveUserData(e),{isAuthenticated:!0,user:await getUserDataObject(e)};{const e=await loadUserData();return e&&e.isAuthenticated&&e.uid?{isAuthenticated:!0,user:e}:{isAuthenticated:!1,user:null}}}catch(e){return{isAuthenticated:!1,user:null}}}async function getUserDataObject(e){return{uid:e.uid,email:e.email,displayName:e.displayName||"User",photoURL:e.photoURL||"",emailVerified:e.emailVerified,isAuthenticated:!0,createdAt:e.metadata.creationTime,lastLoginAt:e.metadata.lastSignInTime,savedAt:(new Date).toISOString()}}async function saveUserData(e){try{const t=await getUserDataObject(e);await chrome.storage.local.set({user:t})}catch(e){}}async function initializeUserOnServer(e,t,a){try{const i="https://leadsagent.io",s={"Content-Type":"application/json"};a&&(s.Authorization=`Bearer ${a}`);const r=await fetch(`${i}/api/subscriptions/init-user`,{method:"POST",headers:s,body:JSON.stringify({uid:e,email:t})}),n=await r.json();if(!r.ok)throw new Error(n.error||`HTTP ${r.status}`);return n}catch(e){throw e}}async function loadUserData(){try{const e=await chrome.storage.local.get("user");return e.user?e.user:null}catch(e){return null}}async function clearUserData(){try{await chrome.storage.local.remove(["user","auth_user","token","user_subscription_cache_v2","isProUIStatus","userPlan","subscription_plan","leadsExtracted","leadsRemaining"])}catch(e){}}async function verifyPremiumSubscription(e){return{isPremium:!1,subscriptionTier:"free",leadsQuota:50,expiresAt:null}}async function syncUserWithBackend(e){return e}function notifyContentScripts(e){chrome.tabs.query({},t=>{t.forEach(t=>{chrome.tabs.sendMessage(t.id,e).catch(()=>{})})})}async function handleAuthMessage(e,t,a){switch(e.action){case"firebaseSignIn":a(await signInWithCredential(e.token));break;case"signOut":a(await signOut());break;case"checkAuthState":a(await checkAuthState());break;case"getUserData":a({user:await loadUserData()});break;case"getIdToken":try{let e=firebaseAuth?firebaseAuth.currentUser:null;if(!e){const t=await loadUserData();if(t&&t.isAuthenticated){const t=await new Promise(e=>{chrome.identity.getAuthToken({interactive:!1},t=>{e({token:t,error:chrome.runtime.lastError})})});t.token&&(await signInWithCredential(t.token),e=firebaseAuth?firebaseAuth.currentUser:null)}}a(e?{success:!0,token:await e.getIdToken()}:{success:!1,error:"No authenticated user"})}catch(e){a({success:!1,error:e.message})}break;default:a({error:"Unknown action"})}return!0}const AuthModule={initializeFirebase:initializeFirebase,signInWithCredential:signInWithCredential,signOut:signOut,checkAuthState:checkAuthState,handleAuthMessage:handleAuthMessage,loadUserData:loadUserData,saveUserData:saveUserData,clearUserData:clearUserData};"undefined"!=typeof self&&(self.AuthModule=AuthModule),"undefined"!=typeof window&&(window.AuthModule=AuthModule);