(function(){"use strict";const re={_REQUIRED_PREBID_MODULES:{_comment:"These modules MUST be included in your Prebid.js build for full functionality",bidAdapters:["adkernelBidAdapter","appnexusBidAdapter","conversantBidAdapter","insticatorBidAdapter","ixBidAdapter","openxBidAdapter","pubmaticBidAdapter","rubiconBidAdapter","seedtagBidAdapter","sharethroughBidAdapter","smartadserverBidAdapter","sovrnBidAdapter","teadsBidAdapter","tripleliftBidAdapter"],_analytics_note:"CocoWrapper uses a custom analytics backend - genericAnalyticsAdapter is optional",analytics:[],consent:["consentManagementGpp","consentManagementTcf","consentManagementUsp","tcfControl","gppControl_usnat","gppControl_usstates"],userIdModules:["userId","33acrossIdSystem","criteoIdSystem","sharedIdSystem","id5IdSystem","pubProvidedIdSystem","uid2IdSystem","unifiedIdSystem"],other:["gptPreAuction","storageControl","allowActivities","bidViewabilityIO","currency","debugging","priceFloors","geolocationRtdProvider","intersectionRtdProvider","multibid","schain","sizeMapping","sizeMappingV2","timeoutRtdProvider"]},COCO_GLOBAL:"coco",version:"1.0.0",SCHAIN:{ver:"1.0",complete:1,nodes:[{asi:"mydramalist.com",sid:"22265847236",hp:1}]},EXTRA_BIDDERS:[{bidder:"conversant",params:{site_id:"126436",bidfloor:.01,secure:1}}],BIDDERS:{"/22265847236/header_top":[{bidder:"appnexus",params:{placementId:"13361065",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"ZKc67L7Xfn2Y997DqK6jkeKV"}},{bidder:"sharethrough",params:{pkey:"CN4xy7G4ZtrTUCnXMCg8jtC8"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448583",delDomain:"nexoff-d.openx.net"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"ix",params:{siteId:"275382",size:[970,90]}},{bidder:"ix",params:{siteId:"275382",size:[728,90]}},{bidder:"ix",params:{siteId:"275382",size:[970,250]}},{bidder:"sovrn",params:{tagid:"639677"}},{bidder:"sovrn",params:{tagid:"639673"}},{bidder:"sovrn",params:{tagid:"639675"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96779}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384070"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384071"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384069"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-header"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35457699",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285750}}],"/22265847236/header_top_mobile":[{bidder:"appnexus",params:{placementId:"13361066",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"3CW8aI5AjyZteIzkUleirDBO"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448585",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275389",size:[320,100]}},{bidder:"ix",params:{siteId:"275389",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639679"}},{bidder:"sovrn",params:{tagid:"639681"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96790}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384072"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384073"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-header-mobile"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35457699",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285751}}],"/22265847236/footer_1":[{bidder:"appnexus",params:{placementId:"13361068",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"ZKc67L7Xfn2Y997DqK6jkeKV"}},{bidder:"sharethrough",params:{pkey:"CN4xy7G4ZtrTUCnXMCg8jtC8"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448586",delDomain:"nexoff-d.openx.net"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"ix",params:{siteId:"275383",size:[970,90]}},{bidder:"ix",params:{siteId:"275383",size:[728,90]}},{bidder:"sovrn",params:{tagid:"639676"}},{bidder:"sovrn",params:{tagid:"639674"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96779}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384074"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384075"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-footer"}}],"/22265847236/footer_1/footer_2":[{bidder:"appnexus",params:{placementId:"13361068",reserve:.03}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"CN4xy7G4ZtrTUCnXMCg8jtC8"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",floor:.03,zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448587",customFloor:.03,delDomain:"nexoff-d.openx.net"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"ix",params:{siteId:"275383",size:[970,90]}},{bidder:"ix",params:{siteId:"275383",size:[728,90]}},{bidder:"sovrn",params:{tagid:"639676"}},{bidder:"sovrn",params:{tagid:"639674"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96779}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384074"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384075"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-footer-2"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426275",placement:"inScreen"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285748}}],"/22265847236/banner":[{bidder:"appnexus",params:{placementId:"13361068",reserve:.03}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"CN4xy7G4ZtrTUCnXMCg8jtC8"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",floor:.03,zoneId:"1005256"}},{bidder:"openx",params:{unit:"540361844",customFloor:.03,delDomain:"nexoff-d.openx.net"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"ix",params:{siteId:"275383",size:[728,90]}},{bidder:"sovrn",params:{tagid:"639676"}},{bidder:"sovrn",params:{tagid:"639674"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:99034}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384075"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-banner"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426294",placement:"inBanner"}}],"/22265847236/footer_1_mobile":[{bidder:"appnexus",params:{placementId:"13361069",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"3CW8aI5AjyZteIzkUleirDBO"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448589",delDomain:"nexoff-d.openx.net"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"ix",params:{siteId:"275390",size:[320,100]}},{bidder:"sovrn",params:{tagid:"639680"}},{bidder:"sovrn",params:{tagid:"639682"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96790}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384077"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384078"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-footer-mobile-0"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426275",placement:"inScreen"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285747}}],"/22265847236/footer_2_mobile":[{bidder:"appnexus",params:{placementId:"13361069",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"3CW8aI5AjyZteIzkUleirDBO"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448589",delDomain:"nexoff-d.openx.net"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"ix",params:{siteId:"275390"}},{bidder:"sovrn",params:{tagid:"639680"}},{bidder:"sovrn",params:{tagid:"639682"}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96790}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384078"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426275",placement:"inScreen"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285749}}],"/22265847236/film_box_1":[{bidder:"appnexus",params:{placementId:"13361070",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448590",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275385",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639684"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384079"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox1-0"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426281",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285719}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426296",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285720}}],"/22265847236/film_box_1_1":[{bidder:"appnexus",params:{placementId:"13361485",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448591",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275386",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639685"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384080"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox1-1"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426296",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285722}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426281",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285721}}],"/22265847236/film_box_1_2":[{bidder:"appnexus",params:{placementId:"13361079",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448592",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275387",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639686"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384081"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox1-2"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426281",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285723}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426296",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285724}}],"/22265847236/film_box_1_3":[{bidder:"appnexus",params:{placementId:"13361484",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448593",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275388",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639687"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384082"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox1-3"}}],"/22265847236/film_box_2":[{bidder:"appnexus",params:{placementId:"13361071",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448594",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275388",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639688"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384083"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox2-0"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426297",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285728}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426285",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285727}}],"/22265847236/film_box_2_1":[{bidder:"appnexus",params:{placementId:"13361486",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448595",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275388",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639689"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384084"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox2-1"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426285",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285729}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426297",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285732}}],"/22265847236/film_box_2_2":[{bidder:"appnexus",params:{placementId:"13361080",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256"}},{bidder:"openx",params:{unit:"540448596",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275388",size:[300,250]}},{bidder:"sovrn",params:{tagid:"639690"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96791}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384085"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox2-2"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426285",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285734}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426297",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285735}}],"/22265847236/film_box_3":[{bidder:"appnexus",params:{placementId:"13361072",reserve:.01}},{bidder:"insticator",params:{adUnitId:"01HN38QZ1GCHX7WG7FJJW4K668"}},{bidder:"sharethrough",params:{pkey:"g6bAt7IfJLJuUSSWBS6ZnhQS"}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540361848",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275384",size:[300,250]}},{bidder:"ix",params:{siteId:"275384",size:[300,600]}},{bidder:"sovrn",params:{tagid:"639691"}},{bidder:"sovrn",params:{tagid:"639683"}},{bidder:"teads",params:{placementId:134154,pageId:123441}},{bidder:"smartadserver",params:{domain:"//prg.smartadserver.com",siteId:385963,pageId:1332659,formatId:96815}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384086"}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3387174"}},{bidder:"triplelift",params:{inventoryCode:"mdl-gpt-fbox2-3"}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35426288",placement:"inArticle"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285736}},{bidder:"seedtag",params:{publisherId:"5077-5504-01",adUnitId:"35457694",placement:"inBanner"}},{bidder:"adkernel",params:{host:"cpm.appocean.media",zoneId:285738}}]},DEFINITIONS:{"/22265847236/header_top":{size:[[970,90],[728,90],[970,250]],key:"mdl-gpt-header"},"/22265847236/header_top_mobile":{size:[[300,250],[320,100],[320,50]],key:"mdl-gpt-header-mobile"},"/22265847236/footer_1":{size:[[970,90],[728,90]],key:"mdl-gpt-footer"},"/22265847236/footer_1/footer_2":{size:[[970,90],[728,90]],key:"mdl-gpt-footer-2"},"/22265847236/banner":{size:[728,90],key:"mdl-gpt-banner"},"/22265847236/footer_1_mobile":{size:[[320,100],[320,50]],key:"mdl-gpt-footer-mobile"},"/22265847236/footer_2_mobile":{size:[[320,100],[320,50]],key:"mdl-gpt-footer-mobile-2"},"/22265847236/film_box_1":{size:[300,250],key:"mdl-gpt-fbox1-0"},"/22265847236/film_box_1_1":{size:[300,250],key:"mdl-gpt-fbox1-1"},"/22265847236/film_box_1_2":{size:[300,250],key:"mdl-gpt-fbox1-2"},"/22265847236/film_box_1_3":{size:[300,250],key:"mdl-gpt-fbox1-3"},"/22265847236/film_box_2":{size:[300,250],key:"mdl-gpt-fbox2-0"},"/22265847236/film_box_2_1":{size:[300,250],key:"mdl-gpt-fbox2-1"},"/22265847236/film_box_2_2":{size:[300,250],key:"mdl-gpt-fbox2-2"},"/22265847236/film_box_3":{size:[[300,600],[300,250]],key:"mdl-gpt-fbox3-0"},"/22265847236/film_box_5":{size:[300,250],key:"mdl-gpt-fbox5-0"}},SLOT_MAPPINGS:{"/47261215/header_top":"/22265847236/header_top","/47261215/header_top_mobile":"/22265847236/header_top_mobile","/47261215/footer_1":"/22265847236/footer_1","/47261215/footer_1_mobile":"/22265847236/footer_1_mobile","/47261215/film_box_1":"/22265847236/film_box_1","/47261215/film_box_1_1":"/22265847236/film_box_1_1","/47261215/film_box_1_2":"/22265847236/film_box_1_2","/47261215/film_box_1_3":"/22265847236/film_box_1_3","/47261215/film_box_2":"/22265847236/film_box_2","/47261215/film_box_2_1":"/22265847236/film_box_2_1","/47261215/film_box_2_2":"/22265847236/film_box_2_2","/47261215/film_box_3":"/22265847236/film_box_3","/47261215/film_box_5":"/22265847236/film_box_5","/47261215/banner":"/22265847236/banner_1"},BID_OPTIMIZATION:{enabled:!0,strategyVersion:"balanced-v1",maxInitialBidders:4,maxRefreshBidders:8,maxRetryBidders:6,minRequestsForConfidentScore:12,minTimeoutMs:900,maxTimeoutMs:2500,timeoutByRequestMode:{initial:1600,refresh:2200,retry:1800},initialBidderGroup:{default:"core",mobile:"mobile_light"},refreshBidderGroup:{default:"extended",mobile:"extended"},retryBidderGroup:{default:"extended",mobile:"core"},bidderGroups:{core:["appnexus","ix","pubmatic","rubicon","triplelift","openx"],extended:["appnexus","ix","pubmatic","rubicon","triplelift","openx","sharethrough","teads","sovrn","smartadserver","insticator"],mobile_light:["appnexus","ix","pubmatic","rubicon"]},weights:{responseRate:.3,timeoutRate:.2,winRate:.2,revenueShare:.15,latency:.15},floorAdjustments:{initial:{multiplier:1},refresh:{multiplier:1.05,highValueRevenuePerRequest:.35,highValueMultiplier:1.08,lowFillThreshold:.25,lowFillMultiplier:.92},retry:{multiplier:.95,lowFillThreshold:.2,lowFillMultiplier:.9}},retry:{maxRetries:2,requireVisibility:!0,minViewability:.5,minSlotRevenue:.05},slotOverrides:{"/22265847236/header_top":{initialBidderGroup:"extended"},"/22265847236/header_top_mobile":{initialBidderGroup:"core"},"/22265847236/footer_1":{refreshBidderGroup:"extended"}}},PREBID_CONFIG:{enableSendAllBids:!1,bidderTimeout:2500,bidderSequence:"random",useBidCache:!0,priceGranularity:{buckets:[{precision:2,min:0,max:3,increment:.01},{precision:2,min:3,max:8,increment:.05},{precision:2,min:8,max:20,increment:.5},{precision:2,min:20,max:35,increment:1}]},targetingControls:{alwaysIncludeDeals:!0},schain:{ver:"1.0",complete:1,nodes:[{asi:"mydramalist.com",sid:"22265847236",hp:1}]},consentManagement:{gdpr:{cmpApi:"iab",timeout:8e3,defaultGdprScope:!0},usp:{cmpApi:"iab",timeout:1e3}},floors:{enforcement:{floorDeals:!1},data:{currency:"USD",modelVersion:"mdl-static-v1",schema:{fields:["mediaType","size"],delimiter:"|"},values:{"banner|728x90":.02,"banner|970x90":.02,"banner|970x250":.05,"banner|300x250":.03,"banner|300x600":.05,"banner|320x100":.01,"banner|320x50":.01,"banner|*":.01,"video|*":.1,"*|*":.01}}},userSync:{syncEnabled:!0,filterSettings:{iframe:{bidders:"*",filter:"include"},image:{bidders:"*",filter:"include"}},syncsPerBidder:5,syncDelay:3e3,auctionDelay:100,userIds:[{name:"criteo"},{_comment:"SharedID",name:"sharedId",storage:{type:"html5",name:"_sharedID",expires:365}},{_comment:"ID5",name:"id5Id",params:{partner:"1322",abTesting:{enabled:!1,controlGroupPct:0}},storage:{type:"html5",name:"id5id",expires:90,refreshInSeconds:28800}}]}},FLOOR_STRATEGY:{enabled:!0,modelVersion:"mdl-adaptive-v1",currency:"USD",schema:{fields:["mediaType","size"],delimiter:"|"},defaults:{values:{"banner|300x250":.03,"banner|*":.01,"video|*":.1,"*|*":.01}},byDevice:{desktop:{values:{"banner|728x90":.02,"banner|970x90":.02,"banner|970x250":.05,"banner|300x600":.05}},mobile:{values:{"banner|320x100":.01,"banner|320x50":.01}}},byGeo:{},byRequestMode:{initial:{},refresh:{values:{}},retry:{values:{}}},geoKeySource:"window.COCO_GEO",debug:!0,enforcement:{floorDeals:!1}},DIV_CUSTOMIZATIONS:[{divId:"mdl-gpt-header",observerConfig:{rootMargin:"200px 0px 200px 0px",threshold:[.25]}},{divId:"mdl-gpt-header-mobile",observerConfig:{rootMargin:"200px 0px 200px 0px",threshold:[.25]}},{divId:"mdl-gpt-footer",observerConfig:{rootMargin:"300px 0px 300px 0px",threshold:[.25]}},{divId:"mdl-gpt-footer-2",observerConfig:{rootMargin:"300px 0px 300px 0px",threshold:[.25]}},{divId:"mdl-gpt-footer-mobile-0",observerConfig:{rootMargin:"300px 0px 300px 0px",threshold:[.25]}},{divId:"mdl-gpt-footer-mobile-2",observerConfig:{rootMargin:"300px 0px 300px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox1-0",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox1-1",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox1-2",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox1-3",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox2-0",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox2-1",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox2-2",observerConfig:{rootMargin:"500px 0px 500px 0px",threshold:[.25]}},{divId:"mdl-gpt-fbox3-0",observerConfig:{rootMargin:"600px 0px 600px 0px",threshold:[.25]}}],REFRESH_SETTINGS:{enabled:!0,minInterval:3e4,maxRefreshes:10,viewabilityThreshold:.5,minViewTime:3e4,idleTimeout:6e4,refreshOnTabReturn:!1,_comment:"refreshOnTabReturn: false = cumulative viewability (industry standard), true = refresh immediately when user returns after 30s+"},NO_BID_SETTINGS:{enabled:!0,maxRetries:2,retryIntervals:[15e3,3e4,45e3],fallbackToGAM:!0,onlyRetryIfEmpty:!0},BID_THROTTLING:{enabled:!1,autoPause:!1,pauseOnConsecutiveNoBids:!1,pauseOnPoorPerformance:!1,consecutiveNoBids:3,pauseDuration:12e4,minRequests:8,maxNoBidRate:.85,maxTimeoutRate:.35,_comment:"Manual throttler API stays available, but automatic bidder pausing is off unless explicitly enabled."},TRAFFIC_SHAPING:{enabled:!1,_comment:"Adaptive bidder filtering by observed performance plus optional manual rules.",performance:{minRequests:8,maxTimeoutRate:.35,maxNoBidRate:.9,maxMobileP90LatencyMs:1800},rules:[{_example:"Run Teads only on mobile in US/EU",bidder:"teads",device:["mobile"],geo:["US","EU","UK"]},{_example:"Skip Seedtag on mobile (too slow)",bidder:"seedtag",device:["mobile"],allow:!1},{_example:"50% sampling for Smart AdServer",bidder:"smartadserver",sampling:.5}]},DYNAMIC_PLACEMENTS:{enabled:!0,skipHomepage:!0,slotClass:"coco-dynamic-slot",containerStyle:"text-align:center; margin:20px 0; min-height:250px;",styles:[".coco-article-placement { margin: 24px auto; text-align: center; clear: both; min-height: 250px; display: flex; justify-content: center; align-items: center; }",".coco-discussion-placement { margin: 16px 0; padding: 12px 0; text-align: center; background: rgba(0,0,0,0.02); border-radius: 4px; min-height: 100px; display: flex; justify-content: center; align-items: center; }",".coco-manual-placement { margin: 20px auto; text-align: center; min-height: 250px; display: flex; justify-content: center; align-items: center; }",".coco-dynamic-slot { display: inline-block; }",'@media print { .coco-article-placement, .coco-discussion-placement, .coco-manual-placement, [id^="mdl-gpt-"] { display: none !important; } }',"@media (max-width: 768px) { .coco-article-placement, .coco-manual-placement { min-height: 100px; } }"],manualPlacementDefaults:{textElements:"p",wordThreshold:300,maxPlacements:3,adUnit:"/22265847236/film_box_1",sizes:[[300,250]],wrapperClass:"coco-manual-placement",cumulativeCount:!0},articleContent:{enabled:!0,container:".html_content_block",textElements:"p",wordThreshold:200,cumulativeCount:!0,maxPlacements:5,activePlacementCap:5,minElementsBetweenPlacements:1,adUnit:"/22265847236/film_box_1",sizes:[[300,250]],wrapperClass:"coco-article-placement",containerStyle:"text-align:center; margin:24px auto; min-height:250px;",variants:{inPlace:{enabled:!0},sticky:{enabled:!1,wrapperClass:"coco-article-placement coco-article-placement-sticky",containerStyle:"position:sticky; bottom:16px; text-align:center; margin:24px auto; min-height:250px; z-index:5;",minViewportWidth:1024,disallowSelector:[".comments-section",".post-list"]}}},discussionThread:{enabled:!0,container:".post-list",items:".comment",initialOffset:2,spacing:10,maxPlacements:8,activePlacementCap:8,minElementsBetweenPlacements:2,adUnit:"/22265847236/film_box_1",sizes:[[300,250]],wrapperClass:"coco-discussion-placement",containerStyle:"text-align:center; margin:16px 0; min-height:100px;",variants:{inPlace:{enabled:!0},sticky:{enabled:!1}}},_bidderPoolComment:"Dynamic demand is separate from fixed SLOT_POLICIES. bidderGroups supports shared default/mobile/desktop pools, with per-placement overrides allowed on articleContent/discussionThread.",bidderGroups:{default:[{bidder:"appnexus",params:{placementId:"13361065",reserve:.01}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448583",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275382",size:[300,250]}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384070"}},{bidder:"triplelift",params:{inventoryCode:"mdl-incontent"}}],mobile:[{bidder:"appnexus",params:{placementId:"13361066",reserve:.01}},{bidder:"rubicon",params:{accountId:"18566",siteId:"203976",zoneId:"1005256",bidonmultiformat:!0}},{bidder:"openx",params:{unit:"540448585",delDomain:"nexoff-d.openx.net"}},{bidder:"ix",params:{siteId:"275382",size:[300,250]}},{bidder:"pubmatic",params:{publisherId:"160275",adSlot:"3384071"}},{bidder:"triplelift",params:{inventoryCode:"mdl-incontent-mobile"}}]}},ANALYTICS:{enabled:!1,url:"https://analytics.mydramalist.com/v1/collect",site:"mydramalist.com",flushInterval:3e4,_comment:"Batches all requestBids results and flushes every flushInterval ms"}};class ae{constructor(){this.events={}}on(e,i){return this.events[e]||(this.events[e]=[]),this.events[e].push(i),()=>this.off(e,i)}off(e,i){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==i))}emit(e,i){this.events[e]&&this.events[e].forEach(r=>{try{r(i)}catch(l){console.error("[CocoWrapper] Event error:",l)}})}}const _={enabled:!0,rootMargin:"400px 0px 400px 0px",threshold:[.25]},j={sticky:!1,oop:!1,interstitial:!1,forceRender:!1};function F(d){return d&&typeof d=="object"?{...d}:d}function P(d){return d?Array.isArray(d)&&Array.isArray(d[0])?d:Array.isArray(d)&&typeof d[0]=="number"?[d]:[]:[]}function ne(d){return Array.isArray(d)?d:typeof d=="number"?[d]:[..._.threshold]}function U(d={},e=_){const i=d&&typeof d=="object"?d:{};return{enabled:i.enabled!==!1,rootMargin:i.rootMargin||e.rootMargin||_.rootMargin,threshold:ne(i.threshold??e.threshold)}}function q(d={},e={}){const i=d&&typeof d=="object"?d:{},r=e&&typeof e=="object"?e:{},l=i.intervalMs??i.minInterval??r.intervalMs??r.minInterval??3e4,c=i.minViewTime??r.minViewTime??l;return{enabled:i.enabled??r.enabled??!0,intervalMs:l,maxRefreshes:i.maxRefreshes??r.maxRefreshes??10,minViewTime:c,viewabilityThreshold:i.viewabilityThreshold??r.viewabilityThreshold??.5,allowEmptyRetry:i.allowEmptyRetry??r.allowEmptyRetry??!0,requireVisibility:i.requireVisibility??r.requireVisibility??!0,idleTimeout:i.idleTimeout??r.idleTimeout??6e4,refreshOnTabReturn:i.refreshOnTabReturn??r.refreshOnTabReturn??!1}}function Z(d={},e=j){return{sticky:!!(d.sticky??e.sticky),oop:!!(d.oop??e.oop),interstitial:!!(d.interstitial??e.interstitial),forceRender:!!(d.forceRender??e.forceRender)}}function Q(d,e,i){return i.has(d)?[]:(i.add(d),N(e[d],e,i))}function N(d,e={},i=new Set){return d?typeof d=="string"?Q(d,e,i):Array.isArray(d)?d.flatMap(r=>typeof r=="string"?Q(r,e,new Set(i)):r&&typeof r=="object"&&r.bidder?[F(r)]:[]):d&&typeof d=="object"&&d.bidder?[F(d)]:[]:[]}function W(d,e,i={}){return d?Array.isArray(d)||typeof d=="string"||d.bidder?{default:N(d,e),mobile:[...i.mobile||[]],desktop:[...i.desktop||[]]}:{default:d.default?N(d.default,e):[...i.default||[]],mobile:d.mobile?N(d.mobile,e):[...i.mobile||[]],desktop:d.desktop?N(d.desktop,e):[...i.desktop||[]]}:{default:[...i.default||[]],mobile:[...i.mobile||[]],desktop:[...i.desktop||[]]}}function Y(d={},e={}){const i=Object.prototype.hasOwnProperty.call(e,"default"),r=Object.prototype.hasOwnProperty.call(e,"mobile"),l=Object.prototype.hasOwnProperty.call(e,"desktop");return{default:P(i?e.default:d.default),mobile:P(r?e.mobile:d.mobile),desktop:P(l?e.desktop:d.desktop)}}function de(d={},e={}){const i=Object.prototype.hasOwnProperty.call(e,"default"),r=Object.prototype.hasOwnProperty.call(e,"mobile"),l=Object.prototype.hasOwnProperty.call(e,"desktop");return{default:i?[...e.default||[]]:[...d.default||[]],mobile:r?[...e.mobile||[]]:[...d.mobile||[]],desktop:l?[...e.desktop||[]]:[...d.desktop||[]]}}function oe(d,e,i){const r=i.BIDDERS||{},l=(i.EXTRA_BIDDERS||[]).map(F),t=(i.DIV_CUSTOMIZATIONS||[]).find(n=>n.divId===e.key),s=q(i.REFRESH_SETTINGS||{});return{key:e.key,sizes:{default:P(e.size),mobile:[],desktop:[]},bidderGroups:{default:[...(r[d]||[]).map(F),...l],mobile:[],desktop:[]},lazyLoad:U((t==null?void 0:t.observerConfig)||{},_),refresh:s,flags:{...j}}}function le(d={}){const e={};return Object.entries(d).forEach(([i,r])=>{e[i]=r}),e}function ce(d,e,i){const r=d.sizes,l=Array.isArray(r)?{default:r}:{default:r&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:d.size||r,mobile:r==null?void 0:r.mobile,desktop:r==null?void 0:r.desktop};return{key:d.key,sizes:Y({},l),bidderGroups:W(d.bidderGroups,e),lazyLoad:U(d.lazyLoad,_),refresh:q(d.refresh,i),flags:Z(d.flags,j)}}function ue(d,e){return d?e?{key:e.key||d.key,sizes:Y(d.sizes,e.sizes),bidderGroups:de(d.bidderGroups,e.bidderGroups),lazyLoad:U(e.lazyLoad,d.lazyLoad),refresh:q(e.refresh,d.refresh),flags:Z(e.flags,d.flags)}:d:e}function he(d={}){const e=new Map,i=q(d.REFRESH_SETTINGS||{}),r=le(d.BIDDER_GROUPS||{}),l=d.DEFINITIONS||{};return Object.entries(l).forEach(([c,t])=>{e.set(c,oe(c,t,d))}),Object.entries(d.SLOT_POLICIES||{}).forEach(([c,t])=>{const s=e.get(c),n=ce(t||{},r,i);e.set(c,ue(s,n))}),e}function $(d={},e=!1){var i,r;return e&&((i=d.mobile)!=null&&i.length)?d.mobile:!e&&((r=d.desktop)!=null&&r.length)?d.desktop:d.default||[]}function me(){return window.location.search.includes("coco_debug=1")||window.COCO_DEBUG}class pe{constructor(e,i){this.settings=e.DYNAMIC_PLACEMENTS||{},this.wrapper=i,this.schain=e.SCHAIN,this.placements=new Map,this.uid=0,this.handledZones=new WeakSet,this.watcher=null,this.debounceTimer=null,this.navigationTimer=null}normalizeSizes(e){return e?Array.isArray(e)&&Array.isArray(e[0])?e:Array.isArray(e)&&typeof e[0]=="number"?[e]:[]:[]}getMobileBreakpoint(){return this.settings.mobileBreakpoint||768}isMobileViewport(){return window.innerWidth<=this.getMobileBreakpoint()}getPlacementSizes(e){const i=e.responsiveSizes||{},r=this.isMobileViewport()?i.mobile||e.sizes:i.desktop||e.sizes;return this.normalizeSizes(r)}getMinHeightForSizes(e){return e.reduce((i,r)=>{if(!Array.isArray(r)||r.length<2)return i;const l=Number(r[1]);return!Number.isFinite(l)||l<=0?i:Math.min(i,l)},Number.POSITIVE_INFINITY)}debug(...e){me()&&console.log("[DynamicPlacer]",...e)}getSlotClass(){return this.settings.slotClass||"coco-dynamic-slot"}getContainerStyle(e){return e.containerStyle||this.settings.containerStyle||""}getNamedBidderGroups(){var e,i;return((i=(e=this.wrapper)==null?void 0:e.config)==null?void 0:i.BIDDER_GROUPS)||{}}getPlacementLimit(e){const i=Number(e.maxPlacements),r=Number(e.activePlacementCap??e.maxActivePlacements??i),l=Number.isFinite(i)&&i>0?i:0,c=Number.isFinite(r)&&r>0?r:l;return l>0?Math.min(l,c||l):0}getMinimumSpacing(e){const i=Number(e.minElementsBetweenPlacements??0);return Number.isFinite(i)&&i>=0?i:0}getDynamicBidderGroups(e){const i=e.bidderGroups||e.bidderPool||this.settings.bidderGroups||this.settings.bidderPool,r=W(this.settings.bidderGroups||this.settings.bidderPool,this.getNamedBidderGroups());return W(i,this.getNamedBidderGroups(),r)}getPlacementBidders(e){return $(this.getDynamicBidderGroups(e),this.isMobileViewport()).map(i=>({...i}))}getVariantConfig(e,i){const r=e.variants||{},l=r==null?void 0:r[i];return l===!1?{enabled:!1}:l===!0?{enabled:!0}:l&&typeof l=="object"?l:{}}isVariantEligible(e,i={}){if(i.enabled===!1)return!1;const r=window.innerWidth;return!(i.minViewportWidth&&ri.maxViewportWidth||i.requireSelector&&!(Array.isArray(i.requireSelector)?i.requireSelector:[i.requireSelector]).some(t=>{var s,n;try{return((s=e.matches)==null?void 0:s.call(e,t))||((n=e.closest)==null?void 0:n.call(e,t))}catch{return!1}})||i.disallowSelector&&(Array.isArray(i.disallowSelector)?i.disallowSelector:[i.disallowSelector]).some(t=>{var s,n;try{return((s=e.matches)==null?void 0:s.call(e,t))||((n=e.closest)==null?void 0:n.call(e,t))}catch{return!1}}))}resolvePlacementVariant(e,i,r){const l=this.getVariantConfig(r,"sticky");if(l.enabled&&this.isVariantEligible(e,l))return{name:"sticky",config:{...r,...l,wrapperClass:l.wrapperClass||r.wrapperClass,containerStyle:l.containerStyle||r.containerStyle}};const c=this.getVariantConfig(r,"inPlace");return{name:"inPlace",config:{...r,...c,wrapperClass:c.wrapperClass||r.wrapperClass,containerStyle:c.containerStyle||r.containerStyle}}}getDefinitionForAdUnit(e){var l,c,t,s;const i=(c=(l=this.wrapper)==null?void 0:l.getSlotDefinitionForAdUnit)==null?void 0:c.call(l,e);if(i)return[e,i];const r=((s=(t=this.wrapper)==null?void 0:t.config)==null?void 0:s.DEFINITIONS)||{};return Object.entries(r).find(([n])=>n===e)||null}countWords(e){return e?e.trim().split(/\s+/).filter(i=>i.length>0).length:0}awaitElement(e,i=40,r=100){return new Promise(l=>{let c=0;const t=()=>{const s=document.querySelector(e);if(s)return l(s);if(++c>=i)return l(null);setTimeout(t,r)};t()})}isHomepage(){const e=window.location.pathname;return e==="/"||e===""}async activate(){if(!this.settings.enabled){this.debug("Dynamic placements disabled");return}if(this.settings.skipHomepage&&this.isHomepage()){this.debug("Skipping homepage");return}this.debug("Activating dynamic ad placer"),await this.scanAndPlace(),this.setupDOMWatcher(),this.bindNavigationEvents(),this.debug("Dynamic ad placer active")}scheduleScan({delay:e=0,resetHandledZones:i=!1,reason:r="unknown"}={}){i&&(this.handledZones=new WeakSet),clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debug(`Rescanning (${r})`),this.scanAndPlace()},e)}setupDOMWatcher(){var i,r;const e=[(i=this.settings.articleContent)==null?void 0:i.container,(r=this.settings.discussionThread)==null?void 0:r.container].filter(Boolean);e.length!==0&&(this.watcher=new MutationObserver(l=>{let c=!1;for(const t of l)if(!(t.type!=="childList"||!t.addedNodes.length)){for(const s of t.addedNodes){if(s.nodeType!==Node.ELEMENT_NODE)continue;if(e.some(a=>{var o,h,u;try{return((o=s.matches)==null?void 0:o.call(s,a))||((h=s.querySelector)==null?void 0:h.call(s,a))||((u=s.closest)==null?void 0:u.call(s,a))}catch{return!1}})){c=!0;break}}if(c)break}c&&this.scheduleScan({delay:150,reason:"dom-mutation"})}),this.watcher.observe(document.body,{childList:!0,subtree:!0}))}bindNavigationEvents(){var i;if(!((i=this.wrapper)!=null&&i.eventBus))return;const e=()=>{this.debug("Navigation detected - rescanning"),clearTimeout(this.navigationTimer),this.navigationTimer=setTimeout(()=>{this.clearAll(),this.scheduleScan({delay:0,resetHandledZones:!0,reason:"navigation"})},250)};this.wrapper.eventBus.on("coco.routeChange",e),this.wrapper.eventBus.on("coco.newPage",e)}async scanAndPlace(){var i,r;this.debug("Scanning content zones...");const e=[];(i=this.settings.articleContent)!=null&&i.enabled&&e.push(this.placeByWordDensity(this.settings.articleContent)),(r=this.settings.discussionThread)!=null&&r.enabled&&e.push(this.placeByIndex(this.settings.discussionThread)),await Promise.all(e)}async placeByWordDensity(e){const i=await this.awaitElement(e.container);if(!i||this.handledZones.has(i))return;this.clearZonePlacements(i,e.wrapperClass);const r=i.querySelectorAll(e.textElements);if(!r.length){this.debug(`No text elements in ${e.container}`);return}let l=0,c=0,t=-1/0;const s=[],n=this.getPlacementLimit(e),a=this.getMinimumSpacing(e);for(let o=0;o=e.wordThreshold){if(o-t<=a)continue;s.push(h),c++,t=o,e.cumulativeCount?l-=e.wordThreshold:l=0}}this.debug(`Article: ${r.length} paragraphs, placing ${s.length} ads`);for(let o=s.length-1;o>=0;o--)this.insertPlacement(s[o],"article",e);this.handledZones.add(i)}async placeByIndex(e){const i=await this.awaitElement(e.container);if(!i||this.handledZones.has(i))return;this.clearZonePlacements(i,e.wrapperClass);const r=i.querySelectorAll(e.items);if(!r.length){this.debug(`No items found in ${e.container}`);return}const l=[];let c=0,t=-1/0;const s=this.getPlacementLimit(e),n=this.getMinimumSpacing(e);for(let a=0;an;(o===e.initialOffset&&h||o>e.initialOffset&&(o-e.initialOffset)%e.spacing===0&&h)&&(l.push(r[a]),c++,t=a)}this.debug(`Discussion: ${r.length} items, placing ${l.length} ads`);for(let a=l.length-1;a>=0;a--)this.insertPlacement(l[a],"discussion",e);this.handledZones.add(i)}clearZonePlacements(e,i){const r=[i];Object.values(this.settings||{}).forEach(s=>{s&&typeof s=="object"&&s.wrapperClass&&r.push(s.wrapperClass),s!=null&&s.variants&&typeof s.variants=="object"&&Object.values(s.variants).forEach(n=>{n&&typeof n=="object"&&n.wrapperClass&&r.push(n.wrapperClass)})});const l=[...new Set(r.filter(Boolean))].map(s=>`.${s}`).join(", "),c=l?e.querySelectorAll(l):[],t=`.${this.getSlotClass()}`;c.forEach(s=>{var a,o,h;const n=(a=s.querySelector(t))==null?void 0:a.id;n&&(this.placements.delete(n),this.wrapper&&((o=this.wrapper.slotRegistry)==null||o.delete(n),(h=this.wrapper.gptSlots)==null||h.delete(n))),s.remove()})}insertPlacement(e,i,r){var p,g;const l=this.getDefinitionForAdUnit(r.adUnit);if(!l)return this.debug(`No definition found for ${r.adUnit}`),null;const c=this.resolvePlacementVariant(e,i,r),t=c.config,[,s]=l,n=`${s.key}-${this.uid++}`,a=document.createElement("div");a.className=t.wrapperClass;const o=this.getPlacementSizes(t),h=this.getContainerStyle(t);h&&(a.style.cssText=h),c.name==="sticky"&&(a.dataset.cocoPlacementVariant="sticky",a.classList.add("coco-dynamic-sticky"));const u=this.getMinHeightForSizes(o);Number.isFinite(u)&&(a.style.minHeight=`${u}px`);const m=document.createElement("div");return m.id=n,m.className=this.getSlotClass(),m.dataset.unit=r.adUnit,m.dataset.type=i,m.dataset.cocoAdUnit=r.adUnit,m.dataset.cocoDynamic="1",m.dataset.cocoPlacementType=i,m.dataset.cocoPlacementVariant=c.name,m.dataset.cocoConfigSource="dynamic",a.appendChild(m),e.parentNode.insertBefore(a,e.nextSibling),this.debug(`Placed: ${n}`),this.placements.set(n,{type:i,variant:c.name,container:a,slot:m,config:t,sizes:o}),(g=(p=this.wrapper)==null?void 0:p.scanForAds)==null||g.call(p,a),n}manualPlace(e,i={}){const l={...this.settings.manualPlacementDefaults||{},...i,container:e};this.placeByWordDensity(l)}clearAll(){this.placements.forEach((e,i)=>{var r,l,c;(r=e.container)!=null&&r.parentNode&&e.container.parentNode.removeChild(e.container),this.wrapper&&((l=this.wrapper.slotRegistry)==null||l.delete(i),(c=this.wrapper.gptSlots)==null||c.delete(i)),this.debug(`Cleared: ${i}`)}),this.placements.clear(),this.handledZones=new WeakSet}clearByType(e){this.placements.forEach((i,r)=>{var l,c,t;i.type===e&&((l=i.container)!=null&&l.parentNode&&i.container.remove(),this.wrapper&&((c=this.wrapper.slotRegistry)==null||c.delete(r),(t=this.wrapper.gptSlots)==null||t.delete(r)),this.placements.delete(r),this.debug(`Cleared: ${r}`))})}getStats(){const e={};return this.placements.forEach(i=>{e[i.type]=(e[i.type]||0)+1}),{total:this.placements.size,byType:e}}teardown(){this.watcher&&(this.watcher.disconnect(),this.watcher=null),clearTimeout(this.debounceTimer),clearTimeout(this.navigationTimer),this.clearAll(),this.debug("Placer torn down")}}const T=[50,100,200,400,800,1200,1600,2e3,3e3,5e3];function k(d){return JSON.parse(JSON.stringify(d))}function E(d){if(!d||typeof d!="object"||Array.isArray(d))return d;const e={};return Object.entries(d).forEach(([i,r])=>{r==null||r===""||Array.isArray(r)&&r.length===0||(e[i]=r)}),e}function H(d){return d||null}function K(d){return Array.isArray(d)&&d.length>=2?`${d[0]}x${d[1]}`:typeof d=="string"?d:null}function X(){return Array(T.length+1).fill(0)}function G(){return{requests:0,responses:0,noBids:0,timeouts:0,wins:0,fills:0,revenue:0,firstBidCount:0,firstBidLatencyMsSum:0,firstRenderCount:0,firstRenderLatencyMsSum:0,gamDirectRequests:0,gamFillWithoutPrebid:0,latencyMsSum:0,latencyCount:0,latencyMsAvg:0,latencyMsP90Approx:0,_histogram:X()}}function ee(d,e={}){Object.keys(G()).forEach(i=>{i!=="_histogram"&&typeof e[i]=="number"&&(d[i]=(d[i]||0)+e[i])}),Array.isArray(e._histogram)&&(e._histogram.forEach((i,r)=>{d._histogram[r]=(d._histogram[r]||0)+i}),d.latencyMsP90Approx=V(d._histogram,.9)),d.latencyCount>0&&(d.latencyMsAvg=Math.round(d.latencyMsSum/d.latencyCount*100)/100)}function V(d,e){const i=d.reduce((c,t)=>c+t,0);if(!i)return 0;const r=Math.ceil(i*e);let l=0;for(let c=0;c=r)return T[c]||T[T.length-1];return T[T.length-1]}class ge{constructor(e){var i;this.config=e,this.settings=e.ANALYTICS||{},this.enabled=this.settings.enabled!==!1,this.url=this.settings.url,this.flushInterval=this.settings.flushInterval||15e3,this.minFlushInterval=this.settings.minFlushInterval||2e3,this.maxRetries=this.settings.maxRetries||3,this.maxWinEventsPerBatch=this.settings.maxWinEventsPerBatch||40,this.flushTimerId=null,this.activityFlushTimerId=null,this.unloadFlushSent=!1,this.activeAuctionIds=new Set,this.auctionFlushGrace=this.settings.auctionFlushGrace||this.minFlushInterval,this.prebidTimeout=((i=this.config.PREBID_CONFIG)==null?void 0:i.bidderTimeout)||0,this.attemptSequence=0,this.ctx={site:this.settings.site||"",device:this.detectDevice()},this.debugEnabled=window.location.search.includes("coco_debug=1")||window.COCO_DEBUG,this.optimizerStorageKey=this.settings.optimizerStorageKey||"__coco_bidder_performance_v1",this.optimizerState=this.loadOptimizationState(),this.resetBatch(),this.stats={flushes:0,totalWins:0,totalRevenue:0,sentBatches:0,failedBatches:0,droppedBatches:0},this.log("Analytics INIT:",{enabled:this.enabled,url:this.url||"(NOT SET)",flushInterval:this.flushInterval})}log(...e){this.debugEnabled&&console.log("[CocoWrapper]",...e)}detectDevice(){const e=navigator.userAgent;return/mobile|android|iphone/i.test(e)?"m":/tablet|ipad/i.test(e)?"t":"d"}resetBatch(){this.auctions=new Map,this.attempts=new Map,this.currentAttemptIdsBySlot=new Map,this.renders=[],this.wins=[],this.bidderSummary={},this.slotSummary={}}loadOptimizationState(){var i,r;const e={updatedAt:0,bidders:{},slots:{}};try{const l=(r=(i=window.localStorage)==null?void 0:i.getItem)==null?void 0:r.call(i,this.optimizerStorageKey);if(!l)return e;const c=JSON.parse(l);return{updatedAt:c.updatedAt||0,bidders:c.bidders||{},slots:c.slots||{}}}catch{return e}}persistOptimizationState(){var e,i;try{(i=(e=window.localStorage)==null?void 0:e.setItem)==null||i.call(e,this.optimizerStorageKey,JSON.stringify({updatedAt:Date.now(),bidders:this.optimizerState.bidders,slots:this.optimizerState.slots}))}catch{}}ensureOptimizationBidderNode(e){return e?(this.optimizerState.bidders[e]||(this.optimizerState.bidders[e]={overall:G(),byDevice:{},byRequestMode:{},bySlot:{}}),this.optimizerState.bidders[e]):null}ensureOptimizationSlotNode(e){return e?(this.optimizerState.slots[e]||(this.optimizerState.slots[e]=G()),this.optimizerState.slots[e]):null}ensureMetricContainer(e,i){return e[i]||(e[i]=G()),e[i]}addOptimizationLatency(e,i){if(!e||!Number.isFinite(i)||i<0)return;e.latencyMsSum+=i,e.latencyCount+=1,e.latencyMsAvg=Math.round(e.latencyMsSum/e.latencyCount*100)/100;let r=T.findIndex(l=>i<=l);r===-1&&(r=e._histogram.length-1),e._histogram[r]+=1,e.latencyMsP90Approx=V(e._histogram,.9)}updateOptimizationBidderMetrics(e,i,r={},l=null){const c=this.ensureOptimizationBidderNode(e);if(!c)return;const t=(i==null?void 0:i.device)||this.ctx.device,s=(i==null?void 0:i.requestMode)||"initial",n=(i==null?void 0:i.divId)||(i==null?void 0:i.adUnitPath)||null,a=[c.overall,this.ensureMetricContainer(c.byDevice,t),this.ensureMetricContainer(c.byRequestMode,s)];n&&a.push(this.ensureMetricContainer(c.bySlot,n)),a.forEach(o=>{ee(o,r),this.addOptimizationLatency(o,l)})}updateOptimizationSlotMetrics(e,i={}){const r=this.ensureOptimizationSlotNode(e);r&&ee(r,i)}getOptimizationSnapshot(){return k(this.optimizerState)}getBaseSlotContext(e={}){return{divId:e.divId||"",adUnitPath:e.adUnitPath||"",device:this.ctx.device,dynamic:!!e.dynamic,dynamicPlacementType:e.dynamicPlacementType||null,dynamicVariant:e.dynamicVariant||null,dynamicConfigSource:e.dynamicConfigSource||null}}ensureAuction(e,i={}){const r=H(e);if(!r)return null;this.auctions.has(r)||this.auctions.set(r,{auctionId:r,startedAt:i.startedAt||Date.now(),endedAt:null,elapsedMs:null,timeoutMs:Number(i.timeoutMs)||this.prebidTimeout||null,slotIds:new Set,bidders:new Set});const l=this.auctions.get(r);return i.startedAt&&!l.startedAt&&(l.startedAt=i.startedAt),typeof i.timeoutMs<"u"&&i.timeoutMs!==null&&(l.timeoutMs=Number(i.timeoutMs)||l.timeoutMs||null),Array.isArray(i.slotIds)&&i.slotIds.forEach(c=>{c&&l.slotIds.add(c)}),Array.isArray(i.bidders)&&i.bidders.forEach(c=>{c&&l.bidders.add(c)}),l}ensureBidderSummary(e){return e?(this.bidderSummary[e]||(this.bidderSummary[e]={bidder:e,requests:0,responses:0,noBids:0,timeouts:0,wins:0,latencyMsMin:null,latencyMsMax:0,latencyMsSum:0,latencyMsAvg:0,latencyMsP50Approx:0,latencyMsP90Approx:0,latencyCount:0,_histogram:X()}),this.bidderSummary[e]):null}addBidderLatency(e,i){const r=this.ensureBidderSummary(e);if(!r||!Number.isFinite(i)||i<0)return;r.latencyMsMin=r.latencyMsMin===null?i:Math.min(r.latencyMsMin,i),r.latencyMsMax=Math.max(r.latencyMsMax,i),r.latencyMsSum+=i,r.latencyCount+=1,r.latencyMsAvg=Math.round(r.latencyMsSum/r.latencyCount*100)/100;let l=T.findIndex(c=>i<=c);l===-1&&(l=r._histogram.length-1),r._histogram[l]+=1,r.latencyMsP50Approx=V(r._histogram,.5),r.latencyMsP90Approx=V(r._histogram,.9)}ensureSlotSummary(e){const i=e==null?void 0:e.divId;if(!i)return null;if(!this.slotSummary[i]){const r=this.getBaseSlotContext(e);this.slotSummary[i]={...r,initialRequests:0,refreshRequests:0,retryRequests:0,initialFilled:0,refreshFilled:0,retryFilled:0,initialEmpty:0,refreshEmpty:0,retryEmpty:0,initialNoBid:0,refreshNoBid:0,retryNoBid:0,wins:0,revenue:0,refreshWins:0,refreshRevenue:0,prebidWinNoRender:0}}return this.slotSummary[i]}incrementSlotModeMetric(e,i,r){if(!e)return;const l=`${i}${r}`;typeof e[l]=="number"&&(e[l]+=1)}createAttemptId(e){return this.attemptSequence+=1,`${e||"slot"}-${Date.now()}-${this.attemptSequence}`}startAttempt(e,i={}){if(!(e!=null&&e.divId))return null;const r=Array.isArray(i.biddersRequested)?[...new Set(i.biddersRequested.filter(Boolean))]:[],l=i.requestMode||"initial",c=this.createAttemptId(e.divId),t=i.startedAt||Date.now(),s={attemptId:c,auctionId:null,...this.getBaseSlotContext(e),requestMode:l,refreshCount:Number(i.refreshCount??e.refreshCount??0)||0,retryCount:Number(i.retryCount??e.noBidRetryCount??0)||0,bidderCountRequested:Number(i.bidderCountRequested??r.length)||0,biddersRequested:r,biddersResponded:new Set,biddersTimedOut:new Set,biddersNoBid:new Set,startedAt:t,bidsBackAt:null,elapsedMs:null,timeoutMs:Number(i.timeoutMs)||null,timeoutBucketMs:Number(i.timeoutMs)||null,usedGamDirect:!!i.usedGamDirect,bidderSetVersion:i.bidderSetVersion||null,bidderGroup:i.bidderGroup||null,biddersFiltered:E(i.biddersFiltered||{}),firstBidAt:null,firstBidLatencyMs:null,firstRenderLatencyMs:null,retryReason:i.retryReason||null,gamFilledWithoutPrebid:!1,hasWinningBid:!1,gamSuppressedWin:!1,renderRecorded:!1,bidsBackRecorded:!1};this.attempts.set(c,s),this.currentAttemptIdsBySlot.set(e.divId,c),e.currentAttemptId=c,e.lastAttemptId=c,e.lastRequestMode=l,e.lastAuctionId=null,e.lastRequestedBidders=r.slice();const n=this.ensureSlotSummary(e);return this.incrementSlotModeMetric(n,l,"Requests"),this.updateOptimizationSlotMetrics(e.divId,{requests:1,...s.usedGamDirect?{gamDirectRequests:1}:{}}),s.biddersRequested.forEach(a=>{this.updateOptimizationBidderMetrics(a,s,{requests:1,...s.usedGamDirect?{gamDirectRequests:1}:{}})}),this.persistOptimizationState(),c}getAttempt(e){if(!e)return null;if(typeof e=="string")return this.attempts.get(e)||null;const i=e.currentAttemptId||e.lastAttemptId;return i&&this.attempts.get(i)||null}getAttemptForDivId(e){if(!e)return null;const i=this.currentAttemptIdsBySlot.get(e);if(i)return this.attempts.get(i)||null;let r=null;return this.attempts.forEach(l=>{l.divId===e&&!l.renderRecorded&&(r=l)}),r}attachAuctionToAttempt(e,i,r={}){const l=this.getAttempt(e),c=H(i);!l||!c||(l.auctionId=c,e&&(e.lastAuctionId=c),this.ensureAuction(c,{startedAt:r.startedAt,timeoutMs:r.timeoutMs,slotIds:[l.divId],bidders:r.bidders||l.biddersRequested}))}markBidsBack(e,i={}){const r=this.getAttempt(e);if(!r||r.bidsBackRecorded)return;const l=i.bidsBackAt||Date.now();r.bidsBackAt=l,r.elapsedMs=Math.max(0,l-r.startedAt),r.bidsBackRecorded=!0,Array.isArray(i.biddersResponded)&&i.biddersResponded.forEach(c=>{c&&r.biddersResponded.add(c)}),Array.isArray(i.biddersTimedOut)&&i.biddersTimedOut.forEach(c=>{c&&r.biddersTimedOut.add(c)}),Array.isArray(i.biddersNoBid)&&i.biddersNoBid.forEach(c=>{c&&r.biddersNoBid.add(c)})}finalizeRender(e,i){var s,n;if(!(e!=null&&e.divId))return null;const r=this.getAttempt(e);if(!r)return null;if(r.bidsBackAt||this.markBidsBack(e,{bidsBackAt:Date.now()}),r.renderRecorded)return e.currentAttemptId=null,null;const l=Date.now(),c={attemptId:r.attemptId,isEmpty:!!(i!=null&&i.isEmpty),renderedSize:K(i==null?void 0:i.size),advertiserId:typeof(i==null?void 0:i.advertiserId)=="number"&&i.advertiserId>=0?i.advertiserId:null,lineItemId:(i==null?void 0:i.lineItemId)||((n=(s=i==null?void 0:i.lineItemId)==null?void 0:s.toString)==null?void 0:n.call(s))||null,renderedAt:l,elapsedMs:Math.max(0,l-r.startedAt),firstRenderLatencyMs:Math.max(0,l-r.startedAt),gamSuppressedWin:!!(r.hasWinningBid&&(i!=null&&i.isEmpty))};this.renders.push(c),r.renderRecorded=!0,r.gamSuppressedWin=c.gamSuppressedWin,r.firstRenderLatencyMs=c.firstRenderLatencyMs,r.gamFilledWithoutPrebid=!r.hasWinningBid&&!(i!=null&&i.isEmpty);const t=this.ensureSlotSummary(e);return this.incrementSlotModeMetric(t,r.requestMode,i!=null&&i.isEmpty?"Empty":"Filled"),t&&c.gamSuppressedWin&&(t.prebidWinNoRender+=1),this.updateOptimizationSlotMetrics(e.divId,{...i!=null&&i.isEmpty?{}:{fills:1},...r.gamFilledWithoutPrebid?{gamFillWithoutPrebid:1}:{},firstRenderCount:1,firstRenderLatencyMsSum:c.firstRenderLatencyMs}),this.persistOptimizationState(),c.gamSuppressedWin&&this.wins.forEach(a=>{a.attemptId===r.attemptId&&(a.gamSuppressedWin=!0)}),this.currentAttemptIdsBySlot.delete(e.divId),e.currentAttemptId=null,c}getWinningBid(e,i){var l;const r=(l=i==null?void 0:i[e])==null?void 0:l.bids;if(Array.isArray(r)&&r.length>0)return r.reduce((c,t)=>(t.cpm||0)>(c.cpm||0)?t:c,r[0]);try{const c=window.pbjs.getHighestCpmBids?window.pbjs.getHighestCpmBids(e):[];if(c&&c.length>0)return c.reduce((t,s)=>(s.cpm||0)>(t.cpm||0)?s:t,c[0])}catch{}try{const t=(window.pbjs.getAllWinningBids?window.pbjs.getAllWinningBids():[]).filter(s=>s.adUnitCode===e);if(t.length>0)return t[0]}catch{}return null}recordWinningBid(e,i){if(!e||!i)return;const r=this.getAttempt(e),l=i.bidderCode||i.bidder;if(!r||!l)return;const c=Number(i.cpm)||0,t={attemptId:r.attemptId,bidder:l,cpm:Math.round(c*1e3)/1e3,revenue:Math.round(c/1e3*1e6)/1e6,size:K(i.size||(i.width&&i.height?[i.width,i.height]:null)),currency:i.currency||"USD",mediaType:i.mediaType||"banner",creativeId:i.creativeId||null,ttl:Number(i.ttl)||null},s=[t.attemptId,t.bidder,t.cpm,t.size,t.adId].join("|");if(r.lastAnalyticsWinKey===s)return;r.lastAnalyticsWinKey=s,r.hasWinningBid=!0,this.wins.length>=this.maxWinEventsPerBatch&&this.flush(),this.wins.push(t);const n=this.ensureBidderSummary(l);n.wins+=1,this.updateOptimizationBidderMetrics(l,r,{wins:1,revenue:c}),this.updateOptimizationSlotMetrics(e.divId,{wins:1,revenue:c}),this.persistOptimizationState();const a=this.ensureSlotSummary(e);a&&(a.wins+=1,a.revenue=Math.round((a.revenue+c)*1e3)/1e3,r.requestMode==="refresh"&&(a.refreshWins+=1,a.refreshRevenue=Math.round((a.refreshRevenue+c)*1e3)/1e3))}recordSlotEvent(e,i,r={}){if(!(i!=null&&i.divId))return;const l=this.ensureSlotSummary(i),c=this.getAttempt(i),t=r.isRetry?"retry":(c==null?void 0:c.requestMode)||i.lastRequestMode||(r.isRefresh?"refresh":"initial");e==="noBid"&&this.incrementSlotModeMetric(l,t,"NoBid")}markAuctionStarted(e,i={}){const r=this.ensureAuction(e,{startedAt:i.startedAt||Date.now(),timeoutMs:i.timeoutMs,slotIds:i.slotIds,bidders:i.bidders});r&&(this.activeAuctionIds.add(r.auctionId),this.activityFlushTimerId&&(clearTimeout(this.activityFlushTimerId),this.activityFlushTimerId=null))}markAuctionEnded(e,i=Date.now()){const r=this.ensureAuction(e);r&&(r.endedAt=i,r.elapsedMs=r.startedAt?Math.max(0,i-r.startedAt):null),e&&this.activeAuctionIds.delete(e),this.activeAuctionIds.size===0&&this.scheduleFlush(this.auctionFlushGrace)}bindBidRequested(e){const i=e.bidderCode,r=Array.isArray(e.bids)?e.bids:[],l=H(e.auctionId||e.auction_id),c=r.map(n=>n.adUnitCode).filter(Boolean),t=Number(e.timeout)||this.prebidTimeout||null,s=this.ensureBidderSummary(i);s&&(s.requests+=r.length||1),this.markAuctionStarted(l,{startedAt:Date.now(),timeoutMs:t,slotIds:c,bidders:i?[i]:[]}),c.forEach(n=>{const a=this.getAttemptForDivId(n);if(!a)return;a.bidderCountRequested=Math.max(a.bidderCountRequested,a.biddersRequested.length),this.attachAuctionToAttempt({currentAttemptId:a.attemptId,lastAttemptId:a.attemptId,lastAuctionId:l},l,{timeoutMs:t,bidders:i?[i]:[]});const o=this.ensureAuction(l);o&&o.slotIds.add(n)}),this.log("bidRequested:",i,"x"+(r.length||1))}bindBidResponse(e){const i=e.bidderCode,r=e.adUnitCode,l=Number(e.timeToRespond)||0,c=this.ensureBidderSummary(i);c&&(c.responses+=1,this.addBidderLatency(i,l));const t=this.getAttemptForDivId(r);t&&(t.biddersResponded.add(i),t.firstBidAt||(t.firstBidAt=Date.now(),t.firstBidLatencyMs=Math.max(0,t.firstBidAt-t.startedAt),this.updateOptimizationSlotMetrics(r,{firstBidCount:1,firstBidLatencyMsSum:t.firstBidLatencyMs})),e.auctionId&&this.attachAuctionToAttempt({currentAttemptId:t.attemptId,lastAttemptId:t.attemptId},e.auctionId,{bidders:i?[i]:[]}),this.updateOptimizationBidderMetrics(i,t,{responses:1},l)),this.log("bidResponse:",i,"$"+(e.cpm||0).toFixed(2),r||"unknown",l+"ms")}bindNoBid(e){const i=e.bidderCode||e.bidder,r=e.adUnitCode,l=this.ensureBidderSummary(i);l&&(l.noBids+=1);const c=this.getAttemptForDivId(r);c&&i&&(c.biddersNoBid.add(i),this.updateOptimizationBidderMetrics(i,c,{noBids:1})),this.log("noBid:",i)}bindBidTimeout(e){(Array.isArray(e)?e:[e]).forEach(r=>{const l=r.bidder||r.bidderCode,c=r.adUnitCode,t=this.ensureBidderSummary(l);t&&(t.timeouts+=1);const s=this.getAttemptForDivId(c);s&&l&&(s.biddersTimedOut.add(l),this.updateOptimizationBidderMetrics(l,s,{timeouts:1})),this.log("bidTimeout:",l)})}serializeAuction(e){return E({auctionId:e.auctionId,startedAt:e.startedAt||null,endedAt:e.endedAt,elapsedMs:e.elapsedMs,timeoutMs:e.timeoutMs,slotCount:e.slotIds.size,bidderCount:e.bidders.size,slotIds:Array.from(e.slotIds)})}serializeAttempt(e){return E({attemptId:e.attemptId,auctionId:e.auctionId,divId:e.divId,adUnitPath:e.adUnitPath,requestMode:e.requestMode,refreshCount:e.refreshCount,retryCount:e.retryCount,dynamic:e.dynamic,dynamicPlacementType:e.dynamicPlacementType,dynamicVariant:e.dynamicVariant,dynamicConfigSource:e.dynamicConfigSource,bidderCountRequested:e.bidderCountRequested,bidderSetVersion:e.bidderSetVersion,bidderGroup:e.bidderGroup,biddersRequested:e.biddersRequested.slice(),biddersFiltered:e.biddersFiltered,biddersResponded:Array.from(e.biddersResponded),biddersTimedOut:Array.from(e.biddersTimedOut),biddersNoBid:Array.from(e.biddersNoBid),startedAt:e.startedAt,bidsBackAt:e.bidsBackAt,elapsedMs:e.elapsedMs,timeoutMs:e.timeoutMs,timeoutBucketMs:e.timeoutBucketMs,firstBidAt:e.firstBidAt,firstBidLatencyMs:e.firstBidLatencyMs,firstRenderLatencyMs:e.firstRenderLatencyMs,usedGamDirect:e.usedGamDirect,retryReason:e.retryReason,hadWinningBid:e.hasWinningBid,gamFilledWithoutPrebid:e.gamFilledWithoutPrebid,gamSuppressedWin:e.gamSuppressedWin})}serializeBidderSummary(e){return E({bidder:e.bidder,requests:e.requests,responses:e.responses,noBids:e.noBids,timeouts:e.timeouts,wins:e.wins,latencyMsMin:e.latencyMsMin,latencyMsMax:e.latencyMsMax,latencyMsSum:Math.round(e.latencyMsSum*100)/100,latencyMsAvg:e.latencyMsAvg,latencyMsP50Approx:e.latencyMsP50Approx,latencyMsP90Approx:e.latencyMsP90Approx})}buildPayload(){return{v:2,ts:Date.now(),site:this.ctx.site,device:this.ctx.device,path:window.location.pathname,auctions:Array.from(this.auctions.values()).map(e=>this.serializeAuction(e)),attempts:Array.from(this.attempts.values()).map(e=>this.serializeAttempt(e)),renders:this.renders.map(e=>E(e)),wins:this.wins.map(e=>E(e)),bidderSummary:Object.values(this.bidderSummary).map(e=>this.serializeBidderSummary(e)),slotSummary:Object.values(this.slotSummary).map(e=>E(e))}}init(){if(this.log("Analytics.init() called, enabled:",this.enabled,"url:",this.url),!this.enabled){this.log("Analytics DISABLED in config");return}if(!this.url){console.warn("[CocoWrapper] Analytics URL not configured! Set ANALYTICS.url in config.json");return}if(window.__COCO_ANALYTICS_LISTENERS_BOUND){console.warn("[CocoWrapper] Analytics listeners already bound, reusing existing registration"),this.exposeDebugAPI();return}this.setupPrebidListeners(),this.startFlushTimer(),this.setupUnloadFlush(),this.exposeDebugAPI(),window.__COCO_ANALYTICS_LISTENERS_BOUND=!0,this.log("[CocoWrapper] Analytics ready (micro-batch mode, min "+this.minFlushInterval+"ms, max "+this.flushInterval+"ms)")}setupPrebidListeners(){const e=this;window.pbjs=window.pbjs||{},window.pbjs.que=window.pbjs.que||[],window.pbjs.que.push(function(){window.pbjs.onEvent&&(window.pbjs.onEvent("bidRequested",function(i){e.bindBidRequested(i)}),window.pbjs.onEvent("bidResponse",function(i){e.bindBidResponse(i)}),window.pbjs.onEvent("noBid",function(i){e.bindNoBid(i)}),window.pbjs.onEvent("bidTimeout",function(i){e.bindBidTimeout(i)}),window.pbjs.onEvent("bidWon",function(i){e.log("[CocoWrapper] bidWon:",i.bidderCode,"$"+(i.cpm||0).toFixed(2),i.adUnitCode||"unknown",K(i.size||(i.width&&i.height?[i.width,i.height]:null))||"unknown size")}),window.pbjs.onEvent("auctionEnd",function(i){e.markAuctionEnded(i&&(i.auctionId||i.auction_id))}),e.log("[CocoWrapper] Prebid analytics listeners active (bidRequested, bidResponse, noBid, bidTimeout, bidWon, auctionEnd)"))})}startFlushTimer(){this.flushTimerId&&clearInterval(this.flushTimerId),this.flushTimerId=setInterval(()=>this.flush(),this.flushInterval)}scheduleFlush(e=this.minFlushInterval){this.activityFlushTimerId&&clearTimeout(this.activityFlushTimerId),this.activityFlushTimerId=setTimeout(()=>{this.activityFlushTimerId=null,this.flush()},e)}setupUnloadFlush(){const e=this;window.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&!e.unloadFlushSent?(e.unloadFlushSent=!0,e.flush(!0)):document.visibilityState==="visible"&&(e.unloadFlushSent=!1)}),window.addEventListener("pagehide",function(){e.unloadFlushSent||(e.unloadFlushSent=!0,e.flush(!0))})}flush(e){const i=this.buildPayload();(i.auctions.length>0||i.attempts.length>0||i.renders.length>0||i.wins.length>0||i.bidderSummary.length>0||i.slotSummary.length>0)&&(this.activityFlushTimerId&&(clearTimeout(this.activityFlushTimerId),this.activityFlushTimerId=null),this.log("Flushing analytics batch counts:",{auctions:i.auctions.length,attempts:i.attempts.length,renders:i.renders.length,wins:i.wins.length}),this.send(i,!!e),this.stats.flushes+=1,this.stats.totalWins+=i.wins.length,this.stats.totalRevenue+=i.wins.reduce((l,c)=>l+(c.cpm||0),0),this.resetBatch())}async send(e,i){if(!this.url)return console.warn("[CocoWrapper] Cannot send - no URL configured"),!1;const r=JSON.stringify(e);try{if(i&&navigator.sendBeacon){const l=new Blob([r],{type:"application/json"}),c=navigator.sendBeacon(this.url,l);if(this.log("sendBeacon:",c?"OK":"FAILED"),c)return this.stats.sentBatches+=1,!0}else return await this.sendFetch(r);return await this.sendFetch(r)}catch(l){return this.stats.failedBatches+=1,console.error("[CocoWrapper] Send error:",l),!1}}async sendFetch(e){const i=await fetch(this.url,{method:"POST",body:e,headers:{"Content-Type":"application/json"},keepalive:!0});return this.log("fetch:",i.status),i.ok?this.stats.sentBatches+=1:this.stats.failedBatches+=1,i.ok}exposeDebugAPI(){const e=this;window.cocoAnalytics={flush:()=>e.flush(),getStats:()=>({...e.stats,pendingCounts:{auctions:e.auctions.size,attempts:e.attempts.size,renders:e.renders.length,wins:e.wins.length,bidderSummary:Object.keys(e.bidderSummary).length,slotSummary:Object.keys(e.slotSummary).length}}),getUrl:()=>e.url,isEnabled:()=>e.enabled,getPendingPayload:()=>k(e.buildPayload()),getPendingAttempts:i=>{const r=Array.from(e.attempts.values()).map(l=>e.serializeAttempt(l));return k(i?r.filter(l=>l.divId===i):r)},getPendingAuctions:()=>k(Array.from(e.auctions.values()).map(i=>e.serializeAuction(i))),sendTest:()=>e.sendTest(),getOptimizationSnapshot:()=>k(e.getOptimizationSnapshot())}}sendTest(){const e={v:2,ts:Date.now(),site:this.ctx.site,device:this.ctx.device,path:window.location.pathname,test:!0};return this.log("Sending TEST:",e),this.send(e,!1),e}}function fe(){return window.location.search.includes("coco_debug=1")||window.COCO_DEBUG}class be{constructor(e){this.config=e.BID_THROTTLING||{},this.enabled=this.config.enabled!==!1,this.autoPause=this.config.autoPause===!0,this.pauseOnConsecutiveNoBids=this.config.pauseOnConsecutiveNoBids===!0,this.pauseOnPoorPerformance=this.config.pauseOnPoorPerformance===!0,this.consecutiveNoBids=this.config.consecutiveNoBids||3,this.pauseDuration=this.config.pauseDuration||12e4,this.minRequests=this.config.minRequests||8,this.maxNoBidRate=this.config.maxNoBidRate??.85,this.maxTimeoutRate=this.config.maxTimeoutRate??.35,this.noBidCounts={},this.pausedBidders={},this.performance={},this.log("BidThrottler initialized")}log(...e){fe()&&console.log("[CocoWrapper] [Throttler]",...e)}recordNoBid(e,i){if(!this.enabled)return;const r=this.ensurePerformanceStats(e,i);r.requests+=1,r.noBids+=1,this.noBidCounts[e]||(this.noBidCounts[e]={}),this.noBidCounts[e][i]=(this.noBidCounts[e][i]||0)+1,this.pauseOnConsecutiveNoBids&&this.noBidCounts[e][i]>=this.consecutiveNoBids&&this.pauseBidder(e,i),this.autoPause&&this.pauseOnPoorPerformance&&this.evaluatePerformancePause(e,i),this.log(`No-bid: ${e} for ${i} (count: ${this.noBidCounts[e][i]})`)}recordBid(e,i){if(!this.enabled)return;const r=this.ensurePerformanceStats(e,i);r.requests+=1,r.responses+=1,this.noBidCounts[e]&&(this.noBidCounts[e][i]=0),this.pausedBidders[e]&&delete this.pausedBidders[e][i]}recordTimeout(e,i){if(!this.enabled)return;const r=this.ensurePerformanceStats(e,i);r.requests+=1,r.timeouts+=1,this.log(`Timeout: ${e} for ${i}`),this.autoPause&&this.pauseOnPoorPerformance&&this.evaluatePerformancePause(e,i)}ensurePerformanceStats(e,i){return this.performance[e]||(this.performance[e]={}),this.performance[e][i]||(this.performance[e][i]={requests:0,responses:0,noBids:0,timeouts:0}),this.performance[e][i]}evaluatePerformancePause(e,i){var t,s;const r=(s=(t=this.performance)==null?void 0:t[e])==null?void 0:s[i];if(!r||r.requests=this.maxTimeoutRate||c>=this.maxNoBidRate)&&(this.pauseBidder(e,i),this.log(`Performance pause: ${e} for ${i}`,{timeoutRate:l,noBidRate:c,requests:r.requests}))}pauseBidder(e,i){this.pausedBidders[e]||(this.pausedBidders[e]={}),this.pausedBidders[e][i]=Date.now()+this.pauseDuration,this.noBidCounts[e][i]=0,this.log(`PAUSED: ${e} for ${i} (${this.pauseDuration/1e3}s)`)}isPaused(e,i){if(!this.enabled||!this.pausedBidders[e]||!this.pausedBidders[e][i])return!1;const r=this.pausedBidders[e][i];return Date.now()>=r?(delete this.pausedBidders[e][i],this.log(`RESUMED: ${e} for ${i}`),!1):!0}evaluateBidders(e,i){if(!this.enabled)return{allowed:e,blocked:[]};const r=[],l=[];return e.forEach(c=>{const t=c.bidder;if(this.isPaused(t,i)){this.log(`Skipping paused bidder: ${t} for ${i}`),l.push({bidder:t,reason:"paused"});return}r.push(c)}),{allowed:r,blocked:l}}filterBidders(e,i){return this.evaluateBidders(e,i).allowed}getStatus(){return{enabled:this.enabled,autoPause:this.autoPause,pauseOnConsecutiveNoBids:this.pauseOnConsecutiveNoBids,pauseOnPoorPerformance:this.pauseOnPoorPerformance,pausedBidders:{...this.pausedBidders},noBidCounts:{...this.noBidCounts},performance:{...this.performance}}}}function ye(){return window.location.search.includes("coco_debug=1")||window.COCO_DEBUG}class Se{constructor(e){this.config=e.TRAFFIC_SHAPING||{},this.enabled=this.config.enabled!==!1,this.rules=this.config.rules||[],this.performance=this.config.performance||{},this.context={device:this.detectDevice(),browser:this.detectBrowser(),geo:null,hour:new Date().getHours(),dayOfWeek:new Date().getDay()},this.detectGeo(),this.log("TrafficShaper initialized",this.context)}log(...e){ye()&&console.log("[CocoWrapper] [TrafficShaper]",...e)}detectDevice(){const e=navigator.userAgent;return/tablet|ipad|playbook|silk/i.test(e)?"tablet":/mobile|iphone|ipod|android|blackberry|opera mini|iemobile/i.test(e)?"mobile":"desktop"}detectBrowser(){const e=navigator.userAgent;return e.includes("Chrome")&&!e.includes("Edg")?"chrome":e.includes("Safari")&&!e.includes("Chrome")?"safari":e.includes("Firefox")?"firefox":e.includes("Edg")?"edge":"other"}detectGeo(){if(window.COCO_GEO){this.context.geo=window.COCO_GEO;return}const e=Intl.DateTimeFormat().resolvedOptions().timeZone;e&&(e.includes("America")?this.context.geo="US":e.includes("Europe/London")?this.context.geo="UK":e.includes("Europe")?this.context.geo="EU":e.includes("Asia")&&(this.context.geo="APAC"));const i=navigator.language||"";!this.context.geo&&i&&(i.includes("en-US")?this.context.geo="US":i.includes("en-GB")&&(this.context.geo="UK"))}setGeo(e){this.context.geo=e,this.log("Geo set:",e)}matchesRule(e){if(e.device&&!(Array.isArray(e.device)?e.device:[e.device]).includes(this.context.device)||e.browser&&!(Array.isArray(e.browser)?e.browser:[e.browser]).includes(this.context.browser))return!1;if(e.geo){const i=Array.isArray(e.geo)?e.geo:[e.geo];if(!this.context.geo||!i.includes(this.context.geo))return!1}if(e.excludeGeo){const i=Array.isArray(e.excludeGeo)?e.excludeGeo:[e.excludeGeo];if(this.context.geo&&i.includes(this.context.geo))return!1}return!(e.hours&&!(Array.isArray(e.hours)?e.hours:[e.hours]).includes(this.context.hour)||e.days&&!(Array.isArray(e.days)?e.days:[e.days]).includes(this.context.dayOfWeek)||e.sampling!==void 0&&Math.random()>e.sampling)}filterBidders(e,i){return this.evaluateBidders(e,i).allowed}getBidderPerformance(e,i){var c,t,s,n,a;const r=(t=(c=I())==null?void 0:c.getOptimizationSnapshot)==null?void 0:t.call(c),l=(s=r==null?void 0:r.bidders)==null?void 0:s[e];return l&&(((n=l.bySlot)==null?void 0:n[i])||((a=l.byDevice)==null?void 0:a[this.context.device])||l.overall)||null}evaluateBidders(e,i){if(!this.enabled)return{allowed:e,blocked:[]};const r=[],l=[];return e.forEach(c=>{const t=c.bidder,s=this.rules.filter(p=>p.bidder===t||p.bidder==="*"),n=this.getBidderPerformance(t,i),a=Number(this.performance.minRequests)||8,o=n?(n.timeouts||0)/Math.max(n.requests||1,1):0,h=n?(n.noBids||0)/Math.max(n.requests||1,1):0,u=Number(n==null?void 0:n.latencyMsP90Approx)||Number(n==null?void 0:n.latencyMsAvg)||0;if(n&&(n.requests||0)>=a&&(o>(this.performance.maxTimeoutRate??.35)||h>(this.performance.maxNoBidRate??.9)||this.context.device!=="desktop"&&u>(this.performance.maxMobileP90LatencyMs??1800))){this.log(`BLOCKED by performance: ${t}`,{timeoutRate:o,noBidRate:h,latencyP90:u,adUnit:i}),l.push({bidder:t,reason:"performance"});return}if(s.length===0){r.push(c);return}for(const p of s)if(p.allow===!1){if(this.matchesRule(p)){this.log(`BLOCKED by rule: ${t}`,p),l.push({bidder:t,reason:"rule"});return}}else if(this.matchesRule(p)){r.push(c);return}if(s.every(p=>p.allow!==!1)){this.log(`No matching allow rule: ${t}`),l.push({bidder:t,reason:"allow-rule-miss"});return}r.push(c)}),{allowed:r,blocked:l}}getContext(){return{...this.context}}getStatus(){return{enabled:this.enabled,context:this.context,rulesCount:this.rules.length}}}function Be(){return window.location.search.includes("coco_debug=1")||window.COCO_DEBUG}class ve{constructor(e={}){const i=e.VIEWABILITY||{};this.slots={},this.useIntersectionObserver=i.useIntersectionObserver!==!1&&typeof IntersectionObserver=="function",this.checkInterval=i.checkInterval||250,this.timer=null,this.observer=null,this.pageVisible=!document.hidden,document.addEventListener("visibilitychange",()=>{const r=this.pageVisible;this.pageVisible=!document.hidden,!this.pageVisible&&r?(this.pauseAllSlots(),this.log("Page hidden - paused viewability tracking")):this.pageVisible&&!r&&this.log("Page visible - resumed viewability tracking")}),this.log("ViewabilityTracker initialized")}log(...e){Be()&&console.log("[CocoWrapper] [Viewability]",...e)}pauseAllSlots(){const e=Date.now();Object.keys(this.slots).forEach(i=>{this.setSlotVisibility(this.slots[i],!1,e)})}track(e,i){const r=this.slots[e];(r==null?void 0:r.element)!==i&&(r&&this.observer&&this.observer.unobserve(r.element),this.slots[e]={element:i,visible:!1,lastCheck:Date.now(),totalViewTime:(r==null?void 0:r.totalViewTime)||0,currentViewStart:(r==null?void 0:r.currentViewStart)||null,lastRefreshTime:(r==null?void 0:r.lastRefreshTime)||Date.now()},this.useIntersectionObserver?(this.ensureObserver(),this.observer.observe(i)):this.timer||this.startTimer())}untrack(e){const i=this.slots[e];i!=null&&i.element&&this.observer&&this.observer.unobserve(i.element),delete this.slots[e],Object.keys(this.slots).length===0&&(this.timer&&(clearInterval(this.timer),this.timer=null),this.observer&&(this.observer.disconnect(),this.observer=null))}ensureObserver(){this.observer||!this.useIntersectionObserver||(this.observer=new IntersectionObserver(e=>{const i=Date.now();e.forEach(r=>{const l=this.slots[r.target.id];l&&this.setSlotVisibility(l,r.intersectionRatio>=.5,i)})},{threshold:[0,.5,1]}))}startTimer(){this.timer=setInterval(()=>this.checkVisibility(),this.checkInterval)}checkVisibility(){if(!this.pageVisible)return;const e=Date.now();Object.keys(this.slots).forEach(i=>{const r=this.slots[i];if(!r.element)return;const l=this.getElementVisibility(r.element);this.setSlotVisibility(r,l>=.5,e),r.lastCheck=e})}setSlotVisibility(e,i,r=Date.now()){if(!e)return;const l=e.visible;e.visible=i,i&&!l?e.currentViewStart=r:!i&&l&&e.currentViewStart&&(e.totalViewTime+=r-e.currentViewStart,e.currentViewStart=null)}getElementVisibility(e){if(!e)return 0;const i=e.getBoundingClientRect(),r=window.innerHeight||document.documentElement.clientHeight,l=window.innerWidth||document.documentElement.clientWidth,c=Math.min(i.right,l)-Math.max(i.left,0),t=Math.min(i.bottom,r)-Math.max(i.top,0);if(c<=0||t<=0)return 0;const s=c*t,n=i.width*i.height;return n>0?s/n:0}getViewTimeSinceRefresh(e){const i=this.slots[e];if(!i)return 0;let r=i.totalViewTime;i.visible&&i.currentViewStart&&(r+=Date.now()-i.currentViewStart);const l=Date.now()-i.lastRefreshTime;return Math.min(r,l)}markRefreshed(e){const i=this.slots[e];i&&(i.lastRefreshTime=Date.now(),i.totalViewTime=0,i.currentViewStart&&(i.currentViewStart=Date.now()))}isEligibleForRefresh(e,i=3e4){const r=this.slots[e];return!r||!r.visible?!1:this.getViewTimeSinceRefresh(e)>=i}getEligibleSlots(e=3e4){return Object.keys(this.slots).filter(i=>this.isEligibleForRefresh(i,e))}getData(){const e={};return Object.keys(this.slots).forEach(i=>{const r=this.slots[i];e[i]={visible:r.visible,viewTimeSinceRefresh:this.getViewTimeSinceRefresh(i),totalViewTime:r.totalViewTime,lastRefresh:r.lastRefreshTime}}),e}}let R={analytics:null,throttler:null,trafficShaper:null,viewabilityTracker:null};function te(){window.__COCO_SERVICES=R,window.__COCO_ANALYTICS_SINGLETON=R.analytics,window.cocoBidThrottler=R.throttler,window.cocoTrafficShaper=R.trafficShaper,window.cocoViewability=R.viewabilityTracker}function Ae(d){const e=window.__COCO_SERVICES;return e!=null&&e.analytics&&(e!=null&&e.throttler)&&(e!=null&&e.trafficShaper)&&(e!=null&&e.viewabilityTracker)?(R=e,te(),R):(R={analytics:new ge(d),throttler:new be(d),trafficShaper:new Se(d),viewabilityTracker:new ve(d)},R.analytics.init(),te(),R)}function Re(d){return Ae(d)}function I(){return R.analytics}function D(){return R.throttler}function L(){return R.trafficShaper}function z(){return R.viewabilityTracker}const ie=["reserve","floor","customFloor","bidfloor"];function C(d){return JSON.parse(JSON.stringify(d))}function se(d){if(!d||typeof d!="object")return{};const e={};return Object.entries(d).forEach(([i,r])=>{const l=Number(r);!i||!Number.isFinite(l)||(e[i]=l)}),e}function O(d={}){const e=d&&typeof d=="object"?d:{},i={},r={};return Object.entries(e.byDevice||{}).forEach(([l,c])=>{i[l]=O(c)}),Object.entries(e.byGeo||{}).forEach(([l,c])=>{r[l]=O(c)}),{values:se(e.values||e),byDevice:i,byGeo:r}}function Ce(d={}){const e={};return Object.entries(d||{}).forEach(([i,r])=>{e[i]=O(r)}),e}function xe(d){return Array.isArray(d)&&d.length>=2?`${d[0]}x${d[1]}`:typeof d=="string"&&d?d:null}function Ie(d,e,i){if(!d||typeof d!="object")return null;const r=[`${e}|${i}`,`${e}|*`,`*|${i}`,"*|*"];for(const l of r)if(Object.prototype.hasOwnProperty.call(d,l))return{key:l,floor:d[l]};return null}function Te(d={}){const e={},i=d.BIDDERS||{};return Object.entries(i).forEach(([r,l])=>{const c=[];(l||[]).forEach(t=>{const s=(t==null?void 0:t.params)||{},n=ie.filter(a=>Object.prototype.hasOwnProperty.call(s,a));n.length&&c.push({bidder:t.bidder||null,keys:n,values:n.reduce((a,o)=>(a[o]=s[o],a),{})})}),c.length&&(e[r]=c)}),e}function Me(d={}){var r,l,c;const e=((r=d.PREBID_CONFIG)==null?void 0:r.floors)||{},i=e.data||{};return{enabled:e!==!1,modelVersion:i.modelVersion||"mdl-static-v1",currency:i.currency||"USD",schema:{fields:Array.isArray((l=i.schema)==null?void 0:l.fields)?[...i.schema.fields]:["mediaType","size"],delimiter:((c=i.schema)==null?void 0:c.delimiter)||"|"},defaults:{values:se(i.values||{})},byDevice:{},byGeo:{},byRequestMode:{},geoKeySource:"window.COCO_GEO",debug:!1,enforcement:C(e.enforcement||{floorDeals:!1})}}class Ee{constructor(e={}){this.config=e,this.legacyAudit=Te(e),this.strategy=this.normalizeStrategy(e.FLOOR_STRATEGY||Me(e))}normalizeStrategy(e={}){var r,l,c,t;const i=e&&typeof e=="object"?e:{};return{enabled:i.enabled!==!1,modelVersion:i.modelVersion||"mdl-adaptive-v1",currency:i.currency||"USD",schema:{fields:Array.isArray((r=i.schema)==null?void 0:r.fields)?[...i.schema.fields]:["mediaType","size"],delimiter:((l=i.schema)==null?void 0:l.delimiter)||"|"},defaults:O(i.defaults),byDevice:O({byDevice:i.byDevice||{}}).byDevice,byGeo:O({byGeo:i.byGeo||{}}).byGeo,byRequestMode:Ce(i.byRequestMode||{}),geoKeySource:i.geoKeySource||"window.COCO_GEO",debug:!!i.debug,enforcement:C(i.enforcement||((t=(c=this.config.PREBID_CONFIG)==null?void 0:c.floors)==null?void 0:t.enforcement)||{floorDeals:!1})}}isEnabled(){return this.strategy.enabled!==!1}getDeviceKey(e){return e?"mobile":"desktop"}getGeoKey(e){return typeof e=="string"&&e.trim()?e.trim():typeof window<"u"&&typeof window.COCO_GEO=="string"&&window.COCO_GEO.trim()?window.COCO_GEO.trim():null}getStrategySnapshot(){return C({enabled:this.strategy.enabled,modelVersion:this.strategy.modelVersion,currency:this.strategy.currency,schema:this.strategy.schema,defaults:this.strategy.defaults,byDevice:this.strategy.byDevice,byGeo:this.strategy.byGeo,byRequestMode:this.strategy.byRequestMode,geoKeySource:this.strategy.geoKeySource,debug:this.strategy.debug,enforcement:this.strategy.enforcement})}getLegacyAudit(e=null){return C(e?this.legacyAudit[e]||[]:this.legacyAudit)}getRuleCandidates(e,i,r){var s,n,a,o,h,u,m;const l=((s=this.strategy.byRequestMode)==null?void 0:s[e])||null,c=i&&((n=this.strategy.byGeo)==null?void 0:n[i])||null,t=l&&i&&((a=l.byGeo)==null?void 0:a[i])||null;return[{label:"requestMode+geo+device",branch:((o=t==null?void 0:t.byDevice)==null?void 0:o[r])||null},{label:"requestMode+device",branch:((h=l==null?void 0:l.byDevice)==null?void 0:h[r])||null},{label:"geo+device",branch:((u=c==null?void 0:c.byDevice)==null?void 0:u[r])||null},{label:"device",branch:((m=this.strategy.byDevice)==null?void 0:m[r])||null},{label:"requestMode",branch:l},{label:"geo",branch:c},{label:"defaults",branch:this.strategy.defaults}]}resolveSizeFloor({mediaType:e="banner",sizeKey:i,requestMode:r="initial",geoKey:l=null,deviceKey:c="desktop"}={}){var s;const t=this.getRuleCandidates(r,l,c);for(const n of t){const a=Ie((s=n.branch)==null?void 0:s.values,e,i);if(a)return{floor:a.floor,matchedRule:{scope:n.label,key:a.key},fallbackUsed:a.key.includes("*")}}return{floor:null,matchedRule:{scope:"none",key:null},fallbackUsed:!0}}resolveForSlot(e,i={}){var p,g;const r=i.requestMode||"initial",l=i.device||this.getDeviceKey(!!i.isMobile),c=this.getGeoKey(i.geo),t=Number(i.floorMultiplier)||1,s=i.floorProfile||r,n=Array.isArray(e==null?void 0:e.sizes)?e.sizes:[],a={},o=[];let h=!1;n.forEach(f=>{const b=xe(f);if(!b)return;const y=this.resolveSizeFloor({mediaType:"banner",sizeKey:b,requestMode:r,geoKey:c,deviceKey:l});if(y.floor===null)return;const S=`banner|${b}`,B=Math.round(y.floor*t*1e3)/1e3;a[S]=B,o.push({size:b,floor:B,matchedRule:y.matchedRule}),h=h||y.fallbackUsed});const u=this.resolveSizeFloor({mediaType:"banner",sizeKey:"*",requestMode:r,geoKey:c,deviceKey:l});u.floor!==null&&(a["banner|*"]=Math.round(u.floor*t*1e3)/1e3,h=h||u.fallbackUsed);const m=this.resolveSizeFloor({mediaType:"*",sizeKey:"*",requestMode:r,geoKey:c,deviceKey:l});return m.floor!==null&&(a["*|*"]=Math.round(m.floor*t*1e3)/1e3,h=h||m.fallbackUsed),{divId:(e==null?void 0:e.divId)||null,adUnitPath:(e==null?void 0:e.adUnitPath)||null,requestMode:r,floorProfile:s,floorMultiplier:t,device:l,geo:c,modelVersion:this.strategy.modelVersion,currency:this.strategy.currency,schema:C(this.strategy.schema),enforcement:C(this.strategy.enforcement),resolvedValues:a,resolvedBySize:o,fallbackUsed:h,matchedRule:((p=o[0])==null?void 0:p.matchedRule)||u.matchedRule,dynamic:!!(e!=null&&e.dynamic),dynamicPlacementType:(e==null?void 0:e.dynamicPlacementType)||null,dynamicVariant:(e==null?void 0:e.dynamicVariant)||null,dynamicConfigSource:(e==null?void 0:e.dynamicConfigSource)||null,legacyWarnings:this.getLegacyAudit(e==null?void 0:e.adUnitPath),debug:{requestMode:r,device:l,geo:c,modelVersion:this.strategy.modelVersion,resolvedValues:C(a),resolvedBySize:C(o),matchedRule:((g=o[0])==null?void 0:g.matchedRule)||u.matchedRule,fallbackUsed:h}}}buildPrebidFloorsPayload(e=[]){const i={...this.strategy.defaults.values};return e.forEach(r=>{Object.entries((r==null?void 0:r.resolvedValues)||{}).forEach(([l,c])=>{i[l]=c})}),Object.keys(i).length===0&&(i["*|*"]=0),{enforcement:C(this.strategy.enforcement),data:{currency:this.strategy.currency,modelVersion:this.strategy.modelVersion,schema:C(this.strategy.schema),values:i}}}sanitizeBidder(e){if(!e||typeof e!="object")return e;if(!this.isEnabled())return C(e);const i=C(e),r=i.params&&typeof i.params=="object"?{...i.params}:null;return r&&(ie.forEach(l=>{delete r[l]}),i.params=r),i}}function De(d){return JSON.parse(JSON.stringify(d))}function Oe(d,e=0,i=1){return Math.min(i,Math.max(e,d))}function w(d,e,i=0){return!Number.isFinite(e)||e<=0?i:d/e}function _e(d=[]){return[...new Set((d||[]).map(e=>e==null?void 0:e.bidder).filter(Boolean))]}function J(d={},e=!1){return e&&d.mobile?d.mobile:!e&&d.desktop?d.desktop:d.default||null}class Pe{constructor(e={}){var i,r,l,c,t,s,n,a;this.config=e,this.settings=e.BID_OPTIMIZATION||{},this.enabled=this.settings.enabled!==!1,this.strategyVersion=this.settings.strategyVersion||"balanced-v1",this.maxBidders={initial:Number(this.settings.maxInitialBidders)||4,refresh:Number(this.settings.maxRefreshBidders)||8,retry:Number(this.settings.maxRetryBidders)||6},this.timeoutByRequestMode={initial:Number((i=this.settings.timeoutByRequestMode)==null?void 0:i.initial)||1600,refresh:Number((r=this.settings.timeoutByRequestMode)==null?void 0:r.refresh)||2200,retry:Number((l=this.settings.timeoutByRequestMode)==null?void 0:l.retry)||1800},this.floorAdjustments=this.settings.floorAdjustments||{},this.retrySettings=this.settings.retry||{},this.weights={responseRate:Number((c=this.settings.weights)==null?void 0:c.responseRate)||.3,timeoutRate:Number((t=this.settings.weights)==null?void 0:t.timeoutRate)||.2,winRate:Number((s=this.settings.weights)==null?void 0:s.winRate)||.2,revenueShare:Number((n=this.settings.weights)==null?void 0:n.revenueShare)||.15,latency:Number((a=this.settings.weights)==null?void 0:a.latency)||.15},this.groupConfig=this.settings.bidderGroups||{},this.slotOverrides=this.settings.slotOverrides||{}}isEnabled(){return this.enabled}getContext(e,i="initial"){var n,a,o;const r=I(),l=((n=r==null?void 0:r.getOptimizationSnapshot)==null?void 0:n.call(r))||null,c=(e==null?void 0:e.device)||((a=r==null?void 0:r.ctx)==null?void 0:a.device)||"d",t=c==="m"||c==="t",s=window.COCO_GEO||((o=r==null?void 0:r.ctx)==null?void 0:o.geo)||null;return{analytics:r,snapshot:l,device:c,isMobile:t,geo:s,requestMode:i}}getBidderGroupNames(e,i,r){const l=this.slotOverrides[e==null?void 0:e.adUnitPath]||this.slotOverrides[e==null?void 0:e.divId]||{},c=l[`${i}BidderGroup`]||l.bidderGroup||this.settings[`${i}BidderGroup`]||J(i==="initial"?this.settings.initialBidderGroup||{}:i==="refresh"?this.settings.refreshBidderGroup||{}:this.settings.retryBidderGroup||{},r.isMobile);return c?Array.isArray(c)?c:[c]:null}resolveEligibleBiddersByGroup(e,i,r,l){const c=this.getBidderGroupNames(i,r,l);if(!c||c.length===0)return{groupNames:[],bidders:e.slice(),matchedGroup:null};const t=new Set;return c.forEach(s=>{const n=this.groupConfig[s];Array.isArray(n)&&n.forEach(a=>{a&&t.add(a)})}),t.size===0?{groupNames:c,bidders:e.slice(),matchedGroup:null}:{groupNames:c,matchedGroup:c.join(","),bidders:e.filter(s=>t.has(s==null?void 0:s.bidder))}}getStatsForBidder(e,i,r,l,c){var u,m,p,g,f;const t=(u=e==null?void 0:e.bidders)==null?void 0:u[i];if(!t)return null;const s=((m=t.bySlot)==null?void 0:m[r==null?void 0:r.divId])||((p=t.bySlot)==null?void 0:p[r==null?void 0:r.adUnitPath])||null,n=((g=t.byDevice)==null?void 0:g[c])||null,a=((f=t.byRequestMode)==null?void 0:f[l])||null,o=t.overall||t;return{requests:((s==null?void 0:s.requests)||0)+((a==null?void 0:a.requests)||0)+((n==null?void 0:n.requests)||0)+(o.requests||0),responses:((s==null?void 0:s.responses)||0)+((a==null?void 0:a.responses)||0)+((n==null?void 0:n.responses)||0)+(o.responses||0),noBids:((s==null?void 0:s.noBids)||0)+((a==null?void 0:a.noBids)||0)+((n==null?void 0:n.noBids)||0)+(o.noBids||0),timeouts:((s==null?void 0:s.timeouts)||0)+((a==null?void 0:a.timeouts)||0)+((n==null?void 0:n.timeouts)||0)+(o.timeouts||0),wins:((s==null?void 0:s.wins)||0)+((a==null?void 0:a.wins)||0)+((n==null?void 0:n.wins)||0)+(o.wins||0),revenue:((s==null?void 0:s.revenue)||0)+((a==null?void 0:a.revenue)||0)+((n==null?void 0:n.revenue)||0)+(o.revenue||0),latencyMsAvg:(s==null?void 0:s.latencyMsAvg)??(a==null?void 0:a.latencyMsAvg)??(n==null?void 0:n.latencyMsAvg)??o.latencyMsAvg??null,latencyMsP90Approx:(s==null?void 0:s.latencyMsP90Approx)??(a==null?void 0:a.latencyMsP90Approx)??(n==null?void 0:n.latencyMsP90Approx)??o.latencyMsP90Approx??null}}scoreBidder(e,i){if(!e)return{score:i==="initial"?.45:.5,confidence:0,metrics:{}};const r=Math.max(e.requests||0,1),l=w(e.responses||0,r),c=w(e.timeouts||0,r),t=w(e.wins||0,r),s=Math.min(1,Number(e.revenue||0)/5),n=Number(e.latencyMsP90Approx)||Number(e.latencyMsAvg)||this.timeoutByRequestMode[i],a=Oe(1-n/Math.max(this.timeoutByRequestMode[i],1),0,1),o=l*this.weights.responseRate+(1-c)*this.weights.timeoutRate+t*this.weights.winRate+s*this.weights.revenueShare+a*this.weights.latency;return{score:Math.round(o*1e4)/1e4,confidence:Math.min(1,r/Math.max(Number(this.settings.minRequestsForConfidentScore)||12,1)),metrics:{requests:r,responseRate:Math.round(l*1e3)/1e3,timeoutRate:Math.round(c*1e3)/1e3,winRate:Math.round(t*1e3)/1e3,revenue:Math.round((Number(e.revenue)||0)*1e3)/1e3,latencyMsP90Approx:n}}}getAdaptiveTimeout(e,i,r=[]){const l=this.timeoutByRequestMode[i]||this.timeoutByRequestMode.initial,c=r.slice(0,Math.max(1,Math.min(3,r.length))).map(n=>{var a,o;return Number((o=(a=n==null?void 0:n.scorecard)==null?void 0:a.metrics)==null?void 0:o.latencyMsP90Approx)||0}).filter(n=>n>0);if(c.length===0)return l;const t=Math.round(c.reduce((n,a)=>n+a,0)/c.length);return Math.min(Number(this.settings.maxTimeoutMs)||2500,Math.max(Number(this.settings.minTimeoutMs)||900,t+(i==="initial"?150:250)))||l}getFloorProfile(e,i,r){var a,o;const l=this.floorAdjustments[i]||{},c=((o=(a=r.snapshot)==null?void 0:a.slots)==null?void 0:o[e==null?void 0:e.divId])||{},t=w(c.fills||0,c.requests||0,.5),s=w(c.revenue||0,c.requests||0,0);let n=Number(l.multiplier)||1;return i==="refresh"&&s>=(Number(l.highValueRevenuePerRequest)||.4)&&(n*=Number(l.highValueMultiplier)||1.05),t<(Number(l.lowFillThreshold)||.25)&&(n*=Number(l.lowFillMultiplier)||.9),{profile:l.profile||i,multiplier:Math.round(n*1e3)/1e3}}shouldAllowRetry(e,i={}){var a,o;const r=this.retrySettings,l=((o=(a=i.snapshot)==null?void 0:a.slots)==null?void 0:o[e==null?void 0:e.divId])||{},c=Number(r.maxRetries);if(Number.isFinite(c)&&c>=0&&((e==null?void 0:e.noBidRetryCount)||0)>=c)return{allowed:!1,reason:"retry-cap"};if(r.requireVisibility!==!1&&i.isVisible===!1&&(e==null?void 0:e.lastRenderEmpty)!==!0)return{allowed:!1,reason:"not-visible"};const t=Number(r.minSlotRevenue)||0,s=Number(l.revenue||0)>=t||Number(l.wins||0)>0,n=i.viewability>=(Number(r.minViewability)||.5);return!s&&!n&&(e==null?void 0:e.lastRenderEmpty)!==!0?{allowed:!1,reason:"low-value"}:{allowed:!0,reason:i.reason||"eligible"}}selectBidders(e,i=[],r="initial"){const l=this.getContext(e,r),c=this.resolveEligibleBiddersByGroup(i,e,r,l),t=c.bidders,s=l.snapshot||{},n=t.map(m=>{const p=m==null?void 0:m.bidder,g=this.getStatsForBidder(s,p,e,r,l.device),f=this.scoreBidder(g,r);return{bidder:m,bidderName:p,stats:g,scorecard:f}}).sort((m,p)=>p.scorecard.score-m.scorecard.score),a=this.enabled?Math.min(this.maxBidders[r]||n.length,n.length):n.length,o=n.slice(0,a),h=this.enabled?this.getAdaptiveTimeout(e,r,o):null,u=this.getFloorProfile(e,r,l);return{requestMode:r,strategyVersion:this.strategyVersion,matchedBidderGroup:c.matchedGroup,bidderGroupsConsidered:c.groupNames,selectedBidders:o.map(m=>m.bidder),scoredBidders:n.map(m=>({bidder:m.bidderName,score:m.scorecard.score,confidence:m.scorecard.confidence,metrics:m.scorecard.metrics})),biddersFiltered:n.slice(a).map(m=>m.bidderName),filterReasons:n.slice(a).reduce((m,p)=>(m[p.bidderName]="score-cut",m),{}),timeoutMs:h,floorProfile:u,allCandidateBidders:_e(t)}}getDebugSnapshot(){return De({enabled:this.enabled,strategyVersion:this.strategyVersion,maxBidders:this.maxBidders,timeoutByRequestMode:this.timeoutByRequestMode,bidderGroups:this.groupConfig,slotOverrides:this.slotOverrides})}}/** * CocoWrapper - Header Bidding Wrapper * Vite Build - Config imported from config.json * * @version 1.0.0 * @license MIT */(function(d){class e{constructor(){this.queue=[],this.processing=!1}addTask(t,s=50,n=10){this.queue.push({task:t,delay:s,retries:0,maxRetries:n}),this.processQueue()}async processQueue(){if(!this.processing){for(this.processing=!0;this.queue.length>0;){const{task:t,delay:s,retries:n,maxRetries:a}=this.queue[0];try{await t()?this.queue.shift():nsetTimeout(h,s))):this.queue.shift()}catch(o){console.error("[CocoWrapper] Task error:",o),this.queue.shift()}}this.processing=!1}}}class i{constructor(t){this.config=t,this.slotPolicies=he(t),this.globalName=t.COCO_GLOBAL||"coco",this.globalBidName=this.globalName+"bid",this.performance=t.PERFORMANCE||{},this.coalesceDomScans=this.performance.coalesceDomScans!==!1,this.mutationDebounceMs=Math.max(0,Number(this.performance.mutationDebounceMs)||0),this.slotRegistry=new Map,this.instanceCounters=new Map,this.divCountMap={},this.refreshCounters={},this.observers=new Map,this.gptSlots=new Map,this.slotDefinitions=[],this.slotDefinitionByBaseId=new Map,this.scanRootQueue=new Set,this.scanFlushTimerId=null,this.scanFlushScheduled=!1,this.autoRefreshState={handlersBound:!1,lastActivity:0,lastActivityEventAt:0,isIdle:!1,tabHiddenTime:null,visibilityRefreshTimerId:null},this.initialLoadBatch={slots:new Map,timerId:null,closed:!1,windowMs:Math.max(0,(t.PREBID_CONFIG||{}).initialLoadBatchWindowMs||100)},this.eventBus=new ae,this.taskQueue=new e,this.floorStrategy=new Ee(t),this.bidOptimizer=new Pe(t),this.initialized=!1,this.firstPageviewFired=!1,this.buildSlotDefinitionIndex(),this.handleNewNode=this.handleNewNode.bind(this),this.handleRouteChange=this.handleRouteChange.bind(this),this.flushPendingScans=this.flushPendingScans.bind(this)}async init(){this.initialized||(this.log("Initializing..."),this.configureGPT(),this.configurePrebid(),this.initAnalytics(),this.createGlobalAPI(),this.setupLazyLoadObservers(),this.startMutationObserver(),this.setupRouteChangeDetection(),this.scanForAds(),this.injectStyles(),this.startAutoRefresh(),this.initDynamicPlacer(),this.initialized=!0,this.eventBus.emit("coco.initialized"),this.log("Initialization complete"))}initDynamicPlacer(){var t;(t=this.config.DYNAMIC_PLACEMENTS)!=null&&t.enabled&&(this.dynamicPlacer=new pe(this.config,this),this.dynamicPlacer.activate(),this.log("Dynamic ad placer activated"))}initAnalytics(){Re(this.config)}configureGPT(){d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>{googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.enableServices(),googletag.pubads().addEventListener("slotRenderEnded",t=>{const s=t.slot.getSlotElementId(),n=this.slotRegistry.get(s),a=I();n&&(n.lastRenderEmpty=t.isEmpty,n.lastRenderTime=Date.now(),this.emitSlotEvent("coco.renderComplete",n,{isEmpty:t.isEmpty,size:t.size||null}),a&&a.finalizeRender(n,t),t.isEmpty?(this.log(`GPT rendered EMPTY for ${s}`),n.pendingRetryCheck&&(n.pendingRetryCheck=!1,(this.config.NO_BID_SETTINGS||{}).enabled!==!1&&(this.log(`No ad rendered for ${s}, scheduling retry`),this.scheduleNoBidRetry(n,"gpt-empty")))):(this.log(`GPT rendered AD for ${s} (${t.size?t.size.join("x"):"unknown size"})`),n.pendingRetryCheck=!1,this.cancelNoBidRetry(n),n.noBidRetryCount=0))}),this.log("GPT configured")})}configurePrebid(){const t=d.pbjs,s=this.config.PREBID_CONFIG||{},n=d.location.search.includes("coco_debug=1")||d.location.search.includes("coco_dev=1")||d.COCO_DEBUG||d.COCO_DEV;t.que.push(()=>{const a={};if(s.priceGranularity&&(a.priceGranularity=s.priceGranularity),typeof s.enableSendAllBids<"u"&&(a.enableSendAllBids=s.enableSendAllBids),s.bidderTimeout&&(a.bidderTimeout=s.bidderTimeout),s.bidderSequence&&(a.bidderSequence=s.bidderSequence),typeof s.useBidCache<"u"&&(a.useBidCache=s.useBidCache),s.targetingControls&&(a.targetingControls=s.targetingControls),(s.schain||this.config.SCHAIN)&&(a.schain=s.schain||this.config.SCHAIN),s.userSync&&(a.userSync=s.userSync),this.floorStrategy.isEnabled()?a.floors=this.floorStrategy.buildPrebidFloorsPayload([]):s.floors&&(a.floors=s.floors),s.pubcid&&(a.pubcid=s.pubcid),n?(this.log("DEV MODE: Disabling consent management"),a.consentManagement={gdpr:{cmpApi:"static",timeout:0,defaultGdprScope:!1,consentData:{getTCData:{tcString:"",gdprApplies:!1,purposeOneTreatment:!1,addtlConsent:""}}},usp:{cmpApi:"static",timeout:0,consentData:{getUSPData:{uspString:"1---"}}},gpp:{cmpApi:"static",timeout:0,consentData:{applicableSections:[],gppString:""}}}):s.consentManagement&&(a.consentManagement=s.consentManagement),t.setConfig(a),this.log("Prebid configured",n?"(DEV MODE - consent bypassed)":""),s.userSync&&s.userSync.userIds&&s.userSync.userIds.length>0){const o=s.userSync.userIds.filter(h=>h.name&&!h.name.startsWith("_")).map(h=>h.name);this.log("User ID modules configured:",o.join(", ")),setTimeout(()=>{if(typeof t.getUserIds=="function"){const h=t.getUserIds(),u=Object.keys(h).filter(m=>h[m]);u.length>0?this.log("User IDs resolved:",u.join(", ")):this.log("No User IDs resolved yet (may need page refresh or user interaction)")}},5e3)}})}createGlobalAPI(){const t=this;d[this.globalBidName]=d[this.globalBidName]||{};const s=d[this.globalBidName];s.cmd=s.cmd||[],s.version="1.0.0",s.state={targeting:{}};const n=Array.isArray(s.cmd)?[...s.cmd]:[];s.cmd={push:a=>a()},n.forEach(a=>{try{a()}catch{}}),s.setTargeting=(a,o)=>{s.state.targeting[a]=o,d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.pubads().setTargeting(a,o))},s.clearTargeting=a=>{a?delete s.state.targeting[a]:s.state.targeting={},d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>{a?d.googletag.pubads().clearTargeting(a):d.googletag.pubads().clearTargeting()})},s.forceRefresh=a=>{a?(Array.isArray(a)?a:[a]).forEach(h=>t.refreshSlot(h)):t.refreshAllAds()},s.newPage=()=>(t.handleRouteChange(d.location.pathname),Promise.resolve()),s.reloadSlot=a=>(t.refreshSlot(a),Promise.resolve()),s.reloadAllSlots=()=>t.refreshAllAds(),s.ensureSlotScript=(a,o,h=!1)=>{const u=document.getElementById(a);u&&!u.classList.contains("coco-processed")&&t.queueScan(u.parentElement||u);const m=t.slotRegistry.get(a);return m?(m.loaded&&h&&(m.lastRefreshTime=0,t.refreshSlot(a)),Promise.resolve(!!m&&(m.adUnitPath===o||!o))):Promise.resolve(!1)},s.injectViaSelectorMappings=(a,o=!1)=>(t.injectViaSelectorMappings(a,o),Promise.resolve()),s.injectScriptViaSelectorMappingsV2=(a,o=!1)=>(t.injectScriptViaSelectorMappingsV2(a,o),Promise.resolve()),s.refreshViaSelectorMappings=(a,o=!1)=>(t.refreshViaSelectorMappings(a,o),Promise.resolve()),s.startAutoRefresh=()=>t.startAutoRefresh(),s.stopAutoRefresh=()=>t.stopAutoRefresh(),s.setFirstPartyData=a=>{d.pbjs.que.push(()=>{d.pbjs.setConfig({ortb2:{site:a.site||{},user:a.user||{}}})})},s.pubads=()=>({setTargeting:(a,o)=>s.setTargeting(a,o),clearTargeting:a=>s.clearTargeting(a),setPublisherProvidedId:a=>{d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.pubads().setPublisherProvidedId(a))},addEventListener:(a,o)=>{d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.pubads().addEventListener(a,o))},disableInitialLoad:()=>{d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.pubads().disableInitialLoad())}}),s.enableServices=()=>{d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.enableServices())},s.display=a=>{d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.display(a))},s.destroySlots=a=>{d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>d.googletag.destroySlots(a))},s.getEventBus=()=>t.eventBus,s.getInjector=()=>t,s.getDynamicPlacer=()=>t.dynamicPlacer,s.placeAds=(a,o)=>{t.dynamicPlacer?t.dynamicPlacer.manualPlace(a,o):console.warn("[CocoWrapper] Dynamic placer not active")},s.clearDynamicAds=a=>{t.dynamicPlacer&&(a?t.dynamicPlacer.clearByType(a):t.dynamicPlacer.clearAll())},s.getPlacementStats=()=>t.dynamicPlacer?t.dynamicPlacer.getStats():{total:0,byType:{}},s.getUserIds=()=>d.pbjs&&typeof d.pbjs.getUserIds=="function"?d.pbjs.getUserIds():{},s.getUserIdsAsEids=()=>d.pbjs&&typeof d.pbjs.getUserIdsAsEids=="function"?d.pbjs.getUserIdsAsEids():[],s.refreshUserIds=a=>{d.pbjs&&typeof d.pbjs.refreshUserIds=="function"?(d.pbjs.refreshUserIds({},a),t.log("User IDs refresh triggered")):t.log("refreshUserIds not available")},s.getThrottleStatus=()=>{const a=D();return a?a.getStatus():{enabled:!1}},s.pauseBidder=(a,o)=>{const h=D();h&&(h.pauseBidder(a,o||"*"),t.log(`Manually paused bidder: ${a}`))},s.getTrafficContext=()=>{const a=L();return a?a.getContext():{}},s.setGeo=a=>{const o=L();o&&o.setGeo(a),d.COCO_GEO=a},s.getViewabilityData=()=>{const a=z();return a?a.getData():{}},s.getEligibleForRefresh=(a=3e4)=>{const o=z();return o?o.getEligibleSlots(a):[]},s.getSlotPolicies=()=>t.getDebugSlotPolicies(),s.getFloorStatus=()=>t.getFloorStatus(),s.getSlotStatus=()=>{const a=z(),o=a?a.getData():{},h={};return t.slotRegistry.forEach((u,m)=>{var v,M,A,x;const p=t.getRefreshPolicy(u),g=t.getElementVisibility(u.element),f=!!o[m],b=f?o[m].viewTimeSinceRefresh:0,y=Date.now()-(u.lastRefreshTime||0),S=g>=p.viewabilityThreshold,B=t.isSlotEligibleForRefresh(u,{forceRefresh:!1,viewTracker:a,viewData:o,now:Date.now()});h[m]={loaded:u.loaded,refreshCount:u.refreshCount,lastRequestMode:u.lastRequestMode||null,maxedOut:u.refreshCount>=p.maxRefreshes,visible:S,visibility:Math.round(g*100)+"%",tracked:f,viewTime:Math.round(b/1e3)+"s",timeSinceRefresh:Math.round(y/1e3)+"s",eligible:B,reason:u.loaded?p.enabled===!1?"refresh disabled":u.refreshCount>=p.maxRefreshes?"max refreshes":!f&&p.requireVisibility!==!1&&!S?"not visible":f&&p.requireVisibility!==!1&&!o[m].visible?"not visible (tracked)":f&&b{const a=I();return a?a.stats:{}},s.flushAnalytics=()=>{const a=I();a&&(a.flush(),t.log("Analytics flushed"))},this.log("Global API created")}startMutationObserver(){new MutationObserver(s=>{s.forEach(n=>{n.type==="childList"?n.addedNodes.forEach(a=>this.handleNewNode(a)):n.type==="attributes"&&n.attributeName==="class"&&n.target instanceof Element&&this.handleNewNode(n.target)})}).observe(document.body,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["class"]})}handleNewNode(t){t instanceof Element&&(t.classList.contains("coco-processed")||this.hasTargetDiv(t)&&this.queueScan(t))}getMobileBreakpoint(){var t;return this.config.MOBILE_BREAKPOINT||((t=this.config.DYNAMIC_PLACEMENTS)==null?void 0:t.mobileBreakpoint)||768}isMobileViewport(){return d.innerWidth<=this.getMobileBreakpoint()}getSlotPolicy(t){const n=(this.config.SLOT_MAPPINGS||{})[t]||t;return this.slotPolicies.get(n)||this.slotPolicies.get(t)||null}buildSlotDefinitionIndex(){this.slotDefinitions=Array.from(this.slotPolicies.entries()).filter(([,t])=>t==null?void 0:t.key).map(([t,s])=>({path:t,policy:s,baseId:s.key,numberedIdPattern:new RegExp(`^${s.key}-\\d+$`)})),this.slotDefinitionByBaseId=new Map(this.slotDefinitions.map(t=>[t.baseId,t]))}getSlotDefinitionEntries(){return this.slotDefinitions.map(t=>[t.path,t.policy])}getSlotDefinitionForAdUnit(t){var n;const s=this.getSlotPolicy(t);return s!=null&&s.key?{key:s.key,size:((n=s.sizes)==null?void 0:n.default)||[]}:null}getExistingMappedSlotElement(t,s,n){if(this.isDirectMappedSlotElement(t,s,n))return t;if(!(t!=null&&t.querySelector))return null;const a=`[data-coco-selector-slot="${n}"]`,o=t.querySelector(a);if(o)return o;const h=t.querySelector(`[id="${s}"]`);return h||Array.from(t.querySelectorAll(`[id^="${s}-"]`)).find(u=>/^.+-\d+$/.test(u.id))||null}isDirectMappedSlotElement(t,s,n){var a,o;return t instanceof Element?!!(((a=t.dataset)==null?void 0:a.cocoAdUnit)===n||t.id===s||t.id&&new RegExp(`^${s}-\\d+$`).test(t.id)||t.classList.contains("coco-dynamic-slot")||((o=t.dataset)==null?void 0:o.cocoDynamic)==="1"):!1}createMappedSlotElement(t,s,n){if(!t||!s)return null;const a=document.createElement("div");let o=s;return(document.getElementById(o)||this.slotRegistry.has(o))&&(o=`${s}-${this.getNextInstanceId(s)}`),a.id=o,a.dataset.cocoAdUnit=n,a.dataset.cocoSelectorSlot=n,t.appendChild(a),a}ensureMappedSlotElement(t,s,n){const a=n==null?void 0:n.key;if(!t||!a)return null;if(this.isDirectMappedSlotElement(t,a,s)){if(!t.id){let o=a;(document.getElementById(o)||this.slotRegistry.has(o))&&(o=`${a}-${this.getNextInstanceId(a)}`),t.id=o}return t.dataset.cocoAdUnit=s,t.dataset.cocoSelectorSlot=s,t}return this.getExistingMappedSlotElement(t,a,s)||this.createMappedSlotElement(t,a,s)}stopObservingSlot(t){if(!(t!=null&&t.divId))return;const s=this.observers.get(t.divId);s&&t.element&&s.unobserve(t.element)}injectViaSelectorMappings(t,s=!1){this.injectScriptViaSelectorMappingsV2(t,s)}injectScriptViaSelectorMappingsV2(t,s=!1){(Array.isArray(t)?t:[t]).forEach(a=>this.injectScriptViaSelectorMappingV2(a,s))}buildSelectorMappingScriptContent(t,s=!1){return` window.cocobid = window.cocobid || { cmd: [] }; window.cocobid.cmd.push(function() { window.cocobid.refreshViaSelectorMappings(${JSON.stringify([{selector:t.selector,adUnitPath:t.adUnitPath}])}, ${s?"true":"false"}); }); `.trim()}buildSlotScriptContent({divId:t,adUnitPath:s},n=!1){return` window.cocobid = window.cocobid || { cmd: [] }; window.cocobid.cmd.push(function() { window.cocobid.ensureSlotScript(${JSON.stringify(t)}, ${JSON.stringify(s)}, ${n?"true":"false"}); }); `.trim()}ensureInjectedSlotScript(t,{divId:s,adUnitPath:n},a=!1){if(!t||!s||!n)return null;const o=`${s}::${n}::slot::${a?"1":"0"}`,h=Array.from(t.querySelectorAll("script")).find(m=>m.dataset.cocoInjectedScript===o);if(h)return h;const u=document.createElement("script");return u.type="text/javascript",u.text=this.buildSlotScriptContent({divId:s,adUnitPath:n},a),t.appendChild(u),u}injectScriptViaSelectorMappingV2(t,s=!1){const n=t==null?void 0:t.selector,a=t==null?void 0:t.adUnitPath;if(!n||!a)return null;const o=Array.from(document.querySelectorAll(n));if(o.length===0)return this.log(`No selector targets found for ${n}`),null;const h=this.buildSelectorMappingScriptContent(t,s),u=`${n}::${a}::${s?"1":"0"}`;return o.map(m=>{if(!m)return null;const p=Array.from(m.querySelectorAll("script")).find(f=>f.dataset.cocoInjectedScript===u);if(p)return p;const g=document.createElement("script");return g.type="text/javascript",g.text=h,m.appendChild(g),g}).filter(Boolean)}injectViaSelectorMapping(t){const s=t==null?void 0:t.selector,n=t==null?void 0:t.adUnitPath;if(!s||!n)return null;const a=this.getSlotDefinitionForAdUnit(n);if(!a)return this.log(`Unknown selector mapping ad unit: ${n}`),null;const o=Array.from(document.querySelectorAll(s));return o.length===0?(this.log(`No selector targets found for ${s}`),null):o.map(h=>{const u=this.ensureMappedSlotElement(h,n,a);return u!=null&&u.id?(u.classList.contains("coco-processed")||this.initializeAdSlot(u,n,a),u.id):null}).filter(Boolean)}refreshViaSelectorMappings(t,s=!1){(Array.isArray(t)?t:[t]).forEach(a=>this.refreshViaSelectorMapping(a,s))}refreshViaSelectorMapping(t,s=!1){const n=this.injectViaSelectorMapping(t);!n||n.length===0||n.forEach(a=>{const o=this.slotRegistry.get(a);if(o){if(!o.loaded){this.stopObservingSlot(o),this.loadAd(o);return}s&&(o.lastRefreshTime=0),this.refreshSlot(o.divId)}})}getDefaultLazyLoadConfig(t=""){return t.includes("header")?{rootMargin:"200px 0px 200px 0px",threshold:[.25]}:t.includes("footer")?{rootMargin:"300px 0px 300px 0px",threshold:[.25]}:t.includes("fbox")?{rootMargin:"500px 0px 500px 0px",threshold:[.25]}:{rootMargin:"400px 0px 400px 0px",threshold:[.25]}}getLegacyDivCustomization(t){return(this.config.DIV_CUSTOMIZATIONS||[]).find(n=>n.divId===t)||null}getResolvedSlotPolicy(t,{divId:s}={}){const n=this.getSlotPolicy(t);if(!n)return null;const a=this.isMobileViewport(),o=this.getDefaultLazyLoadConfig(s||n.key||""),h=s?this.getLegacyDivCustomization(s):null,u={...n.lazyLoad||o,...(h==null?void 0:h.observerConfig)||{}};return Array.isArray(u.threshold)||(u.threshold=typeof u.threshold=="number"?[u.threshold]:[.25]),typeof u.enabled>"u"&&(u.enabled=!0),{key:n.key,sizes:$(n.sizes,a),bidders:$(n.bidderGroups,a),lazyLoad:u,refresh:{...n.refresh||{}},flags:{...n.flags||{}}}}getRefreshPolicy(t){var s,n;return((s=t==null?void 0:t.policy)==null?void 0:s.refresh)||((n=this.getSlotPolicy(t==null?void 0:t.adUnitPath))==null?void 0:n.refresh)||{enabled:!1,intervalMs:3e4,maxRefreshes:10,minViewTime:3e4,viewabilityThreshold:.5,allowEmptyRetry:!0,requireVisibility:!0,idleTimeout:6e4,refreshOnTabReturn:!1}}getDebugSlotPolicies(){const t={};return this.slotPolicies.forEach((s,n)=>{t[n]={key:s.key,sizes:s.sizes,bidderGroups:s.bidderGroups,lazyLoad:s.lazyLoad,refresh:s.refresh,flags:s.flags}}),t}getFloorStatus(){const t={};return this.slotRegistry.forEach((s,n)=>{t[n]={divId:n,adUnitPath:s.adUnitPath,lastRequestMode:s.lastRequestMode||null,dynamic:!!s.dynamic,dynamicPlacementType:s.dynamicPlacementType||null,dynamicVariant:s.dynamicVariant||null,dynamicConfigSource:s.dynamicConfigSource||null,floorData:s.lastFloorData||null,legacyWarnings:s.legacyFloorWarnings||[]}}),{strategy:this.floorStrategy.getStrategySnapshot(),slots:t,legacyAudit:this.floorStrategy.getLegacyAudit()}}hasTargetDiv(t){return this.collectCandidateElements(t).length>0}scanForAds(t=document){this.collectCandidateElements(t).forEach(n=>this.processCandidateElement(n))}getDefinitionForElementId(t){if(!t)return null;if(this.slotDefinitionByBaseId.has(t))return this.slotDefinitionByBaseId.get(t);for(const s of this.slotDefinitions)if(s.numberedIdPattern.test(t))return s;return null}collectCandidateElements(t){var o,h;if(!t)return[];const s=[],n=new Set,a=u=>{!(u instanceof Element)||!u.id||this.getDefinitionForElementId(u.id)&&(n.has(u)||(n.add(u),s.push(u)))};return t instanceof Element?(a(t),(o=t.querySelectorAll)==null||o.call(t,"[id]").forEach(a),s):((h=t.querySelectorAll)==null||h.call(t,"[id]").forEach(a),s)}processCandidateElement(t){if(!t||t.classList.contains("coco-processed"))return;const s=this.getDefinitionForElementId(t.id);if(s){if(t.id===s.baseId&&this.slotRegistry.has(s.baseId)){const n=`${s.baseId}-${this.getNextInstanceId(s.baseId)}`;t.id=n,this.log(`Renamed duplicate: ${s.baseId} -> ${n}`)}this.initializeAdSlot(t,s.path,s.policy)}}queueScan(t=document,s=this.mutationDebounceMs){const n=t instanceof Element||t===document?t:document;if(!this.coalesceDomScans){s>0?setTimeout(()=>this.scanForAds(n),s):this.scanForAds(n);return}this.scanRootQueue.add(n),!this.scanFlushScheduled&&(this.scanFlushScheduled=!0,s>0?this.scanFlushTimerId=setTimeout(this.flushPendingScans,s):typeof requestAnimationFrame=="function"?requestAnimationFrame(this.flushPendingScans):this.scanFlushTimerId=setTimeout(this.flushPendingScans,0))}flushPendingScans(){this.scanFlushScheduled=!1,this.scanFlushTimerId&&(clearTimeout(this.scanFlushTimerId),this.scanFlushTimerId=null);const t=Array.from(this.scanRootQueue);this.scanRootQueue.clear(),t.forEach(s=>this.scanForAds(s))}getNextInstanceId(t){const s=this.instanceCounters.get(t)||0;return this.instanceCounters.set(t,s+1),s+1}getBiddersForSlot(t){var s;return((s=this.getResolvedSlotPolicy(t))==null?void 0:s.bidders)||[]}normalizeSizes(t){return P(t)}getDynamicSlotMetadata(t){var s,n,a,o;return{dynamic:((s=t.dataset)==null?void 0:s.cocoDynamic)==="1",dynamicPlacementType:((n=t.dataset)==null?void 0:n.cocoPlacementType)||null,dynamicVariant:((a=t.dataset)==null?void 0:a.cocoPlacementVariant)||null,dynamicConfigSource:((o=t.dataset)==null?void 0:o.cocoConfigSource)||null}}getSlotEventContext(t,s={}){return{divId:t.divId,adUnitPath:t.adUnitPath,dynamic:!!t.dynamic,dynamicPlacementType:t.dynamicPlacementType||null,dynamicVariant:t.dynamicVariant||null,dynamicConfigSource:t.dynamicConfigSource||null,refreshCount:t.refreshCount||0,...s}}emitSlotEvent(t,s,n={}){this.eventBus.emit(t,this.getSlotEventContext(s,n))}beginAnalyticsAttempt(t,s,n={}){var o,h,u;const a=I();return!a||!t?null:a.startAttempt(t,{requestMode:s,refreshCount:t.refreshCount||0,retryCount:t.noBidRetryCount||0,biddersRequested:t.lastRequestedBidders||[],bidderCountRequested:(t.lastRequestedBidders||[]).length,timeoutMs:t.lastBidTimeout||null,bidderSetVersion:((o=t.lastBidOptimization)==null?void 0:o.strategyVersion)||null,bidderGroup:((h=t.lastBidOptimization)==null?void 0:h.matchedBidderGroup)||null,biddersFiltered:((u=t.lastBidOptimization)==null?void 0:u.filterReasons)||{},retryReason:t.lastRetryReason||null,...n})}initializeAdSlot(t,s,n){var y,S;t.classList.add("coco-processed");const a=t.id,h=((y=t.dataset)==null?void 0:y.cocoAdUnit)||s,u=this.getResolvedSlotPolicy(h,{divId:a}),m=this.normalizeSizes((u==null?void 0:u.sizes)||n.size),p=((u==null?void 0:u.bidders)||[]).map(B=>({...B})),g=new Map(p.map(B=>[B,{...this.floorStrategy.sanitizeBidder(B),...this.config.SCHAIN?{schain:this.config.SCHAIN}:{}}])),f=this.getDynamicSlotMetadata(t),b={divId:a,element:t,adUnitPath:h,sizes:m,bidders:p,bidderPayloadMap:g,policy:{sizes:m,bidders:p,lazyLoad:(u==null?void 0:u.lazyLoad)||this.getDefaultLazyLoadConfig(a),refresh:(u==null?void 0:u.refresh)||this.getRefreshPolicy({adUnitPath:h}),flags:(u==null?void 0:u.flags)||{}},definition:n,baseId:n.key,loaded:!1,refreshCount:0,noBidRetryCount:0,retryTimerId:null,pendingRetryCheck:!1,lastRenderEmpty:null,lastRenderTime:null,lastRefreshTime:0,currentAttemptId:null,lastAttemptId:null,lastRequestMode:null,lastAuctionId:null,lastRequestedBidders:[],lastBidTimeout:null,lastBidOptimization:null,lastRetryReason:null,lastFloorData:null,legacyFloorWarnings:this.floorStrategy.getLegacyAudit(h),dynamic:f.dynamic,dynamicPlacementType:f.dynamicPlacementType,dynamicVariant:f.dynamicVariant,dynamicConfigSource:f.dynamicConfigSource};this.slotRegistry.set(a,b),this.ensureInjectedSlotScript(t,{divId:a,adUnitPath:h}),!b.loaded&&!(b.policy.flags.forceRender||((S=b.policy.lazyLoad)==null?void 0:S.enabled)===!1)&&this.observeSlot(b),this.emitSlotEvent("coco.slotInitialized",b,{bidderCount:p.length}),this.log(`Slot initialized: ${a} -> ${h}`)}setupLazyLoadObservers(){this.observers.clear()}observeSlot(t){const s=t.divId;let n=this.observers.get(s);if(!n){const a=this.getObserverConfig(t);n=new IntersectionObserver(o=>{o.forEach(h=>{if(h.isIntersecting){const u=this.slotRegistry.get(h.target.id);u&&!u.loaded&&(this.loadAd(u),n.unobserve(h.target))}})},a),this.observers.set(s,n)}n.observe(t.element)}getObserverConfig(t){var o;const s=typeof t=="string"?t:t==null?void 0:t.divId,n=typeof t=="string"?null:(o=t==null?void 0:t.policy)==null?void 0:o.lazyLoad,a=this.getDefaultLazyLoadConfig(s||"");return{rootMargin:(n==null?void 0:n.rootMargin)||a.rootMargin,threshold:Array.isArray(n==null?void 0:n.threshold)?n.threshold:a.threshold}}loadAd(t){const{divId:s,adUnitPath:n,sizes:a,bidders:o}=t;if(this.log(`Loading ad: ${s}`),t.loaded=!0,t.lastRefreshTime=Date.now(),!a||a.length===0)return;const h=z();if(h&&t.element&&h.track(s,t.element),!o||o.length===0){t.lastRequestedBidders=[],t.lastRequestMode="initial",t.lastFloorData=this.resolveSlotFloors(t,"initial"),t.lastBidTimeout=null,t.lastBidOptimization={strategyVersion:this.bidOptimizer.strategyVersion,matchedBidderGroup:null,filterReasons:{},timeoutMs:null},this.beginAnalyticsAttempt(t,"initial",{biddersRequested:[],bidderCountRequested:0,usedGamDirect:!0}),this.renderAdDirectly(t);return}this.initialLoadBatch.closed?this.requestSlotBids(t):this.enqueueInitialLoad(t)}enqueueInitialLoad(t){const s=this.prepareSlotForBidding(t,"initial");if(!s){this.log(`All bidders filtered for ${t.divId}, using GAM directly`),t.lastRequestedBidders=[],t.lastRequestMode="initial",t.lastFloorData=this.resolveSlotFloors(t,"initial"),t.lastBidTimeout=null,t.lastBidOptimization={strategyVersion:this.bidOptimizer.strategyVersion,matchedBidderGroup:null,filterReasons:{},timeoutMs:null},this.beginAnalyticsAttempt(t,"initial",{biddersRequested:[],bidderCountRequested:0,usedGamDirect:!0}),this.renderAdDirectly(t),this.emitSlotEvent("coco.adRequested",t,{bidderCount:0});return}this.initialLoadBatch.slots.set(t.divId,s),this.emitSlotEvent("coco.adRequested",t,{bidderCount:s.filteredBidders.length}),!this.initialLoadBatch.timerId&&(this.initialLoadBatch.timerId=setTimeout(()=>{this.flushInitialLoadBatch()},this.initialLoadBatch.windowMs))}flushInitialLoadBatch(){this.initialLoadBatch.timerId&&(clearTimeout(this.initialLoadBatch.timerId),this.initialLoadBatch.timerId=null);const t=Array.from(this.initialLoadBatch.slots.values());this.initialLoadBatch.slots.clear(),this.initialLoadBatch.closed=!0,t.length!==0&&(t.length>1&&this.log(`Batching initial load for ${t.length} slots`),t.forEach(({slotInfo:s})=>{this.beginAnalyticsAttempt(s,"initial")}),this.requestPreparedSlots(t,s=>{t.forEach(({slotInfo:n})=>this.handleBidsBack(n,s))}))}getFloorContext(t="initial"){var n;const s=L();return{requestMode:t,isMobile:this.isMobileViewport(),device:this.isMobileViewport()?"mobile":"desktop",geo:((n=s==null?void 0:s.getContext)==null?void 0:n.call(s).geo)||d.COCO_GEO||null}}resolveSlotFloors(t,s="initial",n={}){return this.floorStrategy.isEnabled()?this.floorStrategy.resolveForSlot(t,{...this.getFloorContext(s),...n}):null}applyFloorConfig(t=[]){if(!this.floorStrategy.isEnabled())return;const s=t.map(n=>(n==null?void 0:n.floorData)||(n!=null&&n.slotInfo?this.resolveSlotFloors(n.slotInfo,n.slotInfo.lastRequestMode||"initial"):null)).filter(Boolean);d.pbjs.setConfig({floors:this.floorStrategy.buildPrebidFloorsPayload(s)})}prepareSlotForBidding(t,s="initial"){var f,b;const{divId:n,bidders:a=[]}=t;if(a.length===0)return null;const o=this.bidOptimizer.selectBidders(t,a,s);let h=o.selectedBidders;const u={...o.filterReasons||{}},m=L();if(m){const y=m.evaluateBidders(h,n);h=y.allowed,y.blocked.forEach(S=>{S!=null&&S.bidder&&(u[S.bidder]=S.reason||"traffic")}),h.length ${h.length} bidders for ${n}`)}const p=D();if(p){const y=h.length,S=p.evaluateBidders(h,n);h=S.allowed,S.blocked.forEach(B=>{B!=null&&B.bidder&&(u[B.bidder]=B.reason||"throttled")}),h.lengthy.bidder),t.lastRequestedBidders=t.activeBidders.slice(),t.lastRequestMode=s,t.lastFloorData=g,t.lastBidTimeout=o.timeoutMs,t.lastBidOptimization={...o,filterReasons:u},{slotInfo:t,filteredBidders:h,floorData:g,timeoutMs:o.timeoutMs,adUnit:{code:n,mediaTypes:{banner:{sizes:t.sizes}},bids:h.map(y=>t.bidderPayloadMap.get(y)||y)}}}requestPreparedSlots(t,s){!t||t.length===0||d.pbjs.que.push(()=>{const n=Math.max(...t.map(a=>Number(a==null?void 0:a.timeoutMs)||0),0)||void 0;this.applyFloorConfig(t),t.forEach(({slotInfo:a})=>{d.pbjs.removeAdUnit(a.divId)}),d.pbjs.addAdUnits(t.map(a=>a.adUnit)),d.pbjs.requestBids({adUnitCodes:t.map(a=>a.slotInfo.divId),...n?{timeout:n}:{},bidsBackHandler:s})})}requestSlotBids(t){const s=this.prepareSlotForBidding(t,"initial");if(!s){this.log(`All bidders filtered for ${t.divId}, using GAM directly`),t.lastRequestedBidders=[],t.lastRequestMode="initial",t.lastFloorData=this.resolveSlotFloors(t,"initial"),t.lastBidTimeout=null,t.lastBidOptimization={strategyVersion:this.bidOptimizer.strategyVersion,matchedBidderGroup:null,filterReasons:{},timeoutMs:null},this.beginAnalyticsAttempt(t,"initial",{biddersRequested:[],bidderCountRequested:0,usedGamDirect:!0}),this.renderAdDirectly(t),this.emitSlotEvent("coco.adRequested",t,{bidderCount:0});return}this.emitSlotEvent("coco.adRequested",t,{bidderCount:s.filteredBidders.length}),this.beginAnalyticsAttempt(t,"initial"),this.requestPreparedSlots([s],n=>this.handleBidsBack(t,n))}inspectBidResults(t,s){var u,m;const n=new Set;let a=[],o=null;const h=(p=[],g="unknown")=>!Array.isArray(p)||p.length===0?!1:(a=p,o=o||p.reduce((f,b)=>((b==null?void 0:b.cpm)||0)>((f==null?void 0:f.cpm)||0)?b:f,p[0]),p.forEach(f=>{const b=(f==null?void 0:f.bidderCode)||(f==null?void 0:f.bidder);b&&n.add(b)}),this.log(`${g} found ${p.length} for ${t}`),!0);try{if(h(d.pbjs.getAllWinningBids?d.pbjs.getAllWinningBids().filter(p=>p.adUnitCode===t):[],"getAllWinningBids"))return{hasBids:!0,bidCount:a.length,biddersWithBids:n,winningBid:o}}catch{}try{if(h(d.pbjs.getHighestCpmBids?d.pbjs.getHighestCpmBids(t):[],"getHighestCpmBids"))return{hasBids:!0,bidCount:a.length,biddersWithBids:n,winningBid:o}}catch{}try{const p=d.pbjs.getBidResponses?d.pbjs.getBidResponses():{};if(h(((u=p==null?void 0:p[t])==null?void 0:u.bids)||[],"getBidResponses"))return{hasBids:!0,bidCount:a.length,biddersWithBids:n,winningBid:o}}catch{}return h(((m=s==null?void 0:s[t])==null?void 0:m.bids)||[],"bidsResponse"),{hasBids:a.length>0,bidCount:a.length,biddersWithBids:n,winningBid:o}}handleBidsBack(t,s){var v,M;const{divId:n}=t,a=this.config.NO_BID_SETTINGS||{},o=D(),h=I(),{hasBids:u,bidCount:m,biddersWithBids:p,winningBid:g}=this.inspectBidResults(n,s),f=t.lastRequestedBidders||[],b=Array.from(p),y=f.filter(A=>!p.has(A)),S=((M=(v=h==null?void 0:h.getAttempt)==null?void 0:v.call(h,t))==null?void 0:M.biddersTimedOut)||new Set,B=f.filter(A=>S.has(A));o&&t.activeBidders&&t.activeBidders.forEach(A=>{S.has(A)?o.recordTimeout(A,n):p.has(A)?o.recordBid(A,n):o.recordNoBid(A,n)}),this.log(`Final bid check for ${n}: hasBids=${u}, bidCount=${m}`),h&&h.markBidsBack(t,{biddersResponded:b,biddersNoBid:y,biddersTimedOut:B}),u?(h&&g&&h.recordWinningBid(t,g),t.pendingRetryCheck=!0,this.cancelNoBidRetry(t),this.log(`✓ Got ${m} bid(s) for ${n} - no retry needed`),this.renderAd(t)):(this.log(`✗ No Prebid bids for ${n}`),this.emitSlotEvent("coco.noBid",t,{retryCount:t.noBidRetryCount,isRefresh:!1}),h&&h.recordSlotEvent("noBid",t,{isRefresh:!1}),a.fallbackToGAM!==!1&&(this.log(`Falling back to GAM for ${n}`),this.renderAd(t)),a.enabled!==!1&&(a.onlyRetryIfEmpty?(this.log(`Waiting for GPT render result before scheduling retry for ${n}`),t.pendingRetryCheck=!0):this.scheduleNoBidRetry(t,"initial-no-bid")))}scheduleNoBidRetry(t,s="no-bid"){const n=this.config.NO_BID_SETTINGS||{},a=n.maxRetries,o=Number(a),u=a===null||o<0?1/0:Number.isFinite(o)&&o>0?o:3,m=n.retryIntervals||[5e3,15e3,3e4],p=this.bidOptimizer.shouldAllowRetry(t,{reason:s,isVisible:this.isElementVisible(t.element),viewability:this.getElementVisibility(t.element)});if(t.noBidRetryCount>=u){this.log(`Max no-bid retries reached for ${t.divId}`);return}if(!p.allowed){this.log(`Retry skipped for ${t.divId} (${p.reason})`);return}const g=Math.min(t.noBidRetryCount,m.length-1),f=m[g];t.noBidRetryCount++,t.lastRetryReason=p.reason||s,this.log(`Scheduling no-bid retry for ${t.divId} in ${f}ms`),this.cancelNoBidRetry(t),t.retryTimerId=setTimeout(()=>{t.retryTimerId=null,t.lastRenderEmpty||this.isElementVisible(t.element)?this.retryBidRequest(t):this.log(`Skipping retry for ${t.divId} - not visible`)},f)}cancelNoBidRetry(t){t.retryTimerId&&(clearTimeout(t.retryTimerId),t.retryTimerId=null,this.log(`Cancelled pending retry for ${t.divId}`))}retryBidRequest(t){const{divId:s}=t;this.log(`Retrying bid request for ${s} (was empty: ${t.lastRenderEmpty})`);const n=this.prepareSlotForBidding(t,"retry");if(!n){this.log(`Retry skipped for ${s} - no eligible bidders`);return}this.beginAnalyticsAttempt(t,"retry"),d.pbjs.que.push(()=>{this.applyFloorConfig([{slotInfo:t,floorData:n.floorData}]),d.pbjs.removeAdUnit(s),d.pbjs.addAdUnits(n.adUnit),d.pbjs.requestBids({adUnitCodes:[s],...n.timeoutMs?{timeout:n.timeoutMs}:{},bidsBackHandler:a=>this.handleRetryBidsBack(t,a)})}),this.emitSlotEvent("coco.noBidRetry",t,{retryCount:t.noBidRetryCount})}handleRetryBidsBack(t,s){var y,S;const{divId:n}=t,a=this.config.NO_BID_SETTINGS||{},o=I(),h=t.lastRequestedBidders||[],{hasBids:u,bidCount:m,biddersWithBids:p,winningBid:g}=this.inspectBidResults(n,s),f=((S=(y=o==null?void 0:o.getAttempt)==null?void 0:y.call(o,t))==null?void 0:S.biddersTimedOut)||new Set;this.log(`Retry bid check for ${n}: hasBids=${u}, bidCount=${m}`),o&&o.markBidsBack(t,{biddersResponded:Array.from(p),biddersNoBid:h.filter(B=>!p.has(B)),biddersTimedOut:h.filter(B=>f.has(B))});const b=this.gptSlots.get(n);b&&(d.pbjs.setTargetingForGPTAsync([n]),d.googletag.pubads().refresh([b])),u?(o&&g&&o.recordWinningBid(t,g),t.pendingRetryCheck=!0,this.cancelNoBidRetry(t),this.log(`✓ Retry got ${m} bid(s) for ${n}`)):(this.log(`✗ Retry got no Prebid bids for ${n}`),this.emitSlotEvent("coco.noBid",t,{retryCount:t.noBidRetryCount,isRefresh:!1,isRetry:!0}),o&&o.recordSlotEvent("noBid",t,{isRefresh:!1,isRetry:!0}),a.enabled!==!1&&(a.onlyRetryIfEmpty?t.pendingRetryCheck=!0:this.scheduleNoBidRetry(t,"retry-no-bid")))}renderAd(t){const{divId:s,adUnitPath:n,sizes:a}=t;d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>{d.pbjs.que.push(()=>d.pbjs.setTargetingForGPTAsync([s]));let o=this.gptSlots.get(s);o||(o=d.googletag.defineSlot(n,a,s),o&&(this.refreshCounters[s]=this.refreshCounters[s]||0,o.setTargeting("coco_refresh",String(this.refreshCounters[s])),o.addService(d.googletag.pubads()),this.gptSlots.set(s,o))),o&&d.googletag.pubads().refresh([o])}),this.emitSlotEvent("coco.adRendered",t),this.log(`Ad rendered: ${s}`)}renderAdDirectly(t){const{divId:s,adUnitPath:n,sizes:a}=t;d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>{let o=this.gptSlots.get(s);o||(o=d.googletag.defineSlot(n,a,s),o&&(o.addService(d.googletag.pubads()),this.gptSlots.set(s,o))),o&&d.googletag.pubads().refresh([o])}),this.emitSlotEvent("coco.adRendered",t)}refreshSlot(t){const s=this.slotRegistry.get(t);s&&this.refreshSlots([s])}refreshSlots(t){const s=t.map(n=>this.prepareRefreshSlot(n)).filter(Boolean);if(s.length!==0){if(s.forEach(({slotInfo:n})=>{this.emitSlotEvent("coco.adRefreshed",n,{refreshCount:n.refreshCount})}),s.length===1){this.runSingleRefresh(s[0]);return}this.runRefreshBatch(s)}}prepareRefreshSlot(t){const{divId:s}=t,n=this.getRefreshPolicy(t);if(n.enabled===!1)return this.log(`Refresh disabled for ${s}`),null;if(t.refreshCount>=n.maxRefreshes)return this.log(`Max refreshes reached for ${s}`),null;t.refreshCount++,t.lastRefreshTime=Date.now(),this.refreshCounters[s]=(this.refreshCounters[s]||0)+1;const a=this.prepareSlotForBidding(t,"refresh");return a||(t.lastRequestMode="refresh",t.lastFloorData=this.resolveSlotFloors(t,"refresh")),{slotInfo:t,filteredBidders:a?a.filteredBidders:[],adUnit:a?a.adUnit:null,floorData:a?a.floorData:this.resolveSlotFloors(t,"refresh")}}runSingleRefresh(t){const{slotInfo:s,filteredBidders:n,adUnit:a}=t,{divId:o}=s;d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>{const h=this.gptSlots.get(o);h&&n.length>0?(this.beginAnalyticsAttempt(s,"refresh"),d.pbjs.que.push(()=>{this.applyFloorConfig([t]),d.pbjs.removeAdUnit(o),d.pbjs.addAdUnits(a),d.pbjs.requestBids({adUnitCodes:[o],...t.timeoutMs?{timeout:t.timeoutMs}:{},bidsBackHandler:u=>this.handleRefreshBidsBack(s,h,u)})})):h&&(s.lastRequestedBidders=[],s.lastBidTimeout=null,s.lastBidOptimization={strategyVersion:this.bidOptimizer.strategyVersion,matchedBidderGroup:null,filterReasons:{},timeoutMs:null},this.beginAnalyticsAttempt(s,"refresh",{biddersRequested:[],bidderCountRequested:0,usedGamDirect:!0}),d.googletag.pubads().refresh([h]))}),this.log(`Slot refreshed: ${o} (${n.length} bidders)`)}runRefreshBatch(t){d.googletag=d.googletag||{cmd:[]},d.googletag.cmd.push(()=>{const s=[],n=[];t.forEach(a=>{const o=this.gptSlots.get(a.slotInfo.divId);o&&(a.gptSlot=o,a.filteredBidders.length>0?(this.beginAnalyticsAttempt(a.slotInfo,"refresh"),n.push(a)):(a.slotInfo.lastRequestedBidders=[],a.slotInfo.lastBidTimeout=null,a.slotInfo.lastBidOptimization={strategyVersion:this.bidOptimizer.strategyVersion,matchedBidderGroup:null,filterReasons:{},timeoutMs:null},this.beginAnalyticsAttempt(a.slotInfo,"refresh",{biddersRequested:[],bidderCountRequested:0,usedGamDirect:!0}),s.push(o)))}),s.length>0&&d.googletag.pubads().refresh(s),n.length!==0&&(this.log(`Batching refresh for ${n.length} slots`),this.requestPreparedSlots(n,a=>{this.handleRefreshBatchBidsBack(n,a)}))}),t.forEach(({slotInfo:s,filteredBidders:n})=>{this.log(`Slot refreshed: ${s.divId} (${n.length} bidders)`)})}handleRefreshBatchBidsBack(t,s){const n=this.config.NO_BID_SETTINGS||{},a=I(),o=D(),h=[],u=[];t.forEach(({slotInfo:m,gptSlot:p})=>{var M,A;if(!p)return;const{divId:g}=m,{hasBids:f,bidCount:b,biddersWithBids:y,winningBid:S}=this.inspectBidResults(g,s),B=m.lastRequestedBidders||[],v=((A=(M=a==null?void 0:a.getAttempt)==null?void 0:M.call(a,m))==null?void 0:A.biddersTimedOut)||new Set;o&&m.activeBidders&&m.activeBidders.forEach(x=>{v.has(x)?o.recordTimeout(x,g):y.has(x)?o.recordBid(x,g):o.recordNoBid(x,g)}),h.push(p),u.push(g),p.setTargeting("coco_refresh",String(this.refreshCounters[g])),a&&a.markBidsBack(m,{biddersResponded:Array.from(y),biddersNoBid:B.filter(x=>!y.has(x)),biddersTimedOut:B.filter(x=>v.has(x))}),f?(a&&S&&a.recordWinningBid(m,S),m.pendingRetryCheck=!0,this.cancelNoBidRetry(m),this.log(`✓ Refresh got ${b} bid(s) for ${g}`)):(this.log(`✗ Refresh got no Prebid bids for ${g}`),this.emitSlotEvent("coco.noBid",m,{retryCount:m.noBidRetryCount,isRefresh:!0}),a&&a.recordSlotEvent("noBid",m,{isRefresh:!0}),n.enabled!==!1&&(n.onlyRetryIfEmpty?m.pendingRetryCheck=!0:this.scheduleNoBidRetry(m,"refresh-no-bid")))}),u.length>0&&(d.pbjs.setTargetingForGPTAsync(u),d.googletag.pubads().refresh(h))}handleRefreshBidsBack(t,s,n){var S,B;const{divId:a}=t,o=this.config.NO_BID_SETTINGS||{},h=D(),u=I(),{hasBids:m,bidCount:p,biddersWithBids:g,winningBid:f}=this.inspectBidResults(a,n),b=t.lastRequestedBidders||[],y=((B=(S=u==null?void 0:u.getAttempt)==null?void 0:S.call(u,t))==null?void 0:B.biddersTimedOut)||new Set;h&&t.activeBidders&&t.activeBidders.forEach(v=>{y.has(v)?h.recordTimeout(v,a):g.has(v)?h.recordBid(v,a):h.recordNoBid(v,a)}),d.pbjs.setTargetingForGPTAsync([a]),s.setTargeting("coco_refresh",String(this.refreshCounters[a])),d.googletag.pubads().refresh([s]),u&&u.markBidsBack(t,{biddersResponded:Array.from(g),biddersNoBid:b.filter(v=>!g.has(v)),biddersTimedOut:b.filter(v=>y.has(v))}),m?(u&&f&&u.recordWinningBid(t,f),t.pendingRetryCheck=!0,this.cancelNoBidRetry(t),this.log(`✓ Refresh got ${p} bid(s) for ${a}`)):(this.log(`✗ Refresh got no Prebid bids for ${a}`),this.emitSlotEvent("coco.noBid",t,{retryCount:t.noBidRetryCount,isRefresh:!0}),u&&u.recordSlotEvent("noBid",t,{isRefresh:!0}),o.enabled!==!1&&(o.onlyRetryIfEmpty?(this.log(`Waiting for GPT render result before scheduling retry for ${a}`),t.pendingRetryCheck=!0):this.scheduleNoBidRetry(t,"refresh-single-no-bid")))}refreshAllAds(){const t=[];this.slotRegistry.forEach((s,n)=>{const a=this.getRefreshPolicy(s);!s.loaded||a.enabled===!1||(s.lastRenderEmpty||a.requireVisibility===!1||this.isElementVisible(s.element))&&t.push(s)}),this.refreshSlots(t)}startAutoRefresh(){if(this.refreshTimer){this.log("Auto-refresh already running");return}const t=Array.from(this.slotPolicies.values()).map(p=>p.refresh).filter(p=>(p==null?void 0:p.enabled)!==!1),s=this.config.REFRESH_SETTINGS||{};if(!s.enabled&&t.length===0){this.log("Auto-refresh disabled");return}const n=t.map(p=>p.intervalMs).filter(p=>Number.isFinite(p)&&p>0);n.push(s.minInterval||3e4);const a=t.map(p=>p.idleTimeout).filter(p=>Number.isFinite(p)&&p>0);a.push(s.idleTimeout||6e4);const o=Math.min(...n),h=Math.min(...a),u=t.some(p=>p.refreshOnTabReturn)||!!s.refreshOnTabReturn,m=this.autoRefreshState;if(m.lastActivity=Date.now(),!m.handlersBound){const p=["mousedown","mousemove","keydown","scroll","touchstart"];m.activityHandler=()=>{const g=Date.now();g-m.lastActivityEventAt<250||(m.lastActivityEventAt=g,m.lastActivity=g,m.isIdle&&(m.isIdle=!1,this.log("User active, resuming auto-refresh")))},m.visibilityHandler=()=>{if(document.hidden){m.tabHiddenTime=Date.now(),this.log("Tab hidden");return}if(this.log("Tab visible"),m.lastActivity=Date.now(),u&&m.tabHiddenTime){const g=Date.now()-m.tabHiddenTime;g>=o&&(this.log(`Tab was hidden for ${Math.round(g/1e3)}s - refreshing visible ads`),m.visibilityRefreshTimerId=setTimeout(()=>this.refreshVisibleAds(!0),100))}m.tabHiddenTime=null},p.forEach(g=>{document.addEventListener(g,m.activityHandler,{passive:!0})}),document.addEventListener("visibilitychange",m.visibilityHandler),m.handlersBound=!0}this.refreshTimer=setInterval(()=>{if(Date.now()-m.lastActivity>h){m.isIdle||(m.isIdle=!0,this.log("User idle, pausing auto-refresh"));return}if(document.hidden){this.log("Tab hidden, skipping refresh");return}this.log("Auto-refresh triggered"),this.refreshVisibleAds()},o),this.log(`Auto-refresh started (${o}ms interval, refreshOnTabReturn: ${u})`)}stopAutoRefresh(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null,this.log("Auto-refresh stopped")),this.autoRefreshState.visibilityRefreshTimerId&&(clearTimeout(this.autoRefreshState.visibilityRefreshTimerId),this.autoRefreshState.visibilityRefreshTimerId=null)}isSlotEligibleForRefresh(t,{forceRefresh:s=!1,viewTracker:n,viewData:a={},refreshPolicy:o=this.getRefreshPolicy(t),now:h=Date.now()}={}){const u=t.divId,m=t.lastRenderEmpty===!0,p=h-(t.lastRefreshTime||0),g=a[u];if(!t.loaded||o.enabled===!1||t.refreshCount>=o.maxRefreshes||p=o.viewabilityThreshold;if(s)return o.requireVisibility===!1||y;if(o.requireVisibility!==!1&&!y)return!1;if(n&&g)return(o.requireVisibility===!1||g.visible)&&g.viewTimeSinceRefresh>=o.minViewTime;n&&t.element&&(n.track(u,t.element),this.log(`Started tracking ${u} for viewability`));const S=Math.max(o.intervalMs,o.minViewTime);return p>=S&&(o.requireVisibility===!1||y)}refreshVisibleAds(t=!1){const s=z(),n=s?s.getData():{},a=Date.now();let o=0,h=0,u=0,m=0;const p=[];this.slotRegistry.forEach((g,f)=>{const b=this.getRefreshPolicy(g);if(!g.loaded){u++;return}if(b.enabled===!1){h++;return}if(g.refreshCount>=b.maxRefreshes){m++;return}if(!this.isSlotEligibleForRefresh(g,{forceRefresh:t,viewTracker:s,viewData:n,refreshPolicy:b,now:a})){h++;return}s&&s.markRefreshed(f),p.push(g),o++}),this.refreshSlots(p),(o>0||d.COCO_DEBUG)&&this.log(`Refresh: ${o} refreshed, ${h} waiting, ${u} not loaded, ${m} maxed out`)}getElementVisibility(t){if(!t)return 0;const s=t.getBoundingClientRect(),n=d.innerHeight||document.documentElement.clientHeight,a=d.innerWidth||document.documentElement.clientWidth,o=Math.min(s.right,a)-Math.max(s.left,0),h=Math.min(s.bottom,n)-Math.max(s.top,0);if(o<=0||h<=0)return 0;const u=o*h,m=s.width*s.height;return m>0?u/m:0}injectByWordCount(t){const{parentSelector:s,itemSelector:n="p",adUnits:a,wordsThreshold:o=300,resetBetweenItems:h=!1,containerClass:u="coco-injected-container",position:m="afterend"}=t,p=document.querySelector(s);if(!p)return!1;const g=p.querySelectorAll(n);if(g.length===0)return!1;p.querySelectorAll(`.${u}`).forEach(S=>S.remove());let f=0,b=0,y=0;return g.forEach(S=>{const B=(S.innerText||"").trim().split(/\s+/).length;if(f+=B,f>=o){const v=a[b%a.length];this.taskQueue.addTask(()=>this.injectAdElement({adUnitKey:v,containerClass:u,targetElement:S,position:m})),b++,y++,f=h?0:f-o}}),y>0}injectByPattern(t){const{parentSelector:s,itemSelector:n,adUnits:a,firstInsertAfter:o=2,insertEvery:h=5,containerClass:u="coco-injected-container",position:m="afterend"}=t,p=document.querySelector(s);if(!p)return!1;const g=p.querySelectorAll(n);if(g.length===0)return!1;let f=0,b=0;return g.forEach((y,S)=>{const B=S+1;if(B===o||B>o&&(B-o)%h===0){const v=a[f%a.length];this.taskQueue.addTask(()=>this.injectAdElement({adUnitKey:v,containerClass:u,targetElement:y,position:m})),f++,b++}}),b>0}injectAdElement(t){const{adUnitKey:s,containerClass:n,targetElement:a,position:o}=t;if(!a)return!1;let h=null;for(const[,p]of this.getSlotDefinitionEntries())if(p.key===s){h=p.key;break}h||(h=`coco-injected-${s}-${Date.now()}`);const u=document.createElement("div");u.className=n;const m=document.createElement("div");return m.id=h,u.appendChild(m),a.insertAdjacentElement(o,u),this.queueScan(u,100),!0}setupRouteChangeDetection(){let t=d.location.pathname;d.addEventListener("popstate",()=>{setTimeout(()=>{t!==d.location.pathname&&(t=d.location.pathname,this.handleRouteChange(t))},100)});const s=history.pushState;history.pushState=(...a)=>{s.apply(history,a),setTimeout(()=>{t!==d.location.pathname&&(t=d.location.pathname,this.handleRouteChange(t))},100)};const n=history.replaceState;history.replaceState=(...a)=>{n.apply(history,a),setTimeout(()=>{t!==d.location.pathname&&(t=d.location.pathname,this.handleRouteChange(t))},100)}}handleRouteChange(t){this.log(`Route changed: ${t}`),this.eventBus.emit("coco.routeChange",{path:t}),this.eventBus.emit("coco.newPage",{path:t}),this.queueScan(document,500),this.firstPageviewFired||(this.firstPageviewFired=!0)}vuePlugin(){const t=this;return{install(s){s.prototype.$cocoAds={refresh:()=>t.refreshAllAds(),refreshSlot:n=>t.refreshSlot(n),scanForAds:()=>t.scanForAds(),injectByWordCount:n=>t.injectByWordCount(n),injectByPattern:n=>t.injectByPattern(n)},s.directive("coco-ad",{inserted(n,a){const o=a.value||a.arg;o&&(n.id=o,t.queueScan(n.parentElement,100))}})}}}isElementVisible(t){if(!t)return!1;const s=t.getBoundingClientRect(),n=d.innerHeight||document.documentElement.clientHeight,a=d.innerWidth||document.documentElement.clientWidth;return s.top0&&s.left0}injectStyles(){var n;if(document.getElementById("coco-wrapper-styles"))return;const t=((n=this.config.DYNAMIC_PLACEMENTS)==null?void 0:n.styles)||[];if(!t.length)return;const s=document.createElement("style");s.id="coco-wrapper-styles",s.textContent=t.join(` `),document.head.appendChild(s)}log(...t){(d.location.search.includes("coco_debug=1")||d.COCO_DEBUG)&&console.log("[CocoWrapper]",...t)}}function r(){return new Promise(c=>{document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>c(!0)):c(!0)})}async function l(){return d.__COCO_WRAPPER_INIT_PROMISE||(console.log("[CocoWrapper] Initializing..."),d.coco=d.coco||{},d.coco.cmd=d.coco.cmd||[],d.coco.version="1.0.0",d.pbjs=d.pbjs||{},d.pbjs.que=d.pbjs.que||[],d.__COCO_WRAPPER_INIT_PROMISE=(async()=>{await r(),d.cocoInjector=new i(re),await d.cocoInjector.init();const c=[...d.coco.cmd];return d.coco.cmd={push:t=>t()},c.forEach(t=>{try{t()}catch{}}),console.log("[CocoWrapper] Ready"),d.cocoInjector})().catch(c=>{throw console.error("[CocoWrapper] Init error:",c),d.__COCO_WRAPPER_INIT_PROMISE=null,c})),d.__COCO_WRAPPER_INIT_PROMISE}l()})(window)})();