1import{J as W}from"./chunk-BVYE6SD7.js";import{a as $,b as K}from"./chunk-JBS34XJW.js";import{B as O,C as V,b as z,gb as x,pb as F,tc as Y,y as M}from"./chunk-LWDTIRCY.js";import{b as G}from"./chunk-KI3OGBFQ.js";import{a as T,b as E,d as B,e as g}from"./chunk-JHI3MBHO.js";var k={lite:{adsPerMonth:30,stockVideosPerDay:4,aiVideosPerDay:2,pureAiVideosPerDay:0,maxDuration:60,hdExport:!0,noWatermark:!0,priorityProcessing:!1,premiumVoices:!1},free:{adsPerMonth:12,adsPerWeek:3,videosPerWeek:1,imagesPerWeek:2,stockVideosPerDay:3,aiVideosPerDay:3,pureAiVideosPerDay:0,maxDuration:30,hdExport:!1,noWatermark:!1,priorityProcessing:!1,premiumVoices:!1,isMonthly:!0},pro:{adsPerMonth:60,stockVideosPerDay:8,aiVideosPerDay:4,pureAiVideosPerDay:0,maxDuration:60,hdExport:!0,noWatermark:!0,priorityProcessing:!1,premiumVoices:!0},premium:{adsPerMonth:120,stockVideosPerDay:25,aiVideosPerDay:8,pureAiVideosPerDay:0,maxDuration:75,hdExport:!0,noWatermark:!0,priorityProcessing:!0,premiumVoices:!0}},U=[{id:"free",name:"free",displayName:"SUBSCRIPTION.PLAN_FREE",price:0,currency:"INR",duration:"forever",features:[{key:"SUBSCRIPTION.FEATURE_AD_STUDIO_FREE"},{key:"SUBSCRIPTION.FEATURE_ALL_FORMATS"},{key:"SUBSCRIPTION.FEATURE_STD_720P"},{key:"SUBSCRIPTION.FEATURE_BASIC_VOICES"},{key:"SUBSCRIPTION.FEATURE_WATERMARK"},{key:"SUBSCRIPTION.FEATURE_COMMUNITY_SUPPORT"}],limits:k.free},{id:"lite",name:"lite_monthly",displayName:"SUBSCRIPTION.PLAN_LITE",price:1249,currency:"INR",duration:"monthly",badge:"SUBSCRIPTION.BADGE_STARTER",features:[{key:"SUBSCRIPTION.FEATURE_AD_STUDIO_LITE"},{key:"SUBSCRIPTION.FEATURE_BRAND_KIT",isNew:!0},{key:"SUBSCRIPTION.FEATURE_NO_WATERMARK"},{key:"SUBSCRIPTION.FEATURE_HD_1080P"},{key:"SUBSCRIPTION.FEATURE_AD_VOICEOVER"},{key:"SUBSCRIPTION.FEATURE_ALL_FORMATS"},{key:"SUBSCRIPTION.FEATURE_EMAIL_SUPPORT"}],limits:k.lite},{id:"pro",name:"pro_monthly",displayName:"SUBSCRIPTION.PLAN_PRO",price:2399,currency:"INR",duration:"monthly",isPopular:!0,badge:"SUBSCRIPTION.BADGE_POPULAR",features:[{key:"SUBSCRIPTION.FEATURE_AD_STUDIO_PRO"},{key:"FEATURE_REAL_PRODUCT",isNew:!0},{key:"FEATURE_MOTION_HERO",isNew:!0},{key:"SUBSCRIPTION.FEATURE_RESEARCH_ANGLES",isNew:!0},{key:"SUBSCRIPTION.FEATURE_AD_DOCTOR",isNew:!0},{key:"SUBSCRIPTION.FEATURE_MULTIFORMAT",isNew:!0},{key:"SUBSCRIPTION.FEATURE_BRAND_KIT"},{key:"SUBSCRIPTION.FEATURE_AD_VOICEOVER"},{key:"SUBSCRIPTION.FEATURE_HD_1080P"},{key:"SUBSCRIPTION.FEATURE_NO_WATERMARK"}],limits:k.pro},{id:"premium",name:"premium_monthly",displayName:"SUBSCRIPTION.PLAN_PREMIUM",price:4799,currency:"INR",duration:"monthly",badge:"SUBSCRIPTION.BADGE_BEST_VALUE",features:[{key:"SUBSCRIPTION.FEATURE_AD_STUDIO_PREMIUM"},{key:"FEATURE_REAL_PRODUCT",isNew:!0},{key:"FEATURE_MOTION_HERO",isNew:!0},{key:"SUBSCRIPTION.FEATURE_BRAND_KITS",isNew:!0},{key:"SUBSCRIPTION.FEATURE_ALL_PRO"},{key:"SUBSCRIPTION.FEATURE_MULTIFORMAT"},{key:"SUBSCRIPTION.FEATURE_HD_1080P"},{key:"SUBSCRIPTION.FEATURE_NO_WATERMARK"},{key:"SUBSCRIPTION.FEATURE_PRIORITY_SUPPORT"},{key:"SUBSCRIPTION.FEATURE_EARLY_ACCESS"}],limits:k.premium}],_=[{id:"lite",name:"lite_yearly",displayName:"SUBSCRIPTION.PLAN_LITE_YEARLY",price:12499,currency:"INR",duration:"yearly",badge:"SUBSCRIPTION.BADGE_SAVE_44",features:U[1].features,limits:k.lite},{id:"pro",name:"pro_yearly",displayName:"SUBSCRIPTION.PLAN_PRO_YEARLY",price:23999,currency:"INR",duration:"yearly",isPopular:!0,badge:"SUBSCRIPTION.BADGE_SAVE_30",features:U[2].features,limits:k.pro},{id:"premium",name:"premium_yearly",displayName:"SUBSCRIPTION.PLAN_PREMIUM_YEARLY",price:47999,currency:"INR",duration:"yearly",badge:"SUBSCRIPTION.BADGE_SAVE_30",features:U[3].features,limits:k.premium}];function D(A){return k[A]||k.free}function N(A){let C={tier:"free",plan:"free",status:"active",stockVideosUsedToday:0,aiVideosUsedToday:0,pureAiVideosUsedToday:0,lastResetDate:new Date().toISOString()};return A!==void 0&&(C.userId=A),C}var b=G("Purchases",{web:()=>import("./chunk-FIRYZHU3.js").then(A=>new A.PurchasesWeb)});var pe=(()=>{let C=class C{constructor(e,t,i){this.platform=e,this.http=t,this.alertController=i,this.subscriptionSubject=ne
1w z(null),this.subscription$=this.subscriptionSubject.asObservable(),this.apiUrl=$.apiUrl,this.razorpayKey="rzp_live_TB4xfXL7JzR0zM",this.revenueCatKey=$.revenueCatKey||$.revenueCatKeyTest||"",this.TRIAL_ENABLED=!1,this.USD_PRICES={lite_monthly:14.99,lite_yearly:149.99,pro_monthly:29.99,pro_yearly:299.99,premium_monthly:59.99,premium_yearly:599.99},this._videosCache=null,this._videosCacheTTL=3e4,this.authService=V(K),this.router=V(F),this.rcIdentifiedFor=null,this._refreshInProgress=!1,this.loadSubscription(),this.initializeRevenueCat(),this.checkDailyReset();let r;this.authService.currentUser$.subscribe(o=>{if(o){if(r!==o.id){o.id&&this.identifyRevenueCatUser(o.id);let s=N(o.id??void 0);s.tier=o.tier,o.subscriptionStatus&&(s.status=o.subscriptionStatus),this.saveSubscription(s),r=o.id}}else this.initializeFreeSubscription(),r=void 0,this.resetRevenueCatUser()})}identifyRevenueCatUser(e){return g(this,null,function*(){if(this.isWeb())return!0;let t=e??this.authService.currentUser?.id??null;if(!t)return!1;if(this.rcIdentifiedFor===t)return!0;for(let i=1;i<=3;i++){try{yield b.logIn({appUserID:String(t)});let r=(yield b.getAppUserID())?.appUserID||"";if(r&&!r.startsWith("$RCAnonymousID"))return this.rcIdentifiedFor=t,console.log("\u2705 RevenueCat logIn \u2192 appUserID="+r),!0}catch(r){console.warn(`RevenueCat logIn attempt ${i}/3 failed`,r)}yield new Promise(r=>setTimeout(r,1500*i))}return!1})}resetRevenueCatUser(){return g(this,null,function*(){if(!(this.isWeb()||this.rcIdentifiedFor===null)){try{yield b.logOut()}catch{}this.rcIdentifiedFor=null}})}isRevenueCatCancel(e){return String(e?.code)==="1"||e?.data?.userCancelled===!0||e?.userCancelled===!0||e?.data?.readableErrorCode==="PURCHASE_CANCELLED"}initializeRevenueCat(){return g(this,null,function*(){if(!this.isWeb()){try{let t=(yield b.getAppUserID())?.appUserID||null;if(t&&this.authService.isAuthenticated){let i=this.authService.getAuthToken();i&&this.http.post(`${this.apiUrl}/api/payment/revenuecat-identify`,{appUserId:t},{headers:{Authorization:`Bearer ${i}`}}).subscribe({next:()=>console.log("\u2705 RevenueCat appUserId mapped to user"),error:r=>console.warn("Could not map RevenueCat appUserId",r)})}}catch(e){console.warn("Could not fetch RevenueCat appUserID (SDK may not be configured yet)",e)}this.retryPendingActivation(),this.autoRecoverEntitlements()}})}
1autoRecoverEntitlements(){return g(this,null,function*(){try{if((this.authService.currentUser?.tier||"free")!=="free")return;let t=localStorage.getItem("pendingRestore");yield new Promise(S=>setTimeout(S,5e3));let i=yield b.restorePurchases(),o=(i?.customerInfo||i)?.entitlements?.active||{},s=o.premium?"premium":o.pro?"pro":o.lite?"lite":null;if(!s){t&&localStorage.removeItem("pendingRestore");return}let n=o[s],c=(n.productIdentifier||"").toLowerCase(),f=(/year|annual|yr/.test(c)?_:U).find(S=>S.id===s);if(!f)return;console.log(`\u{1F504} autoRecoverEntitlements: user is free but RevenueCat has active ${s} \u2014 activating`);let d=n?.expirationDate?new Date(n.expirationDate).getTime():null;this.activateSubscription(f,"google_play",n.productIdentifier||"",d);try{this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,{platform:this.platform.platforms(),planId:f.id,planName:f.name,errorMessage:`autoRecoverEntitlements: user was free but RevenueCat had active ${s} \u2014 auto-activated on startup`,userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,isAndroid:this.isAndroid()}).toPromise().catch(()=>{})}catch{}t&&localStorage.removeItem("pendingRestore")}catch(e){console.warn("autoRecoverEntitlements: failed (non-fatal)",e)}})}retryPendingActivation(){return g(this,null,function*(){try{let t=localStorage.getItem("pendingActivation");if(!t)return;let i=JSON.parse(t);if(!i.timestamp||Date.now()-i.timestamp>10080*60*1e3){localStorage.removeItem("pendingActivation");return}console.log("\u{1F504} Found pending activation \u2014 retrying backend call...");let r=this.authService.getAuthToken(),o={};r&&(o.Authorization=`Bearer ${r}`);let e=i,{email:s,userId:n,timestamp:c}=e,p=B(e,["email","userId","timestamp"]);yield this.http.post(`${this.apiUrl}/api/payment/revenuecat-activate`,p,{headers:o}).toPromise(),localStorage.removeItem("pendingActivation"),console.log("\u2705 Pending activation recovered successfully");try{yield this.refreshUserAfterPurchase()}catch{}}catch(t){console.warn("\u26A0\uFE0F Pending activation retry failed \u2014 will try again on next launch",t)}})}isWeb(){return!this.platform.is("capacitor")&&!this.platform.is("cordova")}isAndroid(){return this.platform.is("android")&&(this.platform.is("capacitor")||this.platform.is("cordova"))}isiOS(){return this.platform.is("ios")&&(this.platform.is("capacitor")||this.platform.is("cordova"))}loadSubscription(){let e=localStorage.getItem("clipnova_subscription");if(e)try{let t=JSON.parse(e);this.subscriptionSubject.next(t)}catch{this.initializeFreeSubscription()}else this.initializeFreeSubscription()}initializeFreeSubscription(){let e=N();this.saveSubscription(e)}saveSubscription(e){localStorage.setItem("clipnova_subscription",JSON.stringify(e)),this.subscriptionSubject.next(e)}updateSubscription(e){let t=this.getCurrentSubscription(),i=T(T({},t),e);this.saveSubscription(i)}getCurrentSubscription(){return this.subscriptionSubject.value||N()}getCurrentTier(){return this.getCurrentSubscription().tier}isPremiumUser(){let e=this.getCurrentTier();return e==="pro"||e==="premium"}isUnlimitedUser(){return this.getCurrentTier()==="premium"}getMaxDuration(){return D(this.getCurrentTier()).maxDuration||45}checkDailyReset(){let e=this.getCurrentSubscription();if(!e.lastResetDate)return;let t=new Date().toDateString(),i=new Date(e.lastResetDate).toDateString();if(t!==i){let r=D(e.tier);if(r.isMonthly||r.isLifetime){e.lastResetDate=new Date().toISOString(),this.saveSubscription(e);return}console.log("\u{1F4C5} Daily reset - resetting usage counters"),e.stockVideosUsedToday=0,e.aiVideosUsedToday=0,e.pureAiVideosUsedToday=0,e.lastResetDate=new Date().toISOString(),this.saveSubscription(e)}}ensureSubscriptionMatchesUser(){let e=this.getCurrentSubscription(),t=this.authService.currentUser;if(t&&e.userId!==t.id){console.log("\u{1F504} Subscription user mismatch detected, resetting counters");let i=N(t.id??void 0);i.tier=t.tier,this.saveSubscription(i)}}fetchUserVideosCached(){if(this._videosCache&&Date.now()-this._videosCache.ts<this._videosCacheTTL)return this._videosCache.data;try{let e=this.authService.getAuthToken();if(!e)return null;let t=new XMLHttpRequest;if(t.open("GET",`${this.apiUrl}/api/user/videos`,!1),t.setRequestHeader("Authorization",`Bearer ${e}`),t.send(null),t.status===200){let i=JSON.parse(t.responseText);return this._videosCache={data:i,ts:Date.now()},i}}catch{}return null}invalidateVideosCache(){this._videosCache=null}canGenerateVideo(){return this.canGenerateStockVideo()}canGenerateStockVideo(){this.ensureSubscriptionMatchesUser(),this.checkDailyReset();let e=this.getCurrentSubscription(),t=D(e.tier);if(this.authService.isAuthenticated)try{let r=this.fetchUserVideosCached();if(r){if((r.videosRemaining??0)>=9999)return{allowed:!0,remaining:9999};let o=new Date().toISOString().slice(0,10),s=new Date().toISOString().slice(0,7),n=t.isMonthly||t.isLifetime,c=r.subscriptionStatus||"";if(n&&c==="refunded")return{allowed:!1,reason:"Your subscription was refunded. Upgrade to create videos again!",remaining:0};let p=(r.videos||[]).filter(S=>{let I=S.video_type||"",a=I==="stock"||I==="stock-multi";return n?a&&S.created_at&&S.created_at.startsWith(s):a&&S.created_at&&S.created_at.startsWith(o)}),f=r.effectiveStockLimit??t.stockVideosPerDay,d=Math.max(0,f-p.length);return d<=0?{allowed:!1,reason:n?"You've used your free stock videos this week. Upgrade for unlimited!":`You've used all ${f} stock videos for today. Upgrade for more!`,remaining:0}:{allowed:!0,remaining:d}}}catch{}let i=t.stockVideosPerDay-e.stockVideosUsedToday;return i<=0?{allowed:!1,reason:`You've used all ${t.stockVideosPerDay} stock videos for today. Upgrade for more!`,remaining:0}:{allowed:!0,remaining:i}}canGenerateAIVideo(){this.ensureSubscriptionMatchesUser(),this.checkDailyReset();let e=this.getCurrentSubscription(),t=D(e.tier);if(this.authService.isAuthenticated){let r=0;try{let o=this.fetchUserVideosCached();if(o){if((o.videosRemaining??0)>=9999)return{allowed:!0,remaining:9999};let s=t.isMonthly||t.isLifetime,n=o.subscriptionStatus||"";if(s&&["refunded","cancelled","expired"].includes(n))return{allowed:!1,reason:"You've used your free AI videos this week. Upgrade to Pro for more!",remaining:0};let c=new Date().toISOString().slice(0,10),p=new Date(Date.now()-10080*60*1e3).toISOString().slice(0,10),f=(o.videos||[]).filter(I=>{let a=I.video_type||"",l=a==="quick"||a.startsWith("ai")||a==="pure-ai";return s?l&&I.created_at&&I.created_at.slice(0,10)>=p:l&&I.created_at&&I.created_at.startsWith(c)}),d=o.queued||0,S=o.effectiveAiLimit??t.aiVideosPerDay;if(r=Math.max(0,S-(f.length+d)),r<=0){let I=s?`You've used your ${S} free AI videos this week. Upgrade to Pro for more!`:`You've used all ${S} AI videos for today. Upgrade for more!`;return d>0&&(I=s?`You already have ${d} AI video queued. Free plan limit is ${S}/week.`:`You have ${d} AI video(s) queued. Daily limit is ${S}.`),{allowed:!1,reason:I,remaining:0}}return{allowed:!0,remaining:r}}}catch{}}let i=Math.max(0,t.aiVideosPerDay-e.aiVideosUsedToday);return i<=0?{allowed:!1,reason:`You've used all ${t.aiVideosPerDay} AI videos for today. Upgrade for more!`,remaining:0}:{allowed:!0,remaining:i}}canGeneratePureAIVideo(){this.checkDailyReset();let e=this.getCurrentSubscription(),i=D(e.tier).pureAiVideosPerDay??0;if(i===0)return{allowed:!1,reason:"Pure AI Video is a premium feature. Upgrade to access it!",remaining:0};let r=e.pureAiVideosUsedToday??0,o=i-r;return o<=0?{allowed:!1,reason:`You've used all ${i}
1 Pure AI videos for this month. Come back next month!`,remaining:0}:{allowed:!0,remaining:o}}useVideo(){return g(this,null,function*(){this.useStockVideo()})}useStockVideo(){this.checkDailyReset();let e=this.getCurrentSubscription(),t=D(e.tier);e.stockVideosUsedToday++,this.saveSubscription(e),this.invalidateVideosCache()}useAIVideo(){this.checkDailyReset();let e=this.getCurrentSubscription(),t=D(e.tier);e.aiVideosUsedToday++,this.saveSubscription(e),this.invalidateVideosCache()}usePureAIVideo(){this.checkDailyReset();let e=this.getCurrentSubscription();e.pureAiVideosUsedToday=(e.pureAiVideosUsedToday??0)+1,this.saveSubscription(e),this.invalidateVideosCache()}getRemainingVideos(){this.checkDailyReset();let e=this.getCurrentSubscription(),t=D(e.tier),i=t.isMonthly||t.isLifetime;if(this.authService.isAuthenticated){let s=0,n=0;try{let c=this.fetchUserVideosCached();if(c){if((c.videosRemaining??0)>=9999)return{stock:"\u221E",ai:"\u221E"};let p=c.subscriptionStatus||"";if(i&&["refunded","cancelled","expired"].includes(p)){let h=c.effectiveStockLimit??t.stockVideosPerDay;return{stock:p==="refunded"?0:Math.max(0,h-(c.videos||[]).filter(y=>y.video_type==="stock"||y.video_type==="stock-multi").length),ai:0}}let f=new Date().toISOString().slice(0,10),d=new Date().toISOString().slice(0,7),S=(c.videos||[]).filter(h=>{let u=h.video_type||"",y=u==="quick"||u.startsWith("ai")||u==="pure-ai";return i?y&&h.created_at&&h.created_at.startsWith(d):y&&h.created_at&&h.created_at.startsWith(f)}),I=(c.videos||[]).filter(h=>{let u=h.video_type||"",y=u==="stock"||u==="stock-multi";return i?y&&h.created_at&&h.created_at.startsWith(d):y&&h.created_at&&h.created_at.startsWith(f)}),a=c.queued||0,l=c.effectiveAiLimit??t.aiVideosPerDay,w=c.effectiveStockLimit??t.stockVideosPerDay;return s=Math.max(0,l-(S.length+a)),n=Math.max(0,w-I.length),{stock:n,ai:s,queuedCount:a}}}catch{return n=Math.max(0,t.stockVideosPerDay-e.stockVideosUsedToday),s=Math.max(0,t.aiVideosPerDay-e.aiVideosUsedToday),{stock:n,ai:s}}}let r=Math.max(0,t.stockVideosPerDay-e.stockVideosUsedToday),o=Math.max(0,t.aiVideosPerDay-e.aiVideosUsedToday);return{stock:r,ai:o}}getDailyLimits(){let e=this.getCurrentSubscription(),t=D(e.tier);return{stock:t.stockVideosPerDay,ai:t.aiVideosPerDay}}getPlans(e=!1){return e?_:U.filter(t=>t.id!=="free")}getAllPlans(){return U}initiatePurchase(e,t="INR"){return g(this,null,function*(){if(e==="pro_trial"&&this.TRIAL_ENABLED)return this.initiateTrialPayment();let r=[...U,..._].find(o=>o.name===e||o.id===e);if(!r)throw new Error("Plan not found");if(r.price===0)throw new Error("Cannot purchase free plan");if(this.isWeb()){if(t==="USD")try{return yield this.initiateDodoSubscription(r.name||e)}catch(o){console.warn("[dodo] unavailable, falling back to Razorpay",o)}try{return yield this.initiateRazorpayPayment(r,t)}catch(o){if(o?.status===409||o?.error?.useUsdRail)return console.warn("[pricing] INR refused for this country, switching to the USD rail"),yield this.initiateDodoSubscription(r.name||e);throw o}}else{if(this.isAndroid())return this.initiateGooglePlayPurchase(r);if(this.isiOS())return this.initiateApplePurchase(r);throw new Error("Platform not supported")}})}initiateTrialPayment(){return g(this,null,function*(){return new Promise((e,t)=>g(this,null,function*(){try{yield this.loadRazorpayScript();let i=this.getUserId(),r=yield this.http.post(`${this.apiUrl}/api/payment/create-order`,{planId:"pro_trial",userId:i,amount:100,currency:"INR",useSubscription:!1}).toPromise();if(!r?.orderId)throw new Error("Failed to create trial order");let o={key:this.razorpayKey,amount:100,currency:"INR",name:"Adloura",description:"3-Day Pro Trial \u2014 auto-charges \u20B9999/mo after 3 days",order_id:r.orderId,prefill:{name:this.authService.currentUser?.name||"",email:this.authService.currentUser?.email||"",contact:""},theme:{color:"#7c6df0"},handler:n=>g(this,null,function*(){try{yield this.http.post(`${this.apiUrl}/api/payment/verify`,{orderId:n.razorpay_order_id,paymentId:n.razorpay_payment_id,signature:n.razorpay_signature,planId:"pro_trial",userId:i},{headers:{Authorization:`Bearer ${this.authService.getAuthToken()}`}}).toPromise(),this.authService.isAuthenticated&&(yield this.authService.getCurrentUser().toPromise()),e()}catch(c){t(c)}}),modal:{ondismiss:()=>t(new Error("Trial payment cancelled"))}};new window.Razorpay(o).open()}catch(i){t(i)}}))})}getServerCurrency(){return g(this,null,function*(){try{let e=yield this.http.get(`${this.apiUrl}
1/api/geo`).toPromise();return e?.source==="server"&&(e.currency==="INR"||e.currency==="USD")?e.currency:null}catch{return null}})}getCreditPacks(e){return this.http.get(`${this.apiUrl}/api/payment/credit-packs?currency=${e}`).toPromise().then(t=>t?.packs??[]).catch(()=>[])}initiateCreditPack(e){return g(this,null,function*(){yield this.loadRazorpayScript();let t=this.getUserId(),i=this.authService.getAuthToken(),r=yield this.http.post(`${this.apiUrl}/api/payment/create-order`,{planId:e.id,userId:t,amount:e.amount,currency:e.currency,useSubscription:!1},{headers:i?{Authorization:`Bearer ${i}`}:{}}).toPromise();if(!r?.orderId)throw new Error("Failed to create order");return new Promise((o,s)=>{let n={key:this.razorpayKey,amount:e.amount,currency:e.currency,name:"Adloura",description:`${e.credits} ad credits \u2014 never expire`,order_id:r.orderId,prefill:{name:this.authService.currentUser?.name||"",email:this.authService.currentUser?.email||"",contact:""},theme:{color:"#7c6df0"},handler:p=>g(this,null,function*(){try{let f=yield this.http.post(`${this.apiUrl}/api/payment/verify`,{orderId:p.razorpay_order_id,paymentId:p.razorpay_payment_id,signature:p.razorpay_signature,planId:e.id,userId:t},{headers:i?{Authorization:`Bearer ${i}`}:{}}).toPromise();localStorage.removeItem("adloura_pack_pending"),o({credits:Number(f?.credits??e.credits),balance:Number(f?.packBalance??0)})}catch{s(new Error("PACK_PENDING"))}}),modal:{ondismiss:()=>s(new Error("CANCELLED"))}};e.currency==="INR"&&(n.config={display:{blocks:{upi_block:{name:"Pay instantly with UPI",instruments:[{method:"upi"}]},other_block:{name:"Cards & Netbanking",instruments:[{method:"card"},{method:"netbanking"},{method:"wallet"}]}},sequence:["block.upi_block","block.other_block"],preferences:{show_default_blocks:!1}}});try{localStorage.setItem("adloura_pack_pending",JSON.stringify({packId:e.id,credits:e.credits,ts:Date.now()}))}catch{}let c=new window.Razorpay(n);c.on("payment.failed",()=>s(new Error("FAILED"))),c.open()})})}hasPendingPack(){try{let e=localStorage.getItem("adloura_pack_pending");if(!e)return!1;let t=JSON.parse(e);return!t?.ts||Date.now()-t.ts>900*1e3?(localStorage.removeItem("adloura_pack_pending"),!1):!0}catch{return!1}}clearPendingPack(){try{localStorage.removeItem("adloura_pack_pending")}catch{}}loadRazorpayScript(){return new Promise((e,t)=>{if(typeof window.Razorpay<"u")return e();let i=document.createElement("script");i.src="https://checkout.razorpay.com/v1/checkout.js",i.async=!0,i.onload=()=>e(),i.onerror=()=>t(new Error("Failed to load Razorpay script")),document.head.appendChild(i)})}initiateRazorpayPayment(e,t="INR"){return g(this,null,function*(){return new Promise((i,r)=>g(this,null,function*(){try{yield this.loadRazorpayScript();let o=this.getUserId(),s=t==="USD",n=this.USD_PRICES[e.name]??this.USD_PRICES[e.id];console.log("\u{1F4B3} Initiating Razorpay checkout",{planName:e.name,currency:t,userId:o});let c=yield this.http.post(`${this.apiUrl}/api/payment/create-order`,{amount:s?Math.round((n??0)*100):e.price*100,currency:t,planId:e.name,userId:o,useSubscription:!s}).toPromise(),p=!s&&c?.isSubscription===!0,f={key:this.razorpayKey,name:"Adloura",description:`${e.displayName} Subscription`,image:"assets/icon/icon.png",currency:t,handler:m=>g(this,null,function*(){try{let P={paymentId:m.razorpay_payment_id,signature:m.razorpay_signature,planId:e.name,userId:o};p?P.subscriptionId=m.razorpay_subscription_id:P.orderId=m.razorpay_order_id,yield this.http.post(`${this.apiUrl}/api/payment/verify`,P,{headers:{Authorization:`Bearer ${this.authService.getAuthToken()}`}}).toPromise(),this.activateSubscription(e,"razorpay",m.razorpay_payment_id),this.authService.isAuthenticated&&(yield this.authService.getCurrentUser().toPromise()),i()}catch(P){r(P)}}),prefill:{name:this.authService.currentUser?.name||"",email:this.authService.currentUser?.email||"",contact:""},theme:{color:"#7c6df0"},modal:{ondismiss:()=>{if(!d.done){if(s){r(new Error("Payment cancelled"));return}if(Date.now()-S<8e3){r(new Error("Payment cancelled"));return}h(new Error("PAYMENT_PENDING"))}}}};p&&c?.subscriptionId?f.subscription_id=c.subscriptionId:(f.amount=s?Math.round((n??0)*100):e.price*100,f.currency=t,f.order_id=c?.orderId),s||(f.config={display:{blocks:{upi_block:{name:"Pay instantly with UPI",instruments:[{method:"upi"}]},other_block:{name:"Cards & Netbanking",instruments:[{method:"card"},{method:"netbanking"},{method:"wallet"}]}},sequence:["block.upi_block","block.other_block"],preferences:{show_default_blocks:!1}}});let d={done:!1},S=0,I=this.getCurrentSubscription(),a=I&&I.endDate&&Date.parse(I.endDate)||0,l=!!(I&&I.tier!=="free"&&I.status==="active"),w={running:!1},h=m=>g(this,null,function*(){if(d.done){i();return}if(w.running)return;w.running=!0,console.log("[razorpay-reconcile] no client-side confirmation \u2014 polling server for webhook activation\u2026");let P=Date.now()+45e3;for(;Date.now()<P;){if(d.done){i();return}try{let v=yield this.authService.getCurrentUser().toPromise(),R=String(v?.tier||"").toLowerCase(),L=String(v?.subscriptionStatus||"").toLowerCase(),J=Date.parse(v?.subscription_end||v?.subscriptionEnd||"")||0;if((R==="pro"||R==="premium"||R==="lite")&&L==="active"&&(!l||J>a)){d.done=!0,this.setSubscriptionFromBackend(v.tier,v.subscription_end||v.subscriptionEnd||null,v.subscriptionStatus),console.log("[razorpay-reconcile] \u2713 webhook activated plan (tier="+R+") \u2014 treating as SUCCESS"),i();return}}catch{}yield new Promise(v=>setTimeout(v,3e3))}console.warn("[razorpay-reconcile] no activation within 45s \u2014 settling with",m?.message),r(m)}
1),u=(m,P)=>g(this,null,function*(){if(d.done){console.log("[razorpay-"+P+"] verify already done, skipping duplicate");return}d.done=!0,console.log("[razorpay-"+P+"] payment response:",m);try{let v={paymentId:m.razorpay_payment_id,signature:m.razorpay_signature,planId:e.name,userId:o};p?v.subscriptionId=m.razorpay_subscription_id:v.orderId=m.razorpay_order_id,console.log("[razorpay-"+P+"] POST /api/payment/verify",v),yield this.http.post(`${this.apiUrl}/api/payment/verify`,v,{headers:{Authorization:`Bearer ${this.authService.getAuthToken()}`}}).toPromise(),console.log("[razorpay-"+P+"] \u2713 /verify success"),this.activateSubscription(e,"razorpay",m.razorpay_payment_id);try{localStorage.removeItem("rzp_pending")}catch{}this.authService.isAuthenticated&&(yield this.authService.getCurrentUser().toPromise()),i()}catch(v){if(console.error("[razorpay-"+P+"] \u2717 /verify failed",v),s){r(v);return}d.done=!1,h(new Error("PAYMENT_PENDING"))}});f.handler=m=>u(m,"handler");let y=new window.Razorpay(f);try{y.on("payment.failed",m=>{console.warn("[razorpay-event] payment.failed:",m)}),y.on("payment.success",m=>{console.log("[razorpay-event] payment.success fired (event-listener fallback path)");let P=m?.payload||m;u(P,"event")})}catch(m){console.warn("[razorpay] event listener registration failed (SDK may be older):",m)}console.log("[razorpay] opening checkout with options",{isSubscription:p,currency:t,amount:f.amount,hasSubId:!!f.subscription_id,hasOrderId:!!f.order_id});try{localStorage.setItem("rzp_pending",JSON.stringify({plan:e.name,displayName:e.displayName,currency:t,ts:Date.now(),endBeforeMs:a,wasActiveBefore:l}))}catch{}S=Date.now(),y.open()}catch(o){r(o)}}))})}hasPendingRazorpay(){try{let e=JSON.parse(localStorage.getItem("rzp_pending")||"null");return!!(e&&e.ts&&Date.now()-Number(e.ts)<=900*1e3)}catch{return!1}}checkRazorpayReturn(){return g(this,null,function*(){let e=null;try{e=JSON.parse(localStorage.getItem("rzp_pending")||"null")}catch{}if(!e||!e.ts)return{status:"none"};try{localStorage.removeItem("rzp_pending")}catch{}if(Date.now()-Number(e.ts)>900*1e3)return{status:"none"};if(!this.authService.isAuthenticated)return{status:"none"};let t=Number(e.endBeforeMs||0),i=!!e.wasActiveBefore,r=e.displayName||e.plan||"",o=Date.now()+18e3,s=0;for(;Date.now()<o;){try{let n=yield this.authService.getCurrentUser().toPromise(),c=String(n?.tier||"").toLowerCase(),p=String(n?.subscriptionStatus||"").toLowerCase(),f=Date.parse(n?.subscription_end||n?.subscriptionEnd||"")||0;if((c==="pro"||c==="premium"||c==="lite")&&p==="active"&&(!i||f>t)){try{this.setSubscriptionFromBackend(n.tier,n.subscription_end||n.subscriptionEnd||null,n.subscriptionStatus)}catch{}return console.log("[razorpay-return] \u2713 webhook activated plan (tier="+c+") \u2014 SUCCESS after redirect"),{status:"activated",planName:r}}}catch{}yield new Promise(n=>setTimeout(n,s++<3?1500:2500))}return console.warn("[razorpay-return] no activation detected within 18s \u2014 treating as not-confirmed (cancelled or pending webhook)"),{status:"pending",planName:r}})}initiatePayPalSubscription(e){return g(this,null,function*(){let r=[...U,..._].find(n=>n.name===e||n.id===e)?.name||e,o=this.authService.getAuthToken();console.log("[paypal] creating subscription for",r);let s=yield this.http.post(`${this.apiUrl}/api/payment/paypal/create-subscription`,{planId:r},{headers:{Authorization:`Bearer ${o}`}}).toPromise();if(!s?.approveUrl)throw new Error(s?.error||"PayPal subscription could not be created");try{localStorage.setItem("paypal_pending",JSON.stringify({subscriptionId:s.subscriptionId,planId:r,ts:Date.now()}))}catch{}return console.log("[paypal] redirecting to approval",s.subscriptionId),window.location.href=s.approveUrl,new Promise(()=>{})})}verifyPayPalReturn(e){return g(this,null,function*(){let t=null;try{t=JSON.parse(localStorage.getItem("paypal_pending")||"null")}catch{}let i=e||t?.subscriptionId,r=t?.planId||"";if(!i)return console.warn("[paypal] verifyPayPalReturn: no subscription id"),null;let o=this.authService.getAuthToken();try{let s=yield this.http.post(`${this.apiUrl}/api/payment/paypal/verify`,{subscriptionId:i,planId:r},{headers:{Authorization:`Bearer ${o}`}}).toPromise();try{localStorage.removeItem("paypal_pending")}catch{}if(s?.success){if(this.authService.isAuthenticated)try{yield this.authService.getCurrentUser().toPromise()}catch{}
1return console.log("[paypal] verified + activated",s.tier,s.plan),{tier:s.tier,plan:s.plan}}return console.warn("[paypal] verify returned non-success",s),null}catch(s){return console.error("[paypal] verify failed",s),null}})}initiateDodoSubscription(e){return g(this,null,function*(){let r=[...U,..._].find(n=>n.name===e||n.id===e)?.name||e,o=this.authService.getAuthToken();console.log("[dodo] creating subscription for",r);let s=yield this.http.post(`${this.apiUrl}/api/payment/dodo/create-subscription`,{planId:r},{headers:{Authorization:`Bearer ${o}`}}).toPromise();if(!s?.paymentLink)throw new Error(s?.error||"Checkout could not be started");try{localStorage.setItem("dodo_pending",JSON.stringify({subscriptionId:s.subscriptionId,planId:r,ts:Date.now()}))}catch{}return console.log("[dodo] redirecting to checkout",s.subscriptionId),window.location.href=s.paymentLink,new Promise(()=>{})})}verifyDodoReturn(e){return g(this,null,function*(){let t=null;try{t=JSON.parse(localStorage.getItem("dodo_pending")||"null")}catch{}let i=e||t?.subscriptionId,r=t?.planId||"";if(!i)return console.warn("[dodo] verifyDodoReturn: no subscription id"),null;let o=this.authService.getAuthToken();try{let s=yield this.http.post(`${this.apiUrl}/api/payment/dodo/verify`,{subscriptionId:i,planId:r},{headers:{Authorization:`Bearer ${o}`}}).toPromise();try{localStorage.removeItem("dodo_pending")}catch{}if(s?.success){if(this.authService.isAuthenticated)try{yield this.authService.getCurrentUser().toPromise()}catch{}return console.log("[dodo] verified + activated",s.tier,s.plan),{tier:s.tier,plan:s.plan}}return console.warn("[dodo] verify returned non-success",s),null}catch(s){return console.error("[dodo] verify failed",s),null}})}initiateGooglePlayPurchase(e){return g(this,null,function*(){let t=null,i=new Set,r=!1;try{if(t=yield g(this,null,function*(){for(let a=0;a<3;a++){try{let l=yield b.getOfferings();if(l?.current)return l}catch{}yield new Promise(l=>setTimeout(l,300*(a+1)))}for(let a=0;a<4;a++){try{try{yield b.invalidateCustomerInfoCache()}catch{}let l=yield b.getOfferings();if(l?.current)return l}catch{}yield new Promise(l=>setTimeout(l,1500))}try{console.warn("RevenueCat offerings still null \u2014 re-configuring SDK"),yield b.configure({apiKey:this.revenueCatKey}),yield new Promise(l=>setTimeout(l,2e3));let a=yield b.getOfferings();if(a?.current)return a}catch(a){console.warn("RevenueCat re-configure failed",a)}return null}),!t?.current){try{let a=yield b.getOfferings(),l=yield b.getAppUserID().catch(()=>null),w={platform:this.platform.platforms(),planId:e.id,planName:e.name,errorMessage:"No offerings available",errorStack:null,offerings:a||{current:null},appUserId:l?.appUserID||null,userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,revenueCatKeyHint:(this.revenueCatKey||"").slice(0,12)+"...",isKeySecret:(this.revenueCatKey||"").startsWith("sk_")};yield this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,w).toPromise()}catch{}throw new Error("No offerings available")}let s=e.duration==="yearly"?/year|annual|yr|p1y/i:/month|monthl|p1m|monthly/i,n=e.duration==="yearly"?["annual","yearly"]:["monthly"],c=[...n,...n.map(a=>`${a}_${e.id}`),...n.map(a=>`${e.id}_${a}`),e.name,`${e.id}_${e.duration}`,`${e.name}`].map(a=>(""+a).toLowerCase()),p=a=>{let l=a.lookup_key||a.identifier||""||"";if(s.test(l))return!0;let w=a.storeProduct?.productId||a.productId||a.storeProductId||"";if(s.test(w))return!0;try{let u=a.products&&a.products.items||[];for(let y of u){let m=(y&&y.product&&y.product.subscription&&y.product.subscription.duration||"").toLowerCase();if(e.duration==="yearly"&&m==="p1y"||e.duration==="monthly"&&m==="p1m")return!0}}catch{}let h=[];try{a.storeProduct&&a.storeProduct.title&&h.push((a.storeProduct.title||"").toLowerCase()),a.storeProduct&&a.storeProduct.description&&h.push((a.storeProduct.description||"").toLowerCase()),a.product&&a.product.title&&h.push((a.product.title||"").toLowerCase())}catch{}return!!h.some(u=>s.test(u))},f=a=>{let l=(a.identifier||"").toLowerCase(),w=(a.storeProduct?.productId||a.productId||a.storeProductId||"").toLowerCase(),h=[];try{a.storeProduct&&a.storeProduct.title&&h.push((a.storeProduct.title||"").toLowerCase()),a.storeProduct&&a.storeProduct.description&&h.push((a.storeProduct.description||"").toLowerCase()),a.product&&a.product.title&&h.push((a.product.title||"").toLowerCase())}catch{}return!!(l.includes(e.id)||w.includes(e.id)||h.some(u=>u.includes(e.id))||e.name&&(l.includes(e.name)||w.includes(e.name)||h.some(u=>u.includes(e.name))))},d=null;if(t.current&&Array.isArray(t.current.availablePackages)){let a=t.current.availablePackages.filter(p),l=a.length?a:[],w=e.duration==="yearly"?["$rc_annual","$rc_yearly"]:["$rc_monthly"];d=l.find(h=>{let u=(h.lookup_key||h.identifier||"").toLowerCase();return w.some(y=>u.includes(y))}
1),!d&&l.length&&(d=l.find(h=>{let u=h.products&&h.products.items||[];for(let y of u){let m=(y&&y.product&&y.product.subscription&&y.product.subscription.duration||"").toLowerCase();if(e.duration==="yearly"&&m==="p1y"||e.duration==="monthly"&&m==="p1m")return!0}return!1})),!d&&e.duration==="yearly"&&l.length&&(d=l.find(h=>{let u=(h.identifier||"").toLowerCase(),y=(h.storeProduct?.productId||h.productId||h.storeProductId||"").toLowerCase(),m=[];try{h.storeProduct&&h.storeProduct.title&&m.push((h.storeProduct.title||"").toLowerCase()),h.storeProduct&&h.storeProduct.description&&m.push((h.storeProduct.description||"").toLowerCase()),h.product&&h.product.title&&m.push((h.product.title||"").toLowerCase())}catch{}return!!(u.includes("year")||u.includes("annual")||y.includes("year")||y.includes("annual")||m.some(P=>/year|annual|yr/.test(P)))})),!d&&a.length===0&&console.warn("No duration-matching packages found in current offerings for",e.id,e.duration)}if(!d)try{if(t&&t.all&&t.all[e.id]&&Array.isArray(t.all[e.id].availablePackages)){let l=t.all[e.id].availablePackages.filter(p),w=l.length?l:[],h=e.duration==="yearly"?["$rc_annual","$rc_yearly"]:["$rc_monthly"];w.length?(d=w.find(u=>{let y=(u.lookup_key||u.identifier||"").toLowerCase();return h.some(m=>y.includes(m))}),d||(d=w.find(u=>{let y=u.products&&u.products.items||[];for(let m of y){let P=(m&&m.product&&m.product.subscription&&m.product.subscription.duration||"").toLowerCase();if(e.duration==="yearly"&&P==="p1y"||e.duration==="monthly"&&P==="p1m")return!0}return!1})),!d&&e.duration==="yearly"&&(d=w.find(u=>{let y=(u.identifier||"").toLowerCase(),m=(u.storeProduct?.productId||u.productId||u.storeProductId||"").toLowerCase(),P=[];try{u.storeProduct&&u.storeProduct.title&&P.push((u.storeProduct.title||"").toLowerCase()),u.storeProduct&&u.storeProduct.description&&P.push((u.storeProduct.description||"").toLowerCase()),u.product&&u.product.title&&P.push((u.product.title||"").toLowerCase())}catch{}return!!(y.includes("year")||y.includes("annual")||m.includes("year")||m.includes("annual")||P.some(v=>/year|annual|yr/.test(v)))})),d||(d=w.find(u=>{let y=(u.identifier||"").toLowerCase(),m=(u.storeProduct?.productId||u.productId||u.storeProductId||"").toLowerCase(),P=[];try{u.storeProduct&&u.storeProduct.title&&P.push((u.storeProduct.title||"").toLowerCase()),u.storeProduct&&u.storeProduct.description&&P.push((u.storeProduct.description||"").toLowerCase()),u.product&&u.product.title&&P.push((u.product.title||"").toLowerCase())}catch{}if(c.includes(y))return!0;for(let R of c)if(y.includes(R)||m.includes(R)||P.some(L=>L.includes(R)))return!0;let v=(e.displayName||"").toLowerCase();return!!(v&&P.some(R=>R.includes(v)))}))):console.warn("No duration-matching packages found in alternative offering for",e.id,e.duration)}}catch{}if(d)try{(!p(d)||!f(d))&&(console.warn("\u26A0\uFE0F Package validation failed",{package:d?.identifier||null,expectedTier:e.id,expectedDuration:e.duration}),d=null)}catch{d=null}if(!d){console.warn("No exact package matched for plan",e.id,"-- falling back to best-effort package across all offerings");let a=[];try{if(t&&t.all)for(let l of Object.keys(t.all)){let w=t.all[l];w&&Array.isArray(w.availablePackages)&&a.push(...w.availablePackages)}t&&t.current&&Array.isArray(t.current.availablePackages)&&a.push(...t.current.availablePackages)}catch{}d=a.find(l=>p(l)&&f(l))||null}if(!d){let a=new Error("PLAN_NOT_ON_STORE");throw a.planName=e.name,a}try{yield this.identifyRevenueCatUser()}catch{}try{let a={platform:this.platform.platforms(),planId:e.id,planName:e.name,chosenPackageIdentifier:d?.identifier||null,chosenStoreProductId:d?.storeProduct?.productId||d?.productId||null,userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null};this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,a).toPromise().catch(()=>{})}catch{}try{console.log("\u{1F3AF} Chosen RevenueCat package",{planId:e.id,planName:e.name,planPrice:e.price,planCurrency:e.currency,chosenPackageIdentifier:d?.identifier||null,chosenStoreProductId:d?.storeProduct?.productId||d?.productId||null})}catch{}try{let a=yield b.getCustomerInfo();i=new Set(Object.keys((a?.customerInfo||a)?.entitlements?.active||{})),r=!0}catch{}let S=yield b.purchasePackage({aPackage:d}),I=e.id==="premium"?"premium":e.id==="lite"?"lite":"pro";if(S.customerInfo.entitlements.active[I]){let a=S.customerInfo.entitlements.active[I],l=a?.expirationDate?new Date(a.expirationDate).getTime():null;this.activateSubscription(e,"google_play",S.productIdentifier,l),console.log("\u2705 Google Play purchase successful")}else throw new Error("Purchase verification failed")}catch(o){if(this.isRevenueCatCancel(o)){let s=e.id==="premium"?"premium":e.id==="lite"?"lite":"pro",n=[0,3e3,6e3];for(let c of n)try{c>0&&(yield new Promise(l=>setTimeout(l,c)));let p=yield b.restorePurchases(),d=(p?.customerInfo||p)?.entitlements?.active||{},I=["premium","pro","lite"].filter(l=>d[l]&&(r?!i.has(l):l===s))[0]||null,a=I?d[I]:null;if(a&&I){console.log(`\u{1F4A1} userCancelled recovered via restorePurchases (delay=${c}ms) \u2014 activating`);let l=e;if(I!==e.id){let h=(a.productIdentifier||"").toLowerCase();l=(/year|annual|yr/.test(h)?_:U).find(y=>y.id===I)||e}let w=a?.expirationDate?new Date(a.expirationDate).getTime():null;this.activateSubscription(l,"google_play",a.productIdentifier||"",w);try{this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,{platform:this.platform.platforms(),planId:l.id,planName:l.name,errorMessage:`userCancelled recovered via restorePurchases (delay=${c}ms) \u2014 subscription activated`,errorStack:null,userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,isAndroid:this.isAndroid()}).toPromise().catch(()=>{})}catch{}return}}catch(p){console.warn(`\u26A0\uFE0F restorePurchases attempt (delay=${c}ms) failed`,p)}try{localStorage.setItem("pendingRestore",JSON.stringify({planId:e.id,planName:e.n
1ame,userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,timestamp:Date.now()}))}catch{}try{this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,{platform:this.platform.platforms(),planId:e.id,planName:e.name,errorMessage:"Purchase was cancelled by user (no active entitlement found after 3 restore attempts with delays)",userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,isAndroid:this.isAndroid()}).toPromise().catch(()=>{})}catch{}throw new Error("Purchase cancelled")}console.error("\u274C Google Play purchase failed:",o);try{let n=(yield b.getAppUserID().catch(()=>null))?.appUserID||null,c=E(T({},t||{}),{current:t?.current?E(T({},t.current),{availablePackages:(t.current.availablePackages||[]).map(f=>({identifier:f.identifier,productId:f.storeProduct?.productId||f.productId||f.storeProductId}))}):null}),p=null;try{b.getVersion&&(p=(yield b.getVersion())||null)}catch{p=null}this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,{platform:this.platform.platforms(),planId:e.id,planName:e.name,errorMessage:o?.message||String(o),errorStack:o?.stack||null,errorCode:o?.code??null,readableErrorCode:o?.data?.readableErrorCode??null,underlyingErrorMessage:o?.data?.underlyingErrorMessage??null,offerings:c,appUserId:n,userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,revenueCatKeyHint:(this.revenueCatKey||"").slice(0,12)+"...",isKeySecret:(this.revenueCatKey||"").startsWith("sk_"),sdkVersion:p,isAndroid:this.isAndroid()}).toPromise().catch(()=>{})}catch{}throw o}})}initiateApplePurchase(e){return g(this,null,function*(){return this.initiateGooglePlayPurchase(e)})}restorePurchases(){return g(this,null,function*(){if(this.isWeb())throw new Error("Restore purchases only available on mobile");try{let e=yield b.restorePurchases(),i=(e?.customerInfo||e)?.entitlements?.active||{};if(i.premium){let r=i.premium,o=(r.productIdentifier||"").toLowerCase(),n=/year|annual|yr/.test(o)?_.find(p=>p.id==="premium")||_[2]:U.find(p=>p.id==="premium")||U[3],c=r?.expirationDate?new Date(r.expirationDate).getTime():null;return this.activateSubscription(n,"google_play",r.productIdentifier||"",c),!0}else if(i.pro){let r=i.pro,o=(r.productIdentifier||"").toLowerCase(),n=/year|annual|yr/.test(o)?_.find(p=>p.id==="pro")||_[1]:U.find(p=>p.id==="pro")||U[2],c=r?.expirationDate?new Date(r.expirationDate).getTime():null;return this.activateSubscription(n,"google_play",r.productIdentifier||"",c),!0}else if(i.lite){let r=i.lite,o=(r.productIdentifier||"").toLowerCase(),n=/year|annual|yr/.test(o)?_.find(p=>p.id==="lite")||_[0]:U.find(p=>p.id==="lite")||U[1],c=r?.expirationDate?new Date(r.expirationDate).getTime():null;return this.activateSubscription(n,"google_play",r.productIdentifier||"",c),!0}return console.log("\u2139\uFE0F No active subscriptions found"),!1}catch(e){throw console.error("\u274C Restore purchases failed:",e),e}})}activateSubscription(e,t,i,r){return g(this,null,function*(){let o=new Date,s;r&&r>Date.now()?s=new Date(r):(s=new Date(o),e.duration==="monthly"?s.setMonth(s.getMonth()+1):e.duration==="yearly"&&s.setFullYear(s.getFullYear()+1));let n={tier:e.id,plan:e.name,status:"active",startDate:o.toISOString(),endDate:s.toISOString(),stockVideosUsedToday:0,aiVideosUsedToday:0,pureAiVideosUsedToday:0,lastResetDate:o.toISOString(),paymentMethod:t,transactionId:i};if(this.saveSubscription(n),t==="google_play"||t==="apple_pay")try{let p=(yield b.getAppUserID().catch(()=>null))?.appUserID||null,f=this.authService.getAuthToken(),d={productId:i,planId:e.id};p&&(d.appUserId=p),r&&r>Date.now()&&(d.expirationAtMs=r);let S={};f&&(S.Authorization=`Bearer ${f}`);let I=!1;for(let a=0;a<3&&!I;a++)try{a>0&&(yield new Promise(l=>setTimeout(l,a*2e3))),yield this.http.post(`${this.apiUrl}/api/payment/revenuecat-activate`,d,{headers:S}).toPromise(),I=!0,console.log(`\u2705 revenuecat-activate succeeded (attempt ${a+1})`);try{yield this.refreshUserAfterPurchase()}catch{}}catch(l){console.warn(`\u26A0\uFE0F revenuecat-activate attempt ${a+1}/3 failed`,l)}if(!I){console.error("\u274C All 3 revenuecat-activate attempts failed \u2014 saving pending activation");try{localStorage.setItem("pendingActivation",JSON.stringify(E(T({},d),{email:this.authService.currentUser?.email||null,userId:this.authService.currentUser?.id||null,timestamp:Date.now()})))}catch{}try{this.http.post(`${this.apiUrl}/api/debug/payment-client-error`,{platform:this.platform.platforms(),planId:e.id,planName:e.n
1ame,errorMessage:"CRITICAL: All 3 revenuecat-activate retries failed \u2014 user paid but server not updated",userId:this.authService.currentUser?.id||null,email:this.authService.currentUser?.email||null,appUserId:p,isAndroid:this.isAndroid()}).toPromise().catch(()=>{})}catch{}}p&&f&&this.http.post(`${this.apiUrl}/api/payment/revenuecat-identify`,{appUserId:p},{headers:S}).toPromise().then(()=>g(this,null,function*(){console.log("\u2705 revenuecat-identify called")})).catch(()=>{})}catch(c){console.warn("activateSubscription: backend notification failed",c)}})}cancelSubscription(e){return g(this,null,function*(){try{let t=this.authService.getAuthToken(),i={};t&&(i.Authorization=`Bearer ${t}`);let r={};e&&(r.reason=e);let o=yield this.http.post(`${this.apiUrl}/api/payment/cancel-subscription`,r,{headers:i}).toPromise();if(o&&o.success){let s=this.getCurrentSubscription(),n=E(T({},s),{status:"cancelled"});return this.saveSubscription(n),{ok:!0}}return{ok:!1}}catch(t){let i=t?.error?.message||void 0;return console.warn("cancelSubscription failed",t),{ok:!1,message:i}}})}setSubscriptionFromBackend(e,t,i){let r=this.getCurrentSubscription(),o={tier:e,plan:e==="premium"?"premium_monthly":e==="pro"?"pro_monthly":e==="lite"?"lite_monthly":"free",status:i??"active",startDate:r.startDate,endDate:t,stockVideosUsedToday:r.stockVideosUsedToday,aiVideosUsedToday:r.aiVideosUsedToday,pureAiVideosUsedToday:r.pureAiVideosUsedToday??0,lastResetDate:r.lastResetDate};this.saveSubscription(o)}getUserId(){let e=localStorage.getItem("currentUser");if(e)try{return JSON.parse(e).id||null}catch{return null}return null}isShopifyMerchant(){return!!this.authService.currentUser?.email?.endsWith("@shopify.adloura.app")}shopifyAdminUrl(){let t=(this.authService.currentUser?.email||"").match(/^store-(.+)-myshopify-com@shopify\.adloura\.app$/);return t&&t[1]?`https://admin.shopify.com/store/${t[1]}/apps`:""}showUpgradePrompt(e){return g(this,null,function*(){let i=this.getCurrentTier()==="free";if(this.isShopifyMerchant()){yield this.showShopifyUpgradePrompt(e,i);return}let r=i?"Pro":"Premium",o=Intl.DateTimeFormat().resolvedOptions().timeZone||"",s=o==="Asia/Kolkata"||o==="Asia/Calcutta",n=i?s?"\u20B92,399":"$29.99":s?"\u20B94,799":"$59.99",c=i?s?"\u20B933":"<$0.67":s?"\u20B966":"<$1.33",p=i?"Upgrade to Pro for more ads & your real product placed by AI.":"Upgrade to Premium for more ads, multiple brand kits & bulk generation.",f=e&&typeof e=="string"&&e.trim()&&e.trim()!=="undefined"?e.trim():p,d=i?`\u2022 60 ad credits / month (10/day) \u2022 Upload your real product 2\u2022 Research \u2192 winning angles \u2022 Ad Doctor`:`\u2022 120 ad credits / month (12/day) \u2022 Multiple Brand Kits 3\u2022 Bulk / catalogue generation \u2022 Priority rendering`,S=null;if(this.isWeb())try{let u=(yield this.getCreditPacks(this.packCurrency())).filter(y=>(y?.amount??0)>0).sort((y,m)=>y.amount-m.amount)[0];u?.display&&(S={credits:u.credits,price:u.display})}catch{S=null}let I=S?`${f} 4 5Keep going for ${S.price} \u2014 ${S.credits} ads, one-time, they never expire. 6 7Or ${r} at ${n}/mo (${c}/day): 8${d} 9 10Secure payment \u2022 7-day money-back guarantee`:`${f} 11 12${r} \u2014 just ${c}/day (${n}/mo) 13 14${d} 15 16Secure payment \u2022 Cancel anytime`,a=[{text:"Not Now",role:"cancel",cssClass:"upgrade-cancel-btn"}];i&&s&&this.TRIAL_ENABLED&&a.push({text:"Start 3-Day Trial for \u20B91",cssClass:"upgrade-trial-btn",handler:()=>{this.initiatePurchase("pro_trial").catch(h=>console.error("Trial failed",h))}}),this.isWeb()?(a.push({text:`${r} plan \u2192`,cssClass:"upgrade-secondary-btn",handler:()=>{this.router.navigate(["/subscription"])}}),a.push({text:S?`Buy ${S.credits} ads \u2014 ${S.price}`:"Buy credits (one-time)",cssClass:"upgrade-action-btn",handler:()=>(this.showCreditPackSheet("upgrade_prompt"),!0)})):a.push({text:`Get ${r} \u2192`,cssClass:"upgrade-action-btn",handler:()=>{this.router.navigate(["/subscription"])}}),yield(yield this.alertController.create({header:`Unlock ${r}`,message:I,cssClass:"upgrade-prompt-alert",buttons:a})).present()})}showShopifyUpgradePrompt(e,t){return g(this,null,function*(){let i=t?"Starter":"Pro",r=t?"$9":"$29",o=t?`\u2022 30 ad credits / month \u2022 Upload your real product 17\u2022 Brand kit \u2014 logo, colours, fonts \u2022 No watermark, HD 1080p`:`\u2022 60 ad credits / month \u2022 Live-motion hero shot
18\u2022 Research \u2192 winning angles \u2022 Ad Doctor`,s=e&&typeof e=="string"&&e.trim()&&e.trim()!=="undefined"?e.trim():`Upgrade to ${i} for more ads and your real product placed by AI.`,n=this.shopifyAdminUrl(),c=n?"Open Adloura in your Shopify admin to switch plans \u2014 one tap, billed with your store.":"Open Adloura from your Shopify admin (Apps \u2192 Adloura) to switch plans \u2014 billed with your store.",p=[{text:"Not Now",role:"cancel",cssClass:"upgrade-cancel-btn"}];n&&p.push({text:`Get ${i} \u2192`,cssClass:"upgrade-action-btn",handler:()=>{try{window.open(n,"_blank")}catch{}return!0}}),yield(yield this.alertController.create({header:`Unlock ${i}`,message:`${s} 19 20${i} \u2014 ${r}/mo, charged through Shopify 21 22${o} 23 24${c}`,cssClass:"upgrade-prompt-alert",buttons:p})).present()})}packCurrency(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone||"";if(e==="Asia/Kolkata"||e==="Asia/Calcutta")return"INR";let t=navigator.language||"";return t.endsWith("-IN")||t==="hi"?"INR":"USD"}catch{return"USD"}}showCreditPackSheet(e="unknown"){return g(this,null,function*(){let t=this.packCurrency(),i=yield this.getCreditPacks(t);return i.length?new Promise(r=>g(this,null,function*(){yield(yield this.alertController.create({header:"Buy ad credits",subHeader:"One-time payment. Credits never expire.",cssClass:"upgrade-prompt-alert",inputs:i.map((s,n)=>({type:"radio",label:`${s.display} \u2014 ${s.credits} ad${s.credits===1?"":"s"}`,value:s.id,checked:n===Math.min(1,i.length-1)})),buttons:[{text:"Not now",role:"cancel",handler:()=>(r(null),!0)},{text:"Continue",handler:s=>{let n=i.find(c=>c.id===s)||i[0];return this.initiateCreditPack(n).then(c=>g(this,null,function*(){yield this.showPackResult(`${c.credits} credits added \u2014 you now have ${c.balance}. They never expire.`),r(c)})).catch(c=>g(this,null,function*(){let p=String(c?.message||"");if(p==="CANCELLED"){r(null);return}if(p==="PACK_PENDING"){yield this.showPackResult("Payment received. Your credits are being added \u2014 refresh in a few seconds."),r(null);return}yield this.showPackResult("That payment did not complete. You have not been charged."),r(null)})),!0}}]})).present()})):(this.router.navigate(["/subscription"]),null)})}showPackResult(e){return g(this,null,function*(){yield(yield this.alertController.create({header:"Credits",message:e,buttons:["OK"]})).present()})}refreshUserAfterPurchase(){return g(this,null,function*(){if(!this._refreshInProgress){this._refreshInProgress=!0;try{let e=yield this.authService.getCurrentUser().toPromise();if(e&&e.tier){this.setSubscriptionFromBackend(e.tier,e.subscription_end||e.subscriptionEnd||null,e.subscriptionStatus),console.log("\u2705 User profile refreshed after purchase, tier:",e.tier,"status:",e.subscriptionStatus);return}yield new Promise(t=>setTimeout(t,1500));try{let t=yield this.authService.getCurrentUser().toPromise();t&&t.tier?(this.setSubscriptionFromBackend(t.tier,t.subscription_end||t.subscriptionEnd||null,t.subscriptionStatus),console.log("\u2705 User profile refreshed (retry) after purchase, tier:",t.tier,"status:",t.subscriptionStatus)):console.log("\u2139\uFE0F User refresh did not return tier; will rely on webhook or manual refresh")}catch(t){console.warn("Second attempt to refresh user failed",t)}}finally{setTimeout(()=>{this._refreshInProgress=!1},3e3)}}})}};C.\u0275fac=function(t){return new(t||C)(O(Y),O(x),O(W))},C.\u0275prov=M({token:C,factory:C.\u0275fac,providedIn:"root"});let A=C;return A})();export{U as a,_ as b,D as c,b as d,pe as e};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.